(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(['module', 'exports'], factory);
  } else if (typeof exports !== "undefined") {
    factory(module, exports);
  } else {
    var mod = {
      exports: {}
    };
    factory(mod, mod.exports);
    global.WOW = mod.exports;
  }
})(this, function (module, exports) {
  'use strict';

  Object.defineProperty(exports, "__esModule", {
    value: true
  });

  var _class, _temp;

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  var _createClass = function () {
    function defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    return function (Constructor, protoProps, staticProps) {
      if (protoProps) defineProperties(Constructor.prototype, protoProps);
      if (staticProps) defineProperties(Constructor, staticProps);
      return Constructor;
    };
  }();

  function isIn(needle, haystack) {
    return haystack.indexOf(needle) >= 0;
  }

  function extend(custom, defaults) {
    for (var key in defaults) {
      if (custom[key] == null) {
        var value = defaults[key];
        custom[key] = value;
      }
    }
    return custom;
  }

  function isMobile(agent) {
    return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(agent)
    );
  }

  function createEvent(event) {
    var bubble = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
    var cancel = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
    var detail = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3];

    var customEvent = void 0;
    if (document.createEvent != null) {
      // W3C DOM
      customEvent = document.createEvent('CustomEvent');
      customEvent.initCustomEvent(event, bubble, cancel, detail);
    } else if (document.createEventObject != null) {
      // IE DOM < 9
      customEvent = document.createEventObject();
      customEvent.eventType = event;
    } else {
      customEvent.eventName = event;
    }

    return customEvent;
  }

  function emitEvent(elem, event) {
    if (elem.dispatchEvent != null) {
      // W3C DOM
      elem.dispatchEvent(event);
    } else if (event in (elem != null)) {
      elem[event]();
    } else if ('on' + event in (elem != null)) {
      elem['on' + event]();
    }
  }

  function addEvent(elem, event, fn) {
    if (elem.addEventListener != null) {
      // W3C DOM
      elem.addEventListener(event, fn, false);
    } else if (elem.attachEvent != null) {
      // IE DOM
      elem.attachEvent('on' + event, fn);
    } else {
      // fallback
      elem[event] = fn;
    }
  }

  function removeEvent(elem, event, fn) {
    if (elem.removeEventListener != null) {
      // W3C DOM
      elem.removeEventListener(event, fn, false);
    } else if (elem.detachEvent != null) {
      // IE DOM
      elem.detachEvent('on' + event, fn);
    } else {
      // fallback
      delete elem[event];
    }
  }

  function getInnerHeight() {
    if ('innerHeight' in window) {
      return window.innerHeight;
    }

    return document.documentElement.clientHeight;
  }

  // Minimalistic WeakMap shim, just in case.
  var WeakMap = window.WeakMap || window.MozWeakMap || function () {
    function WeakMap() {
      _classCallCheck(this, WeakMap);

      this.keys = [];
      this.values = [];
    }

    _createClass(WeakMap, [{
      key: 'get',
      value: function get(key) {
        for (var i = 0; i < this.keys.length; i++) {
          var item = this.keys[i];
          if (item === key) {
            return this.values[i];
          }
        }
        return undefined;
      }
    }, {
      key: 'set',
      value: function set(key, value) {
        for (var i = 0; i < this.keys.length; i++) {
          var item = this.keys[i];
          if (item === key) {
            this.values[i] = value;
            return this;
          }
        }
        this.keys.push(key);
        this.values.push(value);
        return this;
      }
    }]);

    return WeakMap;
  }();

  // Dummy MutationObserver, to avoid raising exceptions.
  var MutationObserver = window.MutationObserver || window.WebkitMutationObserver || window.MozMutationObserver || (_temp = _class = function () {
    function MutationObserver() {
      _classCallCheck(this, MutationObserver);

      if (typeof console !== 'undefined' && console !== null) {
        console.warn('MutationObserver is not supported by your browser.');
        console.warn('WOW.js cannot detect dom mutations, please call .sync() after loading new content.');
      }
    }

    _createClass(MutationObserver, [{
      key: 'observe',
      value: function observe() {}
    }]);

    return MutationObserver;
  }(), _class.notSupported = true, _temp);

  // getComputedStyle shim, from http://stackoverflow.com/a/21797294
  var getComputedStyle = window.getComputedStyle || function getComputedStyle(el) {
    var getComputedStyleRX = /(\-([a-z]){1})/g;
    return {
      getPropertyValue: function getPropertyValue(prop) {
        if (prop === 'float') {
          prop = 'styleFloat';
        }
        if (getComputedStyleRX.test(prop)) {
          prop.replace(getComputedStyleRX, function (_, _char) {
            return _char.toUpperCase();
          });
        }
        var currentStyle = el.currentStyle;

        return (currentStyle != null ? currentStyle[prop] : void 0) || null;
      }
    };
  };

  var WOW = function () {
    function WOW() {
      var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

      _classCallCheck(this, WOW);

      this.defaults = {
        boxClass: 'wow',
        animateClass: 'animated',
        offset: 0,
        mobile: true,
        live: true,
        callback: null,
        scrollContainer: null,
        resetAnimation: true
      };

      this.animate = function animateFactory() {
        if ('requestAnimationFrame' in window) {
          return function (callback) {
            return window.requestAnimationFrame(callback);
          };
        }
        return function (callback) {
          return callback();
        };
      }();

      this.vendors = ['moz', 'webkit'];

      this.start = this.start.bind(this);
      this.resetAnimation = this.resetAnimation.bind(this);
      this.scrollHandler = this.scrollHandler.bind(this);
      this.scrollCallback = this.scrollCallback.bind(this);
      this.scrolled = true;
      this.config = extend(options, this.defaults);
      if (options.scrollContainer != null) {
        this.config.scrollContainer = document.querySelector(options.scrollContainer);
      }
      // Map of elements to animation names:
      this.animationNameCache = new WeakMap();
      this.wowEvent = createEvent(this.config.boxClass);
    }

    _createClass(WOW, [{
      key: 'init',
      value: function init() {
        this.element = window.document.documentElement;
        if (isIn(document.readyState, ['interactive', 'complete'])) {
          this.start();
        } else {
          addEvent(document, 'DOMContentLoaded', this.start);
        }
        this.finished = [];
      }
    }, {
      key: 'start',
      value: function start() {
        var _this = this;

        this.stopped = false;
        this.boxes = [].slice.call(this.element.querySelectorAll('.' + this.config.boxClass));
        this.all = this.boxes.slice(0);
        if (this.boxes.length) {
          if (this.disabled()) {
            this.resetStyle();
          } else {
            for (var i = 0; i < this.boxes.length; i++) {
              var box = this.boxes[i];
              this.applyStyle(box, true);
            }
          }
        }
        if (!this.disabled()) {
          addEvent(this.config.scrollContainer || window, 'scroll', this.scrollHandler);
          addEvent(window, 'resize', this.scrollHandler);
          this.interval = setInterval(this.scrollCallback, 50);
        }
        if (this.config.live) {
          var mut = new MutationObserver(function (records) {
            for (var j = 0; j < records.length; j++) {
              var record = records[j];
              for (var k = 0; k < record.addedNodes.length; k++) {
                var node = record.addedNodes[k];
                _this.doSync(node);
              }
            }
            return undefined;
          });
          mut.observe(document.body, {
            childList: true,
            subtree: true
          });
        }
      }
    }, {
      key: 'stop',
      value: function stop() {
        this.stopped = true;
        removeEvent(this.config.scrollContainer || window, 'scroll', this.scrollHandler);
        removeEvent(window, 'resize', this.scrollHandler);
        if (this.interval != null) {
          clearInterval(this.interval);
        }
      }
    }, {
      key: 'sync',
      value: function sync() {
        if (MutationObserver.notSupported) {
          this.doSync(this.element);
        }
      }
    }, {
      key: 'doSync',
      value: function doSync(element) {
        if (typeof element === 'undefined' || element === null) {
          element = this.element;
        }
        if (element.nodeType !== 1) {
          return;
        }
        element = element.parentNode || element;
        var iterable = element.querySelectorAll('.' + this.config.boxClass);
        for (var i = 0; i < iterable.length; i++) {
          var box = iterable[i];
          if (!isIn(box, this.all)) {
            this.boxes.push(box);
            this.all.push(box);
            if (this.stopped || this.disabled()) {
              this.resetStyle();
            } else {
              this.applyStyle(box, true);
            }
            this.scrolled = true;
          }
        }
      }
    }, {
      key: 'show',
      value: function show(box) {
        this.applyStyle(box);
        box.className = box.className + ' ' + this.config.animateClass;
        if (this.config.callback != null) {
          this.config.callback(box);
        }
        emitEvent(box, this.wowEvent);

        if (this.config.resetAnimation) {
          addEvent(box, 'animationend', this.resetAnimation);
          addEvent(box, 'oanimationend', this.resetAnimation);
          addEvent(box, 'webkitAnimationEnd', this.resetAnimation);
          addEvent(box, 'MSAnimationEnd', this.resetAnimation);
        }

        return box;
      }
    }, {
      key: 'applyStyle',
      value: function applyStyle(box, hidden) {
        var _this2 = this;

        var duration = box.getAttribute('data-wow-duration');
        var delay = box.getAttribute('data-wow-delay');
        var iteration = box.getAttribute('data-wow-iteration');

        return this.animate(function () {
          return _this2.customStyle(box, hidden, duration, delay, iteration);
        });
      }
    }, {
      key: 'resetStyle',
      value: function resetStyle() {
        for (var i = 0; i < this.boxes.length; i++) {
          var box = this.boxes[i];
          box.style.visibility = 'visible';
        }
        return undefined;
      }
    }, {
      key: 'resetAnimation',
      value: function resetAnimation(event) {
        if (event.type.toLowerCase().indexOf('animationend') >= 0) {
          var target = event.target || event.srcElement;
          target.className = target.className.replace(this.config.animateClass, '').trim();
        }
      }
    }, {
      key: 'customStyle',
      value: function customStyle(box, hidden, duration, delay, iteration) {
        if (hidden) {
          this.cacheAnimationName(box);
        }
        box.style.visibility = hidden ? 'hidden' : 'visible';

        if (duration) {
          this.vendorSet(box.style, { animationDuration: duration });
        }
        if (delay) {
          this.vendorSet(box.style, { animationDelay: delay });
        }
        if (iteration) {
          this.vendorSet(box.style, { animationIterationCount: iteration });
        }
        this.vendorSet(box.style, { animationName: hidden ? 'none' : this.cachedAnimationName(box) });

        return box;
      }
    }, {
      key: 'vendorSet',
      value: function vendorSet(elem, properties) {
        for (var name in properties) {
          if (properties.hasOwnProperty(name)) {
            var value = properties[name];
            elem['' + name] = value;
            for (var i = 0; i < this.vendors.length; i++) {
              var vendor = this.vendors[i];
              elem['' + vendor + name.charAt(0).toUpperCase() + name.substr(1)] = value;
            }
          }
        }
      }
    }, {
      key: 'vendorCSS',
      value: function vendorCSS(elem, property) {
        var style = getComputedStyle(elem);
        var result = style.getPropertyCSSValue(property);
        for (var i = 0; i < this.vendors.length; i++) {
          var vendor = this.vendors[i];
          result = result || style.getPropertyCSSValue('-' + vendor + '-' + property);
        }
        return result;
      }
    }, {
      key: 'animationName',
      value: function animationName(box) {
        var aName = void 0;
        try {
          aName = this.vendorCSS(box, 'animation-name').cssText;
        } catch (error) {
          // Opera, fall back to plain property value
          aName = getComputedStyle(box).getPropertyValue('animation-name');
        }

        if (aName === 'none') {
          return ''; // SVG/Firefox, unable to get animation name?
        }

        return aName;
      }
    }, {
      key: 'cacheAnimationName',
      value: function cacheAnimationName(box) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=921834
        // box.dataset is not supported for SVG elements in Firefox
        return this.animationNameCache.set(box, this.animationName(box));
      }
    }, {
      key: 'cachedAnimationName',
      value: function cachedAnimationName(box) {
        return this.animationNameCache.get(box);
      }
    }, {
      key: 'scrollHandler',
      value: function scrollHandler() {
        this.scrolled = true;
      }
    }, {
      key: 'scrollCallback',
      value: function scrollCallback() {
        if (this.scrolled) {
          this.scrolled = false;
          var results = [];
          for (var i = 0; i < this.boxes.length; i++) {
            var box = this.boxes[i];
            if (box) {
              if (this.isVisible(box)) {
                this.show(box);
                continue;
              }
              results.push(box);
            }
          }
          this.boxes = results;
          if (!this.boxes.length && !this.config.live) {
            this.stop();
          }
        }
      }
    }, {
      key: 'offsetTop',
      value: function offsetTop(element) {
        // SVG elements don't have an offsetTop in Firefox.
        // This will use their nearest parent that has an offsetTop.
        // Also, using ('offsetTop' of element) causes an exception in Firefox.
        while (element.offsetTop === undefined) {
          element = element.parentNode;
        }
        var top = element.offsetTop;
        while (element.offsetParent) {
          element = element.offsetParent;
          top += element.offsetTop;
        }
        return top;
      }
    }, {
      key: 'isVisible',
      value: function isVisible(box) {
        var offset = box.getAttribute('data-wow-offset') || this.config.offset;
        var viewTop = this.config.scrollContainer && this.config.scrollContainer.scrollTop || window.pageYOffset;
        var viewBottom = viewTop + Math.min(this.element.clientHeight, getInnerHeight()) - offset;
        var top = this.offsetTop(box);
        var bottom = top + box.clientHeight;

        return top <= viewBottom && bottom >= viewTop;
      }
    }, {
      key: 'disabled',
      value: function disabled() {
        return !this.config.mobile && isMobile(navigator.userAgent);
      }
    }]);

    return WOW;
  }();

  exports.default = WOW;
  module.exports = exports['default'];
});


var housingauthority = (function () {
    var pub = {};

    /**
     * Make an AJAX call.  All AJAX calls should go through this function.
     *
     * @param messageName
     *        Message to send to server.  For example, CorrectAddress.
     * @param message
     *        This parameter is translated into JSON and sent in the HTTP body.  Default: emptyString.
     * @param onSuccess
     *        Callback on success.
     * @param onFailure
     *        Callback on failure.
     * @param isRW5
     *        Type of data expected back.  Default: json.
     * @param dataType
     *        Type of data expected back.  Default: json.
     *
     */

    pub.ajax = ajax;
    pub.ajaxrw = ajaxrw;
    pub.ajaxUnauthenticated = ajaxUnauthenticated;

    function ajax(messageName, message, onSuccess, onFailure, dataType) {
        ajax_call(messageName, message, onSuccess, onFailure, dataType, "/v4/AjaxHandler")
    }

    function ajaxrw(messageName, message, onSuccess, onFailure, dataType ) {
        ajax_call(messageName, message, onSuccess, onFailure, dataType, "/v4/AjaxRWHandler")
    }

    function ajaxUnauthenticated(messageName, message, onSuccess, onFailure, dataType ) {
        ajax_call(messageName,
            message,
            onSuccess,
            onFailure,
            dataType,
            "/v4/AjaxHandlerUnauthenticated");
    }

    function ajax_call(messageName, message, onSuccess, onFailure, dataType, ajaxpath) {
        if (dataType === undefined || dataType === null)
            dataType = "json";
      

        var data = message === undefined || message === null ? "" : JSON.stringify(message);

        var path = ajaxpath;

        if (data.indexOf('<') >= 0 || data.indexOf('>') >= 0 || data.indexOf('&lt;') >= 0 || data.indexOf('&gt;') >= 0) {
            console.log("Cross-site script exploit attempt detected.  Ignoring request.");
        }
        else {
            $.ajax
                ({
                    type: "post",
                    url: path + "?message=" + messageName,
                    contentType: "application/json; charset=utf-8",
                    dataType: dataType,
                    data: data,
                    success: onSuccess,
                    error: onFailure
                });
        }
    }

    pub.getAllHaNames = function (getAllHaNamesOnSuccess, GetAllHaNamesOnFailure) {
        var message = {};
        ajaxUnauthenticated("GetAllHaNames", message, getAllHaNamesOnSuccess, GetAllHaNamesOnFailure);
    }
    return pub;
}
    ());

var columbiaUniversity = (function () {
    var pub = {};

    /**
     * Make an AJAX call.  All AJAX calls should go through this function.
     *
     * @param messageName
     *        Message to send to server.  For example, CorrectAddress.
     * @param message
     *        This parameter is translated into JSON and sent in the HTTP body.  Default: emptyString.
     * @param onSuccess
     *        Callback on success.
     * @param onFailure
     *        Callback on failure.
     * @param isRW5
     *        Type of data expected back.  Default: json.
     * @param dataType
     *        Type of data expected back.  Default: json.
     *
     */

    pub.ajax = ajax;
    pub.ajaxrw = ajaxrw;
    pub.ajaxUnauthenticated = ajaxUnauthenticated;

    function ajax(messageName, message, onSuccess, onFailure, dataType) {
        ajax_call(messageName, message, onSuccess, onFailure, dataType, "/v4/AjaxHandler");
    }

    function ajaxrw(messageName, message, onSuccess, onFailure, dataType) {
        ajax_call(messageName, message, onSuccess, onFailure, dataType, "/v4/AjaxRWHandler");
    }

    function ajaxUnauthenticated(messageName, message, onSuccess, onFailure, dataType) {
        ajax_call(messageName,
            message,
            onSuccess,
            onFailure,
            dataType,
            "/v4/AjaxHandlerUnauthenticated");
    }
    function ajax_call(messageName, message, onSuccess, onFailure, dataType, ajaxpath) {
        if (dataType === undefined || dataType === null)
            dataType = "json";

        var data = message === undefined || message === null ? "" : JSON.stringify(message);

        var path = ajaxpath;

        if (data.indexOf('<') >= 0 || data.indexOf('>') >= 0 || data.indexOf('&lt;') >= 0 || data.indexOf('&gt;') >= 0) {
            console.log("Cross-site script exploit attempt detected.  Ignoring request.");
        }
        else {
            $.ajax
                ({
                    type: "post",
                    url: path + "?message=" + messageName,
                    contentType: "application/json; charset=utf-8",
                    dataType: dataType,
                    async: true,
                    data: data,
                    success: onSuccess,
                    error: onFailure
                });
        }
    }

    pub.saveQuestions = function (dateOfBirth, moveDate, currentZipCode, moveReasonID, haOfficeName, studyGroupID, isHeadOfHouseHold,
        childrenAgeRange, saveQuestionsOnSuccess, saveQuestionsOnFailure) {
        var message =
        {
            StudyQuestions:
            {
                ColumbiaUniversityTenantID: 0,

                StudyGroupID: studyGroupID,
                HousingAuthorityIssuedVoucher: haOfficeName,
                MoveReasonID: moveReasonID,
                CurrentZipCode: currentZipCode,
                DateOfBirth: dateOfBirth,
                DesiredMoveDate: moveDate,
                IsHeadOfHouseHold: isHeadOfHouseHold,
                AgeRangeIDList: childrenAgeRange
            }
        };
        ajax("SaveColumbiaUniversityStudyQuestions", message, saveQuestionsOnSuccess, saveQuestionsOnFailure);
    }

    pub.getMoveReasons = function (getMoveReasonsOnSuccess, getMoveReasonsOnFailure) {
        var message = {};
        ajaxUnauthenticated("GetAllMoveReasons", message, getMoveReasonsOnSuccess, getMoveReasonsOnFailure);
    }

    //pub.getTenantStudyGroup = function (getTenantStudyGroupOnSuccess, getTenantStudyGroupOnFailure) {
    pub.getColumbiaUniversityTenant = function (getTenantStudyGroupOnSuccess, getTenantStudyGroupOnFailure) {
        var message =
        {
        };
        ajax("GetColumbiaUniversityTenant", message, getTenantStudyGroupOnSuccess, getTenantStudyGroupOnFailure);
    }

    pub.getColumbiaUniversityTenantInfo = function (getColumbiaUniversityTenantInfoOnSuccess, getColumbiaUniversityTenantInfoOnFailure) {
        var message =
        {
        };
        ajax("GetColumbiaUniversityTenantInfo", message, getColumbiaUniversityTenantInfoOnSuccess, getColumbiaUniversityTenantInfoOnFailure);
    }

    pub.downgradeTenantStudyGroup = function (downgradeTenantStudyGroupOnSuccess, downgradeTenantStudyGroupOnFailure) {
        var message =
        {
        };
        ajax("DowngradeTenantStudyGroup", message, downgradeTenantStudyGroupOnSuccess, downgradeTenantStudyGroupOnFailure);
    }

    pub.GetChildrenAgeRange = function (GetChildrenAgeRangeOnSuccess, GetChildrenAgeRangeOnFailure) {
        var message = {};
        ajaxUnauthenticated("GetChildrenAgeRange", message, GetChildrenAgeRangeOnSuccess, GetChildrenAgeRangeOnFailure);
    }

    pub.getSchoolsForProperty = function (propertyID, getSchoolsForPropertyOnSuccess, getSchoolsForPropertyOnFailure) {
        message =
        {
            PropertyID: propertyID
        }
        ajaxUnauthenticated("GetSchoolsForProperty", message, getSchoolsForPropertyOnSuccess, getSchoolsForPropertyOnFailure);
    }

    pub.subscribeSMS = function (cityID, schoolType, propertyIDWhereSubscribed, subscribeSMSOnSuccess, subscribeSMSOnFailure) {
        var message =
        {
            CityID: cityID,
            SchoolType: schoolType,
            PropertyIDWhereSubscribed: propertyIDWhereSubscribed
        }
        ajax("SubscribeColumbiaUniversitySMS", message, subscribeSMSOnSuccess, subscribeSMSOnFailure);
    }

    pub.unsubscribeSMS = function (cityID, schoolType, unsubscribeSMSOnSuccess, unsubscribeSMSOnFailure) {
        var message =
        {
            CityID: cityID,
            SchoolType: schoolType
        }
        ajax("UnsubscribeColumbiaUniversitySMS", message, unsubscribeSMSOnSuccess, unsubscribeSMSOnFailure);
    }

    pub.isSubscribedSMS = function (cityID, schoolType, isSubscribedSMSOnSuccess, isSubscribedSMSOnFailure) {
        var message =
        {
            CityID: cityID,
            SchoolType: schoolType
        }
        ajax("IsUserSubscribedColumbiaUniversitySMS", message, isSubscribedSMSOnSuccess, isSubscribedSMSOnFailure);
    }

    pub.linkClickedColumbiaUniversitySMSLog = function (columbiaTenantSMSLogID, linkClickedColumbiaUniversitySMSLogOnSuccess, linkClickedColumbiaUniversitySMSLogOnFailure) {
        var message =
        {
            ColumbiaTenantSMSLogID: columbiaTenantSMSLogID
        }
        ajaxUnauthenticated("LinkClickedColumbiaUniversitySMSLog", message, linkClickedColumbiaUniversitySMSLogOnSuccess, linkClickedColumbiaUniversitySMSLogOnFailure);
    }

    pub.unsubscribeAllSMSSubscriptions = function (unsubscribeAllSMSSubscriptionsOnSuccess, unsubscribeAllSMSSubscriptionsOnFailure) {
        var message = {}
        ajax("UnsubscribeAllSMSSubscriptionsForColumbiaTenant", message, unsubscribeAllSMSSubscriptionsOnSuccess, unsubscribeAllSMSSubscriptionsOnFailure);
    }
    pub.getPropertyCountInSchoolZone = function (go8SchoolID, getPropertyCountInSchoolZoneOnSuccess, getPropertyCountInSchoolZoneOnFailure) {
        var message =
        {
            Go8SchoolID: go8SchoolID
        };
        ajaxUnauthenticated("GetPropertyCountInSchoolZone", message, getPropertyCountInSchoolZoneOnSuccess, getPropertyCountInSchoolZoneOnFailure);
    }
    pub.getPropertiesInSchoolZone = function (go8SchoolID, pageSize, pageNum, sortBy, isLowToHigh,
        lowRent, highRent, propertyTypeValues, bedroomValues, numberOfBathroom,
        lowSquareFeet, highSquareFeet,
        isPictureOnly, isAllowPets, isAccessibleHousing, isSeniorHousing, isSmokingAllowed,
        hasCoveredParking, hasAirConditioning, keywords,
        getPropertiesInSchoolZoneOnSuccess, getPropertiesInSchoolZoneOnFailure) {
        var message =
        {
            Go8SchoolID: go8SchoolID,
            PageSize: pageSize,
            PageNumber: pageNum,
            SortBy: sortBy,
            IsLowToHigh: isLowToHigh,
            LowRent: lowRent,
            HighRent: highRent,
            PropertyTypeValues: propertyTypeValues,
            BedroomValues: bedroomValues,
            NumberOfBathroom: numberOfBathroom,
            LowSquareFeet: lowSquareFeet,
            HighSquareFeet: highSquareFeet,
            IsPictureOnly: isPictureOnly,
            IsAllowPets: isAllowPets,
            IsAccessibleHousing: isAccessibleHousing,
            IsSeniorHousing: isSeniorHousing,
            IsSmokingAllowed: isSmokingAllowed,
            HasCoveredParking: hasCoveredParking,
            HasAirConditioning: hasAirConditioning,
            Keywords: keywords
        };
        ajaxUnauthenticated("GetPropertiesInSchoolZone", message, getPropertiesInSchoolZoneOnSuccess, getPropertiesInSchoolZoneOnFailure);
    }
    pub.printPropertiesInSchoolZone = function (go8SchoolID, pageSize, pageNum, sortBy, isLowToHigh,
        lowRent, highRent, propertyTypeValues, bedroomValues, numberOfBathroom,
        lowSquareFeet, highSquareFeet,
        isPictureOnly, isAllowPets, isAccessibleHousing, isSeniorHousing, isSmokingAllowed,
        hasCoveredParking, hasAirConditioning, keywords,
        printPropertiesInSchoolZoneOnSuccess, printPropertiesInSchoolZoneOnFailure) {
        var message =
        {
            Go8SchoolID: go8SchoolID,
            PageSize: pageSize,
            PageNumber: pageNum,
            SortBy: sortBy,
            IsLowToHigh: isLowToHigh,
            LowRent: lowRent,
            HighRent: highRent,
            PropertyTypeValues: propertyTypeValues,
            BedroomValues: bedroomValues,
            NumberOfBathroom: numberOfBathroom,
            LowSquareFeet: lowSquareFeet,
            HighSquareFeet: highSquareFeet,
            IsPictureOnly: isPictureOnly,
            IsAllowPets: isAllowPets,
            IsAccessibleHousing: isAccessibleHousing,
            IsSeniorHousing: isSeniorHousing,
            IsSmokingAllowed: isSmokingAllowed,
            HasCoveredParking: hasCoveredParking,
            HasAirConditioning: hasAirConditioning,
            Keywords: keywords
        };
        ajaxUnauthenticated("PrintPropertiesInSchoolZone", message, printPropertiesInSchoolZoneOnSuccess, printPropertiesInSchoolZoneOnFailure);
    }

    pub.getSchoolInfoForPropertyDetailPage = function (propertyID, getSchoolInfoForPropertyDetailPageOnSuccess, getSchoolInfoForPropertyDetailPageOnFailure) {
        var message =
        {
            PropertyID: propertyID
        }
        ajaxUnauthenticated("GetSchoolInfoForPropertyDetailPage", message, getSchoolInfoForPropertyDetailPageOnSuccess, getSchoolInfoForPropertyDetailPageOnFailure);
    }

    pub.getSchoolInfoForCommunityDetailPage = function (communityId, latitude, longitude, getSchoolInfoForPropertyDetailPageOnSuccess, getSchoolInfoForPropertyDetailPageOnFailure) {
        var message =
        {
            communityId: communityId,
            latitude: latitude,
            longitude: longitude
        }
        ajaxUnauthenticated("GetSchoolInfoForCommunityDetailPage", message, getSchoolInfoForPropertyDetailPageOnSuccess, getSchoolInfoForPropertyDetailPageOnFailure);
    }

    pub.getSchool = function (go8SchoolID, getSchoolOnSuccess, getSchoolOnFailure) {
        var message =
        {
            Go8SchoolID: go8SchoolID
        }
        ajaxUnauthenticated("GetSchool", message, getSchoolOnSuccess, getSchoolOnFailure);
    }

    return pub;
}());


/**
 * Slowly fades a control into or out of visibility.
 */

ko.bindingHandlers.fadeVisible =
{
    init: function (element, valueAccessor)
    {
        try
        {
            var value = ko.unwrap (valueAccessor());
            $ (element).toggle (value);
        }
        catch (ex)
        {
            go8Error.handleException (ex);
        }
    },

    update: function (element, valueAccessor)
    {
        try
        {
            var value = ko.unwrap (valueAccessor());
            value ? $ (element).fadeIn() : $ (element).fadeOut();
        }
        catch (ex)
        {
            go8Error.handleException (ex);
        }
    }
};



ko.bindingHandlers.scrollTo =
{
    init: function (element, valueAccessor)
    {
    },

    update: function (element, valueAccessor, bindings)
    {
        try
        {
            var value = ko.utils.unwrapObservable (valueAccessor());

            if (value.when)
            {
                var scrollContainerSelector = $ (element).closest (value.who);
                var scrollContainer = scrollContainerSelector[0];
                scrollContainerSelector.scrollTop (0);

                var scrollContainerRect = scrollContainer.getBoundingClientRect();
                var elementRect = element.getBoundingClientRect();
                var offset = elementRect.top - scrollContainerRect.top;

                var offsetTop = offset - getComputedStyle (element)['border-top-width'].slice (0, -2);

                var offsetBottom
                    = offset
                    + parseFloat (getComputedStyle (element)['border-bottom-width'].slice (0, -2))
                    + parseFloat (getComputedStyle (scrollContainer)['border-bottom-width'].slice (0, -2))
                    - (scrollContainerRect.bottom - scrollContainerRect.top)
                    + (elementRect.bottom - elementRect.top);

                var chosenOffset = value.how === 'top' ? offsetTop : offsetBottom;

                scrollContainerSelector.scrollTop (chosenOffset);
            }
        }
        catch (ex)
        {
            go8Error.handleException (ex);
        }
    }
};


/**
 * Slides a control into or out of visibility.
 */

ko.bindingHandlers.slideVisible =
{
    init: function (element, valueAccessor)
    {
        try
        {
            var value = ko.unwrap (valueAccessor());
            $ (element).toggle (value);
        }
        catch (ex)
        {
            go8Error.handleException (ex);
        }
    },

    update: function (element, valueAccessor)
    {
        try
        {
            var value = ko.unwrap (valueAccessor());
            value ? $ (element).slideDown (100) : $ (element).slideUp (100);
        }
        catch (ex)
        {
            go8Error.handleException (ex);
        }
    }
};

var index = (function () {
    try {
        var pub = {};
        var location = null;
        var rentalPanelMinItem = 3;
        var rentalPanelMaxItem = 6;
        
        pub.onPageLoad = function ()
        {
            var qs = helper.getQueryStrings();
            if (qs["st"] != undefined && qs["st"] !== 0) {
                listing.tokenLogin(qs["st"],
                    'hadashboard',
                    function(response) {
                        window.location.href = '../LL/dashboard.aspx';
                    },
                    function(xhr, status, error) {
                    });
            }
            /* Get last Rental Panel Location from local storage */
            if (headerModel.domain.user() == null) {
                helper.updateRentalPanelAfterLogout();
            }

            if (localStorage.getItem(lastsearchRentalPanelLocation)) {
                var recentPanelLocation = ko.mapping.fromJS(JSON.parse(localStorage.getItem(lastsearchRentalPanelLocation)));

                if (recentPanelLocation != null) {
                    indexModel.domain.rentalPanelLocation(recentPanelLocation);
                }
            }

            /* Get last Rental Panel Location listing from local storage */
            if (localStorage.getItem(lastsearchRentalPanelList)){
                helper.updateRentalPanelLocalStorageIfTrustedOwnerNotExists();
                var recentPanelListModel = ko.mapping.fromJS(JSON.parse(localStorage.getItem(lastsearchRentalPanelList)));

                if (recentPanelListModel() != null && recentPanelListModel().length > 0) {
                    indexModel.domain.rentalPanelList(recentPanelListModel());
                }
            }

            if (location == null && $.cookie('userlocation') != null) {
                location = JSON.parse($.cookie('userlocation'));
            }

            //When the visitor has no lastsearchRentalPanelLocation cookie, use previous logic to create the cookie.
            if (!headerModel.domain.user() && !localStorage.getItem(lastsearchRentalPanelLocation)) {
                if (location !== null && !helper.isNullOrEmpty(location["City"]) && !helper.isNullOrEmpty(location["County"]) && !helper.isNullOrEmpty(location["State"])) {
                    if (!helper.isNullOrEmpty(location["City"]))
                        indexModel.view.currentCity(location["City"]);
                    if (!helper.isNullOrEmpty(location["County"]))
                        indexModel.view.currentCounty(location["County"]);
                    if (!helper.isNullOrEmpty(location["State"]))
                        indexModel.view.currentState(location["State"]);
                    if (!helper.isNullOrEmpty(location["Zip"]))
                        indexModel.view.currentZip(location["Zip"]);
                    if (!helper.isNullOrEmpty(location["Latitude"]))
                        indexModel.view.currentLatitude(location["Latitude"]);
                    if (!helper.isNullOrEmpty(location["Longitude"]))
                        indexModel.view.currentLongitude(location["Longitude"]);

                    pub.getRentalPanelListInit();
                }
                else {
                    listing.getLocationByIPAddress(getLocationByIPAddresseOnSuccessInit, getLocationByIPAddressOnFailureInit);
                }
            }

            // Filter should be reset if user navigates to home page
            sessionStorage.removeItem("userdrawings");
            helper.resetSessionPageFilter();
            //sessionStorage.removeItem("pagefilters");
            // helper.removeSEOCookie();
            $.cookie('searchsortquery', '', { expires: -1, path: '/', secure: true });
            $.cookie('searchsortquery2', '', { expires: -1, path: '/', secure: true });
            sessionStorage.removeItem("schoolfilters");
            sessionStorage.removeItem("school-shapefile");

            // Reset isIncomeBasedMatch value after reseting active filter on home page.
            let affordableModel = JSON.parse($.cookie(visitorAffordabilityFilter));
            if (affordableModel != null) {
                affordableModel.filter.isIncomeBasedMatch = false;
                $.cookie(visitorAffordabilityFilter, ko.toJSON(affordableModel), { expires: 30, path: '/', secure: true });
            }

            setTimeout(function ()
            {
                if (headerModel.domain.user())
                {
                    var recentMatchData = JSON.parse($.cookie(recentSearchCookieName));
                    if (!helper.isUndefinedOrNullOrEmpty(recentMatchData) && recentMatchData[0])
                    {
                        recentMatchData = _.filter(recentMatchData, function (item)
                        {
                            return item.isLoggedUserCookie == true;
                        });

                        if (recentMatchData.length > 0 && !helper.isUndefinedOrNullOrEmpty(recentMatchData[0].areaName))
                            go8SearchBoxForListings.updateDisplayText(recentMatchData[0].areaName);
                    }
                }
            }, 1000);

            setTimeout(function () {
                if (sessionStorage.getItem('ShouldShowFocusOnSearchText') !== undefined && sessionStorage.getItem('ShouldShowFocusOnSearchText') === 'true') {
                    $('#searchTextbox').focus();
                    $('#divsearchbarbox').addClass('blink--anim');
                    setTimeout(function () {
                        $('#divsearchbarbox').removeClass('blink--anim');
                    }, 3000)
                    sessionStorage.removeItem('ShouldShowFocusOnSearchText');
                }
            }, 1000);
        }

        

        /**
        * get Affordable Rentals Panel List.
        */
        pub.getRentalPanelListInit = function () {

            var recentState = '';
            var recentCity = '';
            var recentCounty = '';
            
            /* Get existing items from cookie */
            var suggestionsRecent = JSON.parse($.cookie(recentSearchCookieName));
            var isUserLoggedIn = !helper.isUndefinedOrNullOrEmpty(headerModel.domain.user()) ? true : false;

            if (!helper.isUndefinedOrNullOrEmpty(suggestionsRecent))
            {
                suggestionsRecent = _.filter(suggestionsRecent, function (item)
                {
                    return item.isLoggedUserCookie == isUserLoggedIn;
                });
            }

            /* Get most recent seach item */
            if (suggestionsRecent != null && suggestionsRecent != undefined && suggestionsRecent.length > 0) {
                recentState = suggestionsRecent[0].stateCode;
                if (suggestionsRecent[0].areaType === 'county') {
                    recentCounty = suggestionsRecent[0].baseAreaName;
                }
                else if (suggestionsRecent[0].areaType === 'city') {
                    recentCity = suggestionsRecent[0].baseAreaName;
                }
                else if (suggestionsRecent[0].areaType === 'zip') {
                    var fullText = suggestionsRecent[0].baseAreaName.split(',');
                    if (fullText.length > 1) {
                        recentCity = fullText[1].trim();
                    }
                }
                else if (suggestionsRecent[0].areaType === 'address') {
                    var fullText = suggestionsRecent[0].baseAreaName.split(',');
                    if (fullText.length > 3) {
                        recentCity = fullText[fullText.length - 3].trim()
                    }
                }
            }
            listing.getRentalPanelList(indexModel.view.currentState(), indexModel.view.currentCity(), locationHelper.removeCountyText(indexModel.view.currentCounty()),
                recentState, recentCity, recentCounty, rentalPanelMinItem, rentalPanelMaxItem, getRentalPanelListOnSuccessInit, getRentalPanelListOnFailureInit);
        }

        /**
        * Invoked on success when calling getRentalPanelList.
        */
        function getRentalPanelListOnSuccessInit(result) {
            indexModel.view.isLoading(false);
            try {
                if (result && result.location) {
                    var properties = ko.observableArray([]);
                    indexModel.domain.rentalPanelLocation(result.location);

                    if (result.listings.length > 0) {
                        ko.utils.arrayMap(result.listings, function (item) {
                            properties.push(new pub.property(item));
                        });

                        indexModel.domain.rentalPanelList(properties());
                    }

                    /* Update last Rental Panel Location List in local storage */
                    localStorage.setItem(lastsearchRentalPanelList, ko.toJSON(indexModel.domain.rentalPanelList()));

                    /* Update last Rental Panel Location in local storage */
                    localStorage.setItem(lastsearchRentalPanelLocation, ko.toJSON(indexModel.domain.rentalPanelLocation()));
                }
            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }

        /**
         * Invoked on failure when calling getRentalPanelList.
         */
        function getRentalPanelListOnFailureInit() {
            try {

            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }
        /**
         * Invoked on success when calling getLocationByIPAddress.
         */
        function getLocationByIPAddresseOnSuccessInit(result) {
            try {
                // If ip address is identified
                if (result && (!helper.isNullOrEmpty(result.Location.city) || !helper.isNullOrEmpty(result.Location.district) || !helper.isNullOrEmpty(result.Location.state))) {
                    var currentlocation = result.Location;
                    if (!helper.isNullOrEmpty(currentlocation["city"]))
                        indexModel.view.currentCity(currentlocation["city"]);
                    if (!helper.isNullOrEmpty(currentlocation["district"]))
                        indexModel.view.currentCounty(currentlocation["district"]);
                    if (!helper.isNullOrEmpty(currentlocation["stateProv"]))
                        indexModel.view.currentState(currentlocation["stateProv"]);
                    if (!helper.isNullOrEmpty(currentlocation["zipCode"]))
                        indexModel.view.currentZip(currentlocation["zipCode"]);
                    if (!helper.isNullOrEmpty(currentlocation["latitude"]))
                        indexModel.view.currentLatitude(currentlocation["latitude"]);
                    if (!helper.isNullOrEmpty(currentlocation["longitude"]))
                        indexModel.view.currentLongitude(currentlocation["longitude"]);

                    //add cookie for users location
                    var locationString = JSON.stringify({
                        City: indexModel.view.currentCity(),
                        County: indexModel.view.currentCounty(),
                        State: indexModel.view.currentState(),
                        Zip: indexModel.view.currentZip(),
                        Latitude: indexModel.view.currentLatitude(),
                        Longitude: indexModel.view.currentLongitude()
                    });
                    $.cookie("userlocation", locationString, { expires: 365, path: '/' });

                    pub.getRentalPanelListInit();

                }
            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }

        /**
         * Invoked on failure when calling getLocationByIPAddress.
         */
        function getLocationByIPAddressOnFailureInit() {
            try {

            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }
        pub.onClickReadMore = function (renterTipId) {
            showModal(renterTipId);
        }

        pub.property = function (property) {
            var self = this;
            self.CommunityId = ko.observable(property.CommunityId || '');
            self.AddressLine1 = ko.observable(property.AddressLine1 || '');
            self.AddressLine2 = ko.observable(property.AddressLine2 || '');
            self.City = ko.observable(property.City || '');
            self.County = ko.observable(property.County || '');
            self.State = ko.observable(property.State || '');
            self.Zip = ko.observable(property.Zip || '');
            self.MinAskingRent = ko.observable(property.MinAskingRent || '');
            self.MaxAskingRent = ko.observable(property.MaxAskingRent || '');
            self.MinBedroomCount = ko.observable(property.MinBedroomCount || '');
            self.MaxBedroomCount = ko.observable(property.MaxBedroomCount || '');
            self.FullBathCount = ko.observable(property.FullBathCount || '');
            self.HalfBathCount = ko.observable(property.HalfBathCount || '');
            self.MaxFullBathCount = ko.observable(property.MaxFullBathCount || '');
            self.MaxHalfBathCount = ko.observable(property.MaxHalfBathCount || '');
            self.MinFullBathCount = ko.observable(property.MinFullBathCount || '');
            self.MinHalfBathCount = ko.observable(property.MinHalfBathCount || '');
            self.PropertyTypeCategory = ko.observable(property.PropertyTypeCategory || '');
            self.Latitude = ko.observable(property.Latitude || '');
            self.Longitude = ko.observable(property.Longitude || '');
            self.LivingArea = ko.observable(property.LivingArea || '');
            self.MaxLivingArea = ko.observable(property.MaxLivingArea || '');
            self.MinLivingArea = ko.observable(property.MinLivingArea || '');
            self.IsPremiumListing = ko.observable(property.IsPremiumListing);
            self.Photo = ko.observable(property.Photo || '');
            self.AvailabilityText = ko.observable(property.AvailabilityText || '');
            self.ListingStatus = ko.observable(property.ListingStatus || '');
            self.IsNewProperty = ko.observable(property.IsNewProperty || false);
            self.IsJustUpdated = ko.observable(property.IsJustUpdated || false);
            self.IsLeaseIncentives = ko.observable(property.IsLeaseIncentives || false);
            self.ShowBadge = ko.observable(property.ShowSection8Badge || false);
            self.PhotoCount = ko.observable(property.PhotoCount || 0);
            self.CommunityName = ko.observable(property.CommunityName || '');
            self.IsTenantFavourite = ko.observable(property.IsTenantFavourite || false);
            self.SeoFriendlyRentalUrl = ko.observable(property.SeoFriendlyRentalUrl || false);
            self.HasTrustedOwnerBadge = ko.observable(property.HasTrustedOwnerBadge || false);
        }

        /**
         * Invoked on success when calling getLocationByIPAddress.
         */
        function getLocationByIPAddresseOnSuccess(result) {
            try {
                // If ip address is identified
                if (result && (!helper.isNullOrEmpty(result.Location.city) || !helper.isNullOrEmpty(result.Location.district) || !helper.isNullOrEmpty(result.Location.state))) {
                    var currentlocation = result.Location;
                    if (!helper.isNullOrEmpty(currentlocation["city"]))
                        indexModel.view.currentCity(currentlocation["city"]);
                    if (!helper.isNullOrEmpty(currentlocation["district"]))
                        indexModel.view.currentCounty(currentlocation["district"]);
                    if (!helper.isNullOrEmpty(currentlocation["stateProv"]))
                        indexModel.view.currentState(currentlocation["stateProv"]);
                    if (!helper.isNullOrEmpty(currentlocation["zipCode"]))
                        indexModel.view.currentZip(currentlocation["zipCode"]);
                    if (!helper.isNullOrEmpty(currentlocation["latitude"]))
                        indexModel.view.currentLatitude(currentlocation["latitude"]);
                    if (!helper.isNullOrEmpty(currentlocation["longitude"]))
                        indexModel.view.currentLongitude(currentlocation["longitude"]);

                    //add cookie for users location
                    var locationString = JSON.stringify({
                        City: indexModel.view.currentCity(),
                        County: indexModel.view.currentCounty(),
                        State: indexModel.view.currentState(),
                        Zip: indexModel.view.currentZip(),
                        Latitude: indexModel.view.currentLatitude(),
                        Longitude: indexModel.view.currentLongitude()
                    });
                    $.cookie("userlocation", locationString, { expires: 365, path: '/' });

                    var recentState = '';
                    var recentCity = '';
                    var recentCounty = '';
                    var isUserLoggedIn = !helper.isUndefinedOrNullOrEmpty(headerModel.domain.user()) ? true : false;

                    /* Get existing items from cookie */
                    var suggestionsRecent = JSON.parse($.cookie(recentSearchCookieName));

                    if (!helper.isUndefinedOrNullOrEmpty(suggestionsRecent))
                    {
                        suggestionsRecent = _.filter(suggestionsRecent, function (item)
                        {
                            return item.isLoggedUserCookie == isUserLoggedIn;
                        });
                    }

                    /* Get most recent seach item */
                    if (suggestionsRecent != null && suggestionsRecent != undefined && suggestionsRecent.length > 0) {
                        recentState = suggestionsRecent[0].stateCode;
                        if (suggestionsRecent[0].areaType === 'county') {
                            recentCounty = suggestionsRecent[0].baseAreaName;
                        }
                        else if (suggestionsRecent[0].areaType === 'city') {
                            recentCity = suggestionsRecent[0].baseAreaName;
                        }
                        else if (suggestionsRecent[0].areaType === 'zip') {
                            var fullText = suggestionsRecent[0].baseAreaName.split(',');
                            if (fullText.length > 1) {
                                recentCity = fullText[1].trim();
                            }
                        }
                        else if (suggestionsRecent[0].areaType === 'address') {
                            var fullText = suggestionsRecent[0].baseAreaName.split(',');
                            if (fullText.length > 3) {
                                recentCity = fullText[fullText.length - 3].trim()
                            }
                        }
                    }
                    listing.getRentalPanelList(indexModel.view.currentState(), indexModel.view.currentCity(), locationHelper.removeCountyText(indexModel.view.currentCounty()),
                        recentState, recentCity, recentCounty, rentalPanelMinItem, rentalPanelMaxItem, getRentalPanelListOnSuccess, getRentalPanelListOnFailure);

                }
            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }

        /**
         * Invoked on failure when calling getLocationByIPAddress.
         */
        function getLocationByIPAddressOnFailure() {
            try {

            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }

        /**
        * get Affordable Rentals Panel List.
        */
        pub.getRentalPanelList = function () {           
            //To get the current location values.
            listing.getLocationByIPAddress(getLocationByIPAddresseOnSuccess, getLocationByIPAddressOnFailure);
        }

        /**
        * Invoked on success when calling getRentalPanelList.
        */
        function getRentalPanelListOnSuccess(result) {
            indexModel.view.isLoading(false);
            try {
                if (result && result.location) {
                    var properties = ko.observableArray([]);
                    indexModel.domain.rentalPanelLocation(result.location);

                    if (result.listings.length > 0) {
                        ko.utils.arrayMap(result.listings, function (item) {
                            properties.push(new pub.property(item));
                        });

                        indexModel.domain.rentalPanelList(properties());
                    }

                    /* Update last Rental Panel Location List in local storage */
                    localStorage.setItem(lastsearchRentalPanelList, ko.toJSON(indexModel.domain.rentalPanelList()));

                    /* Update last Rental Panel Location in local storage */
                    localStorage.setItem(lastsearchRentalPanelLocation, ko.toJSON(indexModel.domain.rentalPanelLocation()));
                    $("#rentalPanelServer").hide();
                    $("#rentalPanelKO").show();
                }
            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }

        /**
         * Invoked on failure when calling getRentalPanelList.
         */
        function getRentalPanelListOnFailure() {
            try {

            }
            catch (ex) {
                go8Error.handleException(ex);
            }
        }

        pub.populateHomeNearbyHAPanel = function ()
        {
            try
            {
                var city, stateCode = '';
                var lat = 0.00;
                var long = 0.00;
                haPanel.haCount(3);

                /* Get existing items from cookie */
                var suggestionsRecent = JSON.parse($.cookie(recentSearchCookieName));
                var isUserLoggedIn = !helper.isUndefinedOrNullOrEmpty(headerModel.domain.user()) ? true : false;

                if (!helper.isUndefinedOrNullOrEmpty(suggestionsRecent))
                {
                    suggestionsRecent = _.filter(suggestionsRecent, function (item)
                    {
                        return item.isLoggedUserCookie == isUserLoggedIn;
                    });
                }

                /* Get most recent seach item */
                if (!helper.isUndefinedOrNullOrEmpty(suggestionsRecent) && suggestionsRecent.length > 0)
                {
                    city = suggestionsRecent[0].baseAreaName;
                    stateCode = suggestionsRecent[0].stateCode;
                }

                if (helper.isUndefinedOrNullOrEmpty(stateCode) && $.cookie('userlocation') != null)
                {
                    var location = JSON.parse($.cookie('userlocation'));
                    if (!helper.isUndefinedOrNullOrEmpty(location) && !helper.isNullOrEmpty(location["State"]))
                    {
                        city = location["City"];
                        stateCode = location["State"];
                        if (!helper.isUndefinedOrNullOrEmpty(location["Latitude"]))
                            lat = location["Latitude"];
                        if (!helper.isNullOrEmpty(location["Longitude"]))
                            long = location["Longitude"];
                    }

                }
                if (!helper.isUndefinedOrNullOrEmpty(stateCode))
                {
                    haPanel.city(city);
                    haPanel.state(stateCode);

                    listing.getClosestHa(lat, long, stateCode, city, getHomeClosestHaOnSuccess, OnFailure);
                }
                else
                {
                    listing.getLocationByIPAddress(function (result)
                    {
                        if (result && (!helper.isNullOrEmpty(result.Location.city) || !helper.isNullOrEmpty(result.Location.district) || !helper.isNullOrEmpty(result.Location.state)))
                        {
                            var currentlocation = result.Location;

                            //add cookie for users location
                            var locationString = JSON.stringify({
                                City: currentlocation["city"],
                                County: currentlocation["district"],
                                State: currentlocation["stateProv"],
                                Zip: currentlocation["zipCode"],
                                Latitude: currentlocation["latitude"],
                                Longitude: currentlocation["longitude"]
                            });

                            $.cookie("userlocation", locationString, { expires: 365, path: '/' });

                            pub.populateHomeNearbyHAPanel();
                        }
                    }, OnFailure);

                }
            }
            catch (ex)
            {
                go8Error.handleException(ex);
            }
        }

        /**
   * Invoked on success when calling getClosestHa.
   */
        function getHomeClosestHaOnSuccess(result)
        {

            try
            {
                if (result)
                {
                    haPanel.haList([]);
                    ko.utils.arrayMap(result.closestHaList, function (item)
                    {
                        haPanel.haList.push(item.ha);
                    });

                    $("#ucHomeNearByHA_nearByListingDiv").hide();
                }
            }
            catch (ex)
            {
                go8Error.handleException(ex);
            }
        }

        /**
         * Invoked on failure when calling getClosestHa.
         */
        function OnFailure()
        {
            try
            {

            }
            catch (ex)
            {
                go8Error.handleException(ex);
            }
        }

        return pub;
    }
    catch (ex) {
        go8Error.handleException(ex);
    }
}());


//$(window).bind("unload", function () {
//    var scrollPosition = window.pageYOffset;
//    localStorage.setItem("scrollPosition", scrollPosition);
//});

// Added this event to prevent Browser back button in iPad device.
$(window).bind("pageshow", function (event) {
    if (event.originalEvent.persisted) {
        window.location.reload();
    }
});


var indexModel = (function ()
{
    try
    {
        // Public functions and state.
        var pub = {};

        pub =
            {

                // The domain model contains all information relevant to server calls.
                domain:
                {
                    rentalPanelList: ko.observableArray([]),
                    rentalPanelLocation: ko.observable()
                },

                // Any necessary public operations should be exposed here.  Functions here should just call private
                // functions.  This may be ommitted if you have no such requirements.
                operations:
                {
                },

                // The pojo model contains state information that cannot be observable because of constaints imposed by
                // third party software like Google maps.  This may be ommitted if you have no such requirements.
                pojo:
                {
                },

                // The view model contains state only of interest to the view.
                view:
                {
                    isLoading: ko.observable(false),
                    currentCity: ko.observable(""),
                    currentCounty: ko.observable(""),
                    currentState: ko.observable(""),
                    currentLatitude: ko.observable(""),
                    currentLongitude: ko.observable(""),
                    currentZip: ko.observable("")
                },
                async:
                {
                    loading: ko.observable(false),
                    initLoadComplete: ko.observable(false)
                }
            }

        return pub;
    }
    catch (ex)
    {
        go8Error.handleException(ex);
    }
}
    ());

$(function ()
{
    index.onPageLoad();
    ko.cleanNode(document.getElementById("indexInfo"));
    ko.applyBindings(indexModel, document.getElementById('indexInfo'));
})


headerModel.domain.isHomePage(true);
var haPanel = {
    city: ko.observable(),
    county: ko.observable(),
    zip: ko.observable(),
    state: ko.observable(),
    country: ko.observable(),
    latitude: ko.observable(0),
    longitude: ko.observable(0),
    haCount: ko.observable(0),
    minimumCount: ko.observable(0),
    haList: ko.observableArray([])
}

var focuscount = 0;

$(document).ready(function ()
{
    $.cookie('isfromseo', '', { expires: -1, path: '/', secure: true });
    $('body').addClass('global--home');
    ShowHideAH_WelcomeBanner();
    if (headerModel.domain.user() && headerModel.domain.user().UserType() === 'Landlord')
        $('body').addClass('owner--home');

    // Prepop Last Search

    if (lastSearch != null && lastSearch != "")
        $(".search-input").val(lastSearch);
    else
    {
        if (document.createElement("input").placeholder == undefined)
        {
            $(".search-input").val(searchplaceholder);
        }
    }

    $("#homesearchautocomplete").val('');


    // Search Input Events

    $('.search-input').click(function ()
    {
        if (focuscount < 1)
        {
            if (window.getSelection)
                this.setSelectionRange(0, 9999);
            else
                $(this).select();
            focuscount++;
        }
    }).blur(function ()
    {
        if (document.createElement("input").placeholder == undefined)
        {
            if ($(this).val() == "")
                $(this).val(searchplaceholder);
        }
        focuscount = 0;
    }).keyup(function ()
    {
        var searchlocation = $(this).val();
        if (searchlocation.length < 3)
        {
            $("#homesearchautocomplete").val('');
        }
        if (event.which == 13 || event.charCode == 13)
        {

            if (searchlocation != ""
                && searchlocation != searchplaceholder
                && event.keyCode != 13)
            {
                $("#homesearchautocomplete").val('');
                searchrentals(searchlocation);
            }
        }
    });


    // Search Submit Events

    $('.search-submit').click(function ()
    {

        var searchLocation = $(this).closest(".search-container").find(".search-input").val();
        if (searchLocation != "" && searchLocation != searchplaceholder)
            searchrentals(searchLocation);
    });


    // Rotate Home Images

    function homeImages()
    {
        if (!mobile)
        {
            $("#herobg2").delay(5000).fadeIn(1000, function ()
            {
                $("#herobg3").delay(5000).fadeIn(1000, function ()
                {
                    $("#herobg2").delay(5000).fadeOut(1000, function ()
                    {
                        $("#herobg3").hide();
                        homeImages();
                    });
                });
            });
        }
    }

    homeImages();


    // Call Autocomplete

    var results = new Array();
    $("#homesearchinput").autocomplete({
        source: function (req, res)
        {
            var getNewSuggestions = true;
            var prefix = req.term;
            if (prefix.length > 3 && results != null && results.length > 0)
            {
                //no need to go to database? may be store in an array and use that array to filter results;
                var filteredResults = filterSuggestions(prefix);
                if (filteredResults.length > 0)
                    getNewSuggestions = false;
                if (!getNewSuggestions)
                {
                    res($.map(filteredResults, function (result)
                    {
                        return {
                            value: result.SearchTextToDisplay
                        }
                    }));
                }

            }
            if (getNewSuggestions)
            {
                $.ajax({
                    url: "/AJAX/SearchResults.asmx/GetAreas",
                    data: "{'prefix':'" + prefix + "'}",
                    dataType: "json",
                    type: "Post",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (resp) { return resp; },
                    error: function (resp)
                    {
                    },
                    success: function (resp)
                    {
                        results = new Array();
                        if (resp.d.length <= 0)
                        {
                            $("#homesearchautocomplete").val('');
                        }
                        else
                        {
                            results = resp.d;
                        }
                        res($.map(results, function (result)
                        {
                            return {
                                value: result.SearchTextToDisplay
                            }
                        }))
                    }
                });
            }
        },
        appendTo: $("#homesearchinput").closest(".autocomplete"),
        select: function (event, ui)
        {
            $("#homesearchautocomplete").val('');
            searchrentals(ui.item.value);
        },
        minLength: 3,
        open: function (event, ui)
        {
            if ($(this).data("uiAutocomplete") !== undefined)
            {
                var firstSuggestionId = $(this).data("uiAutocomplete").menu.element[0].children[0];
                var firstSuggestion = $(firstSuggestionId).text();
                var searchinput = $('#homesearchinput');
                var inputLength = searchinput.val().length;

                if (firstSuggestion.toLowerCase().indexOf(searchinput.val().toLowerCase()) === 0)
                {
                    //  searchinput.val(firstSuggestion);
                    var regEx = new RegExp(this.value, "ig");
                    var grayText = new Array(this.value.length + 1).join(' ') + firstSuggestion.substring(this.value.length)
                    $("#homesearchautocomplete").val(this.value + firstSuggestion.substring(this.value.length))
                    //highlight from end of input to end
                    //searchinput[0].selectionStart = inputLength;
                    //searchinput[0].selectionEnd = firstSuggestion.length;
                    //may be a different span with gray text instead of selcting the text?
                    // $('#ending').html(firstElementText.substring(this.value.length))

                }
            }
        }
    });

    function filterSuggestions(prefix)
    {
        var res = $.grep(results, function (p)
        {
            return p.FullTextSearch.toLowerCase().startsWith(prefix.toLowerCase()) ||
                p.StandardSearch.toLowerCase().startsWith(prefix.toLowerCase());
        });
        return res;
    }

    var owl = $('.owl-carousel.renter--carousel');
    owl.owlCarousel({
        margin: 30,
        nav: true,
        loop: false,
        slideBy: 2,
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 2
            },
            1000: {
                items: 2
            }
        }
    });
});

function ShowHideAH_WelcomeBanner()
{
    if (IsShowAHWelcomeBanner)
    {
        $('.welcome--cnt--area').show();
    }
    else
    {
        $('.welcome--cnt--area').hide();
    }

}

var propertyPanelControlModel = function (params)
{
    try
    {
        if (!params)
        {
            params = {};
        }
        var self = this;
        self.ControlType = params.controlType;
        self.City = ko.observable(params.city || '');
        self.County = ko.observable(params.county || '');
        self.State = ko.observable(params.state || '');
        self.PropertyCount = ko.observable(params.propertyCount || 0);
        self.MinPropertyCount = ko.observable(params.minPropertyCount || 0);        
        self.PlaceHolderCount = ko.observable(0);
        var PropertyList = ko.observableArray([]);

        var propertyToDisplay = 0;
        if (self.ControlType == 'vertical')
        {
            propertyToDisplay = self.PropertyCount();
        }
        else
        {
            if (self.PropertyCount() == 3 && self.MinPropertyCount() == 2)
            {
                if (params.propertyList.length >= self.PropertyCount())
                {
                    propertyToDisplay = self.PropertyCount();
                }
                else if (params.propertyList.length == self.MinPropertyCount())
                {
                    propertyToDisplay = self.MinPropertyCount();                    
                }
            }
            else
            {
                if ((self.PropertyCount() % params.propertyList.length) == 0)
                {
                    propertyToDisplay = params.propertyList.length;
                }
                else
                {
                    propertyToDisplay = (Math.floor(self.PropertyCount() / params.propertyList.length)) * self.MinPropertyCount();
                }
            }
        }
        
        ko.utils.arrayMap(params.propertyList.slice(0, propertyToDisplay), function (item)
        {
            PropertyList.push(item);
        });

        if (helper.isMobile() || helper.isTablet())
        {
            if ((self.PropertyCount() - PropertyList().length) != self.MinPropertyCount())
            {
                self.PlaceHolderCount((self.PropertyCount() - PropertyList().length));
            }
        }
        else
        {
            self.PlaceHolderCount((self.PropertyCount() - PropertyList().length));
        }

        self.PropertyList = PropertyList;
        self.locationString = ko.computed(function ()
        {
            if (self.PropertyList().length > 0)
            {
                var matchType = self.PropertyList()[0].matchType().toLowerCase();
                if (matchType === 'city')
                {
                    return self.City().toLowerCase() + ", " + self.State();
                }
                else if (matchType === 'state')
                {
                    return self.State();
                }
                else
                {
                    return self.County().replace(" County", "") + " County, " + self.State();
                }
            }
        });

        self.search = (function ()
        {
            window.location = "/Tenant/tn_Results.aspx?Address=" + self.locationString();
        });

        self.SaveFavorite = function (data)
        {
            propertyid = data.propertyId();
            landlordid = 0;

            if (headerModel.domain.user() && headerModel.domain.profile.userType() == headerModel.view.userType.Tenant)
            {
                var curdate = new Date();
                var DateString = curdate.getMilliseconds();
                if (data.propertyFavoriteClass() == "prop-like-icon-red")
                {
                    data.propertyFavoriteClass("prop-like-icon")
                    performTenantAction('RemoveFavoriteHome', JSON.stringify({ PropertyID: propertyid }));
                }
                else
                {
                    var canFav = CanFavoriteHome();
                    if (canFav)
                    {
                        SaveFavoriteHome(propertyid, true);
                    }
                    else
                    {
                        showModal('favoritepropertyconfirmationmodal');
                    }
                }
            }
            else if (headerModel.domain.user() && headerModel.domain.profile.userType() == headerModel.view.userType.Landlord)
            {
                showModal('LLFavPopup');
            }
            else
            {
                regAction = tenantRegAction.saveHome;
                showGreatSchoolPopup = false;
                showTenantRegModal('Save Home');
            }
        }

    } catch (ex)
    {
        go8Error.handleException(ex);
    }
};

function errorfn(xhr, status, error)
{
    alert('Hey i am not loading!!!');
}



var LandLordLeasesCount = (function () {

    var pub = {

    };
    pub.getLeases = function () {
        if (headerModel.domain.user() != null && headerModel.domain.user() != undefined && headerModel.domain.user().UserType() === headerModel.view.userType.Landlord) {
            listing.getLeasesCount(getLeasesOnSuccess, getLeasesOnFailure);
        }
    };

    function getLeasesOnSuccess(result) {
        LandLordLeasesCountModel.leasesCount(result);
        headerModel.menuCount.leasesCount(result);
    };

    function getLeasesOnFailure() {
        try {
            LandLordLeasesCountModel.leasesCount(0);
            headerModel.menuCount.leasesCount(0);
        }
        catch (ex) {
            go8Error.handleException(ex);
        }
    };

    pub.onPageLoad = function () {
        pub.getLeases()
    }

    return pub;
}());

var LandLordLeasesCountModel = (function () {
    var pub =
    {
        leasesCount: ko.observable(),
    };
    return pub;
}());

$(function () {
    LandLordLeasesCount.onPageLoad();
});



var HAPanelControlModel = function (params)
{
    try
    {
        if (!params) 
        {
            params = {};
        }
        var self = this;
        self.shareUrl = ko.observable("");
        self.haCount = ko.observable(params.haCount || 0);
        self.minimumCount = ko.observable(params.minimumCount || 0);
        var haList = ko.observableArray([]);
	   var displayCount = params.haCount;
	   var logoSize = "263x169";
	    if (params.orientation === 'vertical')
            logoSize = "75x75";
       
        if (self.minimumCount() > 0)
        {
            if (self.haCount() == 3 && self.minimumCount() == 2)
            {
                if (params.haList.length >= self.haCount())
                {
                    displayCount = self.haCount();
                }
                else if (params.haList.length == self.minimumCount())
                {
                    displayCount = self.minimumCount();
                }
            }
            else
            {
                var haListLength = params.haList.length >= self.haCount() ? self.haCount() : params.haList.length;
                if ((self.haCount() % haListLength) == 0)
                {
                    displayCount = haListLength;
                }
                else
                {
                    displayCount = (Math.floor(self.haCount() / haListLength)) * self.minimumCount();
                }
            }
        }
     

        function getHaLogoOnSuccess(result)
        {
            try {
			 $.each(haList(), function (j, ha) {
				$.each(result.logo, function (index, haLogo) {
				    if (ha.haId() === haLogo.haId) {
                        ha.haLogo(haLogo.logoPath + `?time=${new Date().getTime()}`);
					   return;
				    }
                });
                
                 $("#ulHalist li").each(function (index, obj) {
                     var location = getLocation(haList()[index]);
                     $($(obj).children()[1]).attr('href', location)
                     $($(obj).children()[1]).attr('title', haList()[index].haDisplayName());
                 });
             });
            }
            catch (ex)
            {
                go8Error.handleException(ex);
            }
        }

        function getHaLogoOnFailure(xhr, status, error)
        {
            try
            {
                //show error message
            }
            catch (ex)
            {
                go8Error.handleException(ex);
            }
	   }

        var comingSoonWLPeriodInDays = 60;
        var logoRequest = [];
        ko.utils.arrayMap(params.haList.slice(0, displayCount), function (item)
	   {
		  haList.push(new formatHa(item));
		  logoRequest.push({ haId: item.haId, participantCode: item.participantCode });
	   });
	   listing.getHaLogo(logoRequest,
		   logoSize,
		   getHaLogoOnSuccess,
		    getHaLogoOnFailure);

        self.haList = haList;
        self.city = ko.observable(params.city || '');
        self.county = ko.observable(params.county || '');
        self.zip = ko.observable(params.zip || '');
        self.state = ko.observable(params.state || '');
        self.country = ko.observable(params.country || '');
        self.latitude = ko.observable(params.latitude || 0);
        self.longitude = ko.observable(params.longitude || 0);
        self.redirectToSearchPage = (function ()
        {
            var url = '/housing-authority';

            if (!helper.isNullOrEmpty(self.state()) && helper.isNullOrEmpty(self.county()) && helper.isNullOrEmpty(self.city()) && helper.isNullOrEmpty(self.zip()))
                url = '/housing-authority-' + (helper.urlFriendlyString(self.state())).toLowerCase() + '/';
	        //include county only if city is empty, becuase city can be in multiple counties and we dont want to restrict to one county results
            if (!helper.isNullOrEmpty(self.city()) && !helper.isNullOrEmpty(self.state()) && helper.isNullOrEmpty(self.county()) && helper.isNullOrEmpty(self.zip()))
                url = '/housing-authority-' + (helper.urlFriendlyString(self.city())).replaceAll(' ', '-').toLowerCase() + "-" + (helper.urlFriendlyString(self.state())).toLowerCase() + '/';
            if (!helper.isNullOrEmpty(self.county()) && !helper.isNullOrEmpty(self.state()) && helper.isNullOrEmpty(self.city()) && helper.isNullOrEmpty(self.zip()))
                url = '/housing-authority-' + (helper.urlFriendlyString(self.county())).replaceAll(' ', '-').toLowerCase() + "-county-" + (helper.urlFriendlyString(self.state())).toLowerCase() + '/';
            if (!helper.isNullOrEmpty(self.zip()) && !helper.isNullOrEmpty(self.state()) && helper.isNullOrEmpty(self.city()) && helper.isNullOrEmpty(self.county()))
                url = '/housing-authority-' + (helper.urlFriendlyString(self.city())).replaceAll(' ', '-').toLowerCase() + '-' + (helper.urlFriendlyString(self.state())).toLowerCase() + '/';

            window.location = url;
        });
        
        self.redirectToLandingPage = (function (data)
        {
            ////Replace any special characters from the haName
            //var haName = data.haName().replace(/[^a-zA-Z0-9(\/\s+)]/g, "");

            //haName = helper.urlFriendlyString(haName);
            //var location = "/housing-authority-{stateCode}/{HaName}-{HaId}/";
            //location = location.replace("{HaId}", data.haId());
            //location = location.replace("{HaName}", haName.toLowerCase().replaceAll(' ', '-'));
            //location = location.replace("{stateCode}", data.state().toLowerCase());

            window.location = getLocation(data);
        });

        function getLocation(data) {
            var haName = data.haName().replace(/[^a-zA-Z0-9(\/\s+)]/g, "");

            haName = helper.urlFriendlyString(haName);
            var location = "/housing-authority-{stateCode}/{HaName}-{HaId}/";
            location = location.replace("{HaId}", data.haId());
            location = location.replace("{HaName}", haName.toLowerCase().replaceAll(' ', '-'));
            location = location.replace("{stateCode}", data.state().toLowerCase());
            return location;

        }
        self.shareHA = function (data)
        {

            //Replace any special characters from the haName
            var haName = data.haName().replace(/[^a-zA-Z0-9(\/\s+)]/g, "");

            haName = helper.urlFriendlyString(haName);
            var location = "{HaName}/HA{HaId}";
            location = location.replace("{HaId}", data.haId());
            location = location.replace("{HaName}", haName);
            location = window.location + location;
            self.shareUrl(location);
            showModal('homehapanel-share-popup');
        }

        self.copyUrl = function ()
        {
            helper.Clipboard.copy(self.shareUrl());
        }
        function formatHa(ha)
        {
            var self = this;
            self.haId = ko.observable(ha.haId || '');
            var displayHaName = null;
            ha.haName = _.startCase(_.toLower(ha.haName)); // Capitalize first letter of each word
            if (ha.haName != '' && !wordInString(ha.haName.toLowerCase(), 'housing') && !wordInString(ha.haName.toLowerCase(), 'agency') &&
                !wordInString(ha.haName.toLowerCase(), 'authority') && !wordInString(ha.haName.toLowerCase(), 'hsg') &&
                !wordInString(ha.haName.toLowerCase(), 'ha') && !wordInString(ha.haName.toLowerCase(), 'auth') && !wordInString(ha.haName.toLowerCase(), 'agcy')) {
                displayHaName = ha.haName + ' Housing Authority';
            }
            self.haName = ko.observable(ha.haName || '');
            self.haDisplayName = ko.observable(displayHaName || ha.haName);
            self.address1 = ko.observable(ha.address || '');
            self.address2 = ko.observable(ha.address2 || '');
            self.city = ko.observable(ha.city || '');
            self.county = ko.observable(ha.county || '');
            self.state = ko.observable(ha.state || '');
            self.zip = ko.observable(ha.zip || '');
            self.email = ko.observable(ha.email || '');
            self.phone = ko.observable(ha.phone || '');
            self.fax = ko.observable(ha.fax || '');
            self.haWebsite = ko.observable(ha.haWebsite || '');
		    self.haLogo = ko.observable(ha.haLogo + `?time=${new Date().getTime()}` || '');
            self.isWaitlistPartner = ko.observable(ha.isWaitlistPartner);

            if (ha.waitlistStatus && ha.waitlistStatus != '')
            {
                self.waitListStatus = ko.observable(_.capitalize(ha.waitlistStatus));
            }
            else
            {
                self.waitListStatus = ko.observable('');
            }

            var waitlistStatus = ha.waitlistStatus || '';
            if (waitlistStatus === 'Closed') {
                var opendate = moment(ha.waitlistOpenDate);
                if (opendate) {
                    var currentDate = new Date();
                    if (opendate.diff(currentDate, 'days') > 0 && opendate.diff(currentDate, 'days') < comingSoonWLPeriodInDays) {
                        waitlistStatus = "OpeningSoon";
                    }
                }
            }

            self.waitListStatus = ko.observable(waitlistStatus);

            self.address = ko.computed(function ()
            {
                var str = '';

                if (self.address1())
                {
                    str = self.address1().trim();
                    if (self.address2())
                        str = str + ", ";
                }
                if (self.address2())
                {
                    str = self.address2().trim();
                }
                if (self.city())
                {
                    if (self.address1() || self.address2())
                        str = str + ", " + self.city().trim();
                    else
                        str = self.city().trim();
                    
                }
                if (self.state())
                {
                    str = str + ", " + self.state();
                }
                if (self.zip())
                {
                    str = str + " " + self.zip();
                }

                return str;
            });
        }
        self.locationString = ko.computed(function ()
        {
            if (self.haList().length > 0)
            {
                if (!helper.isNullOrEmpty(self.city()))
                {
                    return self.city().toLowerCase() + ", " + self.state();
                }
                else if (!helper.isNullOrEmpty(self.county()))
                {
                    return self.county().replace(" County", "") + " County, " + self.state();
                }
                else
                {
                    return self.state();
                }
            }
        });
        //Function to check specific word in string.
        function wordInString(s, word) {
            return new RegExp('\\b' + word + '\\b', 'i').test(s);
        }

    } catch (ex)
    {
        go8Error.handleException(ex);
    }
}

ko.components.register('HAPanelControl', {
    template: { element: 'haPanelControlHtml' },
    viewModel: HAPanelControlModel
});


function errorfn(xhr, status, error)
{
    alert('Hey i am not loading!!!');
}

