/* <![CDATA[ */
window.onload = function() {
	I = new nwz_gallery();
	I.init();

	$('pos').style.height = (10*R) + 'px';

	Slider = new Control.Slider('pos', 'scrollbar', {
		axis : 'vertical',
		range: $R(0, 100),
		values: Positions,
		sliderValue: [0, 100],
		onChange : slideAction,
		onSlide : slideAction
	});
	
	function slideAction(v) {
		SlidePos = parseInt(v);
		$('glist').style.top = (-6.2 * (v / (R * 0.1))) + 'px';
	}
	
	e = $('cat').getElementsByClassName('active')[0];
	if (typeof(e) != 'undefined') {
		I.activeRubric = e;
		I.activeSub = e.getElementsByClassName('subcat')[0];
	}
		
	loadGalleryList(Cvar);
	
	new MouseWheelArea();
	
	new Navigation();
	
	$('cat').onmouseout = resetNavi;
}


function nwz_gallery () {
	this.Images 		= ImageData;
	
	this.Article 		= Article;
	this.Author 		= Author || false;
	this.ads 			= false;
	if (ads === false)
		this.ads = true;
	this.Index 			= Index;
	this.IVWTag 		= 'http://nwz.ivwbox.de/cgi-bin/ivw/CP/' + IVWTag;
	this.Offset 		= 3;
	this.EffectDuration = 700;
	this.OMSZone 		= OMS;
	this.ApplicationURL = AppURL;
	this.Search 		= SearchString;
	
	this.Effects 		= false;
	this.ArrowKeys 		= false;
	this.UpdateText 	= UpdateText;
	
	this.adIsActive 	= false;
	this.imgCounter 	= 0;
	
	this.rating			= Rating || false;
	this.rateDisabled	= [];
	this.ttp			= 0;
	this.rateExpired	= Expired;

	/**
	 * Bild Anzeigen
	 */
	this._displayImage = function() {
		// Counter für die Klickanzahl wird erhöht
		this.imgCounter++;
		
		this.ImgURL = this.ApplicationURL + 'Empfehlung/' + Cvar + '/' + this.Article + '/Bild' + (this.Index + 1);
		
		this._preload((this.Index + 1 < this.Images.length) ? this.Index + 1 : 0);
		this._preload((this.Index - 1 >= 0) ? this.Index - 1 : this.Images.length - 1);

		$('ad_box').hide();
		$('top10').hide();
		$('rateContainer').show();
		$('Browse').show();
		
		$('share_box').hide();
		$('email_box').hide();
		$('url_box').hide();
		$('blinder').hide();
				
		Img = this.Images[this.Index];
		this.Images[this.Index].loaded = true;
		
		this._bindEvents(false);
		$('ImageEffect').width = Img.w;
		$('ImageEffect').height = Img.h;
		$('ImageEffect').style.left = (1 + Math.floor((488 - Img.w)/2)) + 'px';
		$('ImageEffect').style.top = (1 + Math.floor((325 - Img.h)/2)) + 'px';
		$('ImageEffect').src = 'http://www.nwzonline.de/nwz-bilder/500/' + Img.bildpfad + '/' + Img.name;
		
		if(this.Effects == true) {
			this.EffectDuration = 700;				
			new Effect.Parallel([
				new Effect.Appear('ImageEffect', { sync: true }),
				new Effect.Fade('Image', { sync: true })
			], { duration: (I.EffectDuration/1000) });
		}
		else {
			$('ImageEffect').show();
			$('Image').hide();
			this.EffectDuration = 0;
		}
	
		window.setTimeout(function() {
			$('Image').width = Img.w;
			$('Image').height = Img.h;
			$('Image').style.left = (1 + Math.floor((488 - Img.w)/2)) + 'px';
			$('Image').style.top = (1 + Math.floor((325 - Img.h)/2)) + 'px';
			$('Image').src = 'http://www.nwzonline.de/nwz-bilder/500/' + Img.bildpfad + '/' + Img.name;
			I._bindEvents(true);
		}, this.EffectDuration);	
		
		$('Image').show();
		$('ImageEffect').hide();
		
		if(Img.bildunterschrift != '')
			$('ImageTxt').innerHTML = Img.bildunterschrift;

		if(this.UpdateText == true && Img.text.length > 0)
			$('GalleryTxt').innerHTML = Img.text;
		
		if(this.rating) {
			$('rate').innerHTML = '&#xD8; ' + Math.round(Img.rate*10)/10;
			//var rateSlider = $('rateSlider');
			
			$('rateSlider').innerHTML = '';
			for (i=1;i<=10;i++)
				$('rateSlider').innerHTML += '<a class="rate-link" href="#" onclick="I._addRating('+i+');return false;">&nbsp;</a>'; 
			
			/*if (!this.rateExpired) {
				if (this.rateDisabled[this.Index] > 0) {
					this.rateSlider = new Control.Slider(rateSlider.down('.handle'), rateSlider, {
						range: $R(1, 10),
						values: $R(1, 10),
						sliderValue : this.rateDisabled[this.Index],
						disabled : 1
					});
				}
				else {
					this.rateSlider = new Control.Slider(rateSlider.down('.handle'), rateSlider, {
						range: $R(1, 10),
						values: $R(1, 10),
						sliderValue: 5
					});				
				}
			}
			else
			
				$('rate').innerHTML = 'Bewertung: &#xD8; ' + Math.round(Img.rate*10)/10;*/
		}
		
		this._pagination();	
		this._options();
		this._pageImpression();
		this._updateImageViews();
		
		if(typeof(auktion) != 'undefined') {
			new Ajax.Updater('actualBid', '/fotos/getBid.php', {
				parameters : { Item : 'http://www.nwzonline.de/nwz-bilder/500/' + Img.bildpfad + '/' + Img.name }, onComplete : function() { $('bid').show(); }			
			})
		}
		
		if (typeof(PLISTA) != 'undefined') {
			PLISTA.pictureads.hideAll();
			setTimeout(function () {
				PLISTA.pictureads.reInit();
				}, 500);
		}
	}

	this._displayAd = function() {
		$('rateContainer').hide();
		$('Image').hide();
		$('top10').hide();
		$('Browse').hide();
		$('ad_box').innerHTML = '<iframe src="/fotos/rec.php?Zone=' + this.OMSZone + '" frameborder="0" scrolling="no" style="width:300px;height:265px;margin-left:95px;margin-top:30px"></iframe>';
		$('ad_box').show();
	}
	
	/**
	 * Seitenzahlen unterhalb des Bildes errechnen und anzeigen
	 */
	this._pagination = function() {
		Rawlink = '#INDEX" onclick="I.goto(INDEX);return false;';
		Seperator = '';
		First = 1;
		Last = this.Images.length;
		Prv = '&nbsp;...&nbsp;';
		Nxt = '&nbsp;...&nbsp;';
		Links = [];
		
		Start = this.Index - this.Offset;
		End = this.Index + this.Offset;
		NumPages = this.Images.length;

		if(Start <= 0)
			Start = 0;
		End = Start + (this.Offset * 2);
		if(End >= NumPages) {
			End = NumPages - 1;
			Start = End - (this.Offset*2);
			if(Start <= 0)
				Start = 0;
		}
				
		if(this.Index > 0 && NumPages > (this.Offset*2) +1) {
			Links[Links.length] = '<a href="' + Rawlink.replace(/INDEX/g, 0) + '">' + First + '</a>';
			Links[Links.length] = Prv;
		}
		for(i = Start; i <= End; i++) {
			Class = (i == this.Index) ? 'current' : '';
			Links[Links.length] = '<a class="' + Class + '" href="' + Rawlink.replace(/INDEX/g, i) + '">' + (i+1) + '</a>';
		}
		if(this.Index < (NumPages -1) && NumPages > (this.Offset*2) +1) {
			Links[Links.length] = Nxt;		
			Links[Links.length] = '<a href="' + Rawlink.replace(/INDEX/g, (NumPages-1)) + '">' + Last + '</a>';
		}
		if(Links.length > 1) {
			P = '';
			for(i = 0; i < Links.length; i++) {
				P += Seperator + Links[i];
				Seperator = '&nbsp;|&nbsp;';
			}
		}

		$('Pagination').innerHTML = P;
	}
	
	/**
	 * Huh? Was das hier?
	 */
	this._options = function() {
		$('Options').innerHTML = '';
	}
	
	/**
	 * Bestimmtes Bild anzeigen
	 * 
	 * @param	i	integer		Bildnummer
	 */
	this.goto = function(i) {
		this.Index = (0 < i && i < this.Images.length) ? i : 0;
		// wenn der Counter schon 10 ist (ob 10 mal geklickt oder geblättert) wird die Werbung aufgerufen
		if (this.ads && this.imgCounter == 10) {
			this._displayAd();
			this.imgCounter = 0; // Counter startet neu
		} else {
			this._displayImage(); // wenn nicht, passiert nix
		}
	}
	
	/**
	 * vor-/zurückblättern
	 *
	 * @param	d	integer		1, wenn vor, -1, wenn zurück
	 */
	this.browse = function(d) {
		if (this.ads && this.imgCounter == 10) { // wenn der Counter schon 10 ist wird die Werbung aufgerufen
			this._displayAd();
			this.imgCounter = 0;// Counter startet neu
		} else {
			this.adIsActive = false;
			this.Index = (this.Index + d < 0) ? this.Images.length - 1 : ((this.Index + d > this.Images.length - 1) ? 0 : this.Index + d);
			this._displayImage();
		}
		/*
		 * else if (this.adIsActive == false && d == 1 && this.Index + d > this.Images.length - 1) {
			this._displayAd();
			this.adIsActive = true;
		 */

	}
	
	/**
	 * Zähler der Bildviews in der DB erhöhen
	 */	 
	this._updateImageViews = function() {
		new Ajax.Request('/fotos/imageupdate.php', {
			parameters : {
				a: this.Article,
				b: this.Images[this.Index].id
			}
		});
	}
	
	/**
	 * IVW und Ads laden, wenn PageImpression
	 */	  
	this._pageImpression = function() {	
		if(this.PI > 0) {
			$('ivwpixel').src = this.IVWTag + '?r=' + escape(document.referrer) + '&d=' + (Math.random()*100000);
			//$('sb').src = '/fotos/sb.php?Zone=' + this.OMSZone;
			//$('sky').src = '/fotos/sky.php?Zone=' + this.OMSZone;
			
			try {
				var pageTracker = _gat._getTracker("UA-9344885-1");
				pageTracker._trackPageview();
			} catch(err) {}
		}
		this.PI++;
	}

	/**
	 * Eventhandler setzten
	 *
	 * @param 	bool	boolean
	 */
	this._bindEvents = function(bool) {
		if(bool) {
			$('Prev').onclick = function() { I.browse(-1); return false; }
			$('Next').onclick = function() { I.browse(1); return false; }
			$('Browse').onclick = function() { I.browse(1); this.blur(); return false; }
			$('Image').onclick = function() { I.browse(1); this.blur(); return false; }
			$('ad_box').onclick = function() { I.browse(1); this.blur(); return false; }
		}
		else {
			$('Prev').onclick = function() { return false; }
			$('Next').onclick = function() { return false; }
			$('Browse').onclick = function() { this.blur(); return false; }
			$('Image').onclick = function() { this.blur(); return false; }
		}
		$('email').onclick = function() { I.getCaptcha(); blinder('email_box', true); return false; }
		$('share').onclick = function() { blinder('share_box', true); return false; }
		$('url').onclick = function() { 
			$('url_box').getElementsByTagName('input')[1].value = I.ImgURL;
			blinder('url_box', true); 
			return false; 
		}
		
		if(this.rating) {
			$('vt10').onclick = function() { I._top10(); return false; }
			if (!this.rateExpired) {
				$('setMyRate').onclick = function() { 
					I._addRating();
					return false; 
				}
			}
		}

	}
	
	this._top10 = function() {
		this.imgCounter--;
		
		$('Image').hide();
		$('Browse').hide();
		$('ad_box').hide();
		$('rateContainer').hide();
				
		toplist = [];
		
		tt = this.Images.length < 10 ? this.Images.length : 10;
		
		for (i = 0; i < this.Images.length; i++) {
			
			r = this.Images[i].rate;
			if (r*10 < 100)
				r = '0' + r;
			
			toplist[i] = r + '-' + i;
		}
		
		toplist.sort()
		toplist.reverse();
		
		offset = this.ttp *10;
		
		tt = toplist.length < 10 +offset ? toplist.length -offset : 10;
		
		fwd = (toplist.length >= 10 +offset +1) ? '<a href="#" onclick="I.ttp++;I._top10();return false;" class="fr">&raquo;</a>' : '<span class="fr" style="color:#FFF">&raquo;</span>';
		rwd = this.ttp > 0 ? '<a href="#" onclick="I.ttp--;I._top10();return false;" class="fr">&laquo;</a>' : '<span class="fr" style="color:#FFF">&laquo;</span>';
		
		var str = fwd + rwd +  
				  '<h2>Die aktuellen Top10</h2>';
		
		for (i = offset; i < offset + tt; i++) {
			t = toplist[i].split('-');
			str += '<div class="li">' +
					'<a class="fr" href="#' + t[1] + '" onclick="I.goto(' + t[1] + ');return false;">' + (this.rateExpired ? 'Zum Foto' : 'Jetzt bewerten') + '</a>' +
					'<div><h1>' + (i+1) + '</h1>' + 
					'<a href="#' + t[1] + '" onclick="I.goto(' + t[1] + ');return false;"><img src="http://www.nwzonline.de/nwz-bilder/50/' + this.Images[t[1]].bildpfad + '/' + this.Images[t[1]].name + '" /></a>' +
					'<strong>&nbsp;&#xD8;<span>' + (Math.round(t[0]*10)/10) + '</span>/<span>' + this.Images[t[1]].votes + ' Stimmen</span></strong></div></div>';
		};
		
		$('top10').innerHTML = str;
		$('top10').show();
	}
	
	this._addRating = function(v) {
		
		if (this.rateDisabled[this.Index])
			return;
		
		//value = this.rateSlider.value;
		value = v;
		imageId = this.Images[this.Index].id;
		rate = this.Images[this.Index].rate;
		votes = this.Images[this.Index].votes;
		
		new Ajax.Request('/fotos/addRating.php', {
			parameters : { 'rate' : rate, 'votes' : votes, 'value' : value, 'id' : imageId },
			asynchronous : false,
			onComplete : function(r) {
				I.Images[I.Index].rate = r.responseText;
				I.Images[I.Index].votes = parseInt(I.Images[I.Index].votes) +1;
			}
		});
		
		$('rate').innerHTML = '&#xD8; ' + Math.round(parseFloat(this.Images[I.Index].rate) * 10)/10;
		
		this.rateDisabled[this.Index] = value;
		//this.rateSlider.setDisabled();
		
		this.browse(1);
	}	
	
	/**
	 * EffektOption setzen
	 *
	 * @param	e	HTML-Object
	 */
	this.setOption = function(e) {
		switch(e.name) {
			case 'Effects' : 
				this.Effects = e.checked; 
				break;
			case 'Arrowkeys' : 
				if(e.checked == true) {
					$('wrapper').focus();
					$('wrapper').blur();
					document.onkeyup = this._keyPager.bindAsEventListener(this);
					this.ArrowKeys = true;
				}
				else {
					document.onkeyup = function() { return false; }
					
					this.ArrowKeys = false;
				} 
				break;
		}		
	}
	
	/**
	 * Captcha
	 */
	this.getCaptcha = function() {
		new Ajax.Updater('Captcha', '/fotos/captcha.php', { onComplete : function(r) { I.Captcha = r.responseText; }});
	}	  
	
	/**
	 * Bild vorladen
	 *
	 * @param	PreIndex	integer	ID, des Bildes
	 */
	this._preload = function(PreIndex) {
		if(this.Images[PreIndex].loaded != true) {
			Pre = this.Images[PreIndex];
			$('Preload').src = 'http://www.nwzonline.de/nwz-bilder/500/' + Pre.bildpfad + '/' + Pre.name;
		}
	}
	
	/**
	 * Bei Druck auf Pfeiltasten blättern
	 *
	 * @param	e	Event
	 */
	this._keyPager = function(e) {
		if(this.ArrowKeys) { 
			if(e.keyCode == Event.KEY_RIGHT)
				this.browse(1);
			if(e.keyCode == Event.KEY_LEFT) 
				this.browse(-1);
		}
	}
	
	/**
	 * Aktionsboxen verstecken
	 *
	 * @param 	e	HTML-Object
	 */	 
	this.hideActionBoxes = function(e) {
		$('blinder').hide();
		Boxes = document.getElementsByClassName('ico');
		i = Boxes.length;
		while(--i >= 0) {
			if(Boxes[i].id + '_box' != e) {
				B = Boxes[i].id + '_box';
				$(B).hide();
			}
		}
	}
	
	/**
	 * Object initialisieren
	 */	 
	this.init = function() {
		this.PI = 0;
		this._bindEvents(true);
		this._displayImage();
	}
}













function moveSlider(bool) {
	i = 0;
	while(i < Positions.length) {
		if(Positions[i] == SlidePos) {
			if(bool)
				SlidePos = (i+1 < Positions.length) ? Positions[(i+1)] : SlidePos;
			else 
				SlidePos = (i-1 >= 0) ? Positions[(i-1)] : SlidePos;
			i = Positions.length;
			Slider.setValue(SlidePos); 
		}
		i++;
	} 
}


var elm;
function MouseWheelArea(opt) {
	
	var elm = 'right';
	var scrolling = null;
	
	var options = Object.extend({
		ScrollUp :	'arrowup',
		ScrollDown:	'arrowdown',
		ScrollSpeed	:	3
	}, arguments[0] || {});
	Event.observe(options.ScrollUp, 'mousedown', function() { scrolling = window.setInterval("MouseWheelSlide('up', '"+elm+"')", 100);});
	Event.observe(options.ScrollUp, 'mouseup', function() { window.clearInterval(scrolling);});
	Event.observe(options.ScrollUp, 'mouseout', function() { window.clearInterval(scrolling);});
	Event.observe(options.ScrollDown, 'mousedown', function() { scrolling = window.setInterval("MouseWheelSlide('down', '"+elm+"')", 100);});
	Event.observe(options.ScrollDown, 'mouseup', function() { window.clearInterval(scrolling);});
	Event.observe(options.ScrollDown, 'mouseout', function() { window.clearInterval(scrolling);});
	if(window.addEventListener) {$(elm).addEventListener('DOMMouseScroll', function(e) { MouseWheel(e, elm, options);}, false);}
	Event.observe(elm, 'mousewheel', function(e) { MouseWheel(e, elm, options);});
}

function MouseWheelHandle(delta, elm) {
	if (delta < 0)
		MouseWheelSlide('down', elm);
	else
		MouseWheelSlide('up', elm);
}
function MouseWheel(event, elm, options){
	var delta = 0;
	
	if(!event)
		event = window.event;
		
	if(event.wheelDelta) {
		delta = event.wheelDelta / 120; 
		if(window.opera) 
			delta = -delta;
	} else if (event.detail) {
		delta = -event.detail / options.ScrollSpeed;
	}
	
	if(delta)
		MouseWheelHandle(delta, elm);
		
	if(event.preventDefault)
		event.preventDefault();
		
	event.returnValue = false;
}
function MouseWheelSlide(d, elm) {
	cont = $(elm).getElementsByClassName('wContent')[0];	
	tp = parseInt($(cont).getStyle('top'));	
	max = -1 * ($(cont).getHeight() - $(elm).getHeight());
	if(d == 'down')
		moveSlider(true);
	if(d == 'up')
		moveSlider(false);
}

function blinder(e, hide) {
	$('blinder').hide();
	Boxes = document.getElementsByClassName('ico');
	i = Boxes.length;
	while(--i >= 0) {
		if(Boxes[i].id + '_box' != e) {
			B = Boxes[i].id + '_box';
			$(B).hide();
		}
	}
	if(hide) {
		if(I.Effects == true) {
			new Effect.Parallel([
				new Effect.Appear('blinder', { from: 0, to: .6, sync: true }),
				new Effect.Appear(e, { from: 0, to: 1, sync: true })
			], { duration: 0.7 });
		}
		else {
			$('blinder').className = 'opacity';
			$('blinder').show();
			$(e).show();
		}
		Arrows(false);
	} else {
		$('blinder').hide();
		$('blinder').className = '';
		$(e).hide();
		Arrows(true);
	}
}

function resetNavi() {
	/*
	$A($('cat').getElementsByClassName('subcat')).each(function(e){
		e.style.display = 'none';
	});
	*/
	$A($('cat').getElementsByTagName('li')).each(function(e){
		if(e.parentNode.className != 'subcat')
			e.className = '';
	});
	if(I.activeRubric) {
		I.activeRubric.className = 'active';
		I.activeSub.style.display = 'block';
	}
}

function loadGalleryList(IOT, P) {
	$('glist').innerHTML = '<li style="height: 371px;background:url(http://nwzonline.de/fotos/images/loading2.gif)50% 154px no-repeat;"></li>';
	new Ajax.Updater(
		'glist',
		'/fotos/gallerylist.php', {
			parameters : {
				'IOT': IOT,
				'Suche': I.Search,
				'P': P
			},
			evalScripts : true
		});
	Slider.setValue(0);
}

function Arrows(bool) {
	if(bool) {
		I.ArrowKeys = I.tempArrowKeys;
	} else {
		I.tempArrowKeys = I.ArrowKeys;
		I.ArrowKeys = false;	
	}
}

function prepareSearch(IOT) {
	I.Search = $('sf').value;
	loadGalleryList(IOT);
	$('Searchnavi').show();
	
	I.activeRubric = $('Searchnavi')
	I.activeSub = $('Searchnavi').getElementsByClassName('subcat')[0];
	
	new Navigation();
	resetNavi();
}
function Navigation() {
	var MainLi = $('cat').childNodes;
	for(var i = 0; i < MainLi.length; i++) {
		MainLi[i].onmouseover = function() {
			/*
			Subs = $('cat').getElementsByClassName('subcat');
			for(j = 0; j < Subs.length; j++) {
				Subs[j].style.display = 'none';
				Subs[j].parentNode.className = '';
			}
			this.childNodes[1].style.display = 'block';
			*/
			this.className = 'active';
		}
		MainLi[i].onclick = function() {		
			this.className = 'active';
			I.activeRubric = this;
			I.activeSub = this.childNodes[1];
		}
	}
}

function taf() {
	if($('capt').value == I.Captcha) {
		r = $('reciever').value;
		n = $('yourname').value;
		new Ajax.Request('/fotos/taf.php', { parameters:{'r':r,'n':n,'f':I.ImgURL}});
		return true;
	}
	return false;
}


function bookmark(platform) {

	title = encodeURIComponent(document.title);
	desc = encodeURIComponent(document.getElementsByTagName('meta')['description'].content);
	url = encodeURIComponent(location.href);
	url = encodeURIComponent(I.ImgURL);

	switch(platform) {
		case 'wong':
			window.open('http://www.mister-wong.de/?action=addurl&bm_url='+ url +'&bm_description='+ title);
			break;
    	case 'webnews':
    		window.open('http://www.webnews.de/einstellen?url='+ url +'&title='+ title);
    		break;
    	case 'yigg':
    		window.open('http://yigg.de/neu?exturl='+ url +'&exttitle='+ title +'&extdesc='+ desc);
    		break;
    	case 'delicious':
    		window.open('http://del.icio.us/post?url='+ url +'&title='+ title);
    		break;
    	case 'google':
    		window.open('http://www.google.com/bookmarks/mark?op=add&hl=de&bkmk='+ url +'&title='+ title);
    		break;
    	case 'twitter':
    		window.open('http://twitter.com/home?status='+ url);
    		break;
    	case 'facebook':
    		window.open('http://de.facebook.com/sharer.php?u='+ url +'&t='+ title);
    		break;
    	case 'vz':
    		window.open('http://www.studivz.net/Suggest/Selection/?u='+ url +'&desc='+ title + '&prov=NWZonline');
    		break;
	}
}
function bkmtt(elm, x, y) {
	elm.style.backgroundPosition = x + 'px ' + y + 'px';
	//$('platformName').innerHTML = (y == 0) ? elm.title.split(': ')[1] : ''; 
}

/* ]]> */
