﻿$(document).ready(function () {
    init_removeFlyouts();
    init_slideshow();
    init_carousel();
    init_cart_dropdown();
    init_mainmenu_dropdown();
    init_language_dropdown();
    init_showEl();
    init_tabs();
    init_FaqToggle();
    initAddCouponCode();
    init_toggle();
    //init_showOffsetPrice();
    init_showShippingCosts();
    init_ClickImageLabel();

    init_ShowPaymentName();
    init_CheckFlashVersion()

    $('#editor-container').show();
});

function pageLoad() {
    init_validation();
    init_layout();
    init_rating();
    init_innerZoom();
    ReplaceCufonFonts();
    init_ThumbHoverBorder();  
    init_tooltip();
    init_autocomplete();
    check();
    // init_cartReload();
    init_openPopupWindow();
}


function init_CheckFlashVersion() {
    var hasFlash = false;
    //testing for version 10.1.53.64, change here!
    if (swfobject.hasFlashPlayerVersion("10.1.53.64")) {
        hasFlash = true;
    }

    //not present or different version
    if (!hasFlash) {
        $('#editor-container').css('visibility','visible')
    };
}

function init_ShowPaymentName() {
    $('#PaymentOptions img').hover(
      function() {
          var text = $(this).attr('class');
          var position = $(this).position();
          var left = position.left + 40;
          $('#PaymentOptions').append($('<span class="tooltip" style="left:' + left + 'px; top:' + position.top + 'px;position:absolute;z-index:9999">' + text + '</span>'));
      },
      function() {
          $('#PaymentOptions').find("span.tooltip").remove();
      }
    );
}

function init_ClickImageLabel() {
    $("label img").live("click", function() {
        $("#" + $(this).parents("label").attr("for")).click();
    });
}

var mouseOverActiveElementShipping = false;
function init_showShippingCosts() {
    $('.shippingPopup').live('mouseenter', function() { mouseOverActiveElementShipping = true; }).live('mouseleave', function() { mouseOverActiveElementShipping = false; });
    $('#payoff .showshippingcosts').click(function() {
        $(this).blur();
        $('.shippingPopup').show();
    });

    $("html").mouseup(function() {
        if (!mouseOverActiveElementShipping) { $('.shippingPopup').hide(); }
    });

    $('#payoff .shippingPopup .close').click(function() {
        $('.shippingPopup').hide();
    });
    
    if ($.browser.msie) {
        if ($.browser.version == '7.0') {

            $('.shippingPopup').css('top', '-188px');
        };
    };
};


var mouseOverActiveElement = false;
function init_tooltip() {
    $('.tooltip-container').live('mouseenter', function() { mouseOverActiveElement = true; }).live('mouseleave', function() { mouseOverActiveElement = false; });
    $('.tooltip').click(function() {
        var position = $(this).offset();
        var length = $(this).width();
        var content = $(this).children('.tooltipContent').html();
        $(this).blur();
        $('form').append('<div class="tooltip-container" style="top:' + position.top + 'px;left:' + (position.left + length) + 'px"><span class="arrow"></span><a href="javascript:void(0);" onclick="$(this).parents(\'.tooltip-container\').remove();" class="close">&nbsp;</a><div class="tooltip-content">' + content + '</div></div>');
    });
    $("html").mouseup(function() {
        if (!mouseOverActiveElement) { $('.tooltip-container').remove(); }
    });
}

function init_toggle() {
    $(".toggle").toggle(
        function() {
            $(this).addClass('active');
            $(this).blur();
        },
        function() {
            $(this).removeClass('active');
            $(this).blur();
        }
    );
    $(".toggle").click(function() {
        $(".readMore").toggle();
    });
};


function initAddCouponCode() {
    $('.show-codeform').click(function() {
        $('.couponcode-container').append("<div class='popup'><span class='title'>Couponcode</span><input type='text' value='' /><a class='btn-arrow right-align' href='javascript:void(0);'>Activeren<span class='right'>&nbsp;</span></a></div>");
    });
}

function init_layout() {
    $('.btn-arrow').each(function() {
        $(this).append('<span class="right">&nbsp;</span>');
    });
    $('.btn-arrow_blue').each(function() {
        $(this).append('<span class="right">&nbsp;</span>');
    });

    /* HOME */
    var height = $('#homepage-container').height();
    $('#homepage-container #side-column').css('height', height)
    var blocks = ($('#homepage-container #side-column .v1').height() + $('#homepage-container #side-column .v2').height() + $('#homepage-container #side-column .v3').height());
    var rest = height - blocks;
    $('#homepage-container #side-column .homepage-filler').css('height', rest);

    var aboutCase = $('.aboutFlightcases.right').height();
    $('.aboutFlightcases.left').css('height',aboutCase-1);
}

function init_validation() {
    /*** validatie ***/
    $('.validatie_pointer').each(function() {
        active = ($(this).css('display'));
        if (active == "inline") {
            $(this).parents('.row').find('.textbox, label, input, #material, .single-checkbox').addClass('error');
        }
    });    

    $('input, textarea').blur(function() {
        $('.validatie-pointer:hidden').parents('p.row').find('.textbox').removeClass('error');
        $('.validatie-pointer:visible').parents('p.row').find('.textbox').addClass('error');
        $(this).removeClass('has-focus');
    });
    $('input, textarea').focus(function() {
        $('.validatie-pointer:hidden').parents('p.row').find('.textbox').removeClass('error');
        $('.validatie-pointer:visible').parents('p.row').find('.textbox').addClass('error');
        $(this).addClass('has-focus');
    });

    $('.do-validate').click(function() {
        $('.validatie-pointer:hidden').parents('.row').find('.textbox, label, input, #material, .single-checkbox').removeClass('error');
        $('.validatie-pointer:visible').parents('.row').find('.textbox, label, input, #material, .single-checkbox').addClass('error');
        setTimeout(check, 100);
    });
}

function check() {
    $('.validatie-pointer:hidden').parents('.row').find('.textbox, label, input, #material, .single-checkbox').removeClass('error');
    $('.validatie-pointer:visible').parents('.row').find('.textbox, label, input, #material, .single-checkbox').addClass('error');
    if ($('.textbox, label, input, #material').hasClass('error')) {
        $('.validatie-pointer:visible').parents('.form').find('.errorlist').show();
        $('.validatie-pointer:visible').parents('.popup').find('.errorlist').show();
    }
}

function ReplaceCufonFonts() {
    Cufon.replace('.metaplus', { fontFamily: 'MetaPlusLiningBold', hover: true, hoverables: { a: true, div: true, h2: true } });
    Cufon.replace('.conduit', { fontFamily: 'Conduit ITC' });
}

function init_mainmenu_dropdown() {
    $("ul#topnav li.hassub").find('a:first').append('<span class="nav-arrow"></span>');
    function megaHoverOver(el){ $(el).find(".sub").stop().show();  }
    function megaHoverOut(el){ $(el).find(".sub").stop().hide(); } 
    $("ul#topnav li").hover(function() {
        megaHoverOver(this)
    }, function() {
        megaHoverOut(this)
    });
}

function init_cart_dropdown() {
    $('#header .cart-header, #cart-flyout').hover(function() {
        $('#cart-flyout').show();
        $('#header .cart-header').addClass('hover');
        //laat de talendropdown verdwijnen
                //$('#header #language-container').removeClass('hover');
                //$('#language-flyout').hide();
    });
    $('#header .cart-header').mouseleave(function() {
        $('#cart-flyout').hide();
        $('#header .cart-header').removeClass('hover');
    });

    var link = $('#header .cart-header .content p a').attr('href');
    $('#header .cart-header').mouseup(function() {
        window.location = link;
    });
}

function init_language_dropdown() {   
    var mouseOverActiveElement  = false;

    $('#header #language-container').live('mouseenter', function() {
        mouseOverActiveElement = true;
        $('#header #language-container').toggle(
            function() {
            $('#header #language-container').addClass('hover');
                $('#language-flyout').show();
            },
            function() {
                $('#header #language-container').removeClass('hover');
                $('#language-flyout').hide();
            }
        );
    }).live('mouseleave', function() { 
        mouseOverActiveElement = false;     
        	        /* haal dit weg voor klik outside to close */
        	        $('#language-flyout').hide();
	                $('#header #language-container').removeClass('hover');   
    });

	$("html").mouseup(function() {
	    if (!mouseOverActiveElement) {
	        $('#language-flyout').hide();
	        $('#header #language-container').removeClass('hover');
	    }
	});

    $('#language-flyout a').click(function(){
        var url = $(this).attr('href');
        window.location = url;
    });
}

function init_slideshow() {
    if  ($('.slideshow').length > 0) {
        $('.slideshow').cycle({ 
            fx:     'fade', 
            speed:  'fast', 
            timeout: 7000, 
            pager:  '.nav',
            next:   '.slideshow-container .next', 
            prev:   '.slideshow-container .prev',
            before: function(){ $('.slideshow-container .nav-container').fadeIn('fast'); }
            
        });    
        $('.slideshow-container .nav-container a').click(function() {
            $(this).blur();
            $('.slideshow').cycle('pause');
        });
    }
}

function init_carousel() {
    if ($('.carousel').length > 0) {
        $(".carousel").jCarouselLite({
            btnNext: ".carousel-wrapper .next",
            btnPrev: ".carousel-wrapper .prev",
            circular: false,
            visible: 2.3,
            speed: 300
        });
        $('.carousel-wrapper .prev, .carousel-wrapper .next').click(function() { $(this).blur(); }
        );
    }
}

function init_showEl() {
    $(".showEl").click(function() {
        $(this).hide();
        var showEl = $(this).attr('rel');
        $('.'+showEl).show();
    });
}

var lensMaken = true;
function init_innerZoom() {
    $('.innerzoom').jqzoom({
        zoomType: 'standard',
        lens: true,
        preloadImages: false,
        alwaysOn: false,
        preloadText: '',
        title: false,
        position: 'right'
    }).find('.zoomPad img').addClass('thumb-image');

    $('.innerzoom').mouseenter(function() {
        //var preloadText = $('.detailpage-container .preloadText').text();
        //$('.zoomPreload').text(preloadText);
    });

    $('#imagecontainer a').click(function() {
        $(this).blur();
        $('.innerzoom').jqzoom({
            preloadImages: false
        });
    });
    
    //bij mouseover alvast die window laten zien ivm laden en de window goed positioneren
    $('#imagecontainer .thumb-image').hover(function() {
    var correctie = $('#imagecontainer').css('left');
        $('.zoomWindow').css({ 'margin-left': '-' + correctie }).show();
        $('.zoomWindow').addClass('loading');
    });
}

function init_tabs() {
    $('.tab-container').each(function() {
        var active = $(this).find('ul.tabs li a.active').attr('rel');
        $(this).find('.tab').hide();
        $(this).find('.tab#'+active).show();
        
        $(this).find('ul.tabs li a').click(function() {
            $(this).blur();
            $(this).parents('.tabs').find('a.active').removeClass('active');
            $(this).addClass('active');
            active = $(this).attr('rel');
            $(this).parents('.tab-container').find('.tab').hide();
            $(this).parents('.tab-container').find('#'+active).show();
        });
    });
}

function init_FaqToggle() {
    $(".faqToggle").toggle(
        function() {
            $(this).addClass('active');
            $(this).blur();
        },
        function() {
            $(this).removeClass('active');
            $(this).blur();
        }
    );

    $(".faqToggle").click(function() {
        var id = $(this).attr('name');
        $('#faq' + id).toggle();
        $('.toggle').blur();
        return false;
    });
};

var mouseOverActiveElement = false;
function init_tooltip() {
    $('.tooltip-container').live('mouseenter', function() { mouseOverActiveElement = true; }).live('mouseleave', function() { mouseOverActiveElement = false; });
    $('.tooltip').click(function() {
        var position = $(this).offset();
        var length = $(this).width();
        var content = $(this).children('.tooltipContent').html();
        $(this).blur();
        $('form').append('<div class="tooltip-container" style="top:' + position.top + 'px;left:' + (position.left + length) + 'px"><span class="arrow"></span><a href="javascript:void(0);" onclick="$(this).parents(\'.tooltip-container\').remove();" class="close">&nbsp;</a><div class="tooltip-content">' + content + '</div></div>');
    });
    $("html").mouseup(function() {
        if (!mouseOverActiveElement) { $('.tooltip-container').remove(); }
    });
}

function init_showOffsetPrice() {
    $('.tooltip-container').live('mouseenter', function() { mouseOverActiveElement = true; }).live('mouseleave', function() { mouseOverActiveElement = false; });
    $('.offsetPrice').click(function() {
        $(this).blur();
        $(this).parents('.article').find('#offsetPrice').show();
    });

    $('#offsetPrice .close').click(function() {
        $(this).parents('.article').find('#offsetPrice').hide();
    });

    $('.add-container .refresh').live('click', function() {
        setTimeout(function() {
            Cufon.replace('.parts_listview_container .price-container .price')
        }, 200);
    });

    if ($.browser.msie) {
        if ($.browser.version == '9.0') {
            $('#offsetPrice').css('top', '-90px');
            $('#offsetPrice td').css('padding', '0');
        };
    };
};

function init_openPopupWindow() {
    $('a[rel="popup"]').click(function() {
        var url = $(this).attr('href');
        var windowname = '';
        window.open(url, windowname, 'scrollbars=yes,width=770,height=450');
        return false;
    });
}

function startOverlay_div(element) {
    //console.log(element);

    //start lightbox
    $('form').after("<div id=\"overlay\">&nbsp;</div>");
    $('#overlay').css('opacity', '0.5');
    $('#overlay').fadeIn(500, overlay_ingeladen(element));
    //return false;
}

function overlay_ingeladen(element) { 
    $('#' + element).prependTo('form:first');
    //$('#' + element).clone().appendTo('form:first');
    $('#overlay').click(close_overlay);
    $('#' + element + ' .close').click(function() { close_overlay(); });
    $('#' + element).css({ 'z-index': '4000' })
    $('#' + element).center();
    $('#' + element).show();
}

function close_overlay() {
    $('.popup').hide();
    $('#overlay-content').hide();
    $('#overlay-content img#zoom-image').remove();
    overlay_gesloten(); }

function overlay_gesloten() {
    $('#overlay').fadeOut(500);
    setTimeout("$('#overlay').remove()", 500);
}

$(window).resize(function() {
    //centreer();
});

jQuery.fn.center = function() {
    this.css("position", "fixed");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

function DisplayAdded(buttonId) {
    var addedText = $('#addedToCartText').text();   
    
    //pak de elementen (overview of detailpage?)
    var elOverview = $('#'+buttonId).parents('.article');
    var elDetail = $('#' + buttonId).parents('.parts-detailpage-container').find('.left');
    var crossSell = $('#' + buttonId).parents('.content.article');
    
    //welke is van toepassing?
    if (elOverview.length > 0) {
        var el = elOverview
    } else if (elDetail.length > 0) {
        var el = elDetail
    } else {
        var el = crossSell;
    }
    //alert(el);
    
    //eventuele vorige added balkjes weghalen   
    el.find('.added').remove();
    el.append('<span class="added">'+addedText+'</span>'); 
    
    var balk = el.find('.added');
    
    //de positie uitrekenen   
    var left = (((el.width() - balk.width())) / 2) - 15 + 'px';
    var top = (((el.height() - balk.height())) / 2) - 10 + 'px';
    balk.css({'margin-left':left, 'margin-top':top});
        
    $('.added, #cart-flyout').show();
    setTimeout(function() {
        //added balkje weghalen
        balk.remove();
         //pas de winkelwagen dropdown webhalen als alle "added" balkjes weg zijn
         if ( $('.added').length == 0) { $('#cart-flyout').hide()  }
    }, 2000);
}
   

function DisplayShoppingcart() {  
    $('#cart-flyout').show();
        setTimeout(function() {
        $('#cart-flyout').hide();
    }, 2000);
}

function init_rating() {
    var rating1 = $('.ratingContainer .ratings .rating1').text();
    var rating2 = $('.ratingContainer .ratings .rating2').text();
    var rating3 = $('.ratingContainer .ratings .rating3').text();
    var rating4 = $('.ratingContainer .ratings .rating4').text();
    var rating5 = $('.ratingContainer .ratings .rating5').text();
    var rating6 = $('.ratingContainer .ratings .rating6').text();
    
    $('.RadRating li').hover(
        function() {
            $('.RadRating li a').mousemove(function() {
                var rating = $(this).attr('title') * 2;
                if (rating == 1) { $('#textRating').html(rating1) };
                if (rating == 2) { $('#textRating').html(rating1) };
                if (rating == 3) { $('#textRating').html(rating2) };
                if (rating == 4) { $('#textRating').html(rating2) };
                if (rating == 5) { $('#textRating').html(rating3) };
                if (rating == 6) { $('#textRating').html(rating4) };
                if (rating == 7) { $('#textRating').html(rating4) };
                if (rating == 8) { $('#textRating').html(rating5) };
                if (rating == 9) { $('#textRating').html(rating6) };
                if (rating == 10) { $('#textRating').html(rating6) };
            });
        },
    function() {
        $('#textRating').html('');
    });
}

function init_ThumbHoverBorder() {
    $('.detailpage-container #imagecontainer a').hover(
        function() {
            $(this).append('<span class="hover"></span>');
        },
        function() {
            $(this).find('span.hover').remove();
        }
    );

    $('.detailpage-container #imagecontainer a').click(function() {
        $('.detailpage-container #imagecontainer a').find("span:last").remove();
        $(this).append('<span></span>');
    });

    $('.cross-sell-container .item').hoverIntent(
        function() {
            $(this).append('<span class="hover"></span>');
        },
        function() {
            $(this).find('span.hover').remove();
        }
    );    
}

function init_autocomplete() {
    //var OriginalUrl = $('.SiteLanguage').text();

    //var lastThree = OriginalUrl.substr(OriginalUrl.length - 3);

 //   if (lastThree == 'de/') {
 //       var url = "http://" + window.location.hostname + "/de/";
 //   } else if (lastThree == 'en/') {
 //       var url = "http://" + window.location.hostname + "/en/";
 //   } else {
 //       var url = "http://" + window.location.hostname + "/";
    //   }

    url = rooturl;
    //alert(url);

    var input = $('#top-search input');
    //voor multi-language
    var defaulttext = $('.autocomplete-defaulttext').html(); 
    var minimumtext = $('.autocomplete-minimumtext').html(); 
    var sugestiontext = $('.autocomplete-sugestiontext').html(); 
    var nosugestiontext = $('.autocomplete-nosugestiontext').html(); 
    
    input.val(defaulttext);

    input.focus(function() {
        if (input.val() == defaulttext) {
            $(this).val('');
            $('.autocomplete').css({'height':'auto'}).html('<ul><li class="first">'+minimumtext+'</li></ul>').show();
        } else {
            $('.autocomplete').show();
        }
    });

    input.blur(function() {   
        if (input.val() == '') {
            $(this).val(defaulttext);
            setTimeout("$('.autocomplete').hide()",5);
         }
     });

     input.keyup(function (e) {
         if (e.keyCode == 38) {
             // 38 - up
             if ($('.autocomplete li').hasClass('highlight')) {

                 if ($('.autocomplete li:nth-child(2)').hasClass('firstItem')) {
                     $('.autocomplete li').last().addClass('highlight');
                     $('.autocomplete li:nth-child(2)').removeClass('firstItem').removeClass('highlight');
                 } else {
                     $('.autocomplete li.highlight').addClass('temp').removeClass('highlight');
                     $('.autocomplete li.temp').prev().addClass('highlight');
                     $('.autocomplete li.temp').removeClass('temp');
                 }

                 if ($('.autocomplete li:nth-child(2)').hasClass('highlight')) {
                     $('.autocomplete li:nth-child(2)').addClass('firstItem');
                 }
             } else {
                 $('.autocomplete li:first').prev().addClass('highlight');
             }
             return false;
         }

         if (e.keyCode == 40) {
             // 40 - down
             if ($('.autocomplete li').hasClass('highlight')) {
                 $('.autocomplete li.highlight').addClass('temp').removeClass('highlight');
                 $('.autocomplete li.temp').next().addClass('highlight');
                 $('.autocomplete li.temp').removeClass('temp');

                 if ($('.autocomplete li').last().hasClass('lastItem')) {
                     $('.autocomplete li:nth-child(2)').addClass('highlight');
                     $('.autocomplete li.lastItem').removeClass('lastItem');
                 }

                 if ($('.autocomplete li').last().hasClass('highlight')) {
                     $('.autocomplete li').last().addClass('lastItem');
                 }
             } else {
                 $('.autocomplete li:first').next().addClass('highlight');
             }
             return false;
         }

         if (e.keyCode == 13) {
             // 13 - enter
             var search = $('.autocomplete li.highlight a').attr('href');

             if (search == null) {
                 if (input.val().length >= 3) {
                     window.location = url + 'NoResults.aspx';
                 }
             } else {
                 if (input.val().length >= 3) {
                     window.location = search;
                 }
             }
         }

         var query = input.val();
         $('.autocomplete').css({ 'height': $('.autocomplete').height() + 'px' }).html('');
         if (input.val().length < 3) {
             $('.autocomplete').css({ 'height': 'auto' }).html('<ul><li class="first">' + minimumtext + '</li></ul>').show();
         } else {
             $('.autocomplete').html('');
             $.ajax({
                 url: url + "WebServices/CasebuilderWebservice.asmx/Search",
                 data: "{ 'input': '" + query + "' }",
                 dataType: "json",
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 dataFilter: function (data) { return data; },
                 success: function (data) {
                     var result = '<ul>';
                     if (data.d.length > 0) {
                         result += '<li class="first">' + sugestiontext + '</li>';
                         $.each(data.d, function () {
                             result += '<li><a href=' + this.Url + '>' + this.Title + '</a></li>';
                         });
                     }
                     else {
                         $('.autocomplete').html('');
                         result += '<li class="first">' + nosugestiontext + '</li>';
                         if (e.keyCode == 13) {
                             window.location = 'noresults.aspx';
                             return false;
                         }
                     }
                     result += '</ul>';
                     $('.autocomplete').html(result);
                     $('.autocomplete').css({ 'height': 'auto' }).show();
                     //console.log(result);
                 },
                 error: function (XMLHttpRequest, textStatus, errorThrown) {
                     //console.log(textStatus);
                 }
             });
             //einde ajax call
         }
     });  
}


/* wordt nog niet gebruikt en is nog niet af (btw + korting moet nog berekend), en eventueel verzendingstaffel */

function init_cartReload() {   
    $('.amount input.textbox').keyup(function() {

            /*** bestelregel aanpassen ******/
            //nieuw aantal
            var amount = parseInt($(this).val());
            //pak de prijs
            var price = $(this).parents('.item').find('.price p').text();
            price = parseFloat(price.replace(",","."));
            //maak de totaalprijs van de regel
            var totalprice = Currency(amount * price);           
            //var showtotal = totalprice.replace(".",",");
            $(this).parents('.item').find('.totalprice p').html(totalprice);

            /*** subtotaal aanpassen ********/
            var subTotaal = 0;
            $('.shoppingcart-container').find('.item').each(function() {
                var itemPrice = $(this).find('.totalprice p').text();
                itemPrice = parseFloat(itemPrice.replace(",","."));
                subTotaal = subTotaal + itemPrice;
            });
            subTotaal = Currency(subTotaal);
            $('.shoppingcart-container .subtotal').html(subTotaal);
            

            // verzendkosten optellen bij subtotaal
            var shippingCosts = $('.shoppingcart-container .shippingPopup').text();
            shippingCosts = parseFloat(shippingCosts.replace(",","."));
            
            //maak totaalprijs inclusief verzendkosten          
            var subTotaal = $('.shoppingcart-container .subtotal').text();
            subTotaal = parseFloat(subTotaal.replace(",","."));
            Totaal = (subTotaal + shippingCosts);
            
    });
    
  
  function Currency(value) {
    var temp = "" + (Math.round( value * 100));
    if ((temp.slice(0,-2) == 0)) { 
     var euro = 0 } else {
     var euro = temp.slice(0,-2)      }
    return euro + "," + temp.slice(-2);
    }
}

function init_removeFlyouts() {
    $('#editorContainer').parents('body').addClass('Editor');
    $('body.Editor #language-flyout').remove();
    $('body.Editor #cart-flyout').remove();
    $('body.Editor .shippingPopup').remove();
}

