// Just a couple browser tests
var is_chrome = /chrome/.test(navigator.userAgent.toLowerCase());
var is_win = /windows/.test(navigator.userAgent.toLowerCase());
var is_firefox = /firefox/.test(navigator.userAgent.toLowerCase());


$(function() {
	// !===> Browsers
	if ($.browser.safari) 		$("body").addClass("sfr");
	if (is_chrome) 				$("body").addClass("chr");
	if (is_win && is_firefox) 	$("body").addClass("ffwin");


	// !===> Input fields
	$("input[type=text], input[type=password]").addClass("txt");
	$("input[type=checkbox]").addClass("chk");
	if ($.browser.msie) $("select.error").wrap('<span class="error"></span>');


	// !===> Navigation
	$("#nav ul").wrap("<div />");
	$("#nav > li").hover(
		 function() { $(this).addClass("hover"); }
		,function() { $(this).removeClass("hover"); }
	);

	$("#nav li ul li").hover(
		 function() { $(this).addClass("hover");$(this).removeClass("none"); }
		,function() { $(this).removeClass("hover");$(this).addClass("none"); }
	);

	// Brands
	$("#brands a, .brand-list-alt a").each(function() {
		$(this).hover(
			 function() { $(this).addClass("hover"); }
			,function() { $(this).removeClass("hover"); }
		);
	});
	$("#main .brand-list").each(function() {
		$(this).children("ul").children("li").each(function(i) {
			if ((i+4) % 8 == 0) $(this).addClass("mr");
		});
	});



	// Product categories center images
	$(".product-categories .img img").bind("load", function() {
		$(this).css({
			 "padding-left": 	Math.round((178 - $(this).width()) / 2) + "px"
			,"padding-top": 	Math.round((198 - $(this).height()) / 2) + "px"
			,"width": 			$(this).attr("width")+"px"
			,"height": 			$(this).attr("height")+"px"
		});
	});



	// Div links
//	$("ul.product-categories li, .brand-list ul li").divlink();


	(function($){
		// Triggers callback if images inside content are loaded
		$.fn.contentReady=function(callback){
			return $(this).each(function(){
				var $self = $(this);
				var cb = callback || function(){};
				$(document).ready(function(){
					var $imgs = $self.find("img");
					var cnt = $imgs.length;
					$imgs
					.load(function(){
						if(cnt > 1){
							cnt--;
						} else {
							cb.apply($self);
						}
					}).error(function(){
						if(cnt > 1){
							cnt--;
						} else {
							cb.apply($self);
						}
					}).each(function(){
						if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version)==6)){
							$(this).trigger("load");
						}
					});
					if(cnt==0){
						cb.apply($self);
					}
				});
			});
		};
	})(jQuery);

	// Tooltips
	$("#footer .tools a").contentReady(function(){
		$(this).tipTip({maxWidth: 300});
	});


	// Tooltips
	$(".bestellungen td.icns a, .bestellung .c3 a, , .bestellung .c4 a").contentReady(function(){
		$(this).tipTip({maxWidth: 300});
	});



	// !===> Default values for input fields
	$("#cfooter .storelocator input.txt, #cfooter .newsletter input.txt").defaultVal();

	// Initialize automcomplete
	$("#search-form input[name=term], .search input[name=term]").defaultVal();
	$("#search-form input[name=term]").mbAutocomplete();

	$("#footer .fullscreen").click(function() {
		self.moveTo(0,0);
		self.resizeTo(screen.availWidth,screen.availHeight);
		return false;
	});

	/* Open/close filters from sidebar */
	$("#filter-picker .btn a.cancel").live("click", function() { close_filter($("#filter-picker")); return false; });


	/* Brand overlay */
	$(".brand-list ul li a").click(function() { open_overlay_popup($(this).attr("href"), "brand-overlay", $(".brand-list")); return false; });
	$(".brand-list-alpha ul li a").click(function() { open_overlay_popup($(this).attr("href"), "brand-overlay", $(".brand-list-alpha")); return false; });
	$(".brand ul li a").click(function() { open_overlay_popup($(this).attr("href"), "brand-overlay", $(".brand")); return false; });
	$("#brand-overlay a.close").live("click", function() {
		close_overlay_popup("brand-overlay");
		return false;
	});

    ;(function($){
        $.fn.jCarouselSlide=function(){
            return $(this).each(function(){
                $(".slide",$(this)).jCarouselLite({
                    btnNext: $("#magic-slide .next")
                    ,btnPrev: $("#magic-slide .prev")
                    ,visible: 5
                    ,scroll: 1
                    ,speed: 300
                    ,circular: false
                });
                $(".slide a",$(this)).click(function() {
                    var id = $(this).attr("rel");
                    $("#magicZoom").attr("href", $('#'+id).val());
                    $("#magicZoom img").attr("src", $('#'+id).val());
                    $("#magicZoom-big img")
                        .attr("src", $('#'+id).val())
                        .load(function(){
                                window.setTimeout(function(){
                                        $("#magicZoom").css({width:'auto'});
                                        MagicZoom.refresh();
                                },50);
                        })
                        .each(function(){
                                if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
                                        $(this).trigger("load");
                        });
                    return false;
                });
            });
        };
     })(jQuery);
	$("#magic-slide").jCarouselSlide();

	// Simple slider - Removed 20110310 - FN


	// Share layer
	/*$("#main .product-details .inf .meta a.share").click(function() { open_overlay_popup($(this).attr("href"), "share-overlay", $("#main")); return false; });
	$("#share-overlay a.close").live("click", function() {
		close_overlay_popup("share-overlay");
		return false;
	});*/



	// Merkliste layer
	$("#merk-overlay a.close, #merk-overlay a.btn").live("click", function() {
		close_overlay_popup("merk-overlay");
		return false;
	});

    // Empfagner layer
    $("#main .bestellung a.empfagner").click(function() {
    });

    $(".empfagner-overlay a.close").live("click", function() {
        $(".empfagner-overlay").hide();
        return false;
    });


	// Grosse layer
	$("#main .product-details .options .option a.grosse").click(function() { open_overlay_popup($(this).attr("href"), "grosse-overlay", false); return false; });
	$("#grosse-overlay a.close").live("click", function() {
		close_overlay_popup("grosse-overlay");
		return false;
	});


	// PLZ layer
	$("#plz-overlay a.close, #plz-overlay a.cancel").live("click", function() {
		close_overlay_popup("plz-overlay");
		return false;
	});

	// Versandadresse overlay
	$("#main .bestell .c1 h3 a").click(function() { open_overlay_popup($(this).attr("href"), "versandadresse-overlay", false); return false; });
	$("#versandadresse-overlay a.close, #versandadresse-overlay a.cancel").live("click", function() {
		close_overlay_popup("versandadresse-overlay");
		return false;
	});

	// rechnungadresse overlay
	$("#main .bestell .c2 h3 a").click(function() { open_overlay_popup($(this).attr("href"), "rechnungadresse-overlay", false); return false; });
	$("#rechnungadresse-overlay a.close, #rechnungadresse-overlay a.cancel").live("click", function() {
		close_overlay_popup("rechnungadresse-overlay");
		return false;
	});

	$("#bewertung-overlay a.close, #bewertung-overlay a.cancel").live("click", function() {
		close_overlay_popup("bewertung-overlay");
		return false;
	});

	$("#storelocator-popup a.close, #storelocator-popup a.cancel").live("click", function() {
		close_overlay_popup("storelocator-popup");
		return false;
	});

	$("#lang-picker a.close, #lang-picker a.cancel").live("click", function() {
		close_overlay_popup("lang-picker");
		return false;
	});

	$("#contactdealer-overlay a.closeOverlay, #contactdealer-overlay a.cancel").click(function() {
		close_overlay_popup("contactdealer-overlay");
	});
	
    $("#contactdealerorder-overlay a.closeOverlay, #contactdealerorder-overlay a.cancel").click(function() {
        close_overlay_popup("contactdealerorder-overlay");
    });

	// Equal heights
	$("#main .forms-login .box").equalHeight();



	// Login mask
	$("#header .tools a.login").loginMask();



	// Additional accordion
	$("#aside .categories ul ul li a").click(function() {
		$(this).parent("li").toggleClass("shown");
		return false;
	});

	// Store tabs actions
	$(".shopdetails-tabs .tabs li a").click(function() {
		var $el = $(this);
		var index = $el.attr("rel");
		var $cont = $(".shopdetails-tabs .content-"+index);

		// Tab
		$(".shopdetails-tabs .tabs li").removeClass("active");
		$el.parent("li").addClass("active");

		// Content
		$(".shopdetails-tabs .content-x").hide();
		$(".shopdetails-tabs .content-"+index).show();

		return false;

	});

	// Impressum tabs init
	$(".impressum-tabs .tabs li").removeClass("active");
	$(".impressum-tabs .tabs li:eq(0)").addClass("active");
	$(".impressum-tabs .content-x").hide();
	$(".impressum-tabs .content-1").show();

	// Store tabs actions
	$(".impressum-tabs .tabs li a").click(function() {
		var $el = $(this);
		var index = $el.attr("rel");
		var $cont = $(".impressum-tabs .content-"+index);

		// Tab
		$(".impressum-tabs .tabs li").removeClass("active");
		$el.parent("li").addClass("active");

		// Content
		$(".impressum-tabs .content-x").hide();
		$(".impressum-tabs .content-"+index).show();

		return false;

	});



	// Zebra
	$("#main .shopdetails-tabs table tr:odd").addClass("odd");




	// !===> Create custom buttons, selectboxes and checkboxes
	custom_checkboxes();
	custom_selectboxes();
	$(".bestellungen .bestellung:gt(1)").hide();
//	custom_buttons();

	// MSIE 8 Bugfix
	$("a.jqzoom").mouseover(function(){
		$(this).parent().parent().find(".selectedTxt").css({'z-index':-1});
	}).mouseout(function(){
		$(this).parent().parent().find(".selectedTxt").css({'z-index':20});
	});

	// Moving Menus Bugfix
	$("#nav a").each(function(){
	    $(this).css({
	        width:$(this).width()+5,
	        display:'block'
	    });
	});
});



$(".marken-filter-list .marken a").live("click", function() {
	$(this).find("label").click();
	return false;
});

var filter_opening = false;
var filter_open = false;

function open_filter(turl) {
	if ( ! filter_opening) {
		filter_open = true;
		filter_opening = true;
		$("#filter-picker .loader").show();
		$("#filter-picker .cnt").hide();
		$("#filter-picker").show();
		$.ajax({
			 url: 		turl
			,type: 	'post'
			,dataType: 	"html"
			,success: 	function(data) {
				$("#filter-picker .loader").hide();
				$("#filter-picker .cnt").html(data).show();
				$("#filter-picker").show();
				filter_opening = false;
			}
			,error: 	function(data) {
				alert("Error!");
				filter_opening = false;
			}
		});
	} //end if

	$(".slideex-details").hide();
} // end open_filter()


function close_filter() {
	$("#filter-picker .loader").show();
	$("#filter-picker").hide();
	$("#filter-picker .cnt").hide();
	filter_opening = false;
	filter_open = false;
	return false;
} // end close_filter()






var overlay_opening = new Array();
var overlay_open = new Array();

function open_overlay_popup(turl, div_id, el) {
	if (el) var $el = $(el);

	var scrollTop = $(window).scrollTop();

	fade_overlay_show();

	if ( ! overlay_opening[div_id]) {
		overlay_open[div_id] 	= true;
		overlay_opening[div_id] = true;

		if (el) var $eloffset = $el.offset();
		else {
			$eloffset = {
				top: "50%"
				,left: "50%"
			}
		}

		if (el) {
			$("#"+div_id).css({
				top: $eloffset.top -20
				,left: 150
			});
		}

		if (div_id == "bewertung-overlay") {
			if(scrollTop != 0) {
				$("#"+div_id).css({
					top: scrollTop + 100
					,left: 320
				});
			}
		}

		if (div_id == "lang-picker") {
			$("#"+div_id).css({
				left: "25%"
			});
		}

		$("#"+div_id+" .loader").show();
		$("#"+div_id+" .cnt").hide();
		$("#"+div_id).show();
		$.ajax({
			 url: turl
			,type: 	'post'
			,dataType: 	"html"
			,success: 	function(data) {
				$("#"+div_id+" .loader").hide();
				$("#"+div_id+" .cnt").html(data).show();
				$("#"+div_id).show();
				overlay_opening[div_id] = false;
			}
			,error: 	function(data) {
				alert("Error!");
				overlay_opening[div_id] = false;
			}
		});
	} //end if

	$(".slideex-details").hide();
} // end open_filter()

function open_overlay_popup_get(turl, div_id, el) {
	if (el) var $el = $(el);

	var scrollTop = $(window).scrollTop();

	fade_overlay_show();

	if ( ! overlay_opening[div_id]) {
		overlay_open[div_id] 	= true;
		overlay_opening[div_id] = true;

		if (el) var $eloffset = $el.offset();
		else {
			$eloffset = {
				top: "50%"
				,left: "50%"
			}
		}

		if (el) {
			$("#"+div_id).css({
				top: $eloffset.top -20
				,left: 150
			});
		}

		if(div_id == "bewertung-overlay") {
			if(scrollTop != 0) {
				$("#"+div_id).css({
					top: scrollTop + 100
					,left: 320
				});
			}
		}

		$("#"+div_id+" .loader").show();
		$("#"+div_id+" .cnt").hide();
		$("#"+div_id).show();
		$.ajax({
			 url: turl
			,type: 	'get'
			,dataType: 	"html"
			,success: 	function(data) {
				$("#"+div_id+" .loader").hide();
				$("#"+div_id+" .cnt").html(data).show();
				$("#"+div_id).show();
				overlay_opening[div_id] = false;
			}
			,error: 	function(data) {
				alert("Error!");
				overlay_opening[div_id] = false;
			}
		});
	} //end if

	$(".slideex-details").hide();
} // end open_filter()

function close_overlay_popup(div_id) {
	$("#"+div_id+" .loader").show();
	$("#"+div_id).hide();
	$("#"+div_id+" .cnt").hide();
	overlay_open[div_id] 	= false;
	overlay_opening[div_id] = false;
	fade_overlay_hide();
	return false;
} // end close_overlay_popup()



function fade_overlay_show() {
	var $overlay = $("#fade-overlay");

	if ( ! $overlay.length) $("body").append('<div id="fade-overlay"></div>');

	$overlay.show();
}


function fade_overlay_hide() {
	var $overlay = $("#fade-overlay");
	$overlay.hide();
}





// !===> Custom elements functions
function custom_selectboxes() {
	// Custom select boxes
	$("select.ssel").not(".newListSelected").sSelect();

	// perform additional actions on custom select boxes
	$(".newListSelected").each(function() {
		// forward error class
		var prev_class = $(this).prev().attr("class");
		prev_class = prev_class.replace("error", "error newListSelected_error");
		$(this).addClass(prev_class);

		// add custom class to 1st item in custom select
		$(this).find("ul.newList li:first").addClass("first");
		$(this).find("ul.newList li:last").addClass("last");
	});
}

function custom_checkboxes() {


} //end custom_checkboxes()

function custom_buttons() {
	$("input[type=submit], input[type=reset], input[type=button], button").not("#search button").customButton();
}


// !===> Product size
function pick_size(el, size, code, dealer) {

    $('a.button-quickbuy-' + code + '_' + dealer).attr('href', '#');
    $('a.button-quickbuy-' + code + '_' + dealer).addClass('buy-disabled');
    $('a.button-quickbuy-' + code + '_' + dealer).unbind("click");

    updateQuickDealers(code,size, dealer);

    $('#quickBuy_' + code + '_' + dealer + ' [name=size]').val(size);

    var $el = $(el);
	// Set element state
	$el.parent().parent().children("li").removeClass("active");
	$el.parent().addClass("active");

	return false;
} //end pick_size();

function quickBuy(code, dealer) {
    $('#quickBuy_' + code + '_' + dealer + ' form').submit();
}

(function ($) {
	$.fn.loginMask = function(params) {
		// Default options
		var params = jQuery.extend({

		}, params);

		var $el = $(this);

		$el.click(function() {
			$eloff = $el.offset();

			$("#login-mask").css({
				left: $eloff.left
			});

			$(this).toggleClass("active");
			$("#login-mask").toggle();

			return false;
		});

		$("#login-mask a.cancel").click(function() {
			$el.toggleClass("active");
			$("#login-mask").toggle();
			return false;
		});

	}; //end function()
})(jQuery);

function addToWishlist(productCode, catalogId, sizeEl, qntEl, dealer) {

	var showWishlistPopup = $('#showWishlistPopup').val();

    $.ajax({
         url: $.contextPath+'/view/wishlist/add'
        ,type: 	'post'
        ,data: ({ productCode:productCode, catalogId: catalogId, quantity:$('#'+qntEl).val(), size:$('#'+sizeEl).val(), dealer:$('#'+dealer).val() })
        ,dataType: 	"html"
        ,success: 	function(data) {
            $('#merkliste').html(data);
        }
    });

    if (showWishlistPopup == 'true') {
        open_overlay_popup_get('/view/wishlist/confirm', "merk-overlay", false);
    }

}

function empfagnerClick(el,id) {
    var offset = $(el).offset();
    $("#empfagner-overlay-"+id).css( "top", offset.top - 107 );
    $("#empfagner-overlay-"+id).css( "left", offset.left + 1 );
    $("#empfagner-overlay-"+id).show();
    //return false;
}

function updateProductProperties(code, dealer){
    var quant = $('#product-quantity').val();
    if (quant == null){
        quant = 1;
    }
    $.ajax({
         url: $.contextPath+'/view/productdetails/properties'
        ,type: 	'post'
        ,data: ({code:code, size: $('#product-size').val() != null ? $('#product-size').val() : '' , quantity: quant, dealer: dealer })
        ,dataType: 	"html"
        ,success: 	function(data) {
            $('#product-dealer-container').html(data);
            return true;
        }
    });
}

function updateProductDealer(code,dealerCode){
    $.ajax({
         url: $.contextPath+'/view/productdetails/setDealer'
        ,type: 	'post'
        ,data: ({code:code, size:$('#product-size').val(), quantity: $('#product-quantity').val(),dealer:dealerCode })
        ,dataType: 	"html"
        ,success: 	function(data) {
            $('#product-dealer-container').html(data);
            return true;
        }
    });
}

function viewDealersForProduct(code, dealer){
    var size = $('#product-size').val();
    var quantity = $('#product-quantity').val();
    open_overlay_popup($.contextPath+'/view/productdetails/viewDealers?code='+code+'&size='+size+'&quantity='+quantity+"&dealer="+dealer, 'grosse-overlay', false);
}

function updateQuickDealers(code,size, dealer){
    $.ajax({
         url: $.contextPath+'/view/productdetails/quickDealers'
        ,type: 	'post'
        ,data: ({code:code, size:size, dealer: dealer })
        ,dataType: 	"html"
        ,success: 	function(data) {
            $('.quick_dealers_'+code+"_"+dealer).html(data);
            dealers = $(".quick_dealers_"+code+"_"+dealer).find('span').length;
            if (dealers > 0) {
                $('a.button-quickbuy-' + code+'_'+dealer).removeClass('buy-disabled').click(function() {
                       quickBuy(code, dealer);
                });
            }
        }
    });
}

function selectMenuItem(id){
    $("#nav > li").removeClass("selected");
    $("#nav > #menu-"+id).addClass("selected");
}

/*--- FIXED NAVIGATION ---*/

/*$(function () {
  
  var msie6 = $.browser == 'msie' && $.browser.version < 7;
  var msie = $.browser == 'msie';
  
  if (!msie6) {
    var top = 150;
    $(window).scroll(function (event) {
      var y = $(this).scrollTop();
      if (y >= top) {
        $('#aside.filters').addClass('fixed');
		if (msie) {
			$('#aside.filters').addClass('fixedie');
		}
      } else {
        $('#aside.filters').removeClass('fixed');
	 $('#aside.filters').removeClass('fixedie');
      }
    });
  }  
});*/


