// everything that needs to be done after the complete document has been loaded
jQuery(document).ready(
	function()
	{
	ieVersion = getInternetExplorerVersion();
	
	hover1Timeout = 0;
	hover2Timeout = 0;
	scrollElementInterval = 0;
	
	eventAddingForDocument();
	eventAddingForDocumentAndAjax();
	
	checkForAnchorLink();
	checkForClickedLink();

	}
);

// event adding that is not also needed in Ajax-content
function eventAddingForDocument() {

	// add hover effects for main navigation - not pure CSS because of wanted delay (only for modern browsers since IE6 has problems)
	if (ieVersion > 6 || ieVersion == -1) {
		jQuery("#mainMenu>li").hover(function(){showNav(this, 1);}, function(){hideNav(this, 1);});
		jQuery("#mainMenu>li>ul>li").hover(function(){showNav(this, 2 );}, function(){hideNav(this, 2);});
		//jQuery("#mainMenu>li>div").hover(function(){showNav(this, 2 );}, function(){hideNav(this, 2);});
	}
	
	// functionality for the last visited box
	jQuery("#lastVisitedBox2").each(function(){jQuery("#LastVisitedProducts").toggleClass("scrollHandleOpend").slideToggle("slow");});
	jQuery("#lastVisitedBox2").click(function(){jQuery("#LastVisitedProducts").slideToggle("slow");jQuery(this).toggleClass("headline3");});

	// price slider initialization
	jQuery(".priceRangeSlider").each(function(){initPriceRangeSlider(this);});
	
	// show/hide/scroll functionality for the leftpanel guided search (filter navigation)
	jQuery("#guidedSearch .scroll-pane").jScrollPane({scrollbarWidth:12, scrollbarBorder:1, scrollLineHeight:18, scrollbarMargin:0, animateTo:true, animateInterval:100, animateStep:4, showArrows:true, arrowSize:0});
	jQuery("#guidedSearch div.scrollHandle").not(jQuery("div.scrollHandleOpend")).next().slideToggle(0);
	jQuery("#guidedSearch div.scrollHandle").click(function()
		{	
			var current = jQuery(this).context;

			jQuery("#guidedSearch div.scrollHandle").each(function()
			{   
				if ((jQuery(this).attr("class").search(/\bscrollHandleOpend\b/)) != -1)
				{
					jQuery(this).removeClass("scrollHandleOpend").next().animate({height: "hide", opacity: "hide"}, 'slow');
				}
				else
				{	
					var x = jQuery(this).context;
					if (current === x)
					{
						jQuery(this).toggleClass("scrollHandleOpend").next().slideToggle('slow');
					}

				}
			})
		});
	jQuery("#closeAllScroll").click(function(){jQuery("#guidedSearch div.scrollHandle").each(function(){ if ((jQuery(this).attr("class").search(/\bscrollHandleOpend\b/)) != -1) {alert("9c");jQuery(this).removeClass("scrollHandleOpend").next().animate({height: "hide", opacity: "hide"}, 0);}});});

	
	
	jQuery("#rightHelp ul>li>h4").click(function(){jQuery(this).next().slideToggle();});
	
	jQuery(".selectPrivateCompany>select").each(checkForCompanySalutation).change(checkForCompanySalutation);

	jQuery("#WishlistSelectForm_WishlistId").change(WishlistSelect);
	
	/* jQuery("#addToWishlist").click(function(){return updateMiniWishlist(this)}); */
	
	// do the stuff that is needed only for IE6
	if (ieVersion == 6) {
		eventAddingForDocumentIE6();
	}		
}
function closeScroll(content) {
	alert("7");
	//jQuery("#guidedSearch div.scrollHandle").each(function(){alert("8");if ((jQuery(this).attr("class").search(/\bscrollHandleOpend\b/)) != -1) {alert("9");jQuery(this).removeClass("scrollHandleOpend").next().slideUp(0);}});
	alert("10");
}
// combine all the event adding that needs to be done after document load and for AJAX-content
function eventAddingForDocumentAndAjax(context) {

	// initialize the cross selling products slider
	if (jQuery(".accessoriesTipsSlide").size()) {
		jQuery(".accessoriesTipsSlide", context).jFlow({
			slides: "#accessoriesTips",
			width: "100%",
			height: "160px",
			duration: 500
		});
	}

	// show/hide details in Product-Detail (this way clickable over the whole line when closed)
	jQuery("p.detailLabel", context).toggle(
			function () {
				jQuery(this).next().css({display: "none"});
				jQuery(this).removeClass("opend");							
			},			
			function() {
				jQuery(this).addClass("opend");
				jQuery(this).next().css({display: "block"});
			}
		);
	
	// show/hide all product details links functionality
	jQuery("#showAllDetailsLinks", context).bind(
		"click", function(event) {jQuery("p.detailLabel", context).not(".opend").click(); event.preventDefault();}		
	);
	jQuery("#hideAllDetailsLinks", context).bind(
		"click", function(event) {jQuery("p.opend", context).click(); event.preventDefault();}		
	);
	
	// show/hide functionality for Hints (Tool Tipps)
	jQuery(".hintImage", context).hover( function(){hintShow(this);}, function(){hintHide();} );	
	
	// add additional products to basket
	if (jQuery("#ProductDetailForm").size()) {
		jQuery("div.addAdditionalProduct :checkbox", context).change(function(){syncCheckboxValueToForm(this, "#ProductDetailForm");});
	} else {
		// use onclick instead of onchange because of unfortunate IE behaviour (onchange occurs only if element looses focus)
		jQuery("#basketStepM1 div.addAdditionalProduct :checkbox", context).click(function(){directAddToBasket(this);});
	}
	
	// add handling for forms submitted via Ajax (uses the jQuery Form Plugin)
	jQuery("form.ajaxForm", context).each(function(){addAjaxFormHandler(this);});	
	addVariationsFormHandler(context);

	// do the stuff for IE6
	if (ieVersion == 6) {
		eventAddingForDocumentAndAjaxIE6(context);
	}
}

// all the event adding that needs to be done extra for IE6 after document load
function eventAddingForDocumentIE6(context) {
	
	// resolve IE6 flicker bug (http://www.jamescrooke.co.uk/articles/solving-ie6-flicker-bug)
	try {document.execCommand("BackgroundImageCache", false, true);} catch(err) {}

	// add hover effect for the main navigation in IE6 + iframe against select elements
	jQuery("#mainMenu, #mainMenu ul.subMenu div.subMenuTop").children().hover(
		function(){jQuery(this).addClass("hoverIE6");killSelectBeneathNav(this);},
		function(){jQuery(this).removeClass("hoverIE6");jQuery(".killSelectForNav", this).remove();}
	);
	
	// functionality for the product adviser select box
	jQuery("div.selectList").hover(function(){jQuery("ul", this).show();}, function(){jQuery("ul", this).hide();});	
	
}
// all the event adding that needs to be done extra for IE6 after document load and for AJAX-content
function eventAddingForDocumentAndAjaxIE6(context) {

	// add hover effect for nonlink element p.attributeGroup in IE6 
	jQuery("p.detailLabel", context).hover(
		function(){jQuery(this).addClass("hoverIE6");},
		function(){jQuery(this).removeClass("hoverIE6");}
	);
}


// apply jQuery stuff on layerContent after loading
function doWhenThickBoxContentReady(context) {	
	//console.log("*** the layer is ready ***");
	addThickboxFormHandler(context); // extended ThickBox to load form submit response in ThickBox
	jQuery(".countedInput", context).keyup(updateInputCounter).each(updateInputCounter);
	checkForRatingSuccess();
	if (jQuery("#productAdviserFrame").size()) {
		jQuery("#productAdviserFrame").height(parseInt(jQuery("#TB_ajaxContent").height(), 10)-30);
	}	
	if (jQuery("#contentProductCompare").size()) {
		if (ieVersion > 6 || ieVersion == -1) {
			jQuery("#contentProductCompare").height(jQuery("#TB_ajaxContent").height()-90);
		}
	}
    if (jQuery("#productInformationMin").size()) {
		if (ieVersion > 6 || ieVersion == -1) {
			jQuery("#productInformationMin").height(jQuery("#TB_ajaxContent").height()-58);
		}
	}
}

// functionality to hide the main navigation with delay - no longer just CSS
function showNav(element, level) {
	if (level === 1) {
		clearTimeout(hover1Timeout);
		jQuery("#mainMenu>li.menuHover").removeClass("menuHover");
	} else {
		clearTimeout(hover2Timeout);
		jQuery("#mainMenu>li>ul>li.menuHover").removeClass("menuHover");
	}
	if (level === 1) {
		hover3Timeout = setTimeout( function(){jQuery(element).addClass("menuHover");}, 500);
	} else {
		jQuery(element).addClass("menuHover");
	}
}
function hideNav(element, level){
	if (level === 1) {
		clearTimeout(hover3Timeout);
		hover1Timeout = setTimeout( function(){jQuery(element).removeClass("menuHover");}, 200);
	} else {
		hover2Timeout = setTimeout( function(){jQuery(element).removeClass("menuHover");}, 200);
	}
}

// add iframe beneath sub categories navigation to fight select elements
function killSelectBeneathNav(element) {
	element = jQuery(element);
	var elementUL = element.children("ul");
	if (elementUL.length > 0) {
		element.append("<iframe class='killSelectForNav' src='"+webroot+"/js/empty.html' frameborder='0' style='position: absolute; background: yellow;'></iframe>");
		jQuery(".killSelectForNav", element).css({left: elementUL.offset({lite: true, relativeTo:element}).left+1, top: elementUL.offset({relativeTo:element}).top, width: elementUL.width()+2, height: elementUL.height()+2 });
	}
}

// price slider functionality
function initPriceRangeSlider(theSlider) {
	var minP = parseInt(jQuery(".minPrice_limit", theSlider).val(), 10);
	var maxP = parseInt(jQuery(".maxPrice_limit", theSlider).val(), 10);
	var minS = parseInt(jQuery(".minPrice_in", theSlider).val(), 10);
	var maxS = parseInt(jQuery(".maxPrice_in", theSlider).val(), 10);
	//console.log(minP, minS, maxS, maxP);
	
	if ( !isNaN(minP) && !isNaN(maxP) && !isNaN(minS) && !isNaN(maxS) && !(maxP-minP === 0) ) {
		var minSpos = Math.round((118*(minS-minP))/(maxP-minP));
		var maxSpos = Math.ceil((118*(maxS-minP))/(maxP-minP));

		jQuery(".slider", theSlider).Slider(
			{
				accept : '.indicator',
				restricted: true,
				onSlide : function(procx, procy, x, y) {
					price = parseInt(minP + parseInt((maxP-minP) * x/118, 10), 10);
					jQuery((this.SliderIteration === 0 ? ".minPrice_out": ".maxPrice_out"), theSlider).val(price);
					jQuery((this.SliderIteration === 0 ? ".minPrice_label": ".maxPrice_label"), theSlider).html("&euro; "+price+",-");
				},
				values: [[minSpos,0],[maxSpos,0]]
			}
		);
	} else {
		jQuery(theSlider).parents("form").remove();
	}
}

// show/hide functions for Hints (Tool Tipps)
function hintShow(element) {
	//if (typeof element == 'string') { element = jQuery(element); };
	imagePos = jQuery(element).offset();
	imagePos.left = imagePos.left + jQuery(element).width() + 2;
	jQuery("body").append("<div id='hintHover'></div>");
	jQuery("#hintHover").css({left: imagePos.left, top: imagePos.top}).html(jQuery(element).next().html()).show();
	if (ieVersion > -1 && ieVersion < 7) {
		jQuery("body").append("<iframe id='killSelectElement' src='"+webroot+"/js/empty.html' frameborder='0'></iframe>");
		jQuery("#killSelectElement").css({left: imagePos.left, top: imagePos.top, width: jQuery("#hintHover").width(), height: jQuery("#hintHover").height() });
	}
}
function hintHide() {
	jQuery("#hintHover").remove();
	jQuery("#killSelectElement").remove();	
}

function updateMiniWishlist (element) {
	
	// jQuery("#wishlistStatus").load(jQuery(element).attr("href"));
	jQuery.get(jQuery(element).attr("href"), function(data){ 
	
		if (data == "Login") {
			jQuery("#wishlistBox").css({ display: "block" });
		}
		else {
			jQuery("#wishlistStatus").html(data);
			jQuery("#wishlistInfo").css({ display: "block" });
		}
	});
	return false;
}

// adds a product direct to the basket using Ajax
function directAddToBasket(checkboxElement) {
		
	/* 	Disable all remaining 'additionalProduct' checkboxes so that it is not
	 * 	possible to add multiple additional products at the same time because
	 *	this might cause ORMExceptions due to concurrent manipulation of one
	 *	and the same BasketPO.
	 *
	 *	They will get enabled again once the AJAX call for adding the product
	 *	to the basket is finished.
	 */
	 jQuery('input[name=AddAdditionalProduct]').attr('disabled', true);
	 var theElement = jQuery(checkboxElement);
	 var parentElement = theElement.parents("div.addAdditionalProduct");
	 parentElement.load(
		theElement.attr("alt"), 
		function(data){
			jQuery("#miniBasketInformation").html(jQuery("div.directMiniBasketInformation", data).html());
			
			jQuery('input[name=AddAdditionalProduct]').attr('disabled', false);
		}
	 );
}

// copys the value of a checked checkbox with a hidden input in the target form
function syncCheckboxValueToForm(checkboxElement, toForm) {
	var theElement = jQuery(checkboxElement);
	var theForm = jQuery(toForm);
	if (theElement.attr("checked")) {
		jQuery("<input type=\"hidden\" id=\""+ theElement.attr("id")+"_H" +"\" name=\""+ theElement.attr("name") +"\" value=\""+ theElement.val() +"\" />").prependTo(theForm);
		//theElement.clone().attr({type: "hidden", id: theElement.attr("id")+"_H"}).prependTo(theForm); // if it wasn't for the IE
	} else {
		jQuery("#"+theElement.attr("id")+"_H").remove();
	}
}
// function for add more input fields
function addEmail() {
	var theForm = jQuery("#emailTo");
	jQuery("<label></label><input id=\"recommend_EMailTo\" name=\"recommend_EMailTo\" value=\"\" class=\"inputText inputTextSize2\" maxlength=\"50\" />").appendTo(theForm);
}
	
// hide/show relevant input fields for private vs. company addresses
// context is the parent fieldset of the select box for the gender selection
function checkForCompanySalutation() {
	var context = jQuery(this).parents("fieldset");
	var addressAddition = jQuery(".inputAddressAddition", context);
	if (this.value == "FI"){
		jQuery(".companyOnly", context).show();
		jQuery(".privateOnly", context).hide();
		if (addressAddition.val() === "" ){
			addressAddition.val("z. Hd. ");
		}		
	} else {
		jQuery(".privateOnly", context).show();
		jQuery(".companyOnly", context).hide();
		if (addressAddition.val() == "z. Hd. " ){
			addressAddition.val("");
		}		
	}
}


// generic textarea input counter
function updateInputCounter(){
	var msg = jQuery(this);
	var messageMaxLength = jQuery(this).attr("maxlength");
	if (msg.val().length > messageMaxLength) {
		if (msg.attr("lastText") !== null) {	
			msg.val(msg.attr("lastText"));
		}
	}
	msg.attr("lastText", msg.val());
	jQuery("#"+msg.attr("id")+"_counter").text(""+(messageMaxLength - msg.val().length));
}


// add the handling for general forms submitted via Ajax
function addAjaxFormHandler(theForm){
	var contextDiv = jQuery(theForm).parent();
    var options = { 
        target:			contextDiv,   // target element to be updated with server response
        beforeSubmit:	function(){loadingMsg(contextDiv);},  // pre-submit callback 
        success:		responseAjaxForm  // post-submit callback 
    };
    // bind to the form's submit event 
    jQuery("form.ajaxForm", contextDiv).ajaxForm(options);
}
// post-submit callback 
function responseAjaxForm(responseText, statusText)  {
	jQuery("form.ajaxForm", this).each(function(){addAjaxFormHandler(this);});
}


// add the handling for forms submitted within a ThickBox (the response will be shown in the ThickBox too)
// jQuery Form Plugin - http://www.malsup.com/jquery/form/
function addThickboxFormHandler(context){ 
    var options = { 
        target:			'#TB_ajaxContent',   // target element to be updated with server response
        beforeSubmit:	submitThickBoxForm,  // pre-submit callback 
        success:		responseThickBoxForm  // post-submit callback 
    };
    // bind to the form's submit event 
    jQuery("form.thickboxForm", context).ajaxForm(options);
}
// pre-submit callback 
function submitThickBoxForm(formData, jqForm, options) {
	jQuery('#TB_load').show(); 
    return true; 
} 
// post-submit callback 
function responseThickBoxForm(responseText, statusText)  {	
	jQuery("#TB_load").hide();	
	tb_init("#TB_ajaxContent a.thickbox");		// bind ThickBox to a.thickbox links
	doWhenThickBoxContentReady(this);
}

// add the handling for variation products forms submitted via Ajax
function addVariationsFormHandler(context){
    var options = { 
        target:			"#productDetail",   // target element to be updated with server response
        beforeSubmit:	submitVariationsForm,  // pre-submit callback
        success:		responseVariationsForm  // post-submit callback 
    };
    // bind to the form's submit event 
    jQuery("form#variationsForm", context).ajaxForm(options);
}
// pre-submit callback 
function submitVariationsForm(formData, jqForm, options) {
	jQuery("select", jqForm).attr("disabled", "disabled");
    return true; 
} 
// post-submit callback 
function responseVariationsForm(responseText, statusText)  {
	eventAddingForDocumentAndAjax(this);
}


// prevent rating submission if no rating is selected
function submitRating() {
	if (jQuery("#addRating input[type=radio]:checked").size() == 1) {
		return true;
	} else {
		jQuery("#submitRatingError").css("display","block");
		return false;
	}
}

// check for rating success and update the rating on product detail page if so
function checkForRatingSuccess(ratingURLs)  {
	if (jQuery("#ratingSuccess").length == 1)
	{
		jQuery("#rating").load(jQuery("#ratingSuccess").attr("title"),{}, function(){tb_init("#rating a.thickbox");});
	}
} 


// this function creates the link including the parameters for the product compare to be called in a thickbox layer 
function compareProducts(pipelineUrl) {
	pipelineUrl = pipelineUrl+"?height="+(jQuery(window).height()-140)+"&width="+(jQuery(window).width()-100);
	var name = null;
	var value = null;
	// loop through all elements that are enclosed in the current form and build the html string that will be submitted
	for (var elems = 0; elems < document.forms.OfferItemsList.length; elems++)
	{
		name = document.forms.OfferItemsList.elements[elems].name;
		value = document.forms.OfferItemsList.elements[elems].value;
		if (name == "CatalogCategoryID" || document.forms.OfferItemsList.elements[elems].checked === true)
		{
			pipelineUrl = pipelineUrl + "&" + name + "=" + value;
		}
	}
	// add class boxedContentPrintWraper for product compare print preview
	jQuery("#wrapHeaderMainFooter").addClass("boxedContentPrintWraper");
	tb_show(null, pipelineUrl, false);
}

// function to set the product detail page to the same state it was before the user left for Login
function checkForClickedLink() {
    if (!(!( window.clickedLink||false ))) {
		if (clickedLink == "rating") {
			jQuery("a#ratingProduct").click();
		} else if (clickedLink == "recommend") {
			jQuery("a#recommendProduct").click();
		} else if (clickedLink == "wishlist") {
			jQuery("a#addToWishlist").click();
		} else if (clickedLink == "invoiceAddress") {
			jQuery("a#changeInvoiveAddress").click();	
		} else if (clickedLink == "productNotification") {
			jQuery("li#tabProductNotification a").click();	
		} else if (clickedLink == "userActivationNotification") {
			jQuery("a#userActivationNotification").click();	
		}
	}
}

// fixes Kupu generated links with anchor (rewritten links without parameters too)
function checkForAnchorLink() {
	jQuery("a.anchorLink").each(
		function(){
			var theHref = jQuery(this).attr("href");
			if (theHref.search(/html$/) != -1) {
				theHref = theHref.replace(/.html/, "").replace(/%23/, ".html#");
			} else {
				theHref = theHref.replace(/%23/, "#");
			}
			jQuery(this).attr("href", theHref);
		}
	);	
}


/* product detail tabs functionality */

// change shown tab on product detail page (if ajaxContentURL is provided the content is loaded via ajax else it needs to be on the page already)
function showTab(theTab, ajaxContentURL, tabInitFunction) {
	
	jQuery("#productAccessoriesTips").show(); // show if it was hidden by Accessorie Tab
	
	if (typeof theTab == "string") {
		theTab = jQuery("#tab"+theTab+" a")[0];
	}
	
	var contentToShow = jQuery(theTab).attr("href");
	if (contentToShow.substr(0,1) != "#") {
		contentToShow = contentToShow.substring(contentToShow.lastIndexOf("#"));
	}
	
	if (!(ajaxContentURL === undefined)) {
		var ajaxContentContainer = jQuery(contentToShow+" div.ajaxContent");
		if (jQuery.trim(ajaxContentContainer.html()) === "") {
			jQuery.ajax({
				url: ajaxContentURL,
				success: function(data){jQuery(ajaxContentContainer).html(data);},
				error: function(data){jQuery(ajaxContentContainer).empty();},
				beforeSend: function(){loadingMsg(ajaxContentContainer);}
			});
		}
	}
	
	jQuery(theTab).parents("ul.tabList").find("li.active").removeClass("active");
	jQuery(theTab).parent().addClass("active");
	
	jQuery("#productTabs div.tabListContent div.activeTabContent").removeClass("activeTabContent").addClass("hidden");
	jQuery(contentToShow).addClass("activeTabContent").removeClass("hidden");
	
	if (typeof tabInitFunction == "function") {
		tabInitFunction();
	}
	
	//setGlobalMediaLinkClass is defined in mediabox_2.js
	if (typeof setGlobalMediaLinkClass == "function")
	{
		setGlobalMediaLinkClass();
	}
	
	return false; // prevents jumping to anchor if wanted
}
// tabInitFunctions
function hideAccessoryTips () {
	jQuery("#productAccessoriesTips").hide();
}

function showProductImage (image) {
	var imageHTML = document.createElement('img');
	imageHTML.src = image;
	jQuery("#productMainImageZoomLink").empty().append(imageHTML);
}

function showProductImageZoom (image) {
	var imageHTML = document.createElement('img');
	imageHTML.src = image;
	jQuery("#zoomImageRefContainer").empty().append(imageHTML);
}

// displays the loading message at the given target
function loadingMsg(msgTarget) {
	var loadingmsg = '';
	    loadingmsg += '<div style="position:relative;background:#fff;width:200px;height:75px;border:1px solid #646464;margin:10px;">';
	    loadingmsg +=  '<div style="position:absolute;top:20px;left:10px;width:32px;height:32px;">';
	    loadingmsg +=    '<img src="' + ajax_webRoot + '/images/static/loading.gif" width="32" height="32" border="0" alt="bitte warten">';
	    loadingmsg +=  '</div>';
	    loadingmsg +=  '<div style="position:absolute;top:23px;left:55px;">';
	    loadingmsg +=    '<center>';
	    loadingmsg +=      'Bitte warten ...<br>Daten werden geladen!';
	    loadingmsg +=    '</center>';
	    loadingmsg +=  '</div>';
	    loadingmsg += '</div>';
	 jQuery(msgTarget).html(loadingmsg);
}



/* basket/checkout functionality */

// updates the basket of quatities and wishlist stuff.
function updateBasket(theAction) { // theAction needs to be set in the template because of #URL(Action('ViewRequisition-Dispatch'))#
	jQuery("form#dispatchBasket").attr("action", theAction).submit();
}



/* deselect the checked product on productlist if the product is deleted from compare list */
function submitDeleteProductCompare(productUUID) {
	var productCheckBox = document.getElementById("ProductRefID_"+productUUID);
	if (productCheckBox !== null) {
		productCheckBox.checked = false;
	}
	return true;
}

/* deselect all checked product on productlist if all products are deleted from compare list */
function submitDeleteAllProductCompare() {
	
	var cbTotal = document.forms.OfferItemsList.elements.length;
	for (var i=0;i<cbTotal;i++) {
		if ( document.forms.OfferItemsList.elements[i].name == 'ProductRefID') {
			document.forms.OfferItemsList.elements[i].checked = false;
		}	
	}
}




/*** form submit functions ***/

// accept Datenschutz to register user
function registerUser() {
	if (document.getElementById("acceptPrivacy").checked) {
		return true;
	} else {
		jQuery("#confirmSubmitError").remove();
		jQuery("label.inputError").removeClass("inputError");
		document.getElementById("confirmPrivacyError").style.display = "block";
		jQuery("#acceptPrivacyLabel").addClass("inputError");
		return false;
	}
	return false;
}

// Check checkbox is checked before user can invalidate his account
function submitInvalidateAccount() {
	if (document.getElementById("acceptInvalidateAcoount").checked) {
		return true;
	}
	else {	
		document.getElementById("confirmInvalidateAccountError").style.display = "block";
		jQuery("#acceptInvalidateAcoountLabel").addClass("inputError");
		return false;
	}
}

// check checkboxes before submitting Newsletter registration
function submitNewsletter() {
	if (submitNewsletterOptInChecked()) {
		if (document.getElementById("acceptPrivacy").checked) {
			return true;
		}
	}
	jQuery("#confirmSubmitError").remove();
	jQuery("label.inputError").removeClass("inputError");	
	if (submitNewsletterOptInChecked()) {
		document.getElementById("optinCheckboxError").style.display = "none";
		jQuery("#NewsletterFormOptinLabel").removeClass("inputError");		
	} else {
		document.getElementById("optinCheckboxError").style.display = "block";
		jQuery("#NewsletterFormOptinLabel").addClass("inputError");		
	}	
	if (document.getElementById("acceptPrivacy").checked) {
		document.getElementById("confirmPrivacyError").style.display = "none";
		jQuery("#acceptPrivacyLabel").removeClass("inputError");	
	} else {
		document.getElementById("confirmPrivacyError").style.display = "block";
		jQuery("#acceptPrivacyLabel").addClass("inputError");
	}
	return false;
}

// check whether at least one OptIn is checked
function submitNewsletterOptInChecked() {
  for (i = 1; i < 11; i++) {
    var optIn = document.getElementById("NewsletterForm_OptIn_" + i);
    if (optIn && optIn.checked) {
      return true;
    }
  }
  return false;
}

// select another Wishlist from wishlist select box 
function WishlistSelect() {
	document.WishlistSelectForm.submit();
}

// product time counter in order to show left product availability time
function countdown( endtime, adjust, targetID ) {
	var now = new Date();
	var end = new Date( endtime );
	
	now.setTime(now.getTime() + adjust);

	var diff = Math.floor(end.getTime() - now.getTime() );

	// reload page: component is not shown any more 
	if(diff<=0){
		location.reload();
		return;
	}

	var hours = Math.floor(diff/(1000*60*60));
	diff = diff - (hours*1000*60*60);
	var minutes = Math.floor(diff/(1000*60));
	diff = diff - (minutes*1000*60);
	var seconds = Math.floor(diff/1000);
	if (seconds<10) {seconds = '0'+ seconds;}
	if (minutes<10) {minutes = '0'+ minutes;}
	if (hours<10) {hours = '0'+ hours;}
	document.getElementById(targetID).innerHTML = ""+hours+":"+minutes+":"+seconds;

	setTimeout( "countdown("+ endtime +", "+adjust+", '"+ targetID +"')", 1000);
}


// standard show/hide functions (without jQuery)
function showElementById(id){
	document.getElementById(id).style.display = 'block';
}
function hideElementById(id){
	document.getElementById(id).style.display = 'none';
}
function showHideElementById(id){
	try {
	    obj = document.getElementById(id);
	    if (obj.style.display == 'block'){
	    	obj.style.display = 'none';
    	}else {
    		obj.style.display = 'block';
    	}
    } catch(e) {}
}

// ***** last visited products functionality + minified list.js *****

function List(){var A=new Array()}List.prototype.serialize=function(C){var A="";for(var B=0;B<this._list.length;B++){if(B==0){A=this._list[B]}else{A=A+C+this._list[B]}}return A};List.prototype.deserialize=function(B,A){if(B!=null){this._list=B.split(A)}else{this._list=new Array()}};List.prototype.toString=function(){var A="";for(var B=0;B<this._list.length;B++){A=A+this._list[B]+"\n"}return A};List.prototype.add=function(C,A){this._list.length++;for(var B=this._list.length-1;B>=A;B--){this._list[B]=this._list[B-1]}this._list[A]=C};List.prototype.remove=function(B){_newList=new Array();for(var A=0;A<this._list.length;A++){if(B!=this._list[A]||this._list[A]==null){_newList.length++;_newList[_newList.length-1]=this._list[A]}}this._list=_newList};List.prototype.cut=function(A){if(this._list>A){this._list.length=A}};List.prototype.get=function(A){if(A<this._list.length){return this._list[A]}return null};List.prototype.length=function(){return this._list.length};

function addProductUUID2Cookie(productUUID){
	var list = new List();
	list.deserialize(readCookie('lastproducts'),' ');
	list.remove(productUUID);
	list.add(productUUID,0);
	list.cut(25);
	document.cookie='lastproducts='+list.serialize(' ')+'; path=/';
}

function viewLastVisitedProducts(callString, productUUID){	
	var rootElement = document.getElementById('LastVisitedProducts');
	var list = new List();
	list.deserialize(readCookie('lastproducts'),' ');

	var maxCount=5;
	if (productUUID == undefined) 
	{
		startValue=0;
	}
	else 
	{
		startValue=1;
	  	maxCount = 6;
	}
	
	if (list.length()==0 || (list.length()==1 && startValue==1))
	{
		document.getElementById('ViewLastVisitedProductsContainer').innerHTML = '';
		return;	
	}
	
	if (list.length()<maxCount)
	{
		maxCount = list.length();
	}
	var layers = '';
	for (var i = startValue; i<maxCount; i++)
	{
		layers = layers+'<li><div id="'+list.get(i)+'"><\/div><\/li>';
	}
	rootElement.innerHTML = layers;
	
	for (var i = startValue; i<maxCount; i++)
	{
		var targetElement = document.getElementById(list.get(i)); // this way is neccessary because jQuery can't get an element that has a "." in its id (resulting from UUIDs)
		jQuery(targetElement).load(callString, {ProductUUID: list.get(i)});
	}
}	
	
// opens a popup window and sets the focus to the new window
function openPopup(url, target, appearance) {
	if (appearance && appearance != "" && appearance != "undefined") {
		newWindow = window.open (url, target, appearance);
	}
	else {
		newWindow = window.open (url, target);
	}
	newWindow.focus();
	return newWindow;
}


// load retainage data for a given monthly rate
function updateFinanceCalculator(id,url) {
	jQuery(id).load(url);
	jQuery(id).show();
}


// ***** additional functions (3rd party) *****

// determines IE version (http://msdn2.microsoft.com/en-us/library/ms537509.aspx)
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1 (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

// functions tor create, read and erase cookies per JavaScript (http://www.quirksmode.org/js/cookies.html)
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



