var flowplayerSWF = themeDisplay.getPathThemeRoot()+'javascript/flowplayer/flowplayer-3.1.5.swf';

(function($) {
        
    
    $(function() {
       
        var $navigation     = $('#navigation>ul.main-menu');
        var $subnavigation  = $('#navigation>ul.child-menu');
	var $subNavWidth    = 0;
	$subnavigation.find('li').each(function() {
		$subNavWidth += $(this).width() + parseInt($(this).css('padding-left'));
	});
        
        $navigation.width(Math.ceil( ($navigation.width() + 1) / 10) * 10);
        //$subnavigation.width(Math.ceil( ($subnavigation.width() + 1) / 10) * 10);
	$subnavigation.width(Math.ceil( ($subNavWidth + 1) / 10 ) * 10);
        
        $('.lso-order-shop').lsoShopOrderForm();
    	$('.lso-order-tickets').lsoTicketOrderForm();
    	$('.lsou25-club-form').lsoClubForm();
    	
    	$('.lso-event-intro-video').lsoEventIntroVideo();
    	$('.lso-next-event-intro').lsoNextEventVideIntro();
    	
    	$('.mp3').lsoPlayer();
    
    	$('.paragraph-blickfeld-gallery').blickfeldGallery();
    	$('.paragraph-blickfeld-video').blickfeldVideo();
    });
    
    
    
    /**
     * Blickfeld Video
     */
     
    $.fn.blickfeldVideo = function() {
        
        return this.each(function() {
           
           var $obj = $(this);
           
           var $portlet        = $obj.parents('.portlet-content-container').children('div').eq(0).css({position:'relative', overflow: 'hidden'});
           var portletHeight   = $portlet.height();


           var $all_thumbnails = $portlet.find('.thumbnail');
           var $thumbnail      = $obj.find('.thumbnail').css({cursor: 'pointer'});

           var $video           = $obj.find('[data-src]');

           var width = $portlet.width();
           
           var $_close          = null;
           
           var $current         = null; // this will be the video container
           
           var _close = function() {
               if ($current) {
                   $current.remove();
                   $video.hide();
                   $current = null;
               }
                              
               $portlet.animate({height:portletHeight+'px'});
               $all_thumbnails.fadeIn(250);
               $all_thumbnails.css('-webkit-transition', '-webkit-transform 0.25s linear').css('-webkit-transform','scale(1)');
           }
               
           
           var $close = function() {
               if (!$_close) {
                   $_close = $("<span/>")
                       .html('Back')
                       .addClass('blickfeld-gallery-close')
                       .addClass('lsou25-button')
                       .click(function() {
                           _close();
                           return false;
                       })
                       .appendTo($portlet.parent());
               }
               return $_close;
           }
           
           
           $thumbnail.click(function() {
               
               $portlet.css({height:portletHeight+'px'});
               
               // Make sure the close button is visible
               $close();
               
               $all_thumbnails.css('-webkit-transition', '-webkit-transform 0.25s linear').css('-webkit-transform','scale(1.5)');
               $all_thumbnails.fadeOut(250);
               
                              

                    
                setTimeout(function() {
                    var src = $video.attr('data-src');

                    $video.show();
                    $current = $("<a/>")
                        //.addClass('flowplayer')
                        .attr('href',src)
                        .show()
                        .prependTo($video);



                    var opt = {};

                    opt.clip = {
            		    onMetaData: function() { 


            		        var w = this.getClip().metaData.width;
            		        var h = this.getClip().metaData.height;


                            if (w < $current.width()) {
                                $current.css('width', w+'px');
                            }


                            // fh/fw = h/w
                            var fh = Math.floor($current.width() * h / w) + 24;
                            $current.css({height: fh+'px'});
                            $portlet.animate({height: (50+$video.outerHeight())+'px'});

                            setTimeout(function() {
                               $current.css({position: 'static', left: 0});
                            },200);

                        },
            			autoPlay: true,
            			scaling: 'fit'
            		};

            		opt.canvas = {
            		    backgroundColor: '#23A3839',
            			backgroundGradient: 'none'
            		};


                    $current.flowplayer(flowplayerSWF,opt);
                },300);
               
           });
            
        });
        
    }
    
    /**
     * Blickfeld Gallery
     */
    
    $.fn.blickfeldGallery = function() {

                
        return this.each(function() {

            var $obj            = $(this);

            var $portlet        = $obj.parents('.portlet-content-container').children('div').eq(0).css({position:'relative', overflow: 'hidden'});
            var portletHeight   = $portlet.height();

            var $all_thumbnails = $portlet.find('.thumbnail');
            var $thumbnail      = $obj.find('.thumbnail').css({cursor: 'pointer'});

            var $images         = $obj.find('[data-src]');
            var $current        = null;

            var width = $portlet.width();
            
            var $_close          = null;
            var $_prev           = null;
            var $_next           = null;
            
            var $close = function() {
                if (!$_close) {
                    $_close = $("<span/>")
                        .html('Back')
                        .addClass('blickfeld-gallery-close')
                        .addClass('lsou25-button')
                        .click(function() {
                            _close();
                            return false;
                        })
                        .appendTo($portlet.parent());
                }
                return $_close;
            }
            
            var $prev = function() {
                if (!$_prev) {
                    $_prev = $("<span/>")
                        .html("<span>&lsaquo;</span>")
                        .addClass('blickfeld-gallery-prev')
                        .click(function() {
                            var idx = 0;
                            if ($current) {
                                idx = $images.index($current);
                                idx--;
                                if (idx >= $images.length) {
                                    idx = -1;
                                }
                            }

                            if (idx > -1) {
                                _load_image($images.eq(idx), -1, _load_image_callback);
                            }
                            else {
                                _close();
                            }
                        })
                        .appendTo($portlet.parent());
                }
                return $_prev;
            }
            
            var $next = function() {
                if (!$_next) {
                    $_next = $("<span/>")
                        .html("<span>&rsaquo;</span>")
                        .addClass('blickfeld-gallery-next')
                        .click(function() {
                            var idx = 0;
                            if ($current) {
                                idx = $images.index($current);
                                idx++;
                                if (idx >= $images.length) {
                                    idx = -1;
                                }
                            }

                            if (idx > -1) {
                                _load_image($images.eq(idx), 1, _load_image_callback);
                            }
                            else {
                                _close();
                            }
                        })
                        .appendTo($portlet.parent());
                }
                return $_next;
            }
            

            var _close = function() {
                if ($current) {
                    $current.fadeOut(function() {
                        $(this).css({left:0});
                    })
                    $current = null;
                }
                
                _validate();
                
                $portlet.animate({height:portletHeight+'px'});
                $all_thumbnails.fadeIn(250);
                $all_thumbnails.css('-webkit-transition', '-webkit-transform 0.25s linear').css('-webkit-transform','scale(1)');
                
            }

            var _load_image_callback = function($img, dir) {
                $all_thumbnails.css('-webkit-transition', '-webkit-transform 0.25s linear').css('-webkit-transform','scale(1.5)');
                $all_thumbnails.fadeOut(250);
            
            
                $portlet.animate({
                    height: $img.outerHeight()+'px'
                }, function() {

                    if ($current) {
                        $current.animate({left: (dir==1?'-':'')+width+'px'},function() {
                            $(this).hide().css({left: 0});
                        });
                        $current = null;
                        
                        $img.css({left: (dir==1?'':'-')+width+'px'}).show().animate({left: 0});
                    }
                    else {
                        // Use a fade in for the first image
                        $img.css({left:0}).fadeIn();
                    }

                    $current = $img;
                    
                    _validate();
                });
            }

            var _load_image = function($container, dir, callback) {

                if ($container.data('loaded')) {
                    callback($container, dir);
                }
                else {
                    var src = $container.attr('data-src');
                    var img = new Image();
                    img.onload = function() {

                        $container
                            .data('loaded',true)
                            .prepend(img)
                            .css({position:'absolute',top: '0',left: '0'});

                        callback($container, dir);
                    }
                    img.src = src;
                }

            }


            var _validate = function() {
                
                if (!$current) {
                    $close().hide();
                    $prev().hide();
                    $next().hide();
                }
                else {
                    $close().show();
                    var index = $images.index($current);
                    if (index > 0) {
                        $prev().show();
                    }
                    else {
                        $prev().hide();
                    }
                
                    if (index+1 < $images.length) {
                        $next().show();
                    }
                    else {
                        $next().hide();
                    }
                }
                
            }


            $thumbnail.click(function() {                
                
                if ($images.length == 0) {
                    return false;
                }
                
                _load_image($images.eq(0), 1, _load_image_callback);
               
                return false;
            });
            
        });
    }
    
    
    
    /**
     * mp3 player
     */
     
    $.fn.lsoPlayer = function() {
        return this.each(function() {
            var $obj    = $(this);
            var $play   = $obj.find('.play');
            var $stop   = $obj.find('.stop');
            
            var playing = false;
            
            var $player = null;
            
            $play.click(function() {
                if (playing) return false;
                
                playing = true;
                
                $player = $("<a/>")
                    .attr('href', $play.attr('href'))
                    .css({
                        position: 'absolute',
                        left: '-9999px'
                    })
                    .appendTo('body');
                
                $player.flowplayer(flowplayerSWF, {
                    plugins: { 
                        controls: { 
                            fullscreen: false, 
                            height: 30 
                        } 
                    }, 

                    clip: { 
                        autoPlay: true, 
                        onBeforeBegin: function() { 
                            this.unmute(); 
                        } 
                    } 
                })
                
                
                return false;
            });
            
            $stop.click(function() {
               if (!playing) return false;
               
               playing = false;
               
               $player.remove();
               $player = null;
               
               return false; 
            });
            
        });
    };
    
    
    /**
     * Close panel
     */
     
    
    $.fn.panel = function(hideCloseButton) {
        return this.each(function() {
            
            var $content = $(this);
            var $panel = $("<div/>").addClass('lso-top-panel').append($content);
            
            if (!hideCloseButton) {
                var $close = $("<span/>").addClass('lso-top-panel-close').addClass('lsou25-button').html('Close').click(function() {
                    $panel.remove();
                });
            }
            
			$panel.append($close);
            $panel.prependTo('#content-wrapper');
            
        });
    };
    
    
    

    /**
     * Video
     */
    
    $.fn.lsoEventIntroVideo = function() {
        return this.each(function() {
            var $obj = $(this);
            $obj.click(function() {
                var flv = '/content'+$obj.attr('href')+'?guest=true';
                
                var $container = $obj.parents('.lso-event-data');
                $container.css({opacity:0});
                
                var $itemContainer = $container.parents('.lso-event-item-wrapper');
                $itemContainer.addClass('locked');
                
                
                var containerHeight = $itemContainer.height();
                
                var $fp = $("<a/>")
                    //.attr('href',flv)
                    .addClass('lso-video')
                    .prependTo($container.parent())
                    .css({height: '1px', position: 'absolute', left: '-9999px'});

                $fp.flowplayer(flowplayerSWF, {
			clip: {
				url: flv,
				autoPlay: true,
				scaling: 'fit',
				wmode: 'opaque'
			},
			canvas: {
				backgroundColor: '#ffffff',
				backgroundGradient: 'none'
			}
		});
		$fp.css({height: '450px', position: 'relative', left: 'auto', 'margin-top': '20px'});
		var diff = $fp.outerHeight() - $container.outerHeight();
                var h = containerHeight + diff;
		$itemContainer.css({height: h + 'px'});

		/*
                var opt = {};

                opt.clip = {
        		onMetaData: function() { 

        		var w = this.getClip().metaData.width;
        		var h = this.getClip().metaData.height;
                        var fpw = $fp.width();

                        if (w < fpw) {
                            $fp.css({
                                width: w+'px'
                            });
                        }

                        // fh/fw = h/w
                        var fh = Math.floor($fp.width() * h / w) + 24;
                        $fp.css({height: fh+'px'});

                        $fp.css({position: 'relative', left: 'auto'});

                        var diff = $fp.outerHeight() - $container.outerHeight();
                                                
                        var h = containerHeight + diff;
                        
                        $itemContainer.css({
                            height: h + 'px'
                        }); 

                    },
        		autoPlay: true,
        		scaling: 'fit'
        	};
                
                opt.canvas = {
	       		backgroundColor: '#ffffff',
       			backgroundGradient: 'none'
       		};
        		
                $fp.flowplayer(flowplayerSWF, opt);
                $fp.css({height: '450px'});
                */
                // Back/close button
                var $back = $("<span/>").addClass('lso-video-close').addClass('lsou25-button').html('Back').prependTo($container.parent()).click(function() {
                    
                    $fp.remove();
                    $back.remove();
                    $itemContainer.removeClass('locked').css({height: containerHeight+'px'});
                    $container.css({opacity: 1});
                    
                });
            
                return false;
            });
        });
    }
    
    $.fn.lsoNextEventVideIntro = function() {
        return this.each(function() {
            var $container = $(this);
            var $a = $(this).find('a');
            
            var flv = '/content'+$a.attr('href')+'?guest=true';

            var hidden = true;
            
            
            var $fp = null;
                        
            
            var _on = function() {
                            
                if (!hidden) return;
                hidden = false;
            
            
                var tmpHeight = $('.lso-next-event').outerHeight() + $container.height();
            
                $('.lso-next-event').hide();
                
                $container.addClass('loading');
                

                //$container.css({height: $container.height()+'px'});
                $container.css({height: tmpHeight+'px'});
                
                
                $fp = $("<a/>")
                //    .attr('href',flv)
                    .addClass('lso-video')
                    .appendTo($container);
                   // .css({height: '1px', position: 'absolute', left: '-9999px'});
		$fp.flowplayer(flowplayerSWF, {
			clip: {
				url: flv,
				autoPlay: true,
				scaling: 'fit',
				wmode:'opaque'
			},
			canvas: {
				backgroundColor: '#ffffff',
				backgroundGradient: 'none'
			},
			onStart: function() {
				$container.removeClass('loading');
			}
		});
		$fp.css({height: '450px'});
		$container.css({height: 'auto'});
		/*

                setTimeout(function() { // IE needs this
                
                    var opt = {};

                    opt.clip = {

            		onMetaData: function() { 
        		                		        
                            $container.removeClass('loading');

            		        var w = this.getClip().metaData.width;
            		        var h = this.getClip().metaData.height;

                            if (w < $fp.width()) {
                                $fp.css({width: w+'px'});
                            }

                            // fh/fw = h/w
                            var fh = Math.floor($fp.width() * h / w) + 24;
                            $fp.css({height: fh+'px', position: 'relative', left: 'auto'});
                            $container.css({height: 'auto'});

                        },

            			autoPlay: true,
            			scaling: 'fit',
				wmode: 'opaque'
            		};
        		
            		opt.canvas = {
            			backgroundColor: '#ffffff',
            			backgroundGradient: 'none'
            		};
        		
                    $fp.flowplayer(flowplayerSWF, opt);
		    $fp.css({height: '450px'});
		    $container.css({height: 'auto'});
                    
                }, 100);
		*/
            }
            
            var _off = function() {
                
                if (hidden) return;
                hidden = true;

                $('.lso-next-event').show();
                
                $container.removeClass('loading');
		        
                $fp.remove();
            }
            
            
            $buttons = $("<div/>").addClass('lsou25-buttons').append(
                $("<span/>").addClass('lsou25-button').addClass('on').html('On').click(function() {
                    _on();
                }),
                $("<span/>").addClass('lsou25-button').addClass('off').html('Off').click(function() {
                    _off();
                })
            );
            
            $container.append($buttons);
            
            var top = Math.round(($container.outerHeight() - $buttons.outerHeight()) / 2)
            $buttons.css({top: top+'px'});
            
            $a.click(function() {
                _on();
                return false;
            });
            
        });
    }
    




    /**
     * Person display
     */

    
    /**
     * Thumbnails
     */
    
    $(function() {
        
        $('.lso-thumbnail-left, .col-1 .lso-thumbnail, .lso-person-display-2 .lso-thumbnail').each(function() {

    		var $img 	= $(this);
    		var $a 		= $img.parents('.lso-thumbnail-container').eq(0);
					
    		$a.css({
    			cursor: 'default'
    		});

    		var $body	= $(document.body);
	
    		var $btn = $a.find('.lso-thumbnail-hover');
    		if ($btn.length == 0) {
    			$btn = $a;
    		}

	
    		$btn
    			.hover(
    				function() {
    					var pos = $a.offset();
    					$img.css({
    						position: 'absolute',
    						right: ($body.width() - pos.left + 25)+'px',
    						top: pos.top+'px'
    					}).appendTo($body).show();
    				},
    				function() {
    					$img.hide();
    				}
    			)
    			.click(function() {
    				return false;
    			});
	
    	});
	
    	$('.col-2 .lso-thumbnail').each(function() {
    		var $img 	= $(this);
    		var $a 		= $img.parents('.lso-thumbnail-container').eq(0);
					
    		$a.css({
    			cursor: 'default'
    		});

    		var $body	= $(document.body);
	
    		var $btn = $a.find('.lso-thumbnail-hover');
    		if ($btn.length == 0) {
    			$btn = $a;
    		}
	
    		$btn
    			.hover(
    				function() {
    					var pos = $a.offset();
    					$img.css({
    						position: 'absolute',
    						left: (pos.left + $a.outerWidth() + 26)+'px',
    						top: pos.top+'px'
    					}).appendTo($body).show();
    				},
    				function() {
    					$img.hide();
    				}
    			)
    			.click(function() {
    				return false;
    			});
			
	
    	});
    	
    	
    	
    	/**
    	 * Detail dropdown
    	 */
    	 
    	$('.lso-person-display-2 .row .overview').each(function() {

 			var $a = $(this);


 			$a.find('a').click(function() {
 				window.location.href = $(this).attr('href');
 				return false;
 			});

 			if ($a.parent().find('.detail').length==0) return;

 			$a.css({
 				cursor: 'pointer'
 			});


 			var collapsedHeight = 0;
 			var expandedHeight = 0;
 			var $container = null;
 			var $details = null;
 			var expanded = false;



 			$a.click(function() {

 				if (expandedHeight == 0) {
 					$container 		= $a.parent();
 					$details		= $container.find('.detail');

 					$container.css({height: $container.height()+'px', overflow: 'hidden'});

 					$details.show();
 					collapsedHeight	= $a.outerHeight();
 					expandedHeight	= collapsedHeight + $details.outerHeight();

 					$details.hide().css({position: 'static',visibility:'visible'});
 				}

 				if (expanded) {
 					$container.animate({height:collapsedHeight+'px'});
 					$details.fadeOut();
 				}
 				else {
 					$container.animate({height:expandedHeight+'px'});
 					$details.fadeIn();
 				}

 				expanded = !expanded;

 				return false;

 			});


 		});
 		
	
	});
	
	



    /**
     * Event list 
     */
 
    
	$('.lso-event-detail').each(function() {
		var $item = $(this);
		

		var $btn = $item.parent();//('.lso-event-item');
		
		
		var height = 0;
		var fullheight = 0;
		var expanded = false;
		
		$btn.find('.lso-event-item-overview')
			.append('<a href="#" style="position:absolute;top:0;left:0;width:100%;height:100%; background: #fff;"><\/a>')
			.children('a').css({opacity:0})
			.click(function() {

        	if ($item.parents('.lso-event-item-wrapper').hasClass('locked')) return false;

			if (height == 0) {
				height = $btn.height();//$btn.parent().data('lso-height');
				$btn.css({height: height+'px'});
				$item.show();
				fullheight = height + $item.outerHeight();							
				$item.hide();
			}

			var to = expanded ? height : fullheight;
			to += ( $btn.parent().hasClass('last') ? 8 : 0 );
			expanded = !expanded;
			
			$(this).data('expanded',expanded);
			
			if ($.browser.msie) {
				expanded ? $item.fadeIn() : $item.fadeOut();
			}
			else {
				expanded ? $item.fadeIn() : $item.fadeOut();
			}
			$btn.parent().animate({height: to+'px'}, function() {
				if (!expanded) {
					$btn.parent().find('.lso-event-data').show();
					$btn.parent().find('.lso-event-form').remove();
				}
			}).queue(false);

			
			return false;
		});
	});

	


    /**
     * Order Forms
     */


    
    /**
     * Shop order
     */
     
    $.fn.lsoShopOrderForm = function() {
				   
    	return this.each(function() {

    		var $obj = $(this);
					
    		$obj.click(function() {
			
    			var $wrapper = $obj.parents('.lso-shop-article').eq(0);
		
    			$obj.css({visibility: 'hidden'});
		
    			$.get($obj.attr('href'),function(html) {
    				var action = $obj.attr('href').replace("/repository/proxy/content/service/sites/sinfonieorchester/forms/","/repository/proxy/content/service/sites/sinfonieorchester/forms/submit/");
				
    				var validate = function() { return false; } /* The actual validate method gets defined in the submit event handler */

    				var $form = $("<div></div>").attr('class','lso-shop-form lso-shop-article').append('<div class="lso-dotted-m-top"><\/div>').append(html);
				
    				$wrapper.after($form);
				
				
    				$form.find('.form-clear').click(function() {
    					$form.find('form').get(0).reset();
    					validate = function() { return false; } /* Disable validation until the next submit attempt */
    					$form.find('.error').removeClass('error');
    					return false;
    				});
				
    				$form.find('.form-send').click(function() {
    					$form.find('form').submit();
    					return false;
    				});
				
				
    				var submitted = false;
    				$form.find('form').submit(function() {
					
    					if (submitted) return;
					
    					var $f = $(this);
											
    					validate = function() { /* Define the actual validate hanlder */
    						$f.find('.error').removeClass('error');
    						$f.find('.text.required').each(function() {
    							var $req = $(this);
    							if ($.trim($req.val()) == '') {
    								$req.parent().addClass('error');
    							}
    						});
    						$f.find('.radio.required').each(function() {
    							var c = $(this).find('.radio:checked');
    							if (c.length == 0) {
    								$(this).addClass('error');
    							}
    						});
					
    						// $f.find('input').change(function() {
    						// 	validate();
    						// });
						
    						return ($f.find('.error').length==0);
    					}
					
    					if (validate()) {
    						submitted = true;
    						var data = {}
    						$.each($(this).serializeArray(), function(i,field) {
    							data[field.name] = encodeURIComponent(field.value);
    						});
    						$.post(action, data, function(html) {
    							if ($.trim(html)=='ok') {
    								//$form.find('.lso-success').lsoPanel().click();
    								
    								$obj.css({visibility: 'visible'});
    								$form.find('.lso-success + .lso-panel-content').panel();
    								$form.remove();
    								/*
    								$form.children('h2').remove();
    								$form.children('form').remove();
    								$form.children('.lso-buttons').remove();
    								$form.children().show();
    								$form.fadeTo(100,1);
    								*/
    							}
    							else {
    								$form.fadeTo(100,1);
    								$('input').attr("disabled","false");
    							}
    						});
    						$form.fadeTo(500,0.5);
    						$('input').attr("disabled","true");
    					}
					
    					return false;
    				});
				
    				$form.fadeTo(1000,1);
    			});
		
    			return false;
			
    		});
		
		
		
    	});
	
    }
    
    

     
     /**
 	 * Ticket
 	 */

 	$.fn.lsoTicketOrderForm = function() {

 		return this.each(function() {

 			var $obj = $(this);

 			$obj.click(function() {

 				var $wrapper = $obj.parents('.lso-event-item').children('.lso-event-detail').eq(0);

 				$.get($obj.attr('href'),function(html) {
 					var action = $obj.attr('href').replace("/repository/proxy/content/service/sites/sinfonieorchester/forms/","/repository/proxy/content/service/sites/sinfonieorchester/forms/submit/");

 					var validate = function() { return false; } /* The actual validate method gets defined in the submit event handler */

 					var $data = $wrapper.find('.lso-event-data');
 					$data.css({visibility:'hidden'});

 					$data.before('<div class="lso-event-form">'+html+'<\/div>');
 					var $form = $wrapper.find('.lso-event-form');

 					$form.css({opacity:0});

 					$itemWrapper = $wrapper.parents('.lso-event-item-wrapper');

 					var h = $itemWrapper.find('.lso-event-item-overview').outerHeight() + $wrapper.find('.lso-event-form').outerHeight() + 50;
 					

 					$itemWrapper.animate({height:h+'px'},function() {
 						$data.css({visibility:'visible'}).hide();
 						$form.find('input.text').eq(0).focus();
 					});

 					$form.find('.form-clear').click(function() {
 						$form.find('form').get(0).reset();
 						validate = function() { return false; } /* Disable validation until the next submit attempt */
 						$form.find('.error').removeClass('error');
 						return false;
 					});

 					$form.find('.form-send').click(function() {
 						$form.find('form').submit();
 						return false;
 					});


 					var submitted = false;
 					$form.find('form').submit(function() {

 						if (submitted) return;

 						var $f = $(this);

 						validate = function() { /* Define the actual validate hanlder */
 							$f.find('.error').removeClass('error');
 							$f.find('.text.required').each(function() {
 								var $req = $(this);
 								if ($.trim($req.val()) == '') {
 									$req.parent().addClass('error');
 								}
 							});
 							$f.find('.radio.required').each(function() {
 								var c = $(this).find('.radio:checked');
 								if (c.length == 0) {
 									$(this).addClass('error');
 								}
 							});
 							
 							$f.find('.ticketcount').each(function() {
 							    var $req = $(this);
 							    var val = $.trim($req.val());
                                var count = parseInt(val);
                                if (isNaN(count) || count < 1 || count > 5) {
                                    $req.parent().addClass('error');
                                    
                                    if (count > 5) {
                                        $('.ticketcount-error').addClass('error');
                                    }
                                    
                                }
 							});

 							// $f.find('input').change(function() {
 							// 	validate();
 							// });

 							return ($f.find('.error').length==0)
 						}

 						if (validate()) {
 							submitted = true;
 							var data = {}
 							$.each($(this).serializeArray(), function(i,field) {
 								data[field.name] = encodeURIComponent(field.value);
 							});
 							$.post(action, data, function(html) {
 								if ($.trim(html)=='ok') {
 								    /*
    								$form.children('h2, h3, h4').remove();
    								$form.children('form').remove();
    								$form.children('.lso-buttons').remove();
    								$form.children().show();
    								$form.fadeTo(100,1);
    								*/
    								
    								
    								$form.find('.lso-success + .lso-panel-content').panel();
    								$form.parents('.lso-event-item').find('.lso-event-item-overview>a').click();
    								
 								}
 								else {
 									$form.fadeTo(100,1);
 									$('input').attr("disabled","false");
 								}
 							});
 							$form.fadeTo(500,0.5);
 							$('input').attr("disabled","true");
 						}

 						return false;
 					});

 					$form.fadeTo(1000,1);
 				});

 				return false;

 			});



 		});

 	}
 	
 	
 	/**
 	 * LSO U25 Club
 	 */
 	
 	 $.fn.lsoClubForm = function() {

     	return this.each(function() {
     	    
     	    
     	    var $form = $(this);
     	    
     	    var action = '/repository/proxy/content/service/sites/sinfonieorchester/forms/submit/sinfonieorchester/club25/de_CH'

            
            var validate = function() { return false; }
            
            $form.find('.form-send').click(function() {
                $form.find('form').submit();
                return false;
            });


            var submitted = false;
            $form.find('form').submit(function() {
               if (submitted) return false;
               
               var $f = $(this);
               
               
               
				validate = function() { /* Define the actual validate hanlder */
					$f.find('.error').removeClass('error');
					$f.find('.text.required').each(function() {
						var $req = $(this);
						if ($.trim($req.val()) == '') {
							$req.parent().addClass('error');
						}
					});

					return ($f.find('.error').length==0);
				}

				if (validate()) {
					submitted = true;
					var data = {}
					$.each($(this).serializeArray(), function(i,field) {
						data[field.name] = encodeURIComponent(field.value);
					});
					$.post(action, data, function(html) {
						if ($.trim(html)=='ok') {
							//$form.find('.lso-success').lsoPanel().click();

							$form.find('.lso-success + .lso-panel-content').panel(true);
                            $form.remove();2
							/*
							$form.children('h2').remove();
							$form.children('form').remove();
							$form.children('.lso-buttons').remove();
							$form.children().show();
							$form.fadeTo(100,1);
							*/
						}
						else {
							$form.fadeTo(100,1);
							$('input').attr("disabled","false");
						}
					});
					$form.fadeTo(500,0.5);
					$('input').attr("disabled","true");
				}

				return false;

            });



     	});

     }
    
    
 	if ($('.lso-event-list').length) {
    
        if (window.location.hash) {
            var hash = window.location.hash.replace('#','');
        
            if (hash.length) {
                var itemref = '.lso-order-' + hash;
            
                var $toggle = $(itemref + " .lso-event-item-overview>a");
                if ($toggle.length) {
                    $toggle.click();
                    setTimeout(function() {
                        var top = $toggle.offset().top - 10;
                        $(document).scrollTop(top);
                    },300);
                }

            }
        }
    
    }
 	

})(jQuery);
