var localSearch = new GlocalSearch();
var searching = false;

function checkWordCount(obj, count){
    var len = obj.value.split(/[\s]+/);
    if(len.length > count){
        alert('You have entered ' + len.length + ' words, but are only allowed to enter ' + count + '.\nYour text will be chopped.');
        obj.value = '';
        for (i = 0; i < count; i++){        
            obj.value += len[i];
            if (i < count - 1)
                obj.value += ' ';
        }
        return false;
    }
    return true;
}

function geocodeLocation(parentControl){ 
    
    if (!searching){

        var longitudeBox = document.getElementById(parentControl + '_Longitude');
        var latitudeBox = document.getElementById(parentControl + '_Latitude');

        if (longitudeBox && latitudeBox)
            longitudeBox.value = latitudeBox.value = '';
    
        var whereBox = document.getElementById(parentControl + '_Where');
        // check where box to see if looks like a postcode
        
        if (whereBox && whereBox.value){        
            if (whereBox.value.match(/^[A-Za-z]{1,2}[0-9A-Za-z]{1,2}( [0-9][A-Za-z]{2})?$/)){
                var button = document.getElementById(parentControl + '_Search');

                localSearch.setSearchCompleteCallback(
                    null,
                    function(){
                        if (localSearch.results[0]){
                            if (longitudeBox)
                                longitudeBox.value = localSearch.results[0].lng;
                                
                            if (latitudeBox)
                                latitudeBox.value = localSearch.results[0].lat;
                        }
                        
                        button.click();
                    }
                );
                
                localSearch.execute(whereBox.value + ', UK');
            
                searching = true;
                    
                return false;
            } else {
                return true;
            }
        } else {            
            return true;
        }
    } else {        
        return true;
    }    
}
