

// un-Bevocal the sessionid
//voiceruby default sessionid variable
var sessionid = bevocal.sessionid;

//redefined sessionid variable to keep the naming convention consistent to the middleware call
var sessionId = bevocal.sessionid;

// un-Bevocal the log function
function log(text) {
  bevocal.log(text);
}

//############################################################

var context = {
  'max_errors': 3,
  'reentry': false,
  'failure': undefined,
  'skill': undefined,
  'paths': { 'prompt':  'prompts/en-US/',
             'grammar': 'grammars/en-US/',
             'backend': ''                  },
  'states': [],
  'utterances': [],
  'goback': {'stack':[], 'statuses': {'played': false, 'recognized': false}},
  'once_flags': {},
  'transfer': {},
  'app': {}
};

//-------------------------------------------------

context.goback.push = function(name) {
                        log("goback push: '" + name + "'");
                        if (this.stack.last() != name) {
                          this.stack.push(name);
                        }
                      };

context.goback.pop = function() {
                       var name = this.stack.pop();
                       log("goback pop: '" + name + "'");
                       return name == context.states.current.name ? this.pop() : name;
                     };

//-------------------------------------------------

context.states.visit = function(name) {
                         this.previous = this.current;
                         if(this.previous) { this.previous.duration = Date.diff(Date.now(), this.previous.visited_at); }
                         context.states.push({'name':name,'visited_at': Date.now()});
                         this.current = context.states.last();

                         this.current.visit_count = this.visit_count(name);
                         log("visiting '" + name + "' for the " + ordinal(this.current.visit_count) + " time");
                       };

context.states.visit_count = function(name) {
                               return this.count(function(state) { return state.name == name;});
                             };

//############################################################

function utterances_from(state_name) {
  return context.states.filter(function(state) { return state.name == state_name; }).map(function(state) { return state.utterance; }).compact();
}

function register_utterance(utterance) {
  context.utterances.push(utterance);
  context.states.current.utterance = utterance;
}
//-------------------------------------------------

context.once_flags.check = function(name) {
                             var value = context.once_flags.fetch(name, true);
                             context.once_flags[name] = false;
                             return value;
                           };

//-------------------------------------------------

context.states.was_visited = function(name) {
  return context.states.any(function(state) { return state.name == name; });
};

//############################################################

//############################################################
//# DEBUGGING FUNCTIONS
//############################################################

// more complicated because of platform's fake objects
function cloneObject(obj) {
  if(!obj) { return obj; }

  var result;
  if(typeof(obj) == 'object') {
    result = obj.constructor && new obj.constructor() || {};
    for(var property in obj) {
      if(!obj.hasOwnProperty || obj.hasOwnProperty && obj.hasOwnProperty(property)) {
        result[property]= cloneObject( obj[property] );
      }
    }

  } else {
    result = obj;
  }

  return result;
}

//############################################################

// more complicated because of platform's fake objects
function inspect(obj, inherited) {
  var keys = [];
  for(var key in obj) {
    keys.push(key);
  }
  keys.sort();

  log("############################################################");
  for(var i = 0; i <= keys.length; i++) {
    var key = keys[i];

    if(inherited || obj.hasOwnProperty(key)) {
      log(key + ": " + obj[key]);
    }
  }
  log("############################################################");
}

function log_inspect(text, obj, inherited) {
  log(text);
  inspect(obj, inherited);
}

//############################################################
//# JSON
//############################################################

function xml2json(xmldata) {
  var json = xmldata.documentElement.firstChild.data;
  //log("JSON: " + json);
  // Only if empty string, set json to "{}"
  if (json != undefined) { json = json.trim() || "{}"; };
  return eval("(" + json + ")");
}

//############################################################
//# CALL SUMMARY
//############################################################

var call_summary = function(xs, level, indent) {
  var format = {     'state' : function(x) { var secs = x.duration / 1000; return x.name + ' (' + (isNaN(secs) ? "unknown" : (secs.toFixed(2) + "s")) + ') -- ' + x.reason },
                 'utterance' : function(x) { return x.value + ' - ' + (x.confidence * 100).toFixed(0) + '% - ' + x.slot } };

  var call_summary_proper = function(xs, level, indent) {
    level = level || 0;
    indent = indent || 2;

    var i = 1;
    xs.each(function(x) {
      if(x.name) {
        log(".".repeat(level*indent) +
            i + ": " +
            format.state(x) +
            (x.utterance ? (" -------------------- CALLER SAID: " + format.utterance(x.utterance)) : ""));
        i += 1;
      } else {
        call_summary_proper(x, level+1);
      }
    });

  };

  log('############################################################');
  log('CALL SUMMARY:');
  log('############################################################');
  context.states_summary = context.states_summary ? context.states_summary : context.states;
  
  xs = xs || context.states_summary;

  call_summary_proper(xs, level, indent);

  log("############################################################");
};

//############################################################

// flatten the context.states tree to a list
// BUT modified the original because they are references to the original
//
// patches the "return" states' durations AND
// the case for the very last state
function fix_durations(states) {
  var list = states.flatten();

  var now = Date.now();

  for(var i=0; i<(list.length-1); i++) {
    if(list[i].duration === undefined) {
      list[i].duration = Date.diff(list[i+1].visited_at, list[i].visited_at);
    }
  }
  list.last().duration = Date.diff(now, list.last().visited_at);
};

//############################################################
//# RECOGNITION
//############################################################

// more complicated because of platform's fake objects
function extract_slots(rejected_utterances, results) {
  rejected_utterances = rejected_utterances || [];
  log('rejected_utterances: ' + rejected_utterances.toJSONString());
  results = results || cloneObject(application.lastresult$);

  var raw_slots = {};
  for (var i=0; i < results.length; i++) {
    results[i].interpretation.each(function(slot, value) {
      if(slot.match(/^SWI_/)) { return; };
      (raw_slots[slot] = raw_slots[slot] || []).push(value);
    });
  }

  log('raw reco: ' + raw_slots.toJSONString());

  var trimmed_slots = {};
  raw_slots.each(function(slot, values) {
    var rejected_values = rejected_utterances.filter(function(utt) { return utt.slot == slot }).map(function(utt) { return utt.value });
    log('slot: ' + slot + ' -- rejected_values: ' + rejected_values.toJSONString());
    trimmed_slots[slot] = values.subtract(rejected_values)[0] || values[0];
  });

  log('trimmed reco: ' + trimmed_slots.toJSONString());

  return trimmed_slots;
}

//############################################################
//# Counter -- used to throw exceptions on a count
//############################################################

function Counter(n, event) {
  this.n = n;
  this.event = event;
  this.reset();
}

Counter.prototype.tick = function() {
  this.i++;

  if(this.i >= this.n) { this.reached = true; }
};

Counter.prototype.reset = function() {
  this.i = 0;
  this.reached = false;
};

//############################################################
//# Iterator -- external iterator for arrays
//############################################################

function Iterator(list) {
  this.i = -1;
  this.list = list;
}

Iterator.prototype.next = function() {
  this.i++;

  if(this.i < 0 || this.i >= this.list.length) { return undefined; }
  return this.list[this.i];
}

Iterator.prototype.previous = function() {
  this.i--;

  if(this.i < 0 || this.i >= this.list.length) { return undefined; }
  return this.list[this.i];
}

Iterator.prototype.reset = function() {
  this.i = -1;
}

Iterator.prototype.isFirst = function() {
  return this.i == 0;
}

Iterator.prototype.isLast = function() {
  return this.i == this.list.length-1;
}

//############################################################
//# REPORTLOGGER
//############################################################

function reportLogger(label,message) {
  log("Reporting:"+label+" "+message);
}

function register_transition(reason) {
  context.states.current.reason = reason;
  reportLogger("transitionCondition", reason);
}


//############################################################
//# MATH
//############################################################

Math.rand_int = function(num) {
  return Math.floor(Math.random() * num);
};

//############################################################
//# OBJECT
//############################################################

Object.prototype.each = function(f) {
                          for(var key in this) {
                            if(this.hasOwnProperty(key)) {
                              f(key, this[key]);
                            }
                          }
                        };

Object.prototype.fetch = function(name, _default) {
                           if(this[name] === undefined) {
                             return _default;
                           }

                           return this[name];
                         };

Object.prototype.keys = function() {
                          var result = [];

                          this.each(function(key,value) {
                            result.push(key);
                          });

                          return result;
                        };

Object.prototype.values = function() {
                            var result = [];

                            this.each(function(key,value) {
                              result.push(value);
                            });

                            return result;
                          };

Object.prototype.merge = function(other) {
                           var result = cloneObject(this);

                           other.each(function(key,value) {
                             result[key] = value;
                           });

                           return result;
                         };

Object.prototype.to_a = function() {
                           var result = [];

                           this.each(function(key,value) {
                             result.push([key, value]);
                           });

                           return result;
                         };

//############################################################
//# ARRAY
//############################################################

Array.prototype.each = function(f) {
                         for(var i=0; i<this.length; i++) {
                           f(this[i], i);
                         }
                       };

Array.prototype.find = function(f) {
                         for(var i=0; i<this.length; i++) {
                           if(f(this[i])) {
                             return this[i];
                           }
                         }
                         return undefined;
                       };

Array.prototype.all = function(f) {
                        var result = true;

                        this.each(function(value) {
                          if(!f(value)) {
                            result = false;
                          }
                        });

                        return result;
                      };

Array.prototype.any = function(f) {
                        var result = false;

                        this.each(function(value) {
                          if(f(value)) {
                            result = true;
                          }
                        });

                        return result;
                      };

//#-------------------------------------------------

Array.prototype.map = function(f) {
                        var result = [];

                        this.each(function(value) {
                          result.push(f(value));
                        });

                        return result;
                      };

Array.prototype.filter = function(f) {
                           var result = [];

                           this.each(function(value) {
                             if(f(value)) {
                               result.push(value);
                             }
                           });

                           return result;
                         };

Array.prototype.zip_with = function(other, f) {
                             var n = Math.min(this.length, other.length);
                             var result = [];

                             for(var i=0; i<n; i++) {
                               result.push(f(this[i], other[i]));
                             }

                             return result;
                           };

Array.prototype.zip = function(other) {
                        return this.zip_with(other, function(x,y) { return [x,y]; });
                      };

//#-------------------------------------------------

Array.prototype.compact = function() {
                            return this.filter(function(x) { return x !== undefined && x !== null });
                          };

Array.prototype.include = function(x) {
                            return this.any(function(value) { return value == x });
                          };

//#-------------------------------------------------

Array.prototype.first = function() {
                          return this.length > 0 ? this[0] : undefined; // explicit to stop warnings
                        };

Array.prototype.last = function() {
                         return this.length > 0 ? this[this.length-1] : undefined; // explicit to stop warnings
                       };
//#-------------------------------------------------

Array.prototype.pick = function() {
                         return this[Math.rand_int(this.length)];
                       };

//#-------------------------------------------------

Array.prototype.count = function(f) {
                          return this.filter(f).length;
                        };

Array.prototype.subtract = function(other) {
                             return this.filter(function(value) { return !other.include(value) });
                           };

//#-------------------------------------------------

Array.prototype.flatten = function() {
                            var result = [];

                            for(var i=0; i<this.length; i++) {
                              if(this[i].flatten) {
                                result = result.concat(this[i].flatten());
                              } else {
                                result.push(this[i]);
                              }
                            }

                            return result;
                          };

//############################################################
//# STRING
//############################################################

String.prototype.repeat = function(n) {
                            var result = '';
                            for(var i=0; i<n; i++) {
                              result += this;
                            }

                            return result;
                          };

String.prototype.trim = function() {
                          return this.replace(/^\s+|\s+$/g, '');
                        };

//############################################################
//# DATE
//############################################################

Date.now = function() {
  return new Date();
};

Date.today = function() {
  return Date.now().at_midnight();
};

Date.diff = function(date1, date2) {
  return date1.getTime() - date2.getTime();
};

Date.create = function(value) {
  var result = new Date(value);
  log('date: ' + value + ' -> ' + result.toString());
  return (result == 'Invalid Date') ? undefined : result;
};

Date.prototype.at_midnight = function() {
  return new Date(this.getFullYear(), this.getMonth(), this.getDate());
};

Date.prototype.equal = function(other) {
  return Date.diff(this, other) == 0;
};

Date.prototype.not_equal = function(other) {
  return !this.equal(other);
};

Date.prototype.in_months = function() {
  var result = this.getFullYear() * 12 + this.getMonth();
  log('in_months: ' + this.toString() + ' -> ' + result);
  return result;
};

//############################################################
//# FUNCTION
//############################################################

// function adapter: allows you to call a multi-parameter
// function by passing it an array of the parameters instead
// -- useful when you do not control the invocation directly
Function.prototype.uncurry = function() {
  var f = this;
  return function(list) {
    return f.apply(this, list);
  }
}


//############################################################

// 1 -> 1st, 2 -> 2nd, 3 -> 3rd, 4 -> 4th, ...
function ordinal(x) {
  x = String(x);
  var result = 'th'; // usually it's "th"

  // exceptions
  if(x.match(/1$/)) { result = 'st'; }
  if(x.match(/2$/)) { result = 'nd'; }
  if(x.match(/3$/)) { result = 'rd'; }
  // exception to the exceptions
  if(x.match(/1[123]$/)) { result = 'th'; } // changes it back

  return x + result;
}

//############################################################

// 07 -> 7
function cut_leading_zero(number) {
  return parseInt(number, 10).toString();
}

// 7 -> 07
function zero_pad(num, width) {
  var result = num.toString();

  var n = width - result.length;
  for(var i=0; i<n; i++) {
    result = '0' + result;
  }

  return result;
}

//############################################################

// pluralize(1, "person", "people")
// pluralize(2, "flower")
function pluralize(count, singular, plural) {
  if(count == 1) { return singular; }

  // >1 or ... 0 -- 0 flowers
  return plural || singular + "s";
}

//############################################################
//# PROMPT
//############################################################

function make_prompt(filename) {
  return context.paths.prompt + filename + '.wav';
}

//-------------------------------------------------

function to_prompt(tts, path) {
  if(tts && !path) {
    return {'tts': tts.toString() };
  }

  if(path && !tts) {
    return {'path': path };
  }

  return {'tts': tts.toString(), 'path': path};
}

function silence(num) {
  var m = num.toString().match(/(\d+)(ms|s)?/)
  m[2] = m[2] || 'ms';
  m[1] = m[2] == 'ms'  ? Math.max(m[1], 20) : Math.max(m[1], 1);  // for SDP-10
  return to_prompt('<break time="' + m[1] + m[2] + '"/>');
}

function prompt_map(list) {
  return list.map(
           function(elem) {
             if(elem.tts) {
               return elem;
             } else {
               return to_prompt(elem);
             }
           });
}

function prefix_prompts(list, prefix) {
  return list.map(
           function(prompt) {
             var tts = prompt.tts;   // explicit to stop warnings
             var path = prompt.path; // explicit to stop warnings
             return prompt.path ? to_prompt(tts, prefix + path) : prompt;
           });
}


//############################################################

function succ(date) {
  return new Date(date.getTime() + 1000 * 60 * 60 * 24);
}

function business_succ(date) {
  var result = succ(date);
  return (result.getDay() === 0 || result.getDay() == 6) ? business_succ(result) : result;
}

//#-------------------------------------------------

function repeat(f, x, n) {
  return (n === 0) ? x : repeat(f, f(x), n-1);
}

function days(date, n) {
  log('days (+' + n + '): ' + date.toString());
  return repeat(succ, date, n);
}

function business_days(date, n) {
  log('business_days (+' + n + '): ' + date.toString());
  return repeat(business_succ, date, n);
}

//############################################################

function this_month(other) {
  log("this_month: " + other.toString());
  return Date.now().in_months() - other.in_months() === 0;
}

function next_month(other) {
  log("next_month: " + other.toString());
  return Date.now().in_months() - other.in_months() == -1;
}

function last_month(other) {
  log("last_month: " + other.toString());
  return Date.now().in_months() - other.in_months() == 1;
}

//############################################################

/*
    json.js
    2008-02-14

    Public Domain

    No warranty expressed or implied. Use at your own risk.

    This file has been superceded by http://www.JSON.org/json2.js

    See http://www.JSON.org/js.html

    This file adds these methods to JavaScript:

        array.toJSONString(whitelist)
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString(whitelist)
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

            The object and array methods can take an optional whitelist
            argument. A whitelist is an array of strings. If it is provided,
            keys in objects not found in the whitelist are excluded.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.

    This file will break programs with improper for..in loops. See
    http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load untrusted third party
    code into your pages.
*/

/*jslint evil: true */

/*members "\b", "\t", "\n", "\f", "\r", "\"", "\\", apply, charCodeAt,
    floor, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
    getUTCMonth, getUTCSeconds, hasOwnProperty, join, length, parseJSON,
    prototype, push, replace, test, toJSONString, toString
*/

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'object':

// Serialize a JavaScript object value. Treat objects thats lack the
// toJSONString method as null. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                if (v && typeof v.toJSONString === 'function') {
                    a.push(v.toJSONString(w));
                } else {
                    a.push('null');
                }
                break;

            case 'string':
            case 'number':
            case 'boolean':
                a.push(v.toJSONString());
                break;
            default:
                a.push('null');
            }
        }

// Join all of the member texts together and wrap them in brackets.

        return '[' + a.join(',') + ']';
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {

// Eventually, this method will be based on the date.toISOString method.

        function f(n) {

// Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getUTCFullYear()   + '-' +
                   f(this.getUTCMonth() + 1) + '-' +
                   f(this.getUTCDate())      + 'T' +
                   f(this.getUTCHours())     + ':' +
                   f(this.getUTCMinutes())   + ':' +
                   f(this.getUTCSeconds())   + 'Z"';
    };


    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : 'null';
    };


    Object.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            k,          // The current key.
            i,          // The loop counter.
            v;          // The current value.

// If a whitelist (array of keys) is provided, use it assemble the components
// of the object.

        if (w) {
            for (i = 0; i < w.length; i += 1) {
                k = w[i];
                if (typeof k === 'string') {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString(w));
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        } else {

// Iterate through all of the keys in the object, ignoring the proto chain
// and keys that are not strings.

            for (k in this) {
                if (typeof k === 'string' &&
                        Object.prototype.hasOwnProperty.apply(this, [k])) {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString());
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        }

// Join all of the member texts together and wrap them in braces.

        return '{' + a.join(',') + '}';
    };


    (function (s) {

// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.

// m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


        s.parseJSON = function (filter) {
            var j;

            function walk(k, v) {
                var i, n;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                            n = walk(i, v[i]);
                            if (n !== undefined) {
                                v[i] = n;
                            } else {
                                delete v[i];
                            }
                        }
                    }
                }
                return filter(k, v);
            }


// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

// We split the first stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace all backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.test(this.replace(/\\./g, '@').
                    replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
                    replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + this + ')');

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

                return typeof filter === 'function' ? walk('', j) : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('parseJSON');
        };


        s.toJSONString = function () {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) +
                                               (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}