// preload arrow images

function UnCryptMailto( s )
    {
        var n = 0;
        var r = "";
        for( var i = 0; i < s.length; i++)
        {
            n = s.charCodeAt( i );
            if( n >= 8364 )
            {
                n = 128;
            }
            r += String.fromCharCode( n - 1 );
            
            r= r.split('*').join(':');
        }
        return r;
    }

    function linkTo_UnCryptMailto( s )
    {
        location.href=UnCryptMailto( s );
    }

function getBrowser(){
	if(document.ids)x='nc4';
	else if( document.all && !document.getElementById )x='ie4';
	else if( window.opera && !document.createElement )x='op5';
	else if( window.opera && window.getComputedStyle )  {
	          if(document.createRange)x='op8';
	            else if(window.navigate)x='op7.5';
	                             else x='op7.2';                   }
	else if( window.opera && document.compatMode )x='op7';
	else if( window.opera && document.releaseEvents )x='op6';
	else if( document.contains && !window.opera )x='kq3';
	else if(window.pkcs11&&window.XML)x='f15';
	else if( window.getSelection && window.atob )x='nn7';
	else if( window.getSelection && !document.compatMode )x='nn6';
	else if( window.clipboardData && document.compatMode )
	  x=window.XMLHttpRequest? 'IE7' : 'IE6';
	else if( window.clipboardData ){x='ie5';
	     if( !document.createDocumentFragment ) x+='.5';
	     if( document.doctype && !window.print ) x+='m';}
	else if( document.getElementById && !document.all ) x='op4';
	else if( document.images && !document.all ) x='nn3';
	else if(document.clientWidth&&!window.RegExp)x='kq2';
	else x='???';
return x;
}

function removeEmptyPtags(){
      $$('p').each(function(element) {
        if(element.innerHTML == '') element.remove();
      });

}

var curslideId = 0;
var slideCount = 1;
var automate = false;
var timeoutId = false;
var viewportwidth = 0;
var viewportheight = 0;

var rows = 2;

var itemwidth = 200;
var itemheight = 250;
var canvaswidth = 780;
var maxCanvaswidth = 780;

var heightfix = 0;

var duration = 0;

var timeout_resize =false;

var catHrefs = new Array();
var catIndexes = new Array();
var activeCat = 0;

var sorting = '';
var size = 'medium';

var clones = new Object();

var maxPagingButtons = 7;


duration = 750;

document.observe("dom:loaded", function(){    
    
	removeEmptyPtags();

	if($$('.menu3')){
		 observeMenu();
	}

    if($$('.products-wrap')[0]){
    	resetParameters();
    	prepareSlideshow(); 
    	checkForResize();   
    	observeSizeLinks();
    }	
    
    if($$('.product-single')[0]){
    	prepareSingleView();
    }	
   
   
   	if($('extended-searchform')){
   		// observeSearchForm();
   	}
   
     
});

function resetParameters(){

	 curslideId = 0;
	 slideCount = 1;
	 automate = false;
	 timeoutId = false;
	
	 timeout_resize =false;	
	 
	 removeActClass('idTrigger');
	 document.getElementsByClassName('idTrigger')[0].addClassName('act');	
	 
	 applyDetailLinks();	
     observeSortLinks();	 

}

function checkCanvasSize(){
 	
 	// 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
 	}

}	

function debug(str){
	$('content-top').innerHTML = str;
}



// Navigation

function observeMenu(){


	//if($$('a.menu3').length == 1)
		//$$('a.menu3')[0].hide();

	$$('a.menu3').each(
		function(el,catindex){	
		
			
			
			if(-1 != window.location.href.indexOf(el.href)){
				el.addClassName('act');
				activeCat = catindex;
			}
				
			
			catHrefs[el.href] = catindex;
			catIndexes[catindex] = el.href;
			el.observe('click', function(ev){				
				removeActClass('menu3');				
				Event.stop(ev); 
				el = Event.element(ev);
				el.addClassName('act');				
				ajaxRequest($$('.products-wrap')[0],el.href);
			});
		}
	);
	

}

var hovertimer = new Array();
function applyDetailLinks() {
	$$('.product-item').each(
		function(el,prodindex){
			el.observe('mouseover', function() {
				if(false == el.down('.product-item-text').visible()){			
					window.clearTimeout(hovertimer[prodindex]);
					new Effect.Appear(el.down('.product-item-text'),{
						duration: 0.2
					});
				}	
			})
			el.down('.product-item-text').observe('mouseover', function() {
				window.clearTimeout(hovertimer[prodindex]);
			})			
						
			el.observe('mouseout', function() {
				window.clearTimeout(hovertimer[prodindex]);
				hovertimer[prodindex] = window.setTimeout(function(){
					new Effect.Fade(el.down('.product-item-text'),{
						duration: 0.2
					});
				},100);
			})
			el.down('.product-item-text').onclick = function(){				
				window.location.href = el.down('a').href
			};
		}
	);	
}


function observeSortLinks(){
	$$('.product-sorting a').each(
		function(el){
			if(sorting == el.rel)
				el.addClassName('act');
			
			el.observe('click',
				function(ev){
					Event.stop(ev);
					sorting = el.rel;
				
					if(catIndexes[activeCat] != undefined){
						var url = catIndexes[activeCat];
					} else {
						url = el.href;
					}
  				
					new Ajax.Updater($('content'), url, {
						method: 'get',
  						parameters: {type: 123, sort: el.rel },  		
  						onCreate: function() {
 							$('ajaxload').show(); 
							window.clearInterval(resizeListener);
						},  				
  						onComplete: function(){ 
  							$('ajaxload').hide();  			
  							resetParameters();  
  							changeSize();			
  							prepareSlideshow();
  							checkForResize();
  							observeSizeLinks(); 
  								
  						}
					});
					
				}
			);
		}
	);
}

function observeSizeLinks(){
	$$('.product-size a').each(
		function(el){	
			
			if(size == el.rel)
				el.addClassName('act');	
				
			el.observe('click',
				function(){
					$$('.product-size a').each(
						function(sizeel){
							sizeel.removeClassName('act');
						});	
				
					el.addClassName('act');				
					size = el.rel;
					changeSize();
					resetParameters();
				}
			);
		}
	);
}

function changeSize(){
	
	if('small' == size){
		itemwidth = 150;
		itemheight = 188;	
	}
	if('medium' == size){
		itemwidth = 200;
		itemheight = 250;	
	}
	if('large' == size){
		itemwidth = 250;
		itemheight = 313;	
	}
		
	$$('.product-item').each(
		function(el){
			el.style.width=(itemwidth-50)+'px';
			el.style.height=(itemheight-50)+'px';
			el.removeClassName('small');
			el.removeClassName('medium');
			el.removeClassName('large');
			
			el.addClassName(size);
		}
	);
	
		prepareSlideshow();
		scroll(1);
}




// Slide Functions
fx.ElementScroll = Class.create();
fx.ElementScroll.prototype = Object.extend(new fx.Base(), {
      initialize: function(el, options) {
        this.el = el;
        this.iniMarginLeft = this.el.style.marginLeft;
        this.setOptions(options);
    },

    increase: function() {
        this.el.style.marginLeft = this.now + 'px';
    },
    
    toggle: function(){
        if (this.el.marginLeft > 0) this.custom(this.el.marginLeft, 0);
        else this.custom(0, this.iniMarginLeft);
    }
});


fx.ElementScrollV = Class.create();
fx.ElementScrollV.prototype = Object.extend(new fx.Base(), {
      initialize: function(el, options) {
        this.el = el;
        this.iniMarginTop = this.el.style.iniMarginTop;
        this.setOptions(options);
    },

    increase: function() {
        this.el.style.iniMarginTop = this.now + 'px';
    },
    
    toggle: function(){
        if (this.el.iniMarginTop > 0) this.custom(this.el.iniMarginTop, 0);
        else this.custom(0, this.iniMarginTop);
    }
});


function checkForResize(){
	resizeListener = window.setInterval('prepareSlideshow()', duration);
}

function prepareSlideshow(){
	checkCanvasSize();
	
	rows = Math.ceil((viewportheight-350)/itemheight)-1
	if(rows<1) rows =1;

	viewportwidth = $$('body')[0].getWidth();
	
	if(viewportwidth > maxCanvaswidth){
		canvaswidth = viewportwidth - (viewportwidth % itemwidth);
	} else {
		canvaswidth = maxCanvaswidth;
	}
	
	$$('.products-wrap-inner').each(
			function(inner){
				itemCount = inner.select('.product-item').length;
				
				if(itemCount<1){
					$$('.products-wrap')[0].innerHTML = '<div class="products-wrap-inner"><div class="product-item freshItem"></div></div>';
					//return resetParameters();	
				}
									
				itemCount = Math.ceil(itemCount/rows);				
				twoRowWrapWidth = itemCount*itemwidth;				
				slideCount =  Math.ceil(twoRowWrapWidth/canvaswidth);
			
				itemsPerSlide = Math.ceil(itemCount/slideCount)
				maxPagingButtons = itemsPerSlide-2;
				if(maxPagingButtons < 1) maxPagingButtons = 1;
				
				inner.style.width = (slideCount*canvaswidth)+'px';
				inner.style.height = (heightfix+itemheight*rows)+'px';
				inner.style.backgroundImage = 'url(/fileadmin/layout/imgs/2010/grid_'+itemwidth+'.gif)';
			}		
	);	
	
	$$('.products-wrap')[0].style.width = (canvaswidth)+'px';	
	$$('.products-wrap')[0].style.height = (heightfix+itemheight*rows)+'px';	
	$$('.product-functions')[0].style.width = (canvaswidth-50)+'px';
	
	if(curslideId >= slideCount){
		curslideId = slideCount-1;
	}
	
	
	
	if(($$('.idTrigger').length != slideCount) && ($$('.idTrigger')[0])){
	
		firstButton = $$('.idTrigger')[0];
		clone = firstButton.cloneNode(true);
		$('idTriggers').innerHTML = '';
		//clones = new Object();
		
		 for(i=1;i<=slideCount;i++){
			clones[(i-1)] = clone.cloneNode(true);
			clones[(i-1)].innerHTML = i;
			clones[(i-1)].rel = i;
			clones[(i-1)].setAttribute('onclick', 'scroll(\''+i+'\')')
			
			
			if(i > 1)
				clones[(i-1)].removeClassName('act');
				
			if(i > maxPagingButtons){
				clones[(i-1)].hide();	
				$('nextMore').show();
		
			} else {
				$('nextMore').hide();
				$('prevMore').hide();
			}
					
				
			$('idTriggers').appendChild(clones[(i-1)]);
			$('idTriggers').innerHTML += ' ';			
		}	
	}

	Event.stopObserving($('nextTrigger'), 'click');
	Event.stopObserving($('prevTrigger'), 'click');


	$('nextTrigger').observe('click', function(){scroll(curslideId+2)});
	$('prevTrigger').observe('click', function(){scroll(curslideId)});		

}


function scroll(targetSlideId){			
	
			targetSlideId = targetSlideId-1;			
			
			if(targetSlideId < 0) return false;
			if(targetSlideId >= slideCount) return false;

	 		removeActClass('idTrigger');
	 
 		
 			coll = document.getElementsByClassName('idTrigger');	
	 		coll[targetSlideId].addClassName('act');		
			
			
			
	
				if(((targetSlideId+1) < slideCount) && (maxPagingButtons < slideCount)){
					$('nextMore').show();						
				} else {
					$('nextMore').hide();
				}
				
			if(!coll[targetSlideId].visible()){
				coll[targetSlideId].show();				
				if(targetSlideId<curslideId){
					coll[targetSlideId+maxPagingButtons].hide();
				} else {
					coll[targetSlideId-maxPagingButtons].hide();
				}				
			}

				if(!coll[0].visible()){
					$('prevMore').show();						
				} else {
					$('prevMore').hide();
				}

					
	
			from = -canvaswidth*(curslideId);
			to = -(canvaswidth*(targetSlideId));			


            var clientTween = new fx.ElementScroll($$('.products-wrap-inner')[0], {duration: duration, transition: fx.sinoidal});
            clientTween.custom(from, to);
            if(curslideId<slideCount) curslideId = targetSlideId; 
            
     
                       
}


// Ajax Functions
function ajaxLoad(container, url){
		container = $(container);
	new Ajax.Updater(container, url, {
		method: 'get',
  		parameters: {type: 123 },  		
  		onCreate: function() {
 			$('ajaxload').show(); 

		},  				
  		onComplete: function(){ 
  			$('ajaxload').hide();  			
  			resetParameters();  			
  			prepareSlideshow();  						
  		}
	});
}

function ajaxRequest(container, url){
	
	if(catHrefs[url] == activeCat){
		return false;
	}
	
	container = $(container);
	new Ajax.Request(url, {
  	method: 'get',
  	parameters: {type: 123, sort: sorting},
  	onCreate: function() {
 			$('ajaxload').show(); 			
 			$$('.freshItem').each(
				function(element){
					element.removeClassName('freshItem');
				}
			);
 			 			
 			window.clearInterval(resizeListener);

		},   	
  	onSuccess: function(transport) {

		var start= transport.responseText.indexOf("<!-- AJAX_begin -->")+19;
		var end= transport.responseText.indexOf("<!-- AJAX_end -->");
		
		if(catHrefs[url] > activeCat)
			container.innerHTML += transport.responseText.substring(start,end);    	
	
		
		if(catHrefs[url] < activeCat){
			container.innerHTML = transport.responseText.substring(start,end)+container.innerHTML; 
			$$('.products-wrap-inner')[0].style.marginTop='-'+(heightfix+itemheight*rows)+'px'
		}
	    
	    
	    changeSize();
     	resetParameters();
     	prepareSlideshow(); 
		$('ajaxload').hide(); 
    	
    	
    	window.location.hash = catHrefs[url] ;
    	

		if(catHrefs[url] > activeCat){
    		new Effect.Morph(document.getElementsByClassName('products-wrap-inner')[0], {
    			style: 'margin-top:-'+(heightfix+itemheight*rows)+'px;', 
    			duration: 0.6,
    			afterFinish: function(){
    				document.getElementsByClassName('products-wrap-inner')[0].remove();  				   				
    				resetParameters();
					//prepareSlideshow(); 
    				checkForResize();
    				activeCat = catHrefs[url];
    			}
    		});
    	}     	
    	
    	
		if(catHrefs[url] < activeCat){
			new Effect.Morph(document.getElementsByClassName('products-wrap-inner')[0], {
    			style: 'margin-top:0px;', 
    			duration: 0.6,
    			afterFinish: function(){
    				document.getElementsByClassName('products-wrap-inner')[1].remove();  				   				
    				resetParameters();
					//prepareSlideshow(); 
    				checkForResize();
    				activeCat = catHrefs[url];
    			}
    		}); 	
    	
    	}	
    }
});

}

function removeActClass(classe){
	elements = document.getElementsByClassName(classe);
	for(i=0; i<elements.length; i++){
		elements[i].removeClassName('act');
	}
	
} 



// Single View
var images = new Array();
var activeImage = 0;
function prepareSingleView(){

	$('question-button').onclick = function(){toggleQuestionForm()}


	// $('questions-form').show();
	
	
	$('prev-image').onclick = function(){showSingleImage(-1)}
	$('next-image').onclick = function(){showSingleImage(1)}

	$$('.product-single-images-inner br').each(function(el){el.remove()});
	
	
	if($$('.product-single-images-inner a').length > 1){
		$$('.product-single-images-inner a').each(function(el,index){	
			el.observe('click', function(ev){
				Event.stop(ev);
				showSingleImage(1);
			});
			images[index] = el;	
			if(index > 0)
				el.hide()
		});
	} else {
		$$('.product-single-images-inner a')[0].observe('click', function(ev){
			Event.stop(ev);
		});
		
		$('prev-image').addClassName('nohand');
		$('next-image').addClassName('nohand');
		
		images[0] = $$('.product-single-images-inner a')[0];	
		images[0].addClassName('nohand');
	}	
	

	
	updateImageStatus();	
}

function toggleQuestionForm(){
	if($('questions-form').visible()){
		new Effect.SlideUp($('questions-form'), {duration: 0.3 });
	} else {
		new Effect.SlideDown($('questions-form'), {duration: 0.3 });
	}
}

function submitQuestion(){
	formdata = $('questionsForm').serialize();
	
	new Ajax.Updater('question-response', '/fileadmin/php/sendMail.php', {
		method: 'get',
  		parameters: formdata,  		
  		onCreate: function() {
 			$('ajaxload').show();
		},  				
  		onComplete: function(){ 
  			$('ajaxload').hide(); 
  			new Effect.SlideUp($('questions-form'), {duration: 0.3 }); 		
  			$('question-response').show();	
		}
	});;
}

function showSingleImage(number){
	
	targetImage = activeImage+number;


	if(!images[targetImage]){
		targetImage = 0;
	}

	if(images[targetImage]){		
		if(activeImage < targetImage){
			new Effect.Appear(images[targetImage],{
				duration: 0.3,
				afterFinish: function(){					
					images[activeImage].hide();
					activeImage = targetImage;
					updateImageStatus();
				}
			});
		} else if(activeImage > targetImage) {
			images[targetImage].show();
			new Effect.Fade(images[activeImage],{
				duration: 0.3,
				afterFinish: function(){					
					activeImage = targetImage;
					updateImageStatus();
				}
			})		
		}
	} 	
}

function updateImageStatus(){
		$('image-counter').innerHTML = '<span class="orange">'+(activeImage+1)+'</span>/'+images.length;
		imageHeight = images[activeImage].getHeight();
		$$('.product-single-text')[0].style.height = imageHeight+'px';
		$('image-enlarge').href = images[activeImage].href;	
		
		initialHeight = $$('.product-single-text-inner')[0].getHeight();
		if((imageHeight - initialHeight) <= 0){
			$('product-text-expand-more').show();
			$('product-text-expand-more').observe('click', function(){
   					new Effect.Morph(document.getElementsByClassName('product-single-text')[0], {
    					style: 'height:'+(initialHeight+50)+'px;', 
    					duration: 0.6,
    					afterFinish: function(){
    						$('product-text-expand-more').hide();
    						$('product-text-expand-less').show();
    					}
					});
				});	
			
			$('product-text-expand-less').observe('click', function(){
   					new Effect.Morph(document.getElementsByClassName('product-single-text')[0], {
    					style: 'height:'+imageHeight+'px;', 
    					duration: 0.6,
    					afterFinish: function(){
    						$('product-text-expand-less').hide();
    						$('product-text-expand-more').show();
    					}
					});
				});				
		}	
			
		
}


function observeSearchForm(){
	swords = $('sword').value.split(' % ');
	
	
	if(swords.length > 0)
		$('searchtext').value = swords[0];
	
	

	if(swords.length > 1)
		$('searchtribe').value = swords[1];


	if(swords.length > 2)
		$('searchyear').value = swords[2];
		
	
	$('extended-searchform').observe('submit', function(ev){ 
		Event.stop(ev);
		$('sword').value = $('searchtext').value + ' % ' + $('searchtribe').value + ' % ' + $('searchyear').value;
		
		$('extended-searchform').submit();
	
	})
	
	
	
}


