"use strict";
/*jslint onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, regexp: true, newcap: true, immed: true, strict: true */
/*jslint bitwise: false, white: false */
/*global document */
/*global MapOptions, Astrometrics */ // from map.js
/*global AsyncHttpRequest */ // from ajax.js


//////////////////////////////////////////////////////////////////////
//
// Generic Functions
//
//////////////////////////////////////////////////////////////////////

//----------------------------------------------------------------------
// Set the correct selection in a SELECT element
//----------------------------------------------------------------------
function setSelectedOption(select, option)
//----------------------------------------------------------------------
{
    var index = -1, i;

    for (i = 0; i < select.options.length; i += 1) {
        if (select.options[i].value.toString() === option.toString()) {
            index = i;
            break;
        }
    }

    if (select.selectedIndex !== index) {
        select.selectedIndex = index;
    }
}

//----------------------------------------------------------------------
function getUrlParameters()
//----------------------------------------------------------------------
{
    var hash = {
            hasParameter: function(s) { return typeof this[s] !== "undefined"; }
        }, 
        pairs, i, keyValue,
        strSearch = document.location.search;
        
    if (strSearch && strSearch.length > 1) {
        strSearch = strSearch.substring(1);
        pairs = strSearch.split('&');

        for (i = 0; i < pairs.length; i += 1) {
            keyValue = pairs[i].split('=', 2);

            if (keyValue.length === 2) {
                hash[keyValue[0]] = decodeURIComponent(keyValue[1].replace("+", " "));
            }
            else {
                hash[keyValue[0]] = true;
            }
        }
    }

    return hash;

}  // getUrlParameters


//----------------------------------------------------------------------
function escapeHtml( s )
//----------------------------------------------------------------------
{
    return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");

} // escapeHtml



//----------------------------------------------------------------------
function fromHex(c)
//
// This is Traveller "hexadecimal"
//
//----------------------------------------------------------------------
{
    return "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ".indexOf( c.toUpperCase() );
    
} // fromHex


//////////////////////////////////////////////////////////////////////
//
// Extensions to built-in classes
// (Some are based on ECMAScript Version 5 additions)
//
//////////////////////////////////////////////////////////////////////

//
// Array.prototype.contains( o )
//
if (typeof Array.prototype.contains !== 'function') {
    Array.prototype.contains = function(o) {
        var i, len = this.length >>> 0;
        for (i = 0; i < len; i += 1) {
            if (i in this && this[i] === o) {
                return true;
            }
        }
        return false;
    };
}

//
// ECMAScript 5
// Array.prototype.map( f )
//
if (typeof Array.prototype.map !== 'function') {
    Array.prototype.map = function(fun /*, thisp */) {
        if (typeof fun !== 'function') { throw new TypeError(); }
        var i, len = this.length >>> 0, res = new Array(len), thisp = arguments[1];
        for (i = 0; i < len; i += 1) {
            if (i in this) {
                res[i] = fun.call(thisp, this[i], i, this);
            }
        }
        return res;
    };
}

//
// ECMAScript 5
// Array.prototype.some( f )
//
if (typeof Array.prototype.some !== 'function') {
    Array.prototype.some = function(fun /*, thisp */) {
        if (typeof fun !== 'function') { throw new TypeError(); }
        var i, len = this.length >>> 0, thisp = arguments[1];
        for (i = 0; i < len; i += 1) {
            if (i in this && fun.call(thisp, this[i], i, this)) {
                return true;
            }
        }
        return false;
    };
}

//
// ECMAScript 5
// Array.prototype.every( f )
//
if (typeof Array.prototype.every !== 'function') {
    Array.prototype.every = function(fun /*, thisp */) {
        if (typeof fun !== 'function') { throw new TypeError(); }
        var i, len = this.length >>> 0, thisp = arguments[1];
        for (i = 0; i < len; i += 1) {
            if (i in this && !fun.call(thisp, this[i], i, this)) {
                return false;
            }
        }
        return true;
    };
}

//
// String.prototype.startsWith( s )
//
if (typeof String.prototype.startsWith !== 'function') {
    String.prototype.startsWith = function(s) {
        return this.substring(0, s.length) === s;
    };
}

//
// String.prototype.endsWith( s )
//
if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(s) {
        return this.substring(this.length - s.length) === s;
    };
}

//
// ECMAScript 5
// String.prototype.trim()
//
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function(s) {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}



//////////////////////////////////////////////////////////////////////
//
// Location Lookup
//
//////////////////////////////////////////////////////////////////////

function requestCoordinates(sector, hex, callback) {
    if (typeof callback !== 'function') { throw new TypeError(); }

    var request = new AsyncHttpRequest(),
        query = "coordinates.aspx?sector=" + encodeURIComponent(sector);
    if (typeof hex !== 'undefined') { query += "&hex=" + encodeURIComponent(hex); }

    request.setRequestHeader("Accept", "application/json");
    request.invoke(query,
        function(response, data) {
            if (data && typeof data.sx !== 'undefined' && typeof data.sy !== 'undefined') {
                callback(data);
            }
        },
        function(response) {
            callback(null);
        });

}
