//http://www.lotterypost.com/js-compress.aspx
var ts; // latest timestamp json request was sent
var autosuggests; // dict to store the shown autosuggests in
var autosuggestid = null; // currently selected
var as_highlight = 0; // currently focus (keynav)
var max_as_highlight = 0;
var locHints = {
    "": "",
    "none": "",
    "postcode": "Postcode",
    "lonlat": "Postcode of woonplaats"
};
var provider = "All";
var iTimeoutID = null;

function getAutoSuggests(prov, val) {
    if (val && val.length > 0) {
        ts = new Date().getTime();
        $.getJSON('/HttpHandlers/AutoSuggest.ashx?', { q: val, p: prov, ts: ts }, function(data) {
            if (data.timestamp == ts) { // this response was also for the latest request
                if (data.result) {
                    var html = '';
                    autosuggests = new Object();
                    var cnt = 0;
                    var k = 0;
                    var start = 0;

                    // if there are searchlinks it should always be the first one!
                    if (data.result.length > 0 && data.result[0] != null && data.result[0].ProviderName == "Searchlinks") {
                        pr = data.result[0];
                        if (pr.Resultset.length > 0) {
                            html += '<ul class="searchlinks">';
                            for (var j = 0; j < pr.Resultset.length; j++) {
                                rs = pr.Resultset[j];
                                html += '<li>' + rs.Title + rs.SubTitle + '</li>';
                            }
                            html += '</ul>';
                        }
                        start = 1;
                    }

                    html += '<ul class="prov">';
                    for (var i = start; i < data.result.length; i++) {
                        pr = data.result[i];
                        if (pr != null && pr.Resultset.length > 0 && !pr.IsExtraResult) {
                            html += '<li><a href="#' + cnt + '">' + pr.ProviderName + '</a>';
                            autosuggests[cnt++] = { "ProviderName": pr.ProviderName };
                            if (pr.Resultset.length > 0) {
                                html += '<ul class="val">';
                                found = -1;
                                for (var j = 0; j < pr.Resultset.length; j++) {
                                    rs = pr.Resultset[j];
                                    if (rs.Title.toLowerCase() == val.toLowerCase()) { // exact match: preselect
                                        found = cnt;
                                    }
                                    html += '<li><a id="k' + ++k + '" href="#' + cnt + '">' + rs.Title + '<span>' + rs.SubTitle + '</span></a></li>';
                                    autosuggests[cnt++] = pr.Resultset[j];
                                }
                                if (j == 1) { // only one result: preselect
                                    found = cnt - 1;
                                }
                                if (found >= 0) { // preselect the preselected
                                    autosuggestid = found;
                                    var r = autosuggests[found];
                                    $('#z_zorgvalue').val(r.ID);
                                    $('#z_vestigingid').val(r.ExtraID);
                                }
                                max_as_highlight = k;
                                html += '</ul>';
                            }
                            html += '</li>';
                        }
                    }
                    html += '</ul>';
                    if (k == 0) { html = '<ul class="prov"><li>geen resultaten gevonden</li></ul>'; }
                    $('#autosuggestbox').html(html);
                    as_highlight = 0;

                    var hider = function(e) {
                        var a = $(e.target).closest('div#autosuggestbox'); // in or outside click?
                        if (a && a.length == 0) {
                            $('div#autosuggestbox').hide();
                            $('body').unbind('click', hider);
                        }
                    };
                    $('body').bind('click', hider);

                    $(".val li").hover(function(e) {
                        if (as_highlight >= 0) {
                            $("#k" + as_highlight).removeClass("highlight");
                            $(".prov").removeClass("highlighted");
                        }
                        as_highlight = 0;
                    });

                    $('div#autosuggestbox').show();
                }
            }
        });
    }
}

function getProviders() {
    /*ts = new Date().getTime();
    $.getJSON('/HttpHandlers/AutoSuggest.ashx?', { q: "", p: "All", ts: ts }, function(data) {
    if (data.result) {
    var html = '<ul class="provs">';
    for (var i = 0; i < data.result.length; i++) {
    pr = data.result[i];
    html += '<li><a href="#' + pr.ProviderName + '">' + pr.ProviderName + '</a>';
    html += '</li>';
    }
    html += '</ul>';
    $('#providerbox').html(html);

            var hideProviderbox = function(e) {
    $('div#providerbox').hide();
    $('body').unbind('click', hideProviderbox);
    };
    $('body').bind('click', hideProviderbox);

            $('div#providerbox').show();

        }
    });*/

    var hider = function(e) {
        var a = $(e.target).closest('div#providerbox'); // in or outside click?
        if (a && a.length == 0) {
            $('div#providerbox').hide();
            $('body').unbind('click', hider);
        }
    };
    $('body').bind('click', hider);

    $('div#providerbox').show();
}

function keyNav(k) {
    switch (k) {
        case 40:
        case 38:
            $(".prov").addClass("highlighted");
            $("#k" + as_highlight).removeClass("highlight");
            as_highlight += (k == 40) ? +1 : -1;
            if (as_highlight < 1) as_highlight = 1;
            if (as_highlight > max_as_highlight) as_highlight = max_as_highlight;
            $("#k" + as_highlight).addClass("highlight");

            break;
        case 13:
            if (as_highlight == 0) {
                as_highlight = 1;
            }
            var id = $("#k" + as_highlight).attr("hash").substr(1);
            selectAutoSuggest(id);
            break;
    }
}


function selectAutoSuggest(c) {
    var sinp = $('#searchinput');
    var linp = $('#z_place');
    var r = autosuggests[c];
    if ('ProviderName' in r) {
        alert("PROVIDER???"); //We don't do providers anymore
    } else {
        if (r.TypeName == "Vestiging") {
            sinp.val(r.Title);
            //linp.val(r.SubTitle);
            //linp.attr('disabled', 'disabled');
            $('#z_zorgvalue').val(r.ID);
            $('#z_vestigingid').val(r.ExtraID);
        } else {
            //linp.removeAttr('disabled');
            sinp.val(r.Title); // clear selected

            if (linp.attr("title") == linp.val() || linp.val() == "") {
                linp.val(locHints[r.NeededInput]);
            }
            $('#z_zorgvalue').val(r.ID);
            $('#neededinput').val(r.NeededInput);
            linp.attr("title", locHints[r.NeededInput]);
        }
        autosuggestid = c;
        $('#z_zorgtype').val(r.TypeName);
        $('div#autosuggestbox').hide();
    }
}

function validPostcodePlaats(s, required) {
    // begin met 3 cijfers of meer, check dan of begin valide postcode is
    if (required || s.match(/^[0-9]{3,}/) != null) {
        if (s.match(/^[0-9]{4}[ ]*[A-Za-z]{2}(\s+|$)/) == null) {
            return false;
        } else {
            return true;
        }
    }
    return true;
}

function showError(a, b) {
    $('#error' + a.attr("id")).remove();
    html = '<div class="error" id="error' + a.attr("id") + '"><div class="errorcontent"><div>' + b + '</div></div></div>';
    a.before(html);
}

function deepLink(zorgtype, postcode) {
    autosuggestid = 0;
    autosuggests = new Object();
    autosuggests[0]="";
    $('#z_zorgtype').val("Metainfo");
    $('#z_zorgvalue').val(zorgtype);
    //$('#searchinput').val(zorgtype);
    $('#z_place').val(postcode);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': postcode, 'region': 'nl' }, getLonLat);
}

function search() { // & validate
    var linp = $('#z_place');
    var ok = true;
    if (autosuggestid == null) {
        showError($('#searchinput'), "Voer een zorgtype in");
        return;
    }
    var neededinput = autosuggests[autosuggestid].NeededInput;
    var pconly = (neededinput == "postcode");
    if (linp.attr("title") == linp.val() || linp.val() == "") {
        showError(linp, "Vul hier een " + (!pconly ? " plaatsnaam of " : "") + " postcode in, in de vorm: 1051HL");
        return;
    }
    if (!validPostcodePlaats(linp.val(), pconly)) {
        showError(linp, "Vul hier een " + (!pconly ? " plaatsnaam of " : "") + " postcode in, in de vorm: 1051HL");
        return;
    }

    if (pconly) { //no lonlat processing needed (kraamzorg)
        submit();
    } else {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': linp.val(), 'region': 'nl' }, getLonLat);
    }
}

function getLonLat(results, status) {
    var pconly = (autosuggests[autosuggestid].NeededInput == "postcode");

    if (!status == google.maps.GeocoderStatus.OK || !results[0]) {
        showError($('#z_place'), "Geen resultaten gevonden voor deze " + (!pconly ? " plaatsnaam of " : "") + " postcode")
        return false;
    }

    var address_components, acl, types, tl, short_name;
    var rl = results.length;

    for (var i = 0; i < rl; i++) {
        if (address_components = results[i].address_components) {
            acl = address_components.length;
            for (var j = 0; j < acl; j++) {
                if (types = address_components[j].types) {
                    tl = types.length;
                    for (var k = 0; k < tl; k++) {
                        if (types[k] == 'country') {
                            short_name = address_components[j].short_name;
                            break;
                        }
                    }
                }
            }
        }
    }


    if (short_name && short_name != 'NL') {
        showError($('#z_place'), "Dit is geen geldige " + (!pconly ? " plaatsnaam of " : "") + " postcode")
        return false;
    } else {
        place = results[0].geometry.location;
        var latitude = place.lat();
        var longitude = place.lng();
        $('#z_latitude').val(latitude);
        $('#z_longitude').val(longitude);

        submit();
    }
}

function submit() {
    try {
        pageTracker._trackPageview('/zoekactie/' + autosuggests[autosuggestid].TypeName + "/" + autosuggests[autosuggestid].Title);
    } catch (err) {
        alert(err);
    }
    $('input[type=submit]').click();
}

$(document).ready(function () {
    $('#searchinput').keyup(function (e) { // type handler on the autosuggestbox
        if (e.keyCode != 40 && e.keyCode != 38 && e.keyCode != 13) {
            $('#z_place').removeAttr('disabled'); // clear selected
            $('#z_zorgvalue').val('');
            $('#z_zorgtype').val('');
            autosuggestid = null;
            if (iTimeoutID != null) {
                window.clearTimeout(iTimeoutID);
            }
            iTimeoutID = window.setTimeout("getAutoSuggests('" + provider + "','" + e.currentTarget.value + "')", 200);
            // getAutoSuggests(provider, e.currentTarget.value);
        }
    });

    // keypress does not work in chrome on cursor keys
    // but keypress is needed to prevent a submit on enter in firefox
    $('#searchinput').keypress(function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            e.stopPropagation();
            keyNav(e.keyCode);
            return false;
        }
    });

    $('#searchinput').keydown(function (e) { //cursorkeys+enter
        if (e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 13) {
            e.preventDefault();
            e.stopPropagation();
            keyNav(e.keyCode);
            return false;
        }
    });

    $("#autosuggestbox ul.prov li a").live('click', function (e) { // click handler on the autosuggest results
        var a = $(e.target).closest("a");
        var id = $(a).attr("hash").substr(1);
        if (id != '') {
            e.preventDefault();
            e.stopPropagation();
            selectAutoSuggest(id);
        }
    });

  

    $('#searchinput').focus(function (e) { // remove possible error
        $('#errorsearchinput').remove();
        jThis = jQuery(this);
        if (jThis.attr("title") == jThis.val()) {
            this.value = '';
            jThis.removeClass("prefilled");
        }
    });


    $('#z_place').focus(function (e) { // remove hint text&style
        jThis = jQuery(this);
        $('#errorz_place').remove();
        if (jThis.attr("title") == jThis.val()) {
            this.value = '';
            jThis.removeClass("prefilled");
        }
    });
    $('#z_place,#searchinput').blur(function (e) { // set hint text&style
        jThis = jQuery(this);
        if (!this.value) {
            this.value = jThis.attr("title");
            jThis.addClass("prefilled");
        }
    });

    $('#z_place').attr("title", locHints["lonlat"]);
    if ($('#z_place').val() == "") { // set postcode hint when empty (homepage)
        $('#z_place').addClass("prefilled").val(locHints["lonlat"]);
    }
    if ($('#searchinput').val() == "") { // set searchinput hint when empty (homepage)
        $('#searchinput').addClass("prefilled").val($('#searchinput').attr("title"));
    }

    $('#z_place').keypress(function (e) {
        if (e.which == 13) {
            setTimeout("search()", 100);
        }
    });

    $('#searchbtn').click(function (e) { // submit the search
        search();
    });

    $('.suggest_spec').click(function () {  // clicked on a searchsuggestion
        as_highlight = 0;
        $('#z_zorgvalue').val('');
        $('#z_zorgtype').val('');
        $('#searchinput').focus();
        $('#searchinput').attr('value', this.innerHTML.replace(/^\s+|\s+$/, ''));
        $('#searchinput').trigger('keyup');
        return false;
    });



    $("form :input:visible:enabled:first").focus();

    


    window.setInterval(sessionTimer, 10000);

});


//28-12-2010: Timer, this function is designed to keep the session of the user alive
function sessionTimer() { $.get(baseDir + "HttpHandlers/SessionTimer.ashx"); }




