var nzTourism = {};

/**
 * Prototypal methods
 */
// from http://www.svendtofte.com/code/usefull_prototypes/prototypes.js
Array.prototype.compareArrays = function (arr) {
    if (this.length !== arr.length) {
        return false;
    }
    for (var i = 0; i < arr.length; i++) {
        if (this[i].compareArrays) { //likely nested array
            if (!this[i].compareArrays(arr[i])) {
                return false;
            } else {
                continue;
            }
        }
        if (this[i] !== arr[i]) {
            return false;
        }
    }
    return true;
};

Number.prototype.mod = function (base) {
    var num;
    num = this % base;
    return num < 0 ? num + base : num;
};

Date.prototype.addDays = function (numDays) {
    return this.setDate(this.getDate() + numDays);
};

// this ain't the greatest idea, but for some reason Prototype's version doesn't like our JSON
// TODO add stripping of potentially "dangerous" strings
/*
This test from json.org may do the trick:

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

*/
String.prototype.jsonify = function () {
    try {
        var json;
        json = eval('(' + this + ')');
        return json;
    } catch (e) {
        return false;
    }
};

/**
 * Constants used across scripts accessible within the nzTourism namespace
 */
nzTourism.constants = {
    // event handlers
    CLICK       : 'click',
    MOUSEUP     : 'mouseup',
    MOUSEOUT    : 'mouseout',
    MOUSEOVER   : 'mouseover',
    MOUSEDOWN   : 'mousedown',
    MOUSEMOVE   : 'mousemove',
    DRAGSTART   : 'dragstart',
    FOCUS        : 'focus',
    // HTML tags
    DIV         : 'DIV',
    INPUT       : 'INPUT',
    LABEL       : 'LABEL',
    SELECT      : 'SELECT',
    OPTION      : 'OPTION',
    // misc
    HI          : '_hi.',
    PX          : 'px',
    LEFT        : 'left',
    NEXT        : 'next',
    PREVIOUS    : 'previous',
    DASH        : '-',
    SLASH       : '/',
    IN          : 'in',
    OUT         : 'out',
    // SMAPS
    MINI        : 'mini',
    SEARCH      : 'search',
    MODAL       : 'modal',
    // guest details
    SELF        : 'self',
    OTHER       : 'other'
};

/**
* Common GUI functions (should load first because other functions rely on nzTourism.guiUtils.isIE)
*/
nzTourism.guiUtils = (function () {
    // private methods
    var _getExtension;

    /**
    * Return the extension from a filename
    *
    * @param string filename
    * @return string
    */
    _getExtension = function (filename) {
        var pieces;
        pieces = filename.split('.');
        return pieces[pieces.length - 1];
    };

    // public variables and methods
    return {
        /**
         * Determine whether the browser is Internet Explorer
         */
        isIE: (document.all && !window.opera),

        /**
         * Determine whether the browser is that vile creation, Internet Explorer 6
         */
        isIE6: (document.all && !window.opera && navigator.appVersion.indexOf('MSIE 6') > -1),

        /**
         * Determine whether the browser is Safari 2 or below
         */
        isSafari2: (function () {
            var isSafari2, pieces;
            isSafari2 = false;
            if (navigator.userAgent.indexOf('AppleWebKit') > -1) {
                pieces = navigator.appVersion.split('/');
                if (1 * pieces[pieces.length - 1] < 500) {
                    isSafari2 = true;
                }
            }
            return isSafari2;
        })(),

        /**
        * Pop-up a new window in a standard way and set focus on the new window
        * Usage: <a href="myurl.html" onclick="nzTourism.guiUtils.popup(this.href, 'myWindow');return false;">
        */
        popup: function (url, windowName, popupParams) {
            var newWindow;
            popupParams = popupParams || 'location=no,toolbar=no,menubar=no,resizeable=no,width=600,height=500,left=100,top=0';
            newWindow = window.open(url, windowName, popupParams);
            if (window.focus) {
                newWindow.focus();
            }
            return false;
        },
        /**
        * Add an option to a select list
        *
        * @param object selObj DOM object of the select list we want to update
        * @param string value  Value to which to set the option
        * @param string text   Visible label for the option tag
        */
        addOption: function (selObj, value, text) {
            var option;
            option = document.createElement(nzTourism.constants.OPTION);
            selObj.appendChild(option);
            option.value = value;
            option.text = text;
        },
        /**
        * Perform image rollovers and other image stuff
        *
        * @param object img Image element on which we are to perform the action
        */
        images: {
            /**
             * Preload images
             * @param array imgSrcs Array of image sources to preload
             */
            preload: function (imgSrcs) {
                var img;
                img = new Image();
                imgSrcs = imgSrcs || [];
                $A(imgSrcs).each(function (src) {
                    img.src = src;
                });
            },
            hi: function (img) {
                var extension;
                extension = _getExtension(img.src);
                if (img.src.indexOf(nzTourism.constants.HI + extension) < 0) {
                    img.src = img.src.replace('.' + extension, nzTourism.constants.HI + extension);
                }
            },
            lo: function (img) {
                var extension;
                extension = _getExtension(img.src);
                if (img.src.indexOf(nzTourism.constants.HI + extension) > 0) {
                    img.src = img.src.replace(nzTourism.constants.HI + extension, '.' + extension);
                }
            }
        },
        /**
         * Return the hash value from the URL or false if there is none
         */
        getHash: function () {
            return ('' !== window.location.hash && '#' !== window.location.hash)? window.location.hash.slice(1): false;
        }
    };
})();




nzTourism.districts = (function () {
    // public variables and methods
    return {
        districtsAndRegions: undefined,
        update: function () {
            var region, selObj;
            region = $F('region');
            if ('none' === region) {
                region = '';
                $('region').selectedIndex = 0;
            }
            selObj = $('district');
            // blow away current district options
            selObj.options.length = 0;
            nzTourism.guiUtils.addOption(selObj, '', 'Any district');
            nzTourism.guiUtils.addOption(selObj, 'none', '');
            if (region === 'none' || region === '') {
                selObj.disabled = true;
            } else {
                selObj.disabled = false;
                // add new district options
                // TODO make this a prototype loop
                for (var district in nzTourism.districts.districtsAndRegions[region]) {
                    nzTourism.guiUtils.addOption(selObj, district, nzTourism.districts.districtsAndRegions[region][district]);
                }
            }
        }
    };
})();