$(document).ready(function() {

    if ($('#intro').length) {
        randomIntro();
    }
    if ($('#map_canvas').length) {
        loadMap();
    }

    // M.b.v. de jQuery plugin hoverIntent de contentnav werkend krijgen met hovereffecten
    var hiConfig = {
        interval: 0,
        timeout: 200,
        over: function() {
            $(this).addClass('active').children('ul').show();
        },
        out: function() {
            $(this).removeClass('active').children('ul').hide();
        }
    };
    $('.mainitem, .subitem').hoverIntent(hiConfig);

    // Random visual rechts
    var IMG_COUNT = 8;
    var randImg = parseInt((Math.random() * IMG_COUNT), 10);
    $('img#visual').attr('src', '/images/visuals/' + randImg + '.jpg').show();

    $('form#zipcode_finder').submit(function(e) {
        var text = {
            en: {
                loading:            'Loading',
                error:              'No branche can be found.',
                closest_branche:    'Closest branche:',
                contact:            'Click here for contact details.',
                link: {
                  'AGIN Boeder':          '/en/boeder',
                  'AGIN Otten':           '/en/otten',
                  'AGIN Pranger':         '/en/pranger',
                  'AGIN Timmermans':      '/en/timmermans'
                }
            },
            nl: {
                loading:            'Laden',
                error:              'Er kan geen vestiging gevonden worden.',
                closest_branche:    'Dichtstbijzijnde vestiging:',
                contact:            'Klik hier voor de contactgegevens.',
                link: {
                  'AGIN Boeder':          '/nl/boeder',
                  'AGIN Otten':           '/nl/otten',
                  'AGIN Pranger':         '/nl/pranger',
                  'AGIN Timmermans':      '/nl/timmermans'
                }
            }

        };
        $('form#zipcode_finder_result').html(text[getLanguage()]['loading'] + '&hellip;');
        e.preventDefault();
        var zipcode = $('form#zipcode_finder input').val().match(/^\d{4}/);
        $.getJSON('/get_branche_office', {zipcode: zipcode}, function(data) {
            if (data == null) {
                $('p#zipcode_finder_result').html(text[getLanguage()]['error']);
            } else {
                $('p#zipcode_finder_result').html(text[getLanguage()]['closest_branche'] + ' <strong>' + data.branche_office + ', <a href="' + text[getLanguage()]['link'][data.bailiff_office] + '">' + data.bailiff_office + '</a></strong><br /><a href="' + text[getLanguage()]['link'][data.bailiff_office] + '/contact">' + text[getLanguage()]['contact'] + '</a>');
            }
        });
    });

    $('#add_invoice').click(function(e) {
        e.preventDefault();
        var maxInvoices = 10;
        var currentInvoices = $('.invoice-fields[id*="factuur"]').length;
        if (currentInvoices == maxInvoices) {
            $('#add_invoice').hide();
        }
        var newRow = $('#factuur1').clone();
        incrementInvoiceNumber(newRow, 'id', currentInvoices);
        $('input', newRow).each(function(i, el) {
            $(el).val('');
            incrementInvoiceNumber($(el), 'name', currentInvoices);
            incrementInvoiceNumber($(el), 'id', currentInvoices);
        });
        $('tr:has(#add_invoice)').before(newRow);
    });

    updateTotalInvoiceAmount();
    $('input[id*=bedrag]').live('change', updateTotalInvoiceAmount);

});

//http://maps.google.nl/?ie=UTF8&ll=52.028838,5.482178&spn=2.470627,4.938354&z=8

function loadMap() {
    var myLatlng = new google.maps.LatLng(52.068838, 5.342178);
    var myOptions = {
        zoom: 7,
        center: myLatlng,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
// Create our "tiny" marker icon
    aginIcon = "/images/agin_marker_sprite.png";
    aginIconShadow = "/images/agin_marker_sprite_shadow.png";

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var offices = new Array();
    offices[0] = {};
    offices[0].title = 'Agin Pranger';
    offices[0].location = new google.maps.LatLng(52.952964, 5.936258);
    offices[0].content = '<p>President Kennedylaan 33<br />8442 JG Heerenveen<br />051 362 60 82</p><a href="/pranger/">www.agin.nl/pranger</a>';
    offices[1] = {};
    offices[1].title = 'Agin Pranger';
    offices[1].location = new google.maps.LatLng(52.994767, 6.536092);
    offices[1].content = '<p>Oude-Hoofdvaartsweg 1A<br />9405 Assen<br />059 239 03 90</p><a href="/pranger/">www.agin.nl/pranger</a>';
    offices[2] = {};
    offices[2].title = 'Agin Pranger';
    offices[2].location = new google.maps.LatLng(52.286658, 6.78061);
    offices[2].content = '<p>Welbergweg 140<br />7556 PE Hengelo<br />074 249 03 60</p><a href="/pranger/">www.agin.nl/pranger</a>';
    offices[3] = {};
    offices[3].title = 'Agin Otten';
    offices[3].location = new google.maps.LatLng(50.888168, 5.975166);
    offices[3].content = '<p>Schinkelstraat 5<br />6411 LN Heerlen<br />045 560 07 06</p><a href="/otten/">www.agin.nl/otten</a>';
    offices[4] = {};
    offices[4].title = 'Agin Timmermans';
    offices[4].location = new google.maps.LatLng(51.497224, 4.310254);
    offices[4].content = '<p>Gagelboslaan 4<br />4600 AA Bergen op Zoom<br />016 421 30 00</p><a href="/timmermans/">www.agin.nl/timmermans</a>';
    offices[5] = {};
    offices[5].title = 'Agin Timmermans';
    offices[5].location = new google.maps.LatLng(51.537164, 5.040455);
    offices[5].content = '<p>Emma Goldmanweg 8<br />5032 MN Tilburg<br />013 595 20 80</p><a href="/timmermans/">www.agin.nl/timmermans</a>';
    offices[6] = {};
    offices[6].title = 'Agin Timmermans';
    offices[6].location = new google.maps.LatLng(51.645281,4.59977);
    offices[6].content = '<p>Postbus 24<br />4760 AA  Zevenbergen<br />016 832 97 80</p><a href="/timmermans/">www.agin.nl/timmermans</a>';
    offices[7] = {};
    offices[7].title = 'Agin Timmermans';
    offices[7].location = new google.maps.LatLng(51.504963,3.888899);
    offices[7].content = '<p>Vlasmarkt 6<br />4460 MC Goes<br />011 324 63 33</p><a href="/timmermans/">www.agin.nl/timmermans</a>';
    offices[8] = {};
    offices[8].title = 'Agin Boeder';
    offices[8].location = new google.maps.LatLng(52.384942, 4.625715);
    offices[8].content = '<p>Zijlweg 69<br />2013 DD Haarlem<br />023 517 76 66</p><a href="/boeder/">www.agin.nl/boeder</a>';
    offices[9] = {};
    offices[9].title = 'Agin Boeder';
    offices[9].location = new google.maps.LatLng(52.092032,5.124732);
    offices[9].content = '<p>Kromme Nieuwegracht 11<br />3512 HC Utrecht<br />030 410 02 20</p><a href="/boeder/">www.agin.nl/boeder</a>';

    for (var i = 0; i < offices.length; i++) {
        addMarker(map, offices[i]);
    }
}

function addMarker(map, office) {
    var contentString = '<div id="content">' +
            '<div id="siteNotice">' +
            '</div>' +
            '<h1>' + office.title + '</h1><h2>Gerechtsdeurwaarders en incassospecialisten</h2>' +
            '<div>' + office.content +
            '</div>' +
            '</div>';

    office.infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    var marker = new google.maps.Marker({
        position: office.location,
        map: map,
        title: office.title,
        icon: aginIcon,
        shadow: aginIconShadow
    });
    google.maps.event.addListener(marker, 'click', function() {
        office.infowindow.open(map, marker);
    });
}
function submitform(id) {
    var naam = document.getElementById(id).name;
    document.forms[naam].submit();
}

function randomIntro() {
    var n = Math.floor(Math.random() * 8) + 1;
    $("#intro").html('<object width="908" height="520">' +
            '<param name="movie" value="/swf/agin_ani' + n + '.swf">' +
            '<embed src="/swf/agin_ani' + n + '.swf" width="908" height="520"></embed>' +
            '</object>');
    $("#intro param").val("/swf/agin_ani" + n + ".swf");
    $("#intro embed").attr("src", "/swf/agin_ani" + n + ".swf");
}

function clearintro() {
    if (window.location.pathname != "/"){
      window.location = "/nl" + window.location.pathname;
    } else {
      window.location = "/nl/";
    }

}

function getLanguage() {
    var urlParts = window.location.pathname.split('/');
    return urlParts[1];
}

function incrementInvoiceNumber(el, attr, index) {
    $(el).attr(attr, $(el).attr(attr).replace(/\d(.*)$/, index + 1 + '$1'));
}

function updateTotalInvoiceAmount() {
    var totalInvoiceAmount = 0;
    $('input[name*=bedrag]').each(function(i, el) {
        $(el).val(Number($(el).val().replace(/,/g, '.')).toFixed(2));
        if (/^[\d\.]+$/.test($(el).val())) {
            totalInvoiceAmount += Number($(el).val());
        }
    });
    setTotalInvoiceAmount(totalInvoiceAmount);
}

function setTotalInvoiceAmount(amount) {
    $('#totaal').val(Number(amount).toFixed(2));
    $('#total_amount').html('&euro;' + Number(amount).toFixed(2));
}
