$(document).ready(function() {
	if ($.browser.webkit) {
		$('body').addClass('webkit');
		window.isWebkit = true;
	}
	if ($.browser.msie) {
		$('body').addClass('msie' + parseInt($.browser.version, 10));
		window.isMSIE = true;
		window["isMSIE"+(document.documentMode || navigator.userAgent.match(/ MSIE ([0-9])/i)[1])] = true;
	}
	if ($.browser.mozilla) {
		$('body').addClass('mozilla');
		window.isMozilla = true;
	}

	$('#idvf-overlay').click(openInsideDvF);
	$('.idvf .closer').click(closeInsideDvF);

	setTimeout(function() {
		$("select").sb({selectboxClass: "sbox", open: function(sb){
			$(sb[0]).jScrollPane({showArrows: true, scrollbarWidth: 15, arrowSize: 16});
		}});
	}, 100);
	$("input[type='checkbox'], input[type='radio']").ezMark();
	if ((window.isMSIE7 || window.isMSIE8 || window.isMSIE9)) {
		(repeatFunc = function() {
			if (!repeatFunc.content) repeatFunc.content = "";
			if (repeatFunc.content !== document.body.innerHTML) {
				$("select").each(function() {

					if (!this.sbed) {
						this.sbed = true;
						$(this).sb({selectboxClass: "sbox", open: function(sb){
							$(sb[0]).jScrollPane({showArrows: true, scrollbarWidth: 15, arrowSize: 16});
						}});
					}
				});
				$("input[type='checkbox'], input[type='radio']").each(function() {
					if (!this.ezmarked) {
						this.ezmarked = true;
						$(this).ezMark();
					}
				});
				$("button:visible, a.button:visible").each(function() {
					if (!this.resized) {
					  this.style.width = $(this).outerWidth()+"px";
					  this.resized = true;
					}
				});

				repeatFunc.content = document.body.innerHTML;
			}
			setTimeout(repeatFunc, 250);
		})();
	}
	$("body").bind("DOMSubtreeModified", function() {
		setTimeout(function() {
			$("select").sb({selectboxClass: "sbox", open: function(sb){
				$(sb[0]).jScrollPane({showArrows: true, scrollbarWidth: 15, arrowSize: 16});
			}});
		}, 100);
		$("input[type='checkbox'], input[type='radio']").ezMark();
		$("button:visible, a.button:visible").each(function() {
			if (window.isMSIE) {
				this.style.width = $(this).outerWidth()+"px";
			} else {
				this.style.width = this.clientWidth+"px";
			}
		});
	});
	$("button:visible, a.button:visible").each(function() {
		if (window.isMSIE) {
			this.style.width = $(this).outerWidth()+"px";
		} else {
			this.style.width = this.clientWidth+"px";
		}
	});

	$("form span.errormessage").closest("form").find(".errorform").append("<div class='item'>"+$("span.errormessage").html()+"</div>");

	//initializes tooltips globally

	$(".customtooltip").tooltip({
		// tweak the position
		offset: [10, -1],
		// use the "slide" effect
		effect: 'slide'
		// add dynamic plugin with optional configuration for bottom edge
	}).dynamic({ bottom: { direction: 'up', bounce: true } });

	$(".customtooltipbottom").tooltip({
		// tweak the position
		offset: [10, -1],
		// use the "slide" effect
		effect: 'slide',
		tipClass: 'bottomtooltip',
		position: 'bottom center'
		// add dynamic plugin with optional configuration for bottom edge
	}).dynamic({ bottom: { direction: 'down', bounce: false } });

	$(".customtooltipminicart").tooltip({
		// tweak the position
		offset: [0, -1],
		// use the "slide" effect
		effect: 'slide'
		// add dynamic plugin with optional configuration for bottom edge
	}).dynamic({ bottom: { direction: 'up', bounce: true } });

	var initBoxes = null;

	var convertToOverlabel = function(element, content) {
		$(element).wrap("<span class='withLabel'/>");
		$(element).parent().prepend("<label class='overlabel-apply'>"+content+"</label>");
		$("label", $(element).parent()).click(function() {
			$(this).hide();
			$(element).focus();
		}).hover(function() {
			$(this).addClass("hover");
		}, function(){
			$(this).removeClass("hover");
		});

		$(element).blur(function() {
			if ($(this).val().length <= 0) {
				$("label", $(this).parent()).show();
			}
		});
		$(element).focus(function() {
			$("label", $(this).parent()).hide();
		});
	};

	$("label.overlabel, input[type='text'].overlabel, textarea.overlabel").each(function() {
		if (this.nodeName.toUpperCase() == "LABEL") {
			convertToOverlabel($("#"+this.getAttribute("for")), this.innerHTML);
			$(this).remove();
		} else {
			if (!$(this).parent().hasClass("withLabel")) {
				convertToOverlabel(this, this.title);
			}
		}
	});

	(initBoxes = function() {
		// turn on dialogify
		$('a.dialogify').each(function() {
			if (this.dialogified) return true;
			this.dialogified = true;
			$(this).click(function(event) {
				var map = [];
				if (this.getAttribute("rel")) {

					var arr = this.rel.split("|");

					for (var i = 0; i<arr.length; i++ ){
						map[arr[i].split("=")[0]] = arr[i].split("=")[1];

					};

				};
				if (this.getAttribute("href").indexOf('#') >= 0) {
					var el = this.getAttribute("href").replace(location.href.replace(/#(.*)$/gi, ''), '');

					var width = "auto";
					var height = 425;

					if (map["width"] ) {
					    if (map['width'] != 'auto') {
						  width = Number(map['width']);
					    }
						else {
							width = "auto";
						}
					}

					if (map["height"]) {

						   if (map['height'] != 'auto') {
							  height = Number(map['height']);
							}
							else {
								height = "auto";
							}
					}


					$(el).dialog({
						title: this.getAttribute("title"),
						bgiframe: true,
						autoOpen: true,
						modal: true,
						overlay: {
				    		opacity: 0.5,
				     		background: "white"
						},
				    	height: height,
				    	width: width,
				    	resizable: false,

				    	dragStop: function() {
							var pos = jQuery(".ui-dialog").position();
							$(".ie-shadow").css("left", (pos.left + 5) + "px").css("top",(pos.top + 5) + "px");
						},
				    	drag: function() {
							var pos = jQuery(".ui-dialog").position();
							$(".ie-shadow").css("left", (pos.left + 5) + "px").css("top",(pos.top + 5) + "px");
						},
						resizeStop: function() {
							 var $elm = jQuery(".ui-dialog");
							 var pos = $elm.position();

		 				    $(".ie-shadow").width($elm.width()).height($elm.height()).css("left", (pos.left + 5) + "px").css("top",(pos.top + 5) + "px");
						},
				    	close: function(){
							if ( jQuery(".ui-dialog-titlebar-close.customtooltip").length > 0 )	{
							  jQuery(".tooltip").hide();
							}
							$(this).parent().empty().remove();
						}
					});

					window.currentDialog = jQuery(el);

					if (window.isMSIE) {
						setTimeout(function() {
						    var $elm = jQuery(".ui-dialog");
						    var pos = $elm.position();
						    $elm.after("<div class='ie-shadow'></div>");
						    $(".ie-shadow").width($elm.width()).height($elm.height()).css("left", (pos.left + 5) + "px").css("top",(pos.top + 5) + "px");
						}, 100);
						jQuery(el).bind("dialogclose", function(event, ui) {
							$(".ie-shadow").remove();
						});
					}
					jQuery(".ui-dialog-titlebar-close").addClass("customtooltip");
					jQuery(".ui-dialog-titlebar-close").attr("title", app.resources["CLOSE"] );

					$(".ui-dialog-titlebar-close.customtooltip").tooltip({
						// tweak the position
						offset: [10, -1],
						// use the "slide" effect
						effect: 'slide'
						// add dynamic plugin with optional configuration for bottom edge
					}).dynamic({ bottom: { direction: 'up', bounce: true } });
				} else {


					app.dialog.open(this.href, this.getAttribute("title"), map||null);
				}
				event.stopPropagation();
				return false;
			});


		});

		ajaxify();

		if (window.isMSIE7 || window.isMSIE8) {
			var disabledButton = $("button:disabled");
			disabledButton.removeAttr("disabled");
			disabledButton.click(function(event){
				if ($(event.currentTarget).hasClass("disabled")) {
					event.stopPropagation();
					return false;
				}
			});
		}
	})();

	if ((window.isMSIE7 || window.isMSIE8)) {
		(repeatFunc = function() {
			if (!repeatFunc.content) repeatFunc.content = "";
			if (repeatFunc.content !== document.body.innerHTML) {
				initBoxes();

				repeatFunc.content = document.body.innerHTML;
			}
			setTimeout(arguments.callee, 500);
		})();
	}

	$("body").bind("DOMSubtreeModified", function() {
		initBoxes();
	});

	jQuery(".horizontal-site-shadow").each(function () {
		document.body.appendChild($(this).remove()[0].cloneNode(true));
	});

	$('.sbsearcharea').hide();
	$('.sbsearchpink').hide();

	$('#regionchange').mouseenter(showRegionChanger);
	$('#regionchange').mouseleave(hideRegionChanger);
	$('.sbpic_search').click(showSearchRegion);
	$('.sbsearchpink').click(hideSearchRegionOnMouseLeave);
	$('.searchbox').mouseenter(showSearchRegion);

	if (isOtherCountries()) {
		window.isOtherCountries = true;
		document.getElementsByTagName("html")[0].className = document.getElementsByTagName("html")[0].className + " other";
	}
});

var tweet_interval;
var old_tweet = 0;
var current_tweet = 0;

function tweetInit() {
  var tweets = $('div.tweet');
  tweet_count = 10;
  if (tweets != null) {
  tweet_interval = setInterval(tweet_rotate,7500); //time in milliseconds
  }
}

function tweet_rotate() {
  current_tweet = (old_tweet + 1) % tweet_count;
  $('div.tweet:eq(' + old_tweet + ')').animate({top: -50},'slow', function() {
    $(this).css('top','50px');
  });
  $('div.tweet:eq(' + current_tweet + ')').show().animate({top: 0},'slow');
  old_tweet = current_tweet;
}

function ajaxify() {
	$("a.ajax").each(function(){
		if (this.ajaxified) return true;

		this.ajaxified = true;
		$(this).click(function(event) {
			var target = null;
			var callback = function(){};
			if (this.getAttribute("onload")) {
				var load = this.getAttribute("onload");
				callback = function() {
					try {
						eval(load);
					} catch(e) {
						alert(e.message);
					};
				};
			}
			if (this.rel) {
				target = $(this.rel);
			}
			if (target) {
				$(target).load(this.href, callback);
			} else {
				$.get(this.href, callback);
			}
			event.stopPropagation();
			return false;
		});
	});
}

function capitalize(n)  {
	var out = "";
	var wasSpace = false;
	n = n.toLowerCase();
	for (var i=0;i<n.length;i++) {
		var char = n.charAt(i);
		if (i==0) {
			char = char.toUpperCase();
		}
		if (wasSpace) {
			char = char.toUpperCase();
			wasSpace = false;
		}
		if (char == " ") {
			wasSpace = true;
	    } else {
	    	wasSpace = false;
	    }
	    out = out + char;
	}
	return out;
}

function submitNewsletter(form){
	var ret = true;
	var $error = $('.localerrorform');
	if ($('#dwfrm_newsletter_email').val() != $('#dwfrm_newsletter_emailconfirm').val()) {
		$('#dwfrm_newsletter_emailconfirm').addClass('validation-error');
		$(".labeltext:contains('Email:')").addClass('errorlabel');
		ret = false;
	}
	if ($('#dwfrm_newsletter_email').val() == "") {
		$(".labeltext:contains('Email:')").addClass('errorlabel');
		$('#dwfrm_newsletter_email').addClass('validation-error');
		ret = false;
	}
	if ($('#dwfrm_newsletter_emailconfirm').val() == "") {
		$(".labeltext:contains('Confirm Email:')").addClass('errorlabel');
		$('#dwfrm_newsletter_emailconfirm').addClass('validation-error');
		ret = false;
	}
	if ($('#dwfrm_newsletter_firstname').val() == "") {
		$(".labeltext:contains('First Name:')").addClass('errorlabel');
		$('#dwfrm_newsletter_firstname').addClass('validation-error');
		ret = false;
	}
	if ($('#dwfrm_newsletter_lastname').val() == "") {
		$(".labeltext:contains('Last Name:')").addClass('errorlabel');
		$('#dwfrm_newsletter_lastname').addClass('validation-error');
		ret = false;
	}
	if ($('#dwfrm_newsletter_countries_country').val() == "") {
		$(".labeltext:contains('Country:')").addClass('errorlabel');
		$('.selectbox.country a').addClass('validation-error');
		ret = false;
	}

	if (!ret) {
		$error.html('Error: Please correct the highlighted form fields below.');
    	return false;
	} else {
		$error.html('');
		$('#dwfrm_newsletter_email').removeClass('validation-error');
		$('#dwfrm_newsletter_emailconfirm').removeClass('validation-error');
		$(".labeltext:contains('Email:')").removeClass('errorlabel');
		$(".labeltext:contains('Confirm Email:')").removeClass('errorlabel');
		$(".labeltext:contains('First Name:')").removeClass('errorlabel');
		$(".labeltext:contains('Last Name:')").removeClass('errorlabel');
		$('#dwfrm_newsletter_firstname').removeClass('validation-error');
		$('#dwfrm_newsletter_lastname').removeClass('validation-error');
		$(".labeltext:contains('Country:')").removeClass('errorlabel');
		$('.selectbox.country a').removeClass('validation-error');
	};

	$.post(form.action, $(form).serialize()+'&'+$('button', form)[0].name+'=btn_register', function(data, status, request){
		try{
			$('#dialogcontainer').html(data).parent().addClass('flashmessage');
			// with MSIE resize the shadow:
			window.currentDialog.trigger('dialogresizestop');
			// For IE drop Shadow:
			resizeDialogWindow();
		} catch(ex){
			alert(ex.message);
			$('#dialogcontainer').html(data);
		}
	});
}

function showRegionChanger() {
	$('#regionchange .popup').show();
}

function hideRegionChanger() {
	$('#regionchange .popup').hide();
}

var closeSearchFlag = false;

function showSearchRegion(e) {
	e.preventDefault();
	$('.sbsearcharea').show();
	$('.sbsearchpink').show();
	$('.sbsearchbox-inputfield').val("Enter keyword or item");
	$('.sbpic_search').hide();
	closeSearchFlag = false;
	return false;
}

function hideSearchRegionOnMouseLeave() {
	closeSearchFlag = true;
	window.setTimeout('hideSearchRegion()',200);
}

function hideSearchRegion() {
	$('.sbsearcharea').hide();
	$('.sbsearchpink').hide();
	$('.suggestions').hide();
	$('.sbpic_search').show();
	closeSearchFlag = false;
	return false;
}

function resizeDialogWindow() {
	var $elm = jQuery(".ui-dialog");
	var pos = $elm.position();
	$(".ie-shadow").width($elm.width()).height($elm.height()).css("left", (pos.left + 5) + "px").css("top",(pos.top + 5) + "px");
}

function getExpirationDate(){
	var ablauf = new Date();
	var inXTagen = ablauf.getTime() + (86400000);
	ablauf.setTime(inXTagen);
	ablauf.toGMTString()
	return ablauf;
}

function isOtherCountries() {
	var cookies = document.cookie.split(";");
	for(var i=0;i<cookies.length;i++) {
		var val = cookies[i].split("=");
		var name = val[0];
		name = name.replace(/ /,'');

		if (name == "language2") {

			if (val[1] == "DvF_OTHER") {
				return true;
			}
		}
	}
	return false;
}

var storedMargin = parseInt($('.footercontainer').css('margin-top'));
var idvfOpened = false;

function showIdvfContent() {
	if (window.isMSIE) {
		$('.idvf').show(10, function(){
			$('.idvf .closer')[0].style.zoom = 1;
		});
	} else {
		$('.idvf').fadeIn(600);
	}
}

function hideOverlayAndMoveImages(){
	if (window.isMSIE) {
		$('#idvf-overlay .insideDVF').hide();
	} else {
		$('#idvf-overlay .insideDVF').fadeOut(200);
	}

	$('#idvf-overlay').addClass('opened');
	var duration = 1000;
	$('#idvf-overlay .image-0').animate({
		left: -632,
		bottom: 179
	}, duration);
	$('#idvf-overlay .image-1').animate({
		left: -436,
		bottom: 179
	}, duration);
	$('#idvf-overlay .image-2').animate({
		left: -240,
		bottom: 179
	}, duration);
	$('#idvf-overlay .image-3').animate({
		left: -44,
		bottom: 179
	}, duration, function(){
		showIdvfContent();
	});
}

function openInsideDvF() {
	if (idvfOpened) return;
	idvfOpened = true;
	// enlarge the footer container
	$('.footercontainer').animate({
		marginTop: "-200px",
		paddingTop: "200px"
	}, 800);
	hideOverlayAndMoveImages();
}

// inside DvF closing
// ------------------
function showIdvfOverlay() {
	$('#idvf-overlay').removeClass('opened');
	if (window.isMSIE) {
		$('#idvf-overlay .insideDVF').show();
	} else {
		$('#idvf-overlay .insideDVF').fadeIn(400);
	}
}

function restoreIdvfOverlay() {
	var duration = 1000;
	$('#idvf-overlay .image-0').animate({
		left: 90,
		bottom: 0
	}, duration);
	$('#idvf-overlay .image-1').animate({
		left: 103,
		bottom: 7
	}, duration);
	$('#idvf-overlay .image-2').animate({
		left: 116,
		bottom: 14
	}, duration);
	$('#idvf-overlay .image-3').animate({
		left: 116,
		bottom: 14
	}, duration);
	$('.footercontainer').animate({
		marginTop: 0,
		paddingTop: 0
	}, 200, function(){
		showIdvfOverlay();
	});
}

function closeInsideDvF() {
	if (!idvfOpened) return;
	idvfOpened = false;
	if (window.isMSIE) {
		$('.idvf').hide();
		restoreIdvfOverlay();
	} else {
		$('.idvf').fadeOut(900, function(){ //400
			restoreIdvfOverlay();
		});
	}
}

function checkOverlayClick() {
	if (idvfOpened) {
		return truelexer;
	}
	return false;
}
