// SLIDER

var anzahl = 0; // Anzahl der Produktbilder im Slider
var aktuelles_element = 0; // Aktuelles Bild im Slider (ganz links, beginnend bei 0) 
var slideWidth = 71 + 1; // Breite der Bilder
var slideLeft = 0; // Linke Position des Sliders

$(document).ready(function(){
	// zaehlen der bilder
	anzahl = $('#countPictures').text();

	if (anzahl <= 0) {
		$("#productGallery").hide();
	} else if (anzahl > 4) {
		$("#next_button").css("visibility", "visible");
	}

	if (anzahl > 1) {
		$("#flash_player_button_forward").css("visibility", "visible");
	}
});

function setSlider(position) {
	if (position < 0) {
		position = 0;
	} else if (position > anzahl - 4) {
		position = anzahl - 4;
	}

	var diff = position - aktuelles_element;
	var i = 0;

	if (diff > 0) {
		while (i < diff) {
			slideLeft = slideLeft - slideWidth;
			$('#slider').animate({left: slideLeft+'px'}, 10);
			aktuelles_element++;
			i++;
		}
	} else {
		while (i < (diff*-1)) {
			slideLeft = slideLeft + slideWidth;
			$('#slider').animate({left: slideLeft+'px'}, 10);
			aktuelles_element--;
			i++;
		}
	}

	if (aktuelles_element == 0) {
		$("#prev_button").css("visibility", "hidden");
	} else {
		$("#prev_button").css("visibility", "visible");
	}
	if (aktuelles_element < anzahl - 4) {
		$("#next_button").css("visibility", "visible");
	} else {
		$("#next_button").css("visibility", "hidden");
	}
}

function next_spalte() {
	if (anzahl != 1) {
		if (aktuelles_element != (anzahl - 1)) {
			slideLeft = slideLeft - slideWidth;
			$('#slider').animate({left: slideLeft+'px'}, 500);

			aktuelles_element++;
		}

		// wenn das aktuelle element nicht das erste ist, soll der prev button sichtbar werden
		if (aktuelles_element > 0){
			$("#prev_button").css("visibility", "visible");
		}

		// wenn das letzte aktuelle element erreicht wurde, soll der prev button sichtbar werden
		if (aktuelles_element == (anzahl - 4)) {
			$("#next_button").css("visibility", "hidden");
		}
	}
}

function prev_spalte() {
	if (anzahl != 1){
		if (aktuelles_element != 0){
			slideLeft = slideLeft + slideWidth;
			$('#slider').animate({left: slideLeft+'px'}, 500);

			aktuelles_element--;
		}

		// wenn das aktuelle element das erste ist, soll der prev button unsichtbar werden
		if (aktuelles_element == 0){
			$("#prev_button").css("visibility", "hidden");
		}

		// wenn das aktuelle element nicht mehr das letzte ist, soll der next button sichtbar werden
		if (aktuelles_element < anzahl){
			$("#next_button").css("visibility", "visible");
		}
	}
}

//SLIDER ENDE


// BEWERTUNGEN

$(document).ready(function() {
	var errorFlag = $('#errorFlag').text();
	if (errorFlag == 'true') {	
		$("#abgeben").addClass("active");
		$("#ansehen").removeClass();
		$("#reviewShow").css("display","none");
		$("#reviewSubmit").css("display","block");
	}
	prepareReviews();
});

function abgeben(element){
	$(element).addClass("active");
	$(element).prev().removeClass();
	$(".reviewShow").css("display","none");
	$(".reviewSubmit").css("display","block");
	$("#name").css("display","none");
	$("#name").css("display","inline");
	$("#email").css("display","none");
	$("#email").css("display","inline");
	$("#headline").css("display","none");
	$("#headline").css("display","block");
	$("#comments").css("display","none");
	$("#comments").css("display","block");
}

function ansehen(element){
	$(element).addClass("active");
	$(element).next().removeClass();
	$(".reviewSubmit").css("display","none");
	$(".reviewShow").css("display","block");
}

function abgebenLink(){
	$("#abgeben").addClass("active");
	$("#ansehen").removeClass();
	$("#reviewShow").css("display","none");
	$("#reviewSubmit").css("display","block");

	window.location.href = "#review";
}

function nextPage() {
	var nextInt = parseInt($("#next").text());
	var pagingInt = parseInt($("#paging").text());
	nextInt += pagingInt;
	$("#next").html("" + nextInt);

	updateReviews($("#model").text(), $("#next").text(), $("#paging").text());

	$("#previousRatingPage").css("visibility","visible");
	totalInt = parseInt($("#total").text());
	temp = nextInt + pagingInt;
	if (temp < totalInt) {
		$("#nextRatingPage").css("visibility","visible");
	} else {
		$("#nextRatingPage").css("visibility","hidden");
	}

	$("#reviewShow").get(0).scrollTop = 0;
}

function previousPage() {		
	var nextInt = parseInt($("#next").text());
	var pagingInt = parseInt($("#paging").text());
	nextInt -= pagingInt;
	$("#next").html("" + nextInt);
	
	updateReviews($("#model").text(), $("#next").text(), $("#paging").text());

	$("#nextRatingPage").css("visibility","visible");
	totalInt = parseInt($("#total").text());
	temp = nextInt + pagingInt;
	if (temp < totalInt && nextInt != 0) {
		$("#previousRatingPage").css("visibility","visible");
	} else {
		$("#previousRatingPage").css("visibility","hidden");
	}

	$("#reviewShow").get(0).scrollTop = 0;
}

function updateReviews(modelCode, next, paging) {
	$.getJSON("AjaxRetrieveReviewsAction.action",{modelCode: modelCode, next: next, paging: paging, ajax: 'true'}, function(j) {
		$("#reviews").empty();

		for (var i=0; i < j.length; i++) {
			rating = j[i].rating;
			if (rating == "1.0") {
				ratingStars = "<img src=\"media/star_green.png\"> <img src=\"media/star_gray.png\"> <img src=\"media/star_gray.png\"> <img src=\"media/star_gray.png\"> <img src=\"media/star_gray.png\">";
			} else if (rating == "2.0") {
				ratingStars = "<img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_gray.png\"> <img src=\"media/star_gray.png\"> <img src=\"media/star_gray.png\">";
			} else if (rating == "3.0") {
				ratingStars = "<img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_gray.png\"> <img src=\"media/star_gray.png\">";
			} else if (rating == "4.0") {
				ratingStars = "<img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_gray.png\">";
			} else if (rating == "5.0") {
				ratingStars = "<img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_green.png\"> <img src=\"media/star_green.png\">";
			} else {
				ratingStars = "";
			}
			headline = j[i].headline;
			comment = j[i].comment;
			creator = j[i].creator;
			date = j[i].date;
			hncomment = j[i].hncomment;
			firstlineofhncomment = j[i].firstLineOfHnComment;

			reviewAsHtml = "<div><h2>" + headline + "</h2>"
				+ "<div class=\"stars\">" + ratingStars + "</div><br class=\"clear\" />"
				+ "<div class=\"left comment\">" + comment + "</div>"
				+ "<div class=\"right\"><b>" + creator + "</b><br />" + date + "<br /><br /><br />"
				+ "<div class=\"more\">" + getLocalizedText("product.detail.review.more") + "</div></div><br class=\"clear\" />";

			if (hncomment != null) {
				reviewAsHtml = reviewAsHtml
					+ "<div class=\"left\"><i><b>" + getLocalizedText("product.detail.review.hncomment.firstline") + "</b>" + firstlineofhncomment + "</i></div>"
					+ "<div class=\"right\" style=\"position:relative;\">"
					+ "<div onclick=\"popup(this)\"><span class=\"arrowlink reviews_green\">" + getLocalizedText("product.detail.review.hncomment") + "</span></div>"
					+ "<div class=\"popup_container\" id=\"reviews_popup_container\"><div class=\"info_popup_bg\" id=\"reviews_info_popup_bg\"><span>" + hncomment + "</span></div>"
					+ "<div class=\"popup_close\" id=\"reviews_popup_close\"><a href=\"javascript:close_popup()\">" + getLocalizedText("product.detail.close") + "<img src=\"media/close.gif\" class=\"popup_img\" alt=\"schliessen\" /></a></div></div>"
					+ "</div><br class=\"clear\" />";
			}

			reviewAsHtml = reviewAsHtml + "<div class=\"hr\" style=\"width:618px; clear:both;\"></div></div>";

			reviewAsDom = $(reviewAsHtml);
			// For IE comment must be added as text subsequently; otherwise IE kills additional white space chars
			reviewAsDom.find("div.left").get(0).innerText = comment;

			reviewAsDom.appendTo("#reviews");
		}

		prepareReviews();
	});
}

function prepareReviews() {
	$(".details .reviews .comment").each(function() {
		if ($(this).height() > 80) {
			$(this).height(80);
			$(this).next(".right").children(".more").show();
		}
	});
	$(".details .reviews .more").click(function() {
		$(this).parent().prev(".comment").animate({height: "100%"}, "slow");
		$(this).hide();
	});
}

// BEWERTUNGEN


//ARTIKEL EMPFEHLEN

function empfehlen(){
	$('#artikel_empfehlen').css("width",document.body.offsetWidth+"px");
	$('#artikel_empfehlen').css("height",document.body.offsetHeight+"px");
	$('#artikel_empfehlen').css("display","block");

	var pricePopup = $('#price').text();
	var oldPricePopup = $('#priceOld').text();

	$('#pricePopup').html(pricePopup);
	$('#oldPricePopup').html(oldPricePopup);
}

function empfehlen2(){
	$('#error_layer').css("display","none");
	empfehlen();
}

function close_empfehlen(){
	$('#artikel_empfehlen').css("display","none");
}

//ARTIKEL EMPFEHLEN ENDE


// COLORS/SIZES/PRICES/AVAILABILITY

$(document).ready(function() {
	$(".dropdown_list_colors li").click(selectColorViaDropdown);
	$(".dropdown_list_sizes li").click(selectSizeViaDropdown);
	$(".colors a").click(selectColorViaSwatch);
	$("#slider .slide").click(selectColorViaSliderImage);
});

function selectColorViaDropdown(e) {
	var imgUrl = $(this).children(".hidden").eq(2).text();
	var colorCode = $(this).children(".hidden").eq(0).text();
	chooseColor(colorCode);
	changeMainImage(imgUrl);
}

function selectSizeViaDropdown(e) {
	var sizeCode = $(this).children(".hidden").text();
	chooseSize(sizeCode);
	$(this).parent().parent(".dropdown_sub").slideUp("fast");
}

function selectColorViaSwatch(e) {
	e.preventDefault();

	var imgUrl = $(this).find(".hidden").eq(0).text();
	var colorCode = $(this).find(".hidden").eq(1).text();
	chooseColor(colorCode);
	changeMainImage(imgUrl);
}

function selectColorViaSliderImage(e) {
	var imgUrl = $(this).children("img").attr("src");
	var colorCode = extractColorCodeFromImageUrl(imgUrl);
	chooseColor(colorCode);
	changeMainImage(imgUrl);
}

function extractImageCodeFromUrl(imageUrl) {
	var imageCode = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
	imageCode = imageCode.substring(imageCode.lastIndexOf("-") + 1).split("?")[0].split(".jpg")[0];
	return imageCode;
}

function extractColorCodeFromImageUrl(imageUrl) {
	var imageCode = extractImageCodeFromUrl(imageUrl);
	var tokens = imageCode.split("_");
	return tokens[0] == "Z" ? tokens[2] : tokens[1];
}

function getModelCode() {
	return $("#model").text();
}

function isBonus() {
	return eval($("#bonus").val());
}

function getAdvertiser() {
	return $("#advertiser").text();
}

function isBargainMarket() {
	return $("#bargainMarket").text();
}

function getColorCode() {
	return $("#colorCode").val();
}

function setColorCode(colorCode) {
	$("#color").html(colorCode);
	$('#cC').html(colorCode);
	$("#colorCode").val(colorCode);
}

function getSizeCode() {
	return $("#sizeCode").val();
}

function setSizeCode(sizeCode) {
	$("#sizeCode").val(sizeCode);
}

function chooseColor(colorCode) {
	setColorCode(colorCode);

	var colorListElem = $(".optionsColor .dropdown .dropdown_sub ul li").filter(function(index) {
		return $(this).children(".hidden").eq(0).text() == colorCode;
	});
	$("#dropdown_title_color").html(colorListElem.html());

	updateSizes(getModelCode(), isBonus(), getAdvertiser(), colorCode);
}

function chooseSize(sizeCode) {
	setSizeCode(sizeCode);
	
	var sizeListElem = $(".optionsSize .dropdown .dropdown_sub ul li").filter(function(index) {
		return $(this).children(".hidden").eq(0).text() == sizeCode;
	});
	$("#dropdown_title_size").html(sizeListElem.html());

	updateArticleInfo(getModelCode(), isBonus(), getColorCode(), sizeCode);
}

function updateSizes(modelCode, bonus, advertiser, colorCode) {
	$.getJSON("AjaxRetrieveSizesAction.action", {modelCode: modelCode, bonus: bonus, colorCode: colorCode, advertiser: advertiser, ajax: 'true'}, function(j) {
		$("#sizeTitle").empty();
		$(".dropdown_list_sizes").empty();

		var selectedSizeCode = getSizeCode();
		var selectedSizeName;

		var resetSizeSelection = true;
		var item;
		for (item in j) {
			sizeCode = item;
			sizeName = j[item];
			var options = "<li>" + sizeName + "<div class=\"hidden\">" + sizeCode + "</div></li>";
			$(".dropdown_list_sizes").append(options);

			if (sizeCode == selectedSizeCode) {
				selectedSizeName = sizeName
				resetSizeSelection = false;
			}
		}

		if (resetSizeSelection) {
			selectedSizeCode = $(".dropdown_list_sizes li:first div.hidden").text();
		}
		chooseSize(selectedSizeCode);

		// Bind events to new elements
		$(document).ready(function() {
			$('.dropdown_list_sizes li').click(selectSizeViaDropdown);
		});
	});
}

function updateArticleInfo(modelCode, bonus, colorCode, sizeCode) {
	$.getJSON("AjaxRetrieveArticleInfoAction.action", {modelCode: modelCode, bonus: bonus, colorCode: colorCode, sizeCode: sizeCode, ajax: 'true', _: new Date().getTime()}, function(j) {
		$("#hiddenAdvertiserCode").html(j.advertiserCode);

		$(".availabilityText").html(j.availabilityInfo.text);
		$(".availabilityPic").attr("alt", j.availabilityInfo.text);
		$(".availabilityPic").attr("src", j.availabilityInfo.picUrl);
		$(".availabilityInfoText").html(j.availabilityInfo.infoText);

		$("#price").append(span);
		if (j.priceInfo.subscriptionPrice != null) {
			if (j.priceInfo.subscriptionDiscountRate != null) {
				$("#priceOld").html("<del>" + j.priceInfo.subscriptionPrice + "</del> ");
				$("#priceOld").prepend("(-" + j.priceInfo.subscriptionDiscountRate + " " + getLocalizedText("product.detail.discount") + ") &nbsp; " + getLocalizedText("product.detail.oldprice") + ": ");
			} else {
				$("#priceOld").html(j.priceInfo.subscriptionPrice + " ");
				$("#priceOld").prepend(getLocalizedText("product.detail.subscriptionprice") + " " + j.priceInfo.subscriptionDate + ": ");
			}
		} else if (j.priceInfo.oldPrice != null) {
			$("#priceOld").html(getLocalizedText("product.detail.oldprice") + ": <del>" + j.priceInfo.oldPrice + "</del> ");
		} else {
			$("#priceOld").empty();
		}
		
		var span = $("#price span");
		if (bonus) {
			if (j.priceInfo.price != null) {
				$("#price").html(getLocalizedText("product.detail.extrapayment") + ": " + j.priceInfo.price + " ");
			} else {
				$("#price").html(getLocalizedText("product.detail.withoutextrapayment"));
			}
		} else {
			$("#price").html(getLocalizedText("product.detail.price") + ": " + j.priceInfo.price + " ");
		}

	});
}

// COLORS/SIZES/PRICES/AVAILABILITY ENDE


// ZOOM / VIDEO

$(document).ready(function(){
	sj_codebase = "js/lib/flyzoom";
	sjFlyout("flyzoom", $("#flyzoom").attr("src"));
});

function embedZoomViewer(imgCode) {
	var movie = "http://imgs7.hessnatur.com/is-viewers/flash/genericzoom.swf";
	var flashvars = {
		serverUrl: "http://imgs7.hessnatur.com/is/image/",
		instanceName: "35jx2a_" + imgCode,
		image: "HessNatur/" + imgCode + ";HessNatur/" + imgCode + ",HessNatur/" + imgCode + "_S;HessNatur/" + imgCode + "_S",
		contentRoot: "/skins",
		persistence: "0",
		skin: "HessNatur/SWFs/zoomPlayer_hybrisFG_V7_17.swf,HessNatur/SWFs/zoomPlayer_hybrisBG_V7_17.swf",
		ztgLayout: "hotspot,0,0",
		swHighlightColor: "017136",
		swHighlightThickness: "1",
		backgroundColor: "0x000000",
		turnTime: "0.1",
		scrollBars: "false",
		serverSupport: "1",
		splashScreen: "HessNatur/SWFs/zoomPlayerWaiting_hybris_V5_1.swf",
		modifier: "%26op_sharpen%3D1%26resMode%3Dsharp2%26op_usm%3D1.1%2C0.8%2C0%2C0%26qlt%3D70",
		fadeTime: "0.2",
		zoomStep: "0.8",
		clickToZoom: "false",
		transitionTime: "0.2",
		spinSliderHorizontal: "true",
		sliderColors: "000000,666000,666600,FFFFFF,FFFFFF",
		navHighlightColor: "0xff0000",
		navHighlightThickness: "1"
	};
	var params = {
		quality: "high",
		bgcolor: "#000000",
		menu: "false",
		scale: "noscale",
		swLiveConnect: "true",
		allowScriptAccess: "always"
	};
	swfobject.embedSWF(movie, "zoomViewer", "780", "550", "6.0.0", false, flashvars, params, false);
}

function embedVideoPlayer(videoUrl) {
	var movie = "http://imgs7.hessnatur.com/is-viewers-4.0/flash/videoplayer.swf";
	var flashvars = {
		movie: videoUrl,
		vidPaneSize: "0,0",
		vidPaneColor: "0xa6a29c",
		viewSize: "0,0",
		backgroundColor: "0xa6a29c",
		vidPause: "true",
		vidPlayToggle: "true",
		vidSndEnable: "true",
		vidSndMute: "false",
		vpbEnable: "false",
		vpbBarBgColor: "0xFF8C40",
		vpbBarLoadedColor: "0xCCCCCC",
		vpbBarThickness: "3",
		toolTips: "true",
		contentRoot: "/skins",
		skin: "HessNatur/SWFs/videoPlayer_hybris_FG_v1.swf,HessNatur/SWFs/videoPlayer_hybris_BG_v1.swf"
	};
	var params = {
		quality: "high",
		bgcolor: "#a6a29c",
		menu: "false",
		scale: "noscale",
		swLiveConnect: "true",
		allowScriptAccess: "always"
	};
	swfobject.embedSWF(movie, "videoPlayer", "780", "585", "6.0.0", false, flashvars, params, false);
}

function changeMainImage(imageUrl) {
	var imageBaseUrl = imageUrl.substring(0, imageUrl.indexOf("/image/") + 1);
	var imageCode = extractImageCodeFromUrl(imageUrl);

	var position;
	$("#slider .slide img").each(function(i) {
		var thisImageCode = extractImageCodeFromUrl($(this).attr("src"));
		if (thisImageCode == imageCode) {
			position = i;
		}
	});

	if (anzahl > 4) {
		setSlider(position - 1);
	}

	if (position > 0) {
		$("#flash_player_button_back").css("visibility", "visible");
	} else {
		$("#flash_player_button_back").css("visibility", "hidden");
	}
	if (position < anzahl - 1) {
		$("#flash_player_button_forward").css("visibility", "visible");
	} else {
		$("#flash_player_button_forward").css("visibility", "hidden");
	}

	$("#empfehlenPic img").attr("src", imageUrl.replace("hyb_de_productdetail_alternative", "hyb_de_thumbsmall").replace("hyb_de_productdetail", "hyb_de_thumbsmall"));

	sjFlyout("flyzoom", imageBaseUrl + "image/HessNatur/" + imageCode + "?$hyb_de_productdetail$");
	embedZoomViewer(imageCode);
}

function nextZoomImage() {
	var imageUrl = $("#scene7MainImage").find("img").attr("src");
	var imageCode = extractImageCodeFromUrl(imageUrl);

	var actualSlide;
	var nextSlide;

	$("#slider .slide img").each(function(i) {
		var thisImageCode = extractImageCodeFromUrl($(this).attr("src"));
		if (thisImageCode == imageCode) {
			actualSlide = $(this).parents(".slide");			
		}
	});

	if (actualSlide != null) {
		nextSlide = actualSlide.next(".slide");
	} else {		
		nextSlide = $("#slider .slide").eq(0);
	}

	var nextImageUrl = nextSlide.find("img").attr("src");
	var colorCode = extractColorCodeFromImageUrl(nextImageUrl);
	chooseColor(colorCode);
	changeMainImage(nextImageUrl);
}

function prevZoomImage() {
	var imageUrl = $("#scene7MainImage").find("img").attr("src");
	var imageCode = extractImageCodeFromUrl(imageUrl);

	var actualSlide;
	var prevSlide;

	$("#slider .slide img").each(function(i) {
		var thisImageCode = extractImageCodeFromUrl($(this).attr("src"));
		if (thisImageCode == imageCode) {
			actualSlide = $(this).parents(".slide");			
		}
	});

	if (actualSlide != null) {
		prevSlide = actualSlide.prev(".slide");
	} else {
		prevSlide = $("#slider .slide").eq(0);
	}

	var prevImageUrl = prevSlide.find("img").attr("src");
	var colorCode = extractColorCodeFromImageUrl(prevImageUrl);
	chooseColor(colorCode);
	changeMainImage(prevImageUrl);
}

//ZOOM / VIDEO


// POPUPS

$(document).ready(function(){
	// Fade in layers at the mouse position
	$("#maintenanceButtons").click(function(e){
		$("#popup_container_maintenance").css({
			"position" : "absolute",
			"top":  e.pageY + 8 + "px",
			"left":  e.pageX + 5 + "px"
		});
		$(this).next(".popup_container").children().fadeIn("fast");
		$(this).next(".popup_container").children().next().fadeIn("fast");

	});
	$("#paletteButtons").click(function(e){
		$(this).next(".popup_container").css({
			"position" : "absolute",
			"top":  e.pageY + 8 + "px",
			"left":  e.pageX - 12 + "px"
		});
		$(this).next(".popup_container").children().fadeIn("fast");
		$(this).next(".popup_container").children().next().fadeIn("fast");

	});
	$("#brandButtons").click(function(e){
		$(this).next(".popup_container").css({
			"position" : "absolute",
			"top":  e.pageY + 8 + "px",
			"left":  e.pageX - 12 + "px"
		});
		$(this).next(".popup_container").children().fadeIn("fast");
		$(this).next(".popup_container").children().next().fadeIn("fast");

	});
	for (var i = 1; i<6; i++) {
		$("#glossaryButtons_"+i+"").click(function(e){
			close_popup();

			$(this).next(".popup_container").css({
				"position" : "absolute",
				"top":  e.pageY - 10 + "px",
				"left":  e.pageX + 35 + "px"
			});
			$(this).next(".popup_container").children().fadeIn("fast");
			//$(this).next(".popup_container_"+j+"").fadeIn("fast");
			$(this).next(".popup_container").children().next().fadeIn("fast");
			//$(this).next(".popup_container_"+j+"").children().next().fadeIn("fast");
			$("#glossarySpacer").css("display","block");
		});
	}
});

//POPUPS ENDE


function submitCartForm() {
	$('#checkVouchers').val("true");
	$('#cartForm').submit();
}

