$(document).ready(function() {
	/* Sidepicture-Zoom */
	$('div.sidepicture.zoompic').each(function() {
		var _curZP=$(this); // store current zoompic-container
		var _maxWidth=$('#content').width();
		var _prevWidth=$(this).children('div.sidepicture-moreimages').children('img').width();
		var _imgId=1;

		$(this).children('a.zoompic').width($(this).children('a.zoompic').children('img').width()); // fix the a-container width to the size of the image
		$(this).children('img.hugepic').attr('zid',0).appendTo(_curZP); // clone the zoom-picture and use as hugepic
		$(this).children('a.zoompic').children('img').attr('zid',0); // set unique id for this element
		
		$(this).on('click','img.hugepic',function(){$(this).css('left','-9999px');}); // bind hugepic-click to hide it
		$(this).on('click','a.zoompic',function(){_curZP.children('img.hugepic[zid="'+$(this).children('img').attr('zid')+'"]').css('left','0');return false;}); // bind zoompic-click to show the hugepic
		
		$(this).children('div.sidepicture-moreimages').children('img').each(function(){
			$(this).attr('zid',_imgId); // set uid
			$(this).clone().attr('width',null).attr('height',null).addClass('hugepic').appendTo(_curZP); // clone to hugepic
			if (_curZP.children('img.hugepic[zid="'+_imgId+'"]').width()>_maxWidth) _curZP.children('img.hugepic[zid="'+_imgId+'"]').attr('width',_maxWidth); // fix hugepic-width
			_imgId++;
		});
		
		// handle more images
		$(this).children('div.sidepicture-moreimages').on('click','img',function() {
			var pw=_curZP.children('a.zoompic').children('img').attr('width'); //store image width
			_curZP.children('a.zoompic').children('img').appendTo($(this).parent()).attr('width',_prevWidth).attr('height',null); // set current zoompic as more-pic and resize to the correct width
			$(this).appendTo(_curZP.children('a.zoompic')).attr('width',pw); // use current more-pic as new zoompic
			return false;
		});
	});

	/*Foldered-Text*/
	if ($('div.foldered').length > 0) {
		$('div.foldered').each(function(){
			$(this).children('div.box2').parent('div.foldered').append('<a href="javascript:void(0)" class="foldered-action box-closed">mehr lesen</a><div class="clearer"></div>');
			$(this).children('a.foldered-action').bind('click',function(){
				$(this).parent('div.foldered').children('div.box2').slideToggle('fast',function(){
					var b=$(this).parent('div.foldered').children('a.foldered-action')
					if ($(this).is(':hidden')) {
						$(b).removeClass('box-open').addClass('box-closed').text('mehr lesen');
					} else {
						$(b).removeClass('box-closed').addClass('box-open').text('weniger lesen');
					}
				});
				return false;
			});
		});
	}
	
	/* Inscription-Tool */
	if ($('#inscription-tool').length>0) {
		var checkOk = true;
		if (typeof(inscriptionToolData) == 'undefined') {
			$('#inscription-tool').html('Beschriftung: Keine Beschriftungsinformationen vorhanden.');
			checkOk=false;
		}
		if (typeof(productPrice) == 'undefined') {
			$('#inscription-tool').html('Beschriftung: Keine Preisinformationen vorhanden.');
			checkOk = false;
		}
		
		if (checkOk) {
			var inscriptionTool = {
				data: inscriptionToolData,
				el: {
					form: false,
					textBox: false,
					colorBox: false,
					insLines: {},
				},
				price:0,
				
				printTool: function() {
					var toolContent = '<div class="inscriptionText">';
					toolContent += '<div class="hl">Beschriftungstext: </div>';
					for (var i=0;i<this.data.maxLines;i++) {
						toolContent += '<div class="inscriptionLine isl'+i+' '+(i==0?' active':'')+'">';
						toolContent += '	<label for="inscriptionTextLine'+i+'">Zeile '+(1+i)+':</label>';
						toolContent += '	<input type="text" name="inscriptionTextLine'+i+'" id="inscriptionTextLine'+i+'" maxlength="'+this.data.maxCharsPerLine+'" '+(i!=0?'disabled="disabled"':'')+' />';
						toolContent += '	<span class="inscriptionTextCharsLeft'+i+'">Noch '+this.data.maxCharsPerLine+' Zeichen</span>';
						toolContent += '	<span class="inscriptionCost'+i+'"> (+'+format(this.data.linePrice[i+1])+' &euro;)</span>';
						toolContent += '</div>';
					}
					toolContent += '</div>';
					toolContent += '<div class="inscriptionColors">';
					toolContent += '<div class="hl">Beschriftungsfarbe: </div>';
					for (var i=0;i<this.data.colors.length;i++) {
						toolContent += '<div class="colorOption">';
						toolContent += '	<input type="radio" name="inscriptionColorOption"'+(i==0?' checked="checked"':'')+' id="inscriptionColorOption'+i+'" value="'+this.data.colors[i]+'" />';
						toolContent += '  <label for="inscriptionColorOption'+i+'">'+this.data.colors[i]+'</label>';
						toolContent += '</div>';
					}
					toolContent += '</div>';
					toolContent += '<div class="yourInscription"></div><div class="clearer"></div>';
					// Print to Page..
					$('#inscription-tool').append('<form action="#" method="get">'+toolContent+'</form>');
					this.el.form = $('#inscription-tool form');
					this.el.textBox = $('#inscription-tool form div.inscriptionText');
					this.el.colorBox = $('#inscription-tool form div.inscriptionColors');
					this.el.yourInscription = $('#inscription-tool form div.yourInscription');
					this.el.insLines = $('#inscription-tool form div.inscriptionText div.inscriptionLine');
				},
				
				inputHandler: function() {
					var idx = inscriptionTool.el.textBox.children('div.inscriptionLine').children('input[type=text]').index($(this));
					inscriptionTool.el.textBox.children('div.inscriptionLine:eq('+idx+')').children('span.inscriptionTextCharsLeft'+idx).text('Noch '+(inscriptionTool.data.maxCharsPerLine - $(this).val().length)+' Zeichen');
					for (var i=1;i<=inscriptionTool.data.maxLines;i++) {
						var lastInp = $(inscriptionTool.el.insLines[(i-1)]).children('input[type=text]');
						if ($(inscriptionTool.el.insLines[(i-1)]).children('input[type=text]').val().trim().length > 0) {
							$(inscriptionTool.el.insLines[i]).addClass('active');
							$(inscriptionTool.el.insLines[i]).children('input[type=text]').removeAttr('disabled');
						} else {
							$(inscriptionTool.el.insLines[i]).removeClass('active');
							$(inscriptionTool.el.insLines[i]).children('input[type=text]').attr('disabled',true);
							$(inscriptionTool.el.insLines[i]).children('input[type=text]').val('');
						}
					}
					inscriptionTool.printSelection();
				},
				
				usedLinesCount:function() {
					var insLinesFilled = 0;
					for (var i=0;i<this.el.insLines.length;i++) {
						if ($(this.el.insLines[i]).children('input[type=text]').val().trim().length > 0) {
							insLinesFilled++;
						} else {
							break;
						}
					}
					return insLinesFilled;
				},
				
				printSelection: function() {
					if (this.usedLinesCount() > 0) {
						$(this.el.yourInscription).html('<div class="hl">Ihre Auswahl: </div>');
						this.price = 0;
						for (var i=0;i<this.usedLinesCount();i++) {
							this.price += this.data.linePrice[i+1];
							$(this.el.yourInscription).append('<span>Zeile ' + (i+1) + ': ' + $(this.el.insLines[i]).children('input[type=text]').val().trim() + '</span><br />');
						}
						var selColor = false;
						if ($(this.el.colorBox).find('input[name=inscriptionColorOption]:checked').length > 0) {
							selColor = $(this.el.colorBox).find('input[name=inscriptionColorOption]:checked').val();
							$(this.el.yourInscription).append('Farbe: '+selColor+'<br />');
						} else {
							$(this.el.yourInscription).append('<span class="error">Bitte w&auml;hlen Sie eine Beschriftungsfarbe aus.</span><br />');
						}
						$(this.el.yourInscription).append('<strong>Preis f&uuml;r diese Beschriftung: ' + format(this.price) + ' &euro;</strong><br />');
						$(this.el.yourInscription).append('<strong>Gesamtpreis f&uuml;r diesen Artikel: '+format((productPrice+this.price))+' &euro;</strong>');
						if ($(this.el.yourInscription).is(':hidden')) $(this.el.yourInscription).fadeIn('fast');
						if (selColor != false) {
							$('form[name=putform] div.pricebox p.price').html('Preis '+format((productPrice+this.price))+' &euro;');
							$('form[name=putform] div.bputform input[name=price]').val((productPrice+this.price));
							var insData = 'Beschriftung '+this.usedLinesCount()+' Zeile(n). ';
							insData += 'Textfarbe: ' + selColor + '. ' + "\n";
							for (var i=0;i<this.usedLinesCount();i++) {
								insData += 'Zeile ' + (i+1) + ': \'' + $(this.el.insLines[i]).children('input[type=text]').val().trim() + '\'';
								if (this.usedLinesCount() > i) insData += ', ' + "\n";
							}
							insData += '(+' +format(this.price)+' EUR).';
							$('form[name=putform] div.bputform input[name=inscription]').val(insData);
						}
					} else {
						$(this.el.yourInscription).html('');
						if ($(this.el.yourInscription).is(':visible')) {
							$(this.el.yourInscription).fadeOut('fast');
						}
						$('form[name=putform] div.pricebox p.price').html('Preis '+format(productPrice)+' &euro;');
					}
				}
				
			};
			inscriptionTool.printTool();
			
			// Form-Handler
			$('#inscription-tool div.inscriptionLine input[type=text]').on({keyup: inscriptionTool.inputHandler,change: inscriptionTool.inputHandler});
			$('#inscription-tool div.inscriptionColors input[type=radio]').on({change: inscriptionTool.inputHandler});
		}
	}
	
	/*Tabs*/
	if($('div.tabContainer').length>0) {
		var ttc='div.tabContainer';
		var thb='div.tabHeaderBox';
		var tcb='div.tabContentBox';
		$(ttc).each(function(){
			var _tc=0;
			var _tmh=0;
			$(this).append('<div class="tabHeaderBox"></div>');
			$(this).append('<div class="tabContentBox"></div>');
			$(this).children('div.tabbox').each(function(){
				if ($(this).height()>_tmh) _tmh=$(this).height();
			});
			$(this).children('div.tabbox').each(function() {
				_tc++;
				var tt=$(this).find('h2:first').text();$(this).find('h2:first').remove();
				$(this).parent(ttc).children(thb).append('<a href="#" class="tab'+_tc+'">'+tt+'</a>');
				$(this).removeClass('tabbox').addClass('tab tab'+_tc).css('min-height',_tmh-50).appendTo($(this).parent(ttc).children(tcb));
			});
			var _ccb=$(this).children(tcb);
			var _chb=$(this).children(thb);
			_chb.children('a:eq(0)').addClass('active');
			_ccb.children('div.tab:eq(0)').addClass('active');
			_chb.children('a').click(function(){
				var idx=_chb.children('a').index($(this));
				if (_chb.children('a:eq('+idx+')').hasClass('active')) return false;
				_chb.children('a').removeClass('active');
				_ccb.children('div.tab').hide();
				_chb.children('a:eq('+idx+')').addClass('active');
				_ccb.children('div.tab:eq('+idx+')').fadeIn();
				return false;
			});
		});
	}
	
	/*Productrating*/
	if ($('#ekomi-productrating').length>0) {
		function loadProductRating() {
			$('#ekomi-productrating .feedbackbox').hide();
			$.ajax({
				url: "/assets/getProductFeedback.php",
				type: "GET",
				dataType: 'json',
				data: {'product_id':$.trim($('span#productid').text().replace('Art-Nr:',''))},
				success: function(data) {
					$('#ekomi-productrating .feedbackbox').html(''); // feedbackbox leeren..
					if (data.state=="success") {
						$.each(data.data,function(i,l){
							$('#ekomi-productrating .feedbackbox').prepend('<div class="ecfb"><div class="rstars cnt-'+l.rating+'"><div>&nbsp;</div></div><div class="rdate">'+l.rdate+'</div><div class="rtext">'+l.feedback+'</div></div>');
						});
						if (data.data.length>0) {
							$('#ekomi-productrating .infotext').clone().show().appendTo($('#ekomi-productrating .feedbackbox'));
							$('#ekomi-productrating .feedbackbox').fadeIn('fast');
						}
					} else {
						$('#ekomi-productrating .feedbackbox').append('<p>'+data.msg+'</p>').hide().fadeIn('fast');
					}
					
				}
			});
		}
		if ($('span#productid')) {
			$(document).on('ready',loadProductRating);
			$('table.variationTable td.varSelect').on('change','select',loadProductRating);
			
		}
	}

});
