/*
  How to I embed this?
  1) Drop this file as an include (as well as prototype.js)
  2) Done

  To bypass the survey - add in your javascript:
  Survey.skip = true;

  To force the survey to be shown on page load - add
  Survey.fireOnLoad = true;


  How does this work?
  1) Is there a UT cookie
      AND does the path contain a directory
      AND does a SURVEY != done?
     Then attachs an event onload to initialize
  2) Call   /survey/check.asp?url=window.location.pathname&action=check&sc=foo
  3) Get XML Response
  4) case domNode('status')
      none, declined, viewed, taken, maxed
                                There is no survey to view, OR
                                the user declined the survey, OR
                                the user viewed the survey, OR
                                the user took the survey, OR
                                the user has declined 9 times
                            Set survey cookie at path /topmostdir/
      show  - Display the popover now
              Use the other nodes in the document to display the survey
      delay - We are not ready to view the survey yet.


Other notes:
 If we showed you the survey today on any AWI site - don't show the survey.
 Thats why a SURVEY session cookie is set to /


If you wish to bypass the default wait times,etc - you can use the
Survey.trigger() method to bypass the times.

!!IMPORTANT!!
 This has a dependency on prototype.js

*/

var Survey = {
  skip: false,
  fireOnLoad: false,
  cookieName: "SURVEY",
  utCookieName: "UT",

  noop : function () {
  },

  /*
   * called each time a page is loaded to see if we need to do anything
   */
  init : function () {
    if (Survey.skip) {
      return;
    }

    if (Survey.fireOnLoad) {
      Survey.trigger(false);
      return;
    }

    var sc = "";
    // Need to send the 1st survey cookie we see since
    // the check path is a different path than the path of our
    // cookie setting
    if (Survey.Cookie.get(Survey.cookieName)) {
      sc = "&sc=" + Survey.Cookie.get(Survey.cookieName);
    }
    new Ajax.Request("/survey/check.asp?action=check" +
                      "&url=" + window.location.pathname +
                      sc,
                    {onSuccess:Survey.initSurveyCallback});
  },

  nodeValue : function(xml, tagName) {
    var val = xml.getElementsByTagName(tagName);
    try {
      // IE vs ff
      if (val[0].text) {
        return val[0].text;
      } else {
        return val[0].textContent;
      }
    } catch(e) {
      return null;
    }
  },
  /*
  * Show the survey popover
  */
  display: function (xmldoc) {
    try {
      var top = Survey.nodeValue(xmldoc, 'top');
      var width = Survey.nodeValue(xmldoc, 'width');
      var height = Survey.nodeValue(xmldoc, 'height');
      var innerHtml = Survey.nodeValue(xmldoc, 'innerHtml');

      if (width==null || height==null || innerHtml == null) {
        return;
      }


      var surveyDiv = document.createElement('DIV');
      surveyDiv.style.position = 'absolute';
      surveyDiv.style.margin = '0 0 0 0';
      surveyDiv.style.width = width + 'px';
      surveyDiv.style.height = height + 'px';
      surveyDiv.style.zIndex = 1000;
      surveyDiv.style.backgroundColor = "white";
      surveyDiv.id = "surveyDiv";

      surveyDiv.innerHTML =
        "<iframe style='border:1px solid Black;width:100%;height:100%;position:absolute;left:0;top:0;' " +
        "        src='" + innerHtml + "'></iframe>";
      surveyDiv.style.left = ((document.body.clientWidth - width) / 3 + "px");
      // dangerous - since it may not work on the back button
      if (top) {
        surveyDiv.style.top = top;
      } else {
        surveyDiv.style.top = "150px";
      }

      document.body.insertBefore(surveyDiv, document.body.firstChild);

      surveyDiv.style.visibility = 'visible';
    } catch(e) {
    }
  },
  /*
  * starts the timer if the response allows it.
  */
  initSurveyCallback: function (httpRequest) {
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
      try {
        var xmldoc = httpRequest.responseXML;
        if (xmldoc) {
          var status = Survey.nodeValue(xmldoc, 'status');
          if (status=="none" ||
              status=="declined"  ||
              status=="viewed"  ||
              status=="taken"  ||
              status=="maxed"  ||
              status=="error") {
            Survey.Cookie.set(Survey.cookieName, "done", Survey.topLevelDir());
          } else if (status=="delay") {
            var to = Survey.nodeValue(xmldoc, 'timeout');
            if (to) {
              Survey.Cookie.set(Survey.cookieName, to, Survey.topLevelDir());
            } else {
              //wtf
              Survey.Cookie.set(Survey.cookieName, "done", "/");
            }
          } else if (status=="show") {
            Survey.Cookie.remove(Survey.cookieName, Survey.topLevelDir());
            // Set to top level dir to prevent other surveys during this session
            Survey.Cookie.set(Survey.cookieName, "done", "/");
            Survey.display(xmldoc);
            return;
          } else {
            // be conservative - bad stuff came back - set the cookie
            // to prevent future bad things
            Survey.Cookie.set(Survey.cookieName, "done", Survey.topLevelDir());
          }
        } else {
          Survey.Cookie.set(Survey.cookieName, "done", Survey.topLevelDir());
        }
      } catch(e) {
        // crap - bad things happened
        Survey.Cookie.set(Survey.cookieName, "done", Survey.topLevelDir());
      }
    }
  },
  /*
    A user generated event triggered the survey to launch.
    To use this - the developer needs to add Survey.trigger() to their code
    on the action which (of course) is the trigger.

    But the trigger is obeyed IFF the existing survey rules are also obeyed
    to prevent multiple survey views.

    ignoreWait allows the user to bypass any extra timed waits.
    IOW:
      Survey.trigger(true) in the case of a home page bage
      Survey.trigger(false) in the case of a page click where the user doesn't expect the survey
  */
  trigger: function(ignoreWait) {
    var sc = "";
    if (ignoreWait) {
      ignoreWait = "&ignoreWait=Y";
    } else {
      ignoreWait = "&ignoreWait=N";
    }
    // Need to send the 1st survey cookie we see since
    // the check path is a different path than the path of our
    // cookie setting
    if (Survey.Cookie.get(Survey.cookieName)) {
      sc = "&sc=" + Survey.Cookie.get(Survey.cookieName);
    }
    new Ajax.Request("/survey/check.asp?action=trigger" +
                      "&url=" + window.location.pathname +
                      sc +
                      ignoreWait,
                    {onSuccess:Survey.initSurveyCallback});

  },
  takeSurvey : function (site) {
    Survey.surveyResponse("/survey/check.asp?accept=Y&action=respond&siteName=" + site);
  },

  declineSurvey : function (site, dontShowAgain) {
    Survey.surveyResponse("/survey/check.asp?accept=N&action=respond&siteName=" +
                         site +
                         "&decline=" + dontShowAgain);
  },

  surveyResponse : function (url) {
    new Ajax.Request(url,
                    {onSuccess:Survey.noop});

    document.getElementById("surveyDiv").style.visibility = "hidden";
  },

  topLevelDir : function () {
    var path = window.location.pathname.match(/^(\/[^\/]+)./);
    if (path) {
      return path[1];
    }
    return null;
  },

  Cookie: {
    /**
     * Sets a Cookie with the given name and value.
     *
     * name       Name of the cookie
     * value      Value of the cookie
     * [path]     Path where the cookie is valid (default: path of calling document)
     * [expires]  Expiration date of the cookie (default: end of current session)
     * [domain]   Domain where the cookie is valid
     *              (default: domain of calling document)
     * [secure]   Boolean value indicating if the cookie transmission requires a
     *              secure transmission
     */
    set : function(name, value, path, expires, domain, secure) {
        document.cookie= name + "=" + encodeURIComponent(value) +
            ((expires) ? "; expires=" + expires.toGMTString() : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
    },

    /**
     * Gets the value of the specified cookie.
     * Returns null if cookie does not exist.
     */
    get : function(name) {
      try {
        var cookies = document.cookie;
        var index = cookies.indexOf(name + "=");
        if (index == -1) return null;
        index = cookies.indexOf("=", index) + 1;
        var endstr = cookies.indexOf(";", index);
        if (endstr == -1) endstr = cookies.length;
        return decodeURIComponent(cookies.substring(index, endstr));
      } catch(e) {}
      return null;
    },

    /**
     * Deletes the specified cookie.
     * delete is areserved word in javascript
     *
     * name      name of the cookie
     * [path]    path of the cookie (must be same as path used to create cookie)
     */
    remove : function (name, path) {
        if (Survey.Cookie.get(name)) {
            document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    }
  },
  /** Only for testing / debugging */
  hello : function() {
    alert("hello");
  },

  // ctrl, shift,ctrl, shift, test
  testerLaunch : [17,16,17,16,84,69,83,84],
  testerBuffer : [],
  tester: function(e) {
      var key = e.which || e.keyCode;
      if (Survey.testerBuffer.length==0) {
        if (key==Survey.testerLaunch[0]) {
          Survey.testerBuffer.push(key);
        }
      } else {
        /*
          The sequence was already begun - lets see if
          there is more - or we are all done
        */
        Survey.testerBuffer.push(key);
        if (key == Survey.testerLaunch[Survey.testerBuffer.length-1]) {
          // Woohoo - we had a match - are we done?
          if (Survey.testerBuffer.length == Survey.testerLaunch.length) {
            new Ajax.Request("/survey/check.asp?action=test" +
                              "&url=" + window.location.pathname,
                            {onSuccess:Survey.initSurveyCallback});
            Survey.testerBuffer = [];
          }
        } else {
          Survey.testerBuffer = [];
        }
      }
  },
  testerGo : function(httpRequest) {
    Survey.display(httpRequest.responseXML);
  }
};



if (null!=Survey.Cookie.get(Survey.utCookieName) &&
    "done"!=Survey.Cookie.get(Survey.cookieName) &&
    null!=Survey.topLevelDir()) {
  Event.observe(window, "load", Survey.init);
}

if (null!=Survey.Cookie.get(Survey.utCookieName) &&
    null!=Survey.topLevelDir()) {
  Event.observe(document, "keydown", Survey.tester);
}



