function log() {
    var logMsg = new String();
    for(var i = 0; i < log.arguments.length; i++) {
        logMsg += new Date();
        logMsg += " - ";
        logMsg += log.arguments[i];
        logMsg += "\r\n";
    }
    
    if (typeof(console) !== "undefined") {
        console.log(logMsg);
    } else {
        alert(logMsg);
    }
}

// Zie: http://www.quirksmode.org/dom/inputfile.html
var W3CDOM = (document.createElement && document.getElementsByTagName);
function initFileUploads() {
    if (!W3CDOM) return;
    
    var input                   = document.createElement('input');
    input.style.height          = "17px";
	input.style.width           = "128px"
    
    var image                   = document.createElement('button');
    image.innerHTML             = 'Bladeren...'; 
    
    var fakeFileUpload          = document.createElement('div');
    fakeFileUpload.className    = 'fakefile';
    fakeFileUpload.appendChild(input);	    
    fakeFileUpload.appendChild(image);

    var x     = document.getElementById('uploadLogo');
    var clone = fakeFileUpload.cloneNode(true);
    x.parentNode.appendChild(clone);
    x.relatedElement = clone.getElementsByTagName('input')[0];
    x.onchange       = x.onmouseout = function () {
	    this.relatedElement.value = this.value;
    }

    x.onselect = function () {
        this.relatedElement.select();
    }
	
    clone.onclick = function () {
        x.click();
    }
}

$(function() {
    if (typeof($("#opmerking")) !== "undefined")
    {
        $("#opmerking").focus(function(){
            $(this).val("");
        });

        $("#opmerking").blur(function(){
            $(this).val().length === 0 && $(this).val($(this).attr("defaultValue"));
        });
    }
    
    var checkForm = function($thisForm, e){
        var success = true;
        $(":input:not([type='hidden'])", $thisForm).each(function(){
            var $this   = $(this),
                name    = $this.attr('name'),
                id      = $this.attr('id'),
                value   = $this.attr('value');
                
            if (id.length > 0 && value.length <= 0){
                switch(name){
                    case 'bedrijf':
                    case 'opmerking':
                    case 'logo':
                        return true;
                        break;
                    default:
                        alert( id + ' mag niet leeg zijn');
                        success = false;
                        $this.trigger("focus");
                        return false;
                        break;
                }
            }
            
            if (new String(id).toLowerCase() === 'postcode' && !value.match(/^[1-9]{1}[0-9]{3}\s*([a-z]{2})?$/gi)){
                success = false;
                alert('Dit is een ongeldige postcode.\r\nVul minimaal 4 getallen in, gevolgd door eventueel 2 letters.');
                $this.trigger("focus");
                return false;
            }
            
            if (new String(id).toLowerCase() === 'telefoon' && !value.replace(/[^0-9]/g, '').match(/^0[1-9]{1}[0-9]{8,12}$/)){
                success = false;
                alert('Dit is een ongeldig telefoonnummer.\r\nGebruik alleen cijfers, beginnend met een nul.');
                $this.trigger("focus");
                return false;
            }
            if ((new String(id).toLowerCase() === 'email' || new String(id).toLowerCase() === 'e-mail') && !value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g)){
                success = false;
                alert('Dit is een ongeldig e-mailadres');
                $this.trigger("focus");
                return false;
            }
        });
        
        if (!success){
            e.preventDefault();
            return false;
        }else{
            return true;
        }
    }
    
    $(".color_wrapper").each(function(){ 
        $(this).click(function(){
            var jQueryElement = $(this).closest(".colorpicker");
            jQueryElement.children(".prodActive").removeClass("prodActive");
            jQueryElement.children(".color_wrapper").addClass("prodInactive");
            
            var jQueryColourInputElement = jQueryElement.find("input.prod_color");
            jQueryColourInputElement.removeClass("prodActive");
            jQueryColourInputElement.addClass("prodInactive");
            (jQueryColourInputElement.val().length > 0) && jQueryColourInputElement.val("");
            
            $(this).removeClass("prodInactive");
            $(this).addClass("prodActive");
            
            if (window.location.pathname.substr(1, 13).toLowerCase() === "offertemandje")
            {
                $.get(updateBasketUrl($(this).children(".prod_color"), "kleur", $(this).children(".prod_color").attr("rel")));            
            }            
        });
    });

    $("input.prod_color").blur(function(){
        $(this).attr("rel", $(this).val());
        if ($(this).val().length === 0)
        {
            $(this).closest(".colorpicker").children(".prod_color").first().click();
        }
        else
        {
            if (window.location.pathname.substr(1, 13).toLowerCase() === "offertemandje")
            {
                $.get(updateBasketUrl($(this), "kleurAnders", $(this).attr("rel")));            
            }
        }
    });
    
    $("input.prod_color").focus(function(){
        $(this).parent().siblings(".prodActive").removeClass("prodActive");
    });

    $("#ZoekSubmit").click(function(){
        $("#offermailform").submit();
    });

    $(".checkForm").submit(function(e){
        checkForm($(this), e);
    });

    $("a[rel^='prettyPhoto']").prettyPhoto();

    $(".showOfferte").click(function(){
        $("#orderdirect").toggle();
    });
      
    if(typeof($(".amount input:text")) !== "undefined") {
        $(".addToBasket.right a").click(function(e) {
            if(parseInt($(".amount input:text").val(), 10) === 0)
            {
                alert("U kunt geen offerte aanvragen voor 0 producten!");
                e.preventDefault();
                return false;
            }
            else
            {
                this.href = addToBasketHref(this.href);
            } 
        });
    }

    if (typeof($("#order_direct_form")) !== "undefined") { 
        $("#order_direct_form").submit(function(e) {
            if(checkForm($(this), e))
            {
                if(window.location.pathname === "/Offertemandje/Stap2.aspx")
                {
                    return true;
                }
                else
                {
                    if(parseInt($(".amount input:text").val(), 10) === 0)
                    {
                        alert("U kunt geen offerte aanvragen voor 0 producten!");
                        return false;
                    } 
                    else
                    {
                        var href       = $(".prod_details .addToBasket a").attr("href");
                        var productId  = parseInt(href.substring(href.lastIndexOf('/') + 1), 10);
                        this.action   += '/' + addToBasketHref(productId);
                        
                        return true;
                    }
                }
            }
            else
            {
                return false;
            }
        });
    }
    
    if (window.location.pathname.substr(1, 13).toLowerCase() === "offertemandje") {
        function updateBasketUrl(p_jQueryElement, p_strCommand, p_strValue)
        {
            var href = "/Formhandler/UpdateBasket.aspx/";
            href    += parseInt(p_jQueryElement.closest(".product_container_offerte").attr("rel"), 10);
            href    += "/"+ p_strCommand + "/";
            if (typeof(p_strValue) === undefined) {
                href += "nvt";
            } else {
                href += p_strValue;
            }

            return href;
        }

        if (typeof($(".amount input:text")) !== "undefined")
        {
            $(".amount input:text").blur(function(){
                var jQueryElement = $(this);
                var aantal = Math.abs(parseInt(jQueryElement.val(), 10));
                if( aantal === 0)
                {
                    alert("U kunt het product verwijderen middels de verwijder knop!");
                    jQueryElement.val(jQueryElement.attr("defaultValue"));
                }
                else
                {
                    $.get(updateBasketUrl(jQueryElement, "aantal", aantal));
                }
            });
        }
        
        if (typeof($("input:radio")) !== "undefined") {
            $("input:radio").change(function(){
                $.get(updateBasketUrl($(this), "opdrukvoorkeur", $(this).val()));
            });
        }
    }
    else
    {    
        function addToBasketHref(prefix) {
            prefix += '/';
            
            if (typeof($(".amount input:text").val()) === undefined || parseInt($(".amount input:text").val(), 10) === 0) {
                prefix += "nvt";
            } else {
                prefix += Math.abs(parseInt($(".amount input:text").val(), 10));
            }
            
            var $color = $(".colorpicker .prodActive").children(".prod_color").attr("rel");
            
            prefix += '/' + $(".colorpicker .prodActive").children(".prod_color").attr("rel"); //kleur
            prefix += '/' + $("input:radio[name=print[0]]:checked").val(); //opdrukvoorkeur
            return prefix;
        }

        if($(".addToBasket.left a").length > 0) {
            $(".addToBasket.left a").click(function(){
                this.href = addToBasketHref(this.href);
            });
        }

        if (typeof($(".amount input:text")) !== "undefined")
        {
            $(".amount input:text").blur(function() { 
                if (parseInt($(this).val(), 10) === 0)
                {
                    alert("U kunt geen offerte aanvragen voor 0 producten!");
                    $(this).focus();
                }
            });
        }
    }

    $(".showForm").click(function(e){
        $("#offers, #offersmail").toggle();
        e.preventDefault();
    });



    var standardValues = function(object){
        if (object.constructor == Array){
            //if the input is an array, do this function for each item
            for(var i=0,l=object.length; i<l; i++){
                standardValues(object[i]);
            }
        }else{
            //check if input object has the required properties
            if (typeof object.form === "undefined" || typeof object.input === "undefined" || typeof object.standardValue === "undefined" || typeof object.image === "undefined"){
                return;    
            }    
            
            //add events
            object.input.focus(function(){
                if (this.value.toLowerCase() === object.standardValue.toLowerCase()){
                    $(this).val("");
                }
            }).blur(function(){
                if (this.value.toLowerCase() === ""){
                    $(this).val($(this).attr("defaultValue"));   
                }
            });
            
            object.image.click(function(){
                object.form.submit();
            });
        }
    };

    standardValues([
        {
            form:           $("#top_search"),
            input:          $("#top_search input[name=st]"),
            standardValue:  'zoekterm', 
            image:          $("#top_search img")
        },
        {
            form:           $("#offermailform"),
            input:          $("#offermailform input[name=email]"),
            standardValue:  'vul uw e-mail adres in...', 
            image:          $("#offermailform img")
        },
        {
            form:           $("#callmeform"),
            input:          $("#callmeform input[name=phone]"),
            standardValue:  'uw telefoonnummer', 
            image:          $("#callmeform input[type=button]")
        }
    ]);

    var jQueryElement = $("input[name=telefoon]");
    if (typeof(jQueryElement) !== "undefined") {
        jQueryElement.keyup(function(){
            $(this).val($(this).val().replace(/[^0-9\s\-]/g, ''));
        });
    }

    if ($("#callmeform").length > 0) {
        $("input#Telefoon, input#phone").keyup(function(){
            $(this).val($(this).val().replace(/[^0-9\s\-]/g, ''));
        });

        $("#callmeform").submit(function() {
            $.post("/Formhandler/Save.aspx?action=phone", 
                $("#callmeform").serialize(),
                function(data) {
                    if (data === "" || (new String(data).toLowerCase()) === "nok") {
                        alert('Dit is een ongeldig telefoonnummer.\r\nGebruik alleen cijfers, beginnend met een nul.');
                    } else {
                        $("#callmeform input[name=phone]").val($("#callmeform input[name=phone]").attr("defaultValue"));
                        $("#errorMsg").hide();
                        $("#callmeform input").hide();
                        $("#callmeform #succesMsg").show();
                    }
                }
            );
            return false;
        });
    }

    if ($("#offermailform").length > 0) {
        $("#offermailform").submit(function(e) {
            $.post("/Formhandler/Save.aspx?action=email",
                $("#offermailform").serialize(),
                function(data) {
                    if (data === "") {
                        alert('Het e-mailadres is ongeldig.');
                    } else {
                        $("#offermailform input[name=email]").val($("#offermailform input[name=email]").attr("defaultValue"));
                        $("#offersmail").hide();
                        $("#offers").show();
                    }
                }
            );

            e.preventDefault();
            return false;
        });
    }
    
    if ($("#refences_all").length > 0){
        var current = 1,
            max = $("#viewport").children(".ref_item").length,
            $vorige =    $("a[title='Vorige']"),
            $volgende =  $("a[title='Volgende']"),
            disable = function(which){
                if (which === "vorige"){
                    $vorige.css('cursor', 'default').children('img').attr('src', '/Images/btn_vorige_disabled.png');
                }else{
                    $volgende.css('cursor', 'default').children('img').attr('src', '/Images/btn_volgende_disabled.png');
                }
            },
            enable = function(which){
                if (which === "vorige"){
                    $vorige.css('cursor', 'pointer').children('img').attr('src', '/Images/btn_vorige.png');
                }else{
                    $volgende.css('cursor', 'pointer').children('img').attr('src', '/Images/btn_volgende.png');
                }
            },
            updateList = function(){
                $(".ref_item").each(function(){
                    var $this = $(this), id = $this.attr('id').split('ref')[1];                    
                    if (id < current || id > (current+4))
                        $this.hide();
                    else 
                        $this.show(); 
                });
                
                if (current > 1)
                    enable('vorige');
                else 
                    disable('vorige');
                
                if (current+3 < max)
                    enable('volgende');
                else 
                    disable('volgende');
            },
            showIt = function(which){
                if (which === 'volgende'){
                    if (current+1 <= max){
                        current++;
                        updateList();
                    }else{
                        disable('volgende');
                    }
                }else{
                    if (current-1 >= 1){
                        current--;
                        updateList();
                    }else{
                        disable('vorige');
                    }                
                }
            };
        
        $vorige.click(function(){
            var $cursor = $(this).css('cursor');
            if ($cursor === 'pointer' || $cursor === 'auto')  
                showIt('vorige');
        });
        
        $volgende.click(function(){
            var $cursor = $(this).css('cursor');
            if ($cursor === 'pointer' || $cursor === 'auto')
                showIt('volgende');
        });
        
        disable('vorige');
        if (max < 5) disable('volgende');
    } 
});