﻿$(function() {
    // --------------------
    // Newsletter & search
    // --------------------
    setValue('#zoekField');
    setValue('#nieuwsbriefField');

    // Linker zoekveld
    $('input#zoekBtnLeft').click(function() {
        doZoeken($('input#zoekField').val());
    });
    $('input#zoekField').keydown(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            $('input#zoekBtnLeft').click();
        }
    });

    $('#nieuwsbriefField').keydown(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            doNieuwsbrief();
        }
    });
    $('input#nieuwsbriefButton').click(doNieuwsbrief);

    // --------------------
    // Topnav init, hover, submenu, etc
    // --------------------
    initMenu();

    // -------------------
    // Overige functies
    // -------------------

    // Rechtermuis click disablen
    if (location.host !== 'matrabike.juicedev.nl') {
        $(this).bind('contextmenu', function(e) {
            e.preventDefault();
        });
    }

    // Initialisatie Lightbox
    $('a.lightbox').lightBox(); // Select all links with lightbox class

    //Voeg onclick toe voor alle uitgaande links
    //BV:http://www.fietsned.nl/
    $("a[href^='http://']:not([href^='http://www.matrabike.nl'])").click(function() { // href beging met http:// en begint niet met http://www.matrabike.nl
        _gaq.push(['_trackPageview', '/exit/' + $(this).attr("href")]);
    });

    //Voeg onclick toe voor alle pdf's
    //BV: http://www.matrabike.nl/itemhandler.aspx?path=ROOT/customers/matrabike/documents/handleidingen/montage AXA montagebeugel.pdf
    $("a[href$='.pdf']").click(function() { // href eindigt op .pdf
        var regexp = /(\w|[-. ])+$/
        a = regexp.exec($(this).attr("href"));
        _gaq.push(['_trackPageview', '/download/' + a[0]]);
    });

    // Rotator
    placeRotator();

    /*
    Mobile browsing
    */
    var maxResolution = { width: 800, height: 600 };
    if ((screen.height < maxResolution.height && screen.width < maxResolution.width)) {
        // Verwijder flash
        $('object').remove();
        //Zet producten onder elkaar i.p.v. langs elkaar
        $('#right .title, #right .row').css({ width: 490 });
    }

    $('div.boxvergelijk div.infoRow div.Value').each(function() {
        if ($(this).attr('scrollWidth') > $(this).width()) {
            $(this).attr('title', $(this).text()).append('<div class="dots">...</div>');
        }
    });
});

// Navigation
var menuTimer = false;
function initMenu() {
    // Data opslaan
    $("#topNav a").each(function() {
        $(this).data('is-selected', $(this).parent().hasClass("selected"));

        if ($(this).parent().hasClass("selected")) {
            $text = $(this).find(".roundCenter").html();
        }
        else {
            $text = $(this).html();
        }
        $(this).data('text', $text);
    });

    // Submenu hiden
    $(".topNavSub").hide();

    $(".topNavSub").hover(
        function() {
            clearTimeout(menuTimer);
        }, function() {
            menuTimer = setTimeout(menuHide, 500);
        }
    );

    // Hover instellen
    $("#topNav a").hover(function() {
        // Timeout clearen indien nodig
        clearTimeout(menuTimer);

        // Remove selection
        menuRemoveSelected();

        // Hide alle submenu's
        $(".topNavSub").hide();

        // Make me hover!
        menuSelect($(this));

        // Activate sub menu
        $parent = $(this).parent();

        // Submenu instellen
        $(".topNavSub").each(function() {
            if ($($parent).attr("pos") == $(this).attr("pos")) {
                $(this).find("a:last").each(function() {
                    $(this).css({ 'background-image': 'none' });
                });

                $(this).show();
                $parentPos = $($parent).position();
                $(this).css({ left: ($parentPos.left + 8) });

                $(this).data('visible', true);
            }
        });
    },
    function() {
        menuTimer = setTimeout(menuHide, 500);
    });
}

function menuRemoveSelected() {
    // Back to basic
    $("#topNav .selected a").each(function() {
        $(this).parent().removeClass("selected");
        $(this).html($(this).data('text'));
    });
}

function menuHide() {
    // Remove selection
    menuRemoveSelected();

    // Selecteer standaard waarde
    $("#topNav a").each(function() {
        if ($(this).data("is-selected"))
            menuSelect($(this));
    });

    // Submenu hiden
    $(".topNavSub").hide();
}

function menuSelect(obj) {
    $(obj).parent().addClass("selected");
    var html = '<span class="roundLeft"></span><span class="roundCenter">';
    html += $(obj).data('text');
    html += '</span><span class="roundRight"></span>';
    $(obj).html(html);
}

// Left side (newsletter & search)
function doNieuwsbrief() {
    if (checkEmail('nieuwsbriefField')) {
        doPostBack();
    }
    else {
        alert('Het door u ingevulde e-mail adres is geen geldig e-mail adres.');
    }
}
function doZoeken(searchString) {
    if (trim(searchString) !== 'Zoeken naar...') {
        redirect('/Zoeken/' + optimizeSearchString(searchString) + '.aspx');
    }
}
/*
setValue 
Onclick de waarde weghalen. En onBlur terug zetten.
@param val klasse of id van het object (.class, #id)
*/
function setValue(val) {
    $(val).click(
		function() {
		    if (this.value == this.defaultValue) this.value = '';
		}
	);
    $(val).blur(
		function() {
		    if (this.value == '') this.value = this.defaultValue;
		}
	);
}

function optimizeSearchString(zoekstr) {
    /* 
    Alles eruit filteren behalve:
    - 0-9 (0-9)
    - a-z (a-z)
    - A-Z (A-Z)
    - Koppelstreepje (-)
    - Spaties (\s)
    Extra uitleg
    - begin met / Start regex
    - Eind met / Eind regex
    - Achter de laatste / nog een letter dus g staat voor global. Dus over hele string uitvoeren
    */
    zoekstr = zoekstr.replace(/[^0-9a-z''A-Z-\s]/g, '');
    zoekstr = zoekstr.replace(/\s+/g, ' ');
    zoekstr = trim(zoekstr);
    return zoekstr;
}

function trim(value) {
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    return value;
}

function checkEmail(veld) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/i.test($('input#' + veld).val())) {
        return true;
    }
    return false;
}

function redirect(loc) {
    document.location = loc;
}
function doPostBack() {
    url = document.location;
    document.aspnetForm.action = url;
    document.aspnetForm.submit();
}
function submitUrl(url, target) {
    document.aspnetForm.action = url;
    if (target != '') {
        if (target == '_blank') {
            window.open(url); //Anders blijft de action onthouden en worden alle links in een nieuw scherm geopend
        }
        else {
            document.aspnetForm.target = target;
            document.aspnetForm.submit();
        }
    }
    else {
        document.aspnetForm.submit();
    }
}
function submitform() {
    //var theForm = document.forms['aspnetForm'];
    //if (!theForm) {
    //    theForm = document.aspnetForm;
    //}
    var theForm = $('form#aspnetForm');
    theForm.submit();
}
function placeRotator() {
    var d = "";
    d = d + ('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="206" height="135" id="Rotator" align="middle">');
    d = d + ('<param name="allowScriptAccess" value="sameDomain" />');
    d = d + ('<param name="allowFullScreen" value="false" />');
    d = d + ('<param name="movie" value="/flash/rotator.swf" />');
    d = d + ('<param name="quality" value="high" />');
    d = d + ('<param name="bgcolor" value="#ffffff" />');
    d = d + ('<embed src="/flash/rotator.swf" quality="high" bgcolor="#ffffff" width="206" height="135" name="Rotator" ');
    d = d + (' align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="https://get.adobe.com/nl/flashplayer" />');
    d = d + ('</object>');
    try {
        document.getElementById("box").innerHTML = d;
    }
    catch (err) { }
}
function backToNormal(obj) {
    if (obj.value == "geen geldig e-mail adres")
        obj.value = "";
    //alert(obj.style.backgroundColor);
    obj.style.backgroundColor = "";
}
