$(document).ready(function(){

	/**
	 * Javascript to be run once the DOM has been loaded.
	 *
	 * Used on ALL pages.
	 *
	 */

	/**
	 * Default language vars.
	 */
	VFLang.listShowMore		= (VFLang.listShowMore 		? 	VFLang.listShowMore 		: 'Show more');
	VFLang.listShowLess		= (VFLang.listShowLess 		? 	VFLang.listShowLess 		: 'Show less');

	/**
	 * Check whether cookies are enabled, display warning message otherwise.
	 */
	date = new Date();
	chkcookie = (date.getTime() + '');
	document.cookie = "chkcookie=" + chkcookie + "; path=/";
	if (document.cookie.indexOf(chkcookie, 0) < 0) {
		$('#noCookiesMsgDiv').show();
		if ($('.divBannerHeader').length > 0 && $('.divBannerHeader').offset()) {
			$('.divBannerHeader').css("top", $('.divBannerHeader').offset().top + $('#noCookiesMsgDiv').outerHeight());
		}
	}

	/**
	 * Enable print buttons
	 */
	$('ul#page-functions li.print').show();
	$('ul#page-functions li.print a').click(function() {
		window.print();
		return false;
	});

	/**
	 * Handle premium shop 1st level menu highlighting
	 */
	if (typeof(subShopMenuHighlightingSelection) != 'undefined') {
		// check if premium shop as li#li1 is only existing there
		if ($("ul.ulNavigationMain li#li1").length > 0) {
			$("ul.ulNavigationMain li.liActive").removeClass("liActive");
			$("ul.ulNavigationMain li#li" + subShopMenuHighlightingSelection).addClass("liActive");
		}
	}

	/**
	 * Turn regular HTML buttons into graphical buttons (CSS styled links)
	 * and apply javascript onclick event handling to them.
	 */
	// Iterate through all submit buttons on page
	var buttons = $("div.actions :submit").each(function() {

		// Retrieve content, classes and id of button
		var fstext = $(this).val();
		var fsclass = $(this).attr("class");
		var fsid = $(this).attr("id");

		// In case of submit button being surrounded by DIV with class "actions":
		$(this).parent('div.actions')

		// Add button-like image as FIRST element of surrounding DIV
		.prepend('<a ' + (fsid ? 'id="' + fsid + '"' : '') + ' class="' + fsclass + /*'" title="' + fstext +*/ '" href="#"><span><b>' + fstext + '</b></span></a>')

		// Apply onclick-submit event handler to this new FIRST element
		.children(':first').click(function() {
			if (fsclass.indexOf("disabled") < 0 && fsclass.indexOf("Disabled") < 0) {
				$(this).parents('form').submit();
			}
			return false;
		}).bind("focus", function() {
			if (fsclass.indexOf("disabled") >= 0 || fsclass.indexOf("Disabled") >= 0) {
				$(this).blur();
			}
		});

		// Hide original submit button
		$(this).hide();

		// In case of invisible submit input button, IE won't submit a form when hitting 'Enter' in a form field.
		// Only clicking the js button will trigger form submission. The following lines re-enable standard behaviour.
		if ($.browser.msie) {
			$(this).parents('form').find("input[type='text']," +
					"input[type='password']," +
					"input[type='radio']," +
					"input[type='checkbox']," +
					"input[type='file']," +
					"input[type='submit']," +
					"select").bind("keypress", function(e) {
						if (e.keyCode == 13) {
							$(this).parents('form').submit();
						}
					});
		}

	});



	/**
	 * Initialize popup CSS interface
	 */
	var popupCssInterface = ".popupLink";
	if ($(popupCssInterface).length) {
		$(popupCssInterface).each(function() {
			var classClassIndicator = "popupLink_";
			var classUrlParamsIndicator = "popupLinkUrlParams_";
			var classReloadParamsIndicator = "popupLinkReloadParams_";
			var classes = $(this).attr("class").split(" ");
			var popupClasses = '';
			var urlParams = '';
			var reloadParams = '';
			var targetUrl = $(this).attr("href");
			for (var i = 0; i < classes.length; i++) {
				if (classes[i].substr(0, classClassIndicator.length) == classClassIndicator) {
					popupClasses += ' ' + classes[i].substr(classClassIndicator.length);
				}
				if (classes[i].substr(0, classUrlParamsIndicator.length) == classUrlParamsIndicator) {
					urlParams += classes[i].substr(classUrlParamsIndicator.length);
				}
				if (classes[i].substr(0, classReloadParamsIndicator.length) == classReloadParamsIndicator) {
					reloadParams += classes[i].substr(classReloadParamsIndicator.length);
				}
			}
			if (urlParams != '') {
				if (targetUrl.indexOf('?') != -1) {
					targetUrl = targetUrl.replace(/\?/, "?" + urlParams + "&");
				} else if (targetUrl.indexOf('#') != -1) {
					targetUrl = targetUrl.replace(/#/, "?" + urlParams + "#");
				} else {
					targetUrl = targetUrl + "?" + urlParams;
				}
			}
			$(this).inlinePopup({
				isAjax : $(this).hasClass("popupLinkAjax"),
				isIframe : $(this).hasClass("popupLinkIframe"),
				isDiv : $(this).hasClass("popupLinkDiv"),
				isOnLoad : $(this).hasClass("popupLinkOpenOnLoad"),
				isRefreshIfIframeChanged : $(this).hasClass("popupLinkRefreshIfIframeChanged"),
				isReloadWithoutParamsIfIframeChanged : $(this).hasClass("popupLinkReloadWithoutParamsIfIframeChanged"),
				reloadParams : reloadParams,
				targetUrl : targetUrl,
				isModal : $(this).hasClass("popupLinkModal"),
				isButtonBarTop : ($(this).hasClass("popupLinkModal") || $(this).hasClass("popupLinkButtonsDisabled") || $(this).hasClass("popupLinkButtonsTopDisabled") ? false : true),
				isButtonBarBottom : ($(this).hasClass("popupLinkModal") || $(this).hasClass("popupLinkButtonsDisabled") || !$(this).hasClass("popupLinkButtonsBottomEnabled")  ? false : true),
				isPrintButtons : !$(this).hasClass("popupLinkPrintButtonsDisabled"),
				isRefocussing : !$(this).hasClass("popupLinkRefocussingDisabled"),
				classes : popupClasses
			});
		});
	}



	/**
	 * Initialize popup CSS interface for non-link/standalone popups
	 * To avoid conflicts, only the first popup on page will be used (:first)
	 */
	var popupCssInterfaceStandalone = "div.popupLinkDivLayerStandalone:first";
	if ($(popupCssInterfaceStandalone).length) {
		$(popupCssInterfaceStandalone).each(function() {
			$('<a></a>').inlinePopup({
				isDiv : true,
				isOnLoad : true,
				targetUrl : '#' + $(this).attr("id"),
				isModal : $(this).hasClass("popupLinkModal"),
				isButtonBarTop : ($(this).hasClass("popupLinkModal") || $(this).hasClass("popupLinkButtonsDisabled") || $(this).hasClass("popupLinkButtonsTopDisabled") ? false : true),
				isButtonBarBottom : ($(this).hasClass("popupLinkModal") || $(this).hasClass("popupLinkButtonsDisabled") || !$(this).hasClass("popupLinkButtonsBottomEnabled")  ? false : true),
				isPrintButtons : !$(this).hasClass("popupLinkPrintButtonsDisabled")
			});
		});
	}



	/**
	 * Bind tracking to all neccessary links
	 */
	$("a.triggerTracking").bind("click", function() {
		triggerTrackingRequest("", "");
	});



    /**
     * Hides list items in long lists and adds a link to show them again.
     *
     */

    /* Hide list items */
    $("ul.ulToggleable li.toggleFromHere").hide().nextAll().hide();

    /* Add toggling link to all lists with hidden list elements */
    $("ul.ulToggleable:has(li.toggleFromHere)")
      .after('<p><a href="#">' + VFLang.listShowMore + '</a></p>')
      .next().children().toggle(
           function () {
               $(this).parent("p").prev("ul.ulToggleable").children("li.toggleFromHere").show().nextAll().show();
               $(this).html(VFLang.listShowLess);
               return false;
           },
           function () {
               $(this).parent("p").prev("ul.ulToggleable").children("li.toggleFromHere").hide().nextAll().hide();
               $(this).html(VFLang.listShowMore);
               return false;
           }
      );


    /**
     * Optimize text repository key display in debug mode.
     * => Move key from button's value attribute to it's title attribute.
     *
     */
	$("input:submit, input:reset, input[type='button']").each(function(){
		if ($(this).attr("value").match("^<span class=debugToolTip")) {

			// Get string and key from button's value attribute
			var debugText = $(this).attr("value");
			var string = $(debugText).text();
			var key = $(debugText).attr("title");

			// Display plain value attribute and debug message in title attribute
			$(this).attr("value", string);
			$(this).attr("title", key);
		}
	});


	/**
     * Last viewed proposition carousel ("candyrack").
     *
     */

	$(".jcarousel-skin-lastviewed li:not(.noContent)").hover(
			function () {
				$(this).addClass("hover");
				$(this).bind("click", function() {
					window.location=$(this).find("a").attr("href");
					return false;
				});
			},
			function () {
				$(this).removeClass("hover");
				$(this).unbind("click");
			}
	);

	$("#lastviewedCarousel-vertical").jcarousel({
		vertical: true,
		scroll: 3,
		initCallback: function carouselIniniated() {
			$(".loadingAnimation").css({
				display:"none"
			});
		}
	});

	$("#lastviewedCarousel-horizontal").jcarousel({
		vertical: false,
		scroll: 4,
		initCallback: function carouselIniniated() {
			$(".loadingAnimation").css({
				display:"none"
			});
		}
	});


	/**
	 * Vertical centering for buttons in a message box
	 *
	 */

	$(".message .button").each(function() {
		var marginTop = (($(this).parent().height() - $(this).height()) / 2) + 4;
		$(this).css("margin-top", marginTop);
	});


    /**
     * Reset button functionality for find bar section (find_bar.jsp)
     */
	
	// bind click event for reset
    $("div.divProductOverviewSearch a#findBarReset").bind("click", function() {
        $("form#findForm").find(':input').each(function() {
            switch(this.type) {
            case 'select-one':
                $(this).val('');
                break;
            case 'checkbox':
                this.checked = false;
            }
        });
        $("form#findForm").submit();
        return false;
    });

});
