$(function() {

    /*
    var cssLink = document.createElement("link") 
    cssLink.href = "http://xales.juicetest.nl/css/frame.css"; 
    cssLink .rel = "stylesheet"; 
    cssLink .type = "text/css"; 
    cssLink.media = 'screen';

document.getElementsByTagName("iframe")[0].contentWindow.document.getElementsByTagName("head")[0].appendChild(cssLink);
    */

    // naar search url gaan
    if ($(".searchSelect, .colorSelect").length > 0) {
        $(".searchSelect, .colorSelect").change(function() {
            document.location = $(this).find("option:selected").attr("data-url");
        });
    }

    if ($(".mailMeWhenProductIsBack").length > 0) {
        $(".mailMeWhenProductIsBack").click(function(e) {
            if (!$(e.target).is(".popupClose"))
                $(this).find(".prodPopup").show();
        });

        $(".popupClose").click(function(e) {
            $(".prodPopup").hide();
        });

        $("body").click(function(e) {
            if ($(e.target).closest(".mailMeWhenProductIsBack").length == 0 && !$(e.target).is(".mailMeWhenProductIsBack"))
                $(".prodPopup").hide();
        });

        //wanneer email goed gevuld dan deze posten en bedankt html tonen
        $(".productPopupSend").click(function() {
            $('[name="jclc_emailfirst"]').rules('add', {
                required: true,
                email: true,
                messages: {
                    required: ' ',
                    email: ' '
                }
            });
            if ($("#aspnetForm").valid()) {
                $(".popupError").hide();
                $.ajax({
                    type: "POST",
                    url: "/productdetail.aspx/informEmail",
                    data: "{'prodid':'" + $("[name='jclc_emailfirst']").attr("data-prodid") + "','email':'" + $("[name='jclc_emailfirst']").val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(response) {
                        $(".prodPopup").html(response.d);
                        $(".popupClose").unbind("click");
                        $(".popupClose").click(function(e) {
                            $(".prodPopup").hide();
                        });
                    }
                });
            }
            else {
                $(".popupError").show();
            }
        });
    }

    // Product detail afbeeldingen
    if ($(".scroller").length > 0) {
        $(".scroller a").lightBox();

        $("#prod-img, .loop").click(function() {
            var url = $("#prod-img").attr("src").replace("groot", "vergroting");
            $(".scroller a[href='" + url + "']").eq(0).trigger("click");
        });

        $(".scroller").photoScroller({
            scrollTag: "a",
            largeImgTag: "#prod-img",
            scrollOnClick: true,
            nextBtn: "#next",
            prevBtn: "#prev"
        });
    }
    else {
        if ($("#prod-img").length > 0) {
            // Attributen ophalen
            var url = $("#prod-img").attr("src").replace("groot", "vergroting");
            var title = $("#prod-img").attr("title");
            // Een link maken
            var link = $('<a></a>').attr({
                "href": url,
                "title": title
            });
            // De image voorzien van deze link
            $("#prod-img").wrap(link);
            // LightBox toepassen op de link
            $(".prod-large-detail-bottom a").lightBox();
            // Loepje ook een click geven
            $(".loop").click(function() {
                $(".prod-large-detail-bottom a[href='" + url + "']").eq(0).trigger("click");
            });
        }
    }

    //winkelmandje language drop initialiseren
    initLangDrop();

    // Product detail dropdown
    $('.detail-drop ul').dropDownMenu({ linkClass: "span", timer: 300, parentMO: 'parent-hover', childMO: 'child-hover1' });
    // Order form dropdown
    $('.orderForm ul').not(".trans-element").dropDownMenu({ linkClass: "span", timer: 300, parentMO: 'parent-hover', childMO: 'child-hover1' });
    $('.detail-kentons ul').dropDownMenu({ linkClass: "span", timer: 300, parentMO: 'parent-hover', childMO: 'child-hover1' });

    $('.orderForm li ul li, .detail-kentons li ul li').click(function() {
        $(this).parent().parent().find('span').html($(this).html());
    });

    $(".transformSelect").transformSelect({
        dropDownClass: "formDrop"
    }).next().mouseenter(function() {
        $(this).find("span").eq(0).trigger("click");
    }).mouseleave(function() {
        $("body").click();
    });

    $(".searchSelect").transformSelect({
        showFirstItemInDrop: false,
        dropDownClass: "searchTransformSelect"
    }).next().mouseenter(function() {
        $(this).find("span").eq(0).trigger("click");
    }).mouseleave(function() {
        $("body").click();
    });

    $(".colorSelect").transformSelect({
        showFirstItemInDrop: false,
        dropDownClass: "searchSelectColor",
        subTemplate: function() { return "<span><div class='colorImg' style='background-color: " + $(this).attr("data-color") + ";'></div>" + $(this).text() + "</span>"; },
        initValue: function() { return $(this).text(); },
        valueTemplate: function() { return "<div class='colorImg' style='background-color: " + $(this).find("div").css("backgroundColor") + ";'></div>" + $(this).text(); }
    }).next().mouseenter(function() {
        $(this).find("span").eq(0).trigger("click");
    }).mouseleave(function() {
        $("body").click();
    });

    $("#order_type").change(function() {
        if ($(this).val() != "Particulier") {
            $(".bedrijfsgegevensVelden").slideDown();
            if ($('input#jclc_Companyname').length > 0) {
                $('input#jclc_Companyname').addClass("required").rules('add', {
                    required: true
                });
            }
            if ($('input#jclc_TAXno').length > 0) {
                $('input#jclc_TAXno').addClass("required").rules('add', {
                    required: true
                });
            }
        }
        else {
            $(".bedrijfsgegevensVelden").slideUp();
            if ($('input#jclc_Companyname').length > 0) {
                $('input#jclc_Companyname').removeClass("required").rules("remove");
            }
            if ($('input#jclc_TAXno').length > 0) {
                $('input#jclc_TAXno').removeClass("required").rules("remove");
            }
        }
    });

    $(".concept-nav a, .concept-nav span").hover(function() {
        if ($("." + $(this).attr("class") + "-hover").length > 0) {
            $obj = $("." + $(this).attr("class") + "-hover");
        }
        else {
            $obj = $("<div />").css({
                position: 'absolute'
            })
															  					.attr("class", $(this).attr("class") + "-hover");

            $("<img />").attr("src", "/images/" + $(this).attr("class") + ".png")
															 				.appendTo($obj);
            $("body").append($obj);
        }
        $o = $(this).offset();
        var $left = (parseInt($o.left) + 5) + "px";
        var $top = (parseInt($o.top) + 20) + "px";

        $obj.css({ left: $left, top: $top })
																	.show();
    },
											function() {
											    $("." + $(this).attr("class") + "-hover").hide();
											});
    $("#txtarea").textarea();


    $('a.lightbox').lightBox({
        overlayBgColor: '#000000',
        overlayOpacity: 0.6,
        imageLoading: '/images/lightbox-ico-loading.gif',
        imageBtnClose: '/images/lightbox-btn-close.gif',
        imageBtnPrev: '/images/lightbox-btn-prev.gif',
        imageBtnNext: '/images/lightbox-btn-next.gif',
        imageBlank: '/images/lightbox-blank.gif',
        containerResizeSpeed: 350,
        txtImage: 'Afbeelding',
        txtOf: 'van'
    });

    $(".thickbox").click(showDialog);

    // Move box naar body
    $c = $(".dialog").html();
    $(".dialog").remove();
    $("body").append($("<div />").addClass("dialog").html($c));
});
 
 function initLangDrop()
 {
    $('.landSelection ul').dropDownMenu({linkClass : "span", timer: 300, parentMO: 'parent-hover', childMO: 'child-hover1'});
	$('.landSelection li ul li')
		    .click(
		        function()
		        {
	                $(this)
	                    .parent()
	                        .parent()
	                            .parent()
	                            .find(".smalldrop")
                                    .html(
                                        $(this).html()
                                     );
                    $("#jclc_a_country").val($(this).attr("langid"));
                    __doPostBack('ctl00$ContentPlaceHolder2$TriggerExtraRegels', '');
		        }
		    );
	
 }

function showDialog()
{
	$("<div />")	.addClass("dialog-shadow")
					.css({
							   	position	: 'absolute', 
								width 		: '100%', 
								left		: 0,
								top			: 0,
								height 		: $("body").innerHeight(),
								background	: '#000000',
								'z-index'		: 0,
								opacity : 0.5
								})
					.appendTo("body")
					.click(closeDialog);	
	
	$d = $(".dialog");
	// Hoogte - (margin top + margin bottom) - padding
	$d.css({height : $(window).height() - 100 - 30});
	$d.data("html", $d.html());
	
	// Close dialog
	$("<div />").addClass("dialog-close").appendTo($d).click(closeDialog);
	
	$dt = $("<div />").addClass("dialog-top");
	$db = $("<div />").addClass("dialog-bottom");
	$d.wrap($db).wrap($dt);
	
	$d.show();
}
function closeDialog(){
	$html = $(".dialog").data("html");
	$classes = $(".dialog").attr("class"); // IVM type
	$(".dialog-bottom").remove();
	$("<div />").attr("class", $classes).html($html).appendTo($("body")).hide();
	$(".dialog-shadow").remove();
}

(function($){
    $.fn.extend({
				
		/*
			css			the style of the element
			name		the name of the element + number starting with 0
		*/
        textarea: function(options) {
            var defaults = {
				css : {
					width		: 410,
					height		: 64,
					background	: 'url(/images/opmerkingen.gif)',
					padding		: 10
				},
				name 		: "textarea-",
				rel			: 'jstextarea',
				cursor		: '|'
            };

            var options = $.extend(defaults, options);
            
            return this.each(function() {				
				// obj maken
				$obj = $(this);
				$scroller = $("<div />").css({
											width		: options.css.width,
											overflow	: 'hidden'
								})
								.appendTo($obj);
				
				// CSS toepassen
				$(this).css(options.css)
						.css({
							 overflow	: 'hidden',
							 cursor		: 'text'
						});
				
				// Textarea aanmaken
				$("<textarea />").attr({
									  rel : options.rel,
									  name : options.name + $("[rel='" + options.rel + "']").length
								})
								.css({
									 border	: 'none',
									 background	: 'none',
									 width		: options.css.width,
									 height		: options.css.height
								})
								.appendTo($scroller)
								.autoResize({
											onResize : function(){
												$scroller.animate({scrollTop : $(this).height()}, 100);
											},
											animate  	: false,
											extraSpace 	: 0
											});
				
				// Onclick dan 
				$(this).click(function(){
									   		// Active zetten
									   		if (!$(this).hasClass("active") )
											{
												$(this).addClass("active");												
											}	
											return false;
									   });
				
				// on body click
				$('body').click(function(event)
										 {
											// Controleren of je binnen het element klikt
											if(!isClickOnElement(event, $obj))
												$($obj).removeClass("active");
										 });
				
				// Hover plaatsen
				$(this).hover(function(){
									$(this).addClass("hover");   
							  },
							  function(){
									 $(this).removeClass("hover");
							  });
				
				return this;
			})	
        }
    });    
    
	function isClickOnElement(event, $obj)
	{
		$offset = $($obj).offset();
		if( $offset.top < event.pageY && ( $offset.top + $($obj).innerHeight() ) > event.pageY )
			if( $offset.left < event.pageX && ( $offset.left + $($obj).innerWidth() ) > event.pageX )
				return true;
		return false;
	}
	
})(jQuery);

function ToevoegenAanWinkelmandje(productid) {
    document.aspnetForm.action = "/winkelmandje.aspx?addproduct=" + productid;
    document.aspnetForm.submit();
}

function postUrl(url) {
    document.aspnetForm.action = url;
    document.aspnetForm.submit();
}

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function submitform() {
    var theForm = document.forms['aspnetForm'];
    if (!theForm) {
        theForm = document.aspnetForm;
    }
    theForm.submit();
}

function aantallenAanpassen(aantalveld) {
    if (aantalveld.value != '') {
        document.body.style.cursor = "wait";
        MM_findObj('mode').value = 'aantallenaangepast';
        MM_findObj('ProdAanpas').value = aantalveld.id;
        url = document.location;
        document.aspnetForm.action = url;
        setTimeout("submitform();", 500);
    }
}

function productDetailsChange(fromprice, forprice, colorstring, prodid, hidefromprice) {
    // Strings maken van de nummers
    var price1 = new Number(fromprice).toFixed(2).replace('.', ',');
    var price2 = new Number(forprice).toFixed(2).replace('.', ',');
    
    // Bepalen of de "van prijs"-DIV moet worden getoond
    if (forprice < fromprice && fromprice != 0) {
        $('div.prod-van').css('display', '');
    }
    else {
        $('div.prod-van').css('display', 'none');
    }
    
    // De waardes tonen
    $('div.prod-van span').html('&euro; ' + price1);
    $('div.prod-voor span').html('&euro; ' + price2);
    $('span#kleur-hover').text(colorstring);
    $('img#prod-img').attr('src', '/picture.aspx?formaatnaam=groot&prodid=' + prodid + '&fotonumber=0');
    
    // Eventueel de "van prijs"-DIV weer verbergen
    if (hidefromprice) {
        $('div.prod-van').css('display', 'none');
    }
}

function setValue(id, value) {
    $('#'+id).val(value);
}

function triggerPickUp() {
    $("#pickup").val($("#PickUpDiscountCheck").is(':checked'));
    __doPostBack('ctl00$ContentPlaceHolder2$TriggerExtraRegels', '');
}

function setPickUpTrue() {
    $("#pickup").val("true");
    __doPostBack('ctl00$ContentPlaceHolder2$TriggerExtraRegels', '');
}

function setPickUpFalse() {
    $("#pickup").val("false");
    __doPostBack('ctl00$ContentPlaceHolder2$TriggerExtraRegels', '');
}
