Converted from PHP to JavaScript!