var jq = jQuery.noConflict();

function MA_Ajax_Document_Composer(/*linkContainer, */contentContainer) {
   	var ajaxReferences = new Array();
   	//var lc = linkContainer;
   	var cc = contentContainer;
   	var currentURL = window.location;
   	//var callbackTrigger = '.js_mainMenu';//callbackTrigger;
   	var controller = function() {
   		//alert(currentURL+' == '+*/window.location);
   		if(currentURL != window.location) {
   			loadNewContents({href : window.location}, true);
   		}
   	}
   	//window.setInterval(controller, 200);
	function getURL(href) {
		var tmp = href;
		var end = document.URL.indexOf('#');// alert(end);
		return document.URL.substring(0,(end>=0)?end:document.URL.length)
					+'#'
					+tmp.substring(tmp.lastIndexOf('/')+1, tmp.length);
	}
	this.getURL = getURL;

	this.addHref = addHref;
	function addHref (el, href) {
		var tmp = getURL(href);
		jq(el).attr('href' ,tmp);
		ajaxReferences[tmp] = href;
		clickTriggerFkt = loadNewContents;
		jq(el).click(function() {
			clickTriggerFkt(this, true);
		});
		//alert(window.location);
	
	}
	this.initAfterHrefSetting = function() {
		if(window.location) {
			loadNewContents({href : window.location}, false);
		}
	
	}
	function loadNewContents(el, before) {
		//alert('loadNewContent');
		//alert('before: '+currentURL);
		currentURL = el.href;
		//alert('after: '+currentURL);
		//if(jq(callbackTrigger).find(jq(el)).length > 0) {
		//	alert('trigger');
		//}
		var reRef = function(a,b){addHref(a,b)};
		var millis = 0;
		//Before Callbacks
		for(var i = 0; i < cc.length; i++) {
			if(cc[i].beforeCallback != undefined && before) {
				cc[i].beforeCallback();
				if(millis < cc[i].wait) {
					millis = cc[i].wait;
				}
			}
		}
		var date = new Date();
		var curDate = null;
		//Ajax Init
		var loadHref = (ajaxReferences[el.href] != undefined)?
								ajaxReferences[el.href]:
								window.location.href;
		if(loadHref.indexOf('#') > 0) {
			loadHref = loadHref.substring(0, loadHref.indexOf('#'));
		}
		jq.get(loadHref, function(data){
			curDate = new Date();
			setTimeout(function() {
				for(var i = 0; i < cc.length; i++) {
					jq(cc[i].clazzName).html(jq(data).find(cc[i].clazzName).html());
					//jq(cc[i].clazzName).find('a').each(function(){
					//	addHref(this, this.href);
					//});
				}
			    //document.title = jq.trim(data.replace( /([\s\S]+)<title>/, '' ).replace(/<\/title>([\s\S]+)/, '' ));
				//jq('.js_invisible').removeClass('js_invisible');
				for(var i = 0; i < cc.length; i++) {
					if(cc[i].afterCallback != undefined) {
						cc[i].afterCallback();
					}
				}
			},millis-(curDate-date));
		});
		//After Callbacks
			
		
		
	}
}


/**
** Original copyright to jqueryfordesigners.com
** converted by Jan Pietrzyk <programming@must-art.de> must art 2009
**/
jq.fn.finiteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = jq(this).css('overflow', 'hidden').wrap('<div class="clearfix"></div>'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':eq('+($items.size()-2)+')'),
            
            singleMargin = ( $single.outerWidth(true)-$single.outerWidth() )/ 2,
            singleWidth = $single.outerWidth(true), 
            singleHeight = $single.outerHeight(true),
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = $items.length+1;            
		   
		//$items.each(function() {jq(this).css({'width': $single.innerWidth(),
        //    															'margin': singleMargin})})
		//console.log($wrapper.width(), singleWidth,visible, pages);
		//alert($wrapper.width());
		$slider.css('width', 99999);
		//visible = Math.ceil($wrapper.innerWidth() / singleWidth);
		//var maxpage =pages - visible;
		//alert(visible);
        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        //if (($items.length % visible) != 0) {
            //$slider.append(repeat('<li class="empty" style="width:'+$single.innerWidth()+'px; margin: '+singleMargin+'px;" />', visible - ($items.length % visible)));
         //   $items = $slider.find('> li');
        //}

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        //$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        //$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        //$wrapper.scrollLeft(singleWidth * visible);
        
        var $possibleArrow = $wrapper.parent().prev();
        if($possibleArrow.hasClass('arrow')) {
        	$possibleArrow.remove();
        	$wrapper.before($possibleArrow);
        }
        $possibleArrow = $wrapper.parent().prev();
        if($possibleArrow.hasClass('arrow')) {
        	$possibleArrow.remove();
        	$wrapper.before($possibleArrow);
        }
        if(jq('a.back',$wrapper.parent()).size() == 0)
        	$wrapper.before('<a class="arrow back">&nbsp;</a>');

        if(jq('a.forward',$wrapper.parent()).size() == 0)        	
        	$wrapper.before('<a class="arrow forward">&nbsp;</a>');
        
        // 5. Bind to the forward and back buttons
        
        $wrapper.css({
        		'margin-left': jq('a.back').outerWidth(),
        		'margin-right':jq('a.forward').outerWidth() 
        });
        $wrapper.css({'height': singleHeight, 'width':740});
		
		var laSelct = 'a.back',
			raSelect = 'a.forward';
		//if('rtl' == $wrapper.css('direction')) {
		//	var tausch;
		//	tausch = laSelect;
		//	laSelect = raSelect
		//	raSelect = tausch;
		//}
		//console.log($wrapper.innerWidth());
        visible = Math.round($wrapper.innerWidth() / singleWidth); // note: doesn't include padding or border
		var maxpage =pages - visible;
		var gotoIndex = -1//currentPage;
		/*
		$items.each(function(index) {
			//alert(this);
			if(jq(this).hasClass('active')) {
				gotoIndex = currentPage = (maxpage - index);
			};
		});*/
		
		//alert(maxpage);
		 // 4. paging function
        function gotoPage(page) {
            //alert('goto '+page);
			var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir  * n,
                returnVal = true;
            //alert(currentPage);
            //console.log(page,visible, pages, dir, n, left, currentPage, maxpage);
            if(currentPage + dir > 0 ) {
				if(currentPage + dir <= maxpage) {
					//alert('max');
            		$wrapper.filter(':not(:animated)').animate({
           		     scrollLeft: '+=' + left
           	 		}, 200, function () {
						//if(console.log) {
						//	console.log('page: '+page);
						//}
      	 	           	if(page==1){	
			            	jq('a.back', $wrapper.parent()).addClass('inactive');
			            	if(dir < 0) {
			            		returnVal = false;
			            	}
				        } else {
				        	jq('a.back', $wrapper.parent()).removeClass('inactive');
				        } 
				        if(page >= maxpage){
           	 	       		jq('a.forward', $wrapper.parent()).addClass('inactive');
           	 	       		if(dir > 0) {
           	 	       			returnVal = false;
           	 	       		}
           	 	       	} else {
           	 	       		jq('a.forward', $wrapper.parent()).removeClass('inactive');
           	 	       	}
           	 	       
					//alert(page);
	                currentPage = page;
	              });
            	} else {returnVal = false;}
            } else {returnVal = false;}            
            
            return returnVal;
        }
		
        jq(laSelct, $wrapper.parent()).click(function (event) {
            var prevent = gotoPage(currentPage - 1);
            if(prevent) {
            	event.preventDefault();
            } else if(jq(this).attr('href') && jq(this).attr('href').length > 2){
            	//jq(this).removeClass('inactive');
            }
        });
        
        if(! jq(laSelct , $wrapper.parent()).attr('href')) {
        	jq(laSelct, $wrapper.parent()).addClass('inactive');
        }
        
        jq(raSelect, $wrapper.parent()).click(function (event) {
            var prevent = gotoPage(currentPage + 1);
            if(prevent) {
            	event.preventDefault();
            } else if(jq(this).attr('href') && jq(this).attr('href').length > 2){
            	//jq(this).removeClass('inactive');
            }
        });
        
        if(($items.size() <= visible
        			)) {
        	
        	jq(raSelect, $wrapper.parent()).addClass('inactive');
        }
        
        /* create a public interface to move to a specific page
        jq(this).bind('goto', function (event, page) {
            gotoPage(page);
        });*/
       var resetDone = false;
		$items.each(function(index) {
			//alert(this);

			if(jq(this).hasClass('active')) {/*Hier die Wechsel Logik*/
				resetDone= true;
				//if(console.log) {
				//	console.log('index: '+index, 'maxpage: '+maxpage, 'scroll'+$wrapper.scrollLeft());
				//}
				//alert('befotre'+currentPage);
				//currentPage = (index+1);
				//$wraper.scrollLeft(100000);
				//if(console.log) {
					
				//}
				//
				
				//console.log('index: '+index, 'maxpage: '+maxpage, 'scroll'+$wrapper.scrollLeft());
				gotoPage(maxpage - index > 0 ? maxpage-index : 0);
				$wrapper.queue('fx', function() { 
										var scAmount = -((Math.abs(index) * singleWidth)),
											scMax = -((maxpage-1)*singleWidth),
											amount = ((scAmount < scMax) ? scMax : scAmount);
										$wrapper.scrollLeft(100000000000000);
										if(jQuery.browser.webkit || jQuery.browser.msie) {
											amount = $wrapper.scrollLeft()+amount;
										}
										//alert(scAmount);
										//alert( 'wrSc '+$wrapper.scrollLeft() );
										//alert(amount);
										/*jq('.galery_counter').click(function() {
															console.log(
																'Wrapper '+$wrapper.scrollLeft(), 
																'Slider '+$slider.width(),
																'Amount '+amount
															);
													})*/
										$wrapper.scrollLeft(amount); 
										//alert( 'wrSc '+$wrapper.scrollLeft() );
										$wrapper.dequeue();
										//console.log('index: '+index, 'maxpage: '+maxpage, 'scroll'+$wrapper.scrollLeft());
				});
				
				//alert('after'+currentPage);
				

				/*
				if(currentPage==1){	
			        jq('a.back', $wrapper.parent()).addClass('inactive');
				} else {
				    jq('a.back', $wrapper.parent()).removeClass('inactive');
				} 
				if(currentPage >= maxpage){
           	 		jq('a.forward', $wrapper.parent()).addClass('inactive');
           	 	} else {
           	 		jq('a.forward', $wrapper.parent()).removeClass('inactive');
           	 	}*/
				
			}
		});
		if('rtl' == $wrapper.css('direction') && !resetDone) {
			gotoPage(maxpage);
		}

    });  
};


jq(document).ready(function () {
  if(jq('body').hasClass('print')) {
  	window.print();
  }
  
  if(jq('.jsTaf').size() > 0){jq('.rc').hide();}
  jq('.jsTaf').toggle(function(){
  										jq('.rc').show();
  										jq('.article').hide();
  										jq('.articleFooter').hide();
  										jq(this).toggleClass('selected')
  										return false;
  									},
  									function() {
  										jq('.rc').hide();
  										jq('.article').show();
  										jq('.articleFooter').show();
  										jq(this).toggleClass('selected')
  										return false;
  								}); 
  
  
  jq('.js_formAutoDelete').each(function() {

       var default_value = this.value;
	   //alert(default_value);
	   
       jq(this).focus(function(){
               if(this.value == default_value) {
                       this.value = '';
               }
       });

       jq(this).blur(function(){
               if(this.value == '') {
                       this.value = default_value;
               }
       });

	});
  
  
  jq('.featureListContainer').css('overflow', 'auto').find('ul li').each(function() {
  	var $me = jq(this);
	if(!$me.parent().hasClass('articleProperties')) {
		$me.css({width: $me.innerWidth(), height: $me.innerHeight()});
	}
  });
  
  /*
  'js_galeryCaption'
  'js_galeryImage'
  'js_galeryList'
  
  if(jq(',js_galeryImage').size() >0 ) {
  		var adc = new MA_Ajax_Document_Composer(
  			new Array(
  			{
  				clazzName:'.js_galeryCaption',
  			 	callbackTrigger: true
  			 }, 
  			{
  				clazzName:'.js_galeryImage',
  				wait: 1500,
  				beforeCallback: function() {jq('.js_galeryImage').animate({
  					opacity: 0}, this.wait/2);
  				},
  			 	afterCallback: function() {
  		 							//startSlideshow();
  		 							jq('.js_galeryImage').animate({opacity: 1}, this.wait/2);
  			 	}
  			},
  			{	
  				clazzName:'.galery_counter'
  				
  			}
  		)
	  );
 	 jq('.js_galeryList a').each(function() {
 	 	var href = this.href;
		//Ajax readying
		var tmp = href;
		adc.addHref(this, href);
	  });
	}*/
	//adc.initAfterHrefSetting();
  
   if(!(jq.browser.msie && jq.browser.version <= 6)) {	
 	 $inputs = jq('.poll input[type=radio]');
 	 $pollForm = jq('.poll form:first');
 	 jq('.poll input[type=submit]').css('display', 'none');
 	 var defaultImageSrc = "tl_files/template/images/voting/voting-passiv.png";
 	 //var defaultImage = new Image("tl_files/template/images/voting/voting-passiv.png");
 	 var mouseOverImageSrc = "tl_files/template/images/voting/voting-passiv.png";
 	 //var mouseOverImage = new Image("tl_fildes/template/images/voting/voting-aktiv.png");
  
  
	  $inputs.each(function() {
	  	var $actInp = jq(this);
		jq(this).css('display', 'none').before('<a herf="#" class="radioSubstitute">&nbsp;</a>').parent().css({
	  		'line-height': '20px',
	  		'position': 'relative',
	  		'padding-left': 25
	  	}).find('.radioSubstitute').click(function() {
			$actInp.attr('checked'  , 'checked');
			$pollForm.submit();
  		});
  		
  		
   	});
   }
   if(jq('.archive').size() < 1 && jq('.articlePropertyContainer .articlePropertiesBig').size() > 0 && jq('.articlePropertyContainer .articlePropertiesBig li').size() == 3) {
   		jq('.articlePropertyContainer .articlePropertiesBig').append('<li class="printButtonBig"><a>&nbsp;</a></li>');   		
   		jq('.printButtonBig a').click(function() {
   			window.print();
   		});
   }
   jq('.printButtonBig a').click(function(event) {
   			event.preventDefault();

   			if(jq(this).attr('href')) {
   				//alert('print');

   				var fenster = window.open(jq(this).attr('href'), 
   								"worldandsportswindow",
   							 "width=600,height=400,status=no,scrollbars=yes,resizable=yes");
				 fenster.focus();
 				return false;

   			} else {
   				window.print();
   			}
   		});
  //Optical Shuggar for form's
  jq('div.formbody fieldset legend').each(function() {
	var tmpText = jq(this).html();
	var tmpSize = jq(this).innerWidth();
	jq(this).css('margin-bottom', 0).after('<hr style="padding-bottom: 0pt; margin-top: 0pt;" class="line"/>').html('<h1 style="margin-bottom: 0pt;" class="head"><span>'+tmpText+'</span></h1>');
	
	jq('span', this).css('width', (tmpSize+30));	
	jq('h1', this).css('width', (tmpSize+46));
  });
  jq('div.formbody table[id!=recaptcha_table]').each(function() {
    //jq(this).after('<div class="clearfix articleFooter"><div>&nbsp;</div> </div>');
  });
  
  
  jq('.featureListContainer').finiteCarousel();
  //alert(jq('.js_video').flowplayer);
  if(!(jq.browser.msie && jq.browser.version <= 6)) {
  	var $marqueeParent = jq('marquee').parent();
  	jq('marquee').marquee().mouseover(function () { jq(this).trigger('stop'); }).mouseout(function () { jq(this).trigger('start'); });
  	$marqueeParent.find(":nth-child(1)").css({'margin-left': 0, 'margin-right': 0, 'padding-top':0});
  }
  //jq('a').each(function() {
  	
  //});
  jq('.sportsTable input').hide();
  jq('.sportsTable select').change(function() {
  	//alert('trigger');
  	jq('.sportsTable form').submit();
  });
  
  if(jq('.js_video').size() > 0) {
  	jq('.js_video').each(function(){jq(this).html('');})
  	jq('.js_video').flowplayer("tl_files/template/flowplayer/flowplayer-3.1.5.swf", 
  	{
  		clip: {
  			autoPlay: false,
  			autoBuffering: true,
  			scaling: 'fit'
  		}
  	});
  	//alert(jq())
  }
  if(jq('.js_audio').size() > 0) {
  	jq('.js_audio').each(function(){jq(this).html('');})
  	jq('.js_audio').flowplayer("tl_files/template/flowplayer/flowplayer-3.1.5.swf", 
  	{
		 // fullscreen button not needed here 
    	plugins: { 
    		audio: {
    			url: 'tl_files/template/flowplayer/flowplayer.audio-3.1.2.swf'
    		},
    	    controls: { 
    	        fullscreen: false, 
    	        height: 30 
    	    } 
    	}, 
 	
 	   clip: { 
 	       autoPlay: false
 	   } 

  	});
  }
  
  
});
/*Image Preload*/
var imgPreload = new Array(
'tl_files/template/images/GalerieBackDeOrange.jpg',
'tl_files/template/images/GalerieBackOrange.jpg',
'tl_files/template/images/GalerieNextDeOrange.jpg',
'tl_files/template/images/GalerieNextOrange.jpg',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-end-orange-unten.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-end-orange.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-end-rot-unten.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-end-rot.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-links-orange-unten.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-mitte-orange.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-orange-orange.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-uberlap-orange-rot.png',
'tl_files/template/css/screen/images/sliding_door/top/Reiter-end-rot.png',
'tl_files/template/css/screen/images/sliding_door/top/Reiter-links-rot.png',
'tl_files/template/css/screen/images/sliding_door/top/Reiter-uberlap-orange-rot.png',
'tl_files/template/css/screen/images/sliding_door/top/Reiter-mitte-rot.png',
'tl_files/template/css/screen/images/sliding_door/top_rtl/Reiter-end-rot.png',
'tl_files/template/css/screen/images/sliding_door/top_rtl/Reiter-mitte-rot.png',
'tl_files/template/css/screen/images/sliding_door/top_rtl/Reiter-rechts-rot.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-end-orange.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-mitte.orange.png',
'tl_files/template/css/screen/images/sliding_door/content/Reiter-rechts-orange.png',
'tl_files/template/css/screen/images/sliding_door/top/Reiter-end-orange.png',
'tl_files/template/css/screen/images/sliding_door/top/Reiter-links-orange.png'
);

for(var i = 0; i < imgPreload.length; i++) {
	var tmp = new Image();
	tmp.src = imgPreload[i];
}
