﻿IBingMap = new Class.create();
var url = "hotelmap.axd?#{qString}=#{qParam}";
var mapTitle = "<div style='display:none;'>#{mapTitle}</div>";
var divBox = "<div class=\"popup_mian\">#{waitingscript}</div>";
var waitingScript = "<div id='#{shapeID}_Content'><img src='images/progress_loading.gif'  align='absmiddle' style='padding:10px' /> Loading data....</div>";
IBingMap.prototype = {
    locations: null,
    combo: null,
    mapType: { single: 1, popup: 2, selected: 3 },
    initialize: function (mapId, type, mapObjects, mapFeatures, items, qString) {
        var instance = this;
        this.map = new VEMap(mapId);
        this.map.LoadMap(new VELatLong(mapObjects.latitude, mapObjects.longitude), mapObjects.zoomlevel, VEMapStyle.Road, false);

        if (type == this.mapType.single) {
            this.addShape(items, mapObjects.latitude, mapObjects.longitude, mapObjects.customicon);
            this.mType = this.mapType.single;
        }
        else if (type == this.mapType.popup) {
            this.locations = items;

            if (this.locations != null) {
                for (var l = 0; l < this.locations.length; l++) {
                    var args = this.locations[l].split('|');
                    this.addShape(args[0], args[1], args[2], mapObjects.customicon);
                }
            }
            this.mType = this.mapType.popup;
            this.popupwindow = new IModelPopup('IpopupWindow', 'closeWindow');
        }
        else if (type == this.mapType.selected) {
            this.hotels = items;
            for (var a = 1; a < this.hotels.length; a++) {
                var args = this.hotels[a].split('|');
                this.addShape(args[2], args[0], args[1], mapObjects.customicon);
            }
            this.mType = this.mapType.selected;
        }
        if (qString != undefined) {
            this.qString = qString;
        }

        if (mapFeatures != null) {
            this.mapFeatures = mapFeatures;
            this.addMapFeature();
        }
        this.map.AttachEvent("onmouseover", function (e) { instance.OnMouseHandler(e); });
    },
    apply: function () {
        if (this.onload) {
            this.onload();
        }
    },
    addShape: function (title, latitude, longitude, customicon) {
        var pnts = new VELatLong(latitude, longitude);
        var shape = new VEShape(VEShapeType.Pushpin, pnts);
        shape.SetTitle(mapTitle.interpolate({ mapTitle: title }));
        shape.SetCustomIcon(customicon);
        this.map.ClearInfoBoxStyles();
        this.map.AddShape(shape);
    },
    addMapFeature: function () {
        var mps = this.mapFeatures.split('#');
        for (var i = 0; i < mps.length; i++) {
            mpsv = mps[i].split('|');
            this.addShape(mpsv[0] + '|' + mpsv[4], mpsv[1], mpsv[2], mpsv[3]);
        }
    },
    OnMouseHandler: function (e) {
        onhandler = this;
        var _divbox = divBox;
        var _waitingscript = waitingScript;
        var _url = url;
        if (e.elementID) {
            var shape = this.map.GetShapeByID(e.elementID);
            if (!shape.GetDescription() || shape.GetDescription().include('Loading data....')) {
                var title = shape.GetTitle();
                title = title.stripTags();
                _waitingscript = _waitingscript.interpolate({ shapeID: shape.GetID() });
                _divbox = _divbox.interpolate({ waitingscript: _waitingscript });
                shape.SetDescription(_divbox);
                if (title.include('|')) {
                    var mpid = title.split('|')[1];
                    _url = _url.interpolate({ qString: 'mapfuture', qParam: mpid });
                }
                else if (title.include('#')) {
                    var qId = title.split('#');
                    _url = _url.interpolate({ qString: qId[0], qParam: qId[1] });
                }
                else {
                    if (this.mType == this.mapType.popup) {
                        _url = _url.interpolate({ qString: 'location', qParam: title });
                    } else {
                        var _qString = 'title';
                        if (this.qString != undefined) {
                            _qString = this.qString;
                        }
                        _url = _url.interpolate({ qString: _qString, qParam: title });
                    }
                }
                new Ajax.Request(_url, {
                    method: 'get',
                    onSuccess: function (transport) {
                        $(shape.GetID() + '_Content').update(transport.responseText);
                        shape.SetDescription(transport.responseText);
                    }
                });
                this.makeTransparent();
            }
        }
    },
    makeTransparent: function () {
        var divs = document.getElementsByClassName('undefined customInfoBox-with-leftBeak');
        divs = $A(divs);
        divs.each(function (d) {
            d.setStyle({ backgroundColor: 'transparent', zIndex: '10000' });
        });

        divs = document.getElementsByClassName('customInfoBox-shadow');
        divs = $A(divs);
        divs.each(function (d) {
            d.setStyle({ backgroundColor: 'transparent' });
        });

        divs = document.getElementsByClassName('customInfoBox-body');
        divs = $A(divs);
        divs.each(function (d) {
            d.setStyle({ backgroundColor: 'transparent', border: '0px' });
        });

        divs = document.getElementsByClassName('VE_Pushpin_Popup_Title');
        divs = $A(divs);
        divs.each(function (d) {
            d.setStyle({ display: 'none', visibility: 'hidden' });
            d.className = '';
        });
    },
    onClick: function (_click, _args) {
        if (this.mType == this.mapType.popup && _click == 'popup') {
            this.popupwindow.show();
            $('lblLocationName').innerHTML = _args;
            var _this = this;
            $A(this.combo.options).each(function (opt) {
                if (opt.text == _args) {
                    _this.combo.options[opt.index].selected = true;
                    throw $break;
                }
            });
            this.receiveServerData(_args);
        } else if (_click == 'open') {
            window.location.href = _args;
            return false;
        }
    },
    receiveServerData: function (args) {
        var zoom = (args == 'All of Samui') ? 12 : 14;
        var responseString = '';
        var _url = url.interpolate({ qString: 'LocationName', qParam: args });
        new Ajax.Request(_url, {
            method: 'get',
            onSuccess: function (transport) {
                responseString = transport.responseText;
                if (responseString.empty()) return;
                responseString = responseString.split('#^#');
                var arg = responseString[0].split('|');
                new IBingMap('hotelMap', 3, { latitude: arg[0], longitude: arg[1], zoomlevel: zoom, customicon: "<img src=\"images/iconset/pinicongreen.png\" />" }, mapfeatures, responseString);
            }
        });
    },
    distance: function (lat1, lon1, lat2, lon2) {

        //var lat1 = ThailandMap.latitude;
        //var lon1 = ThailandMap.longitude;
        var a = 6378137, b = 6356752.3142, f = 1 / 298.257223563;  // WGS-84 ellipsoid params
        var L = this.toRad((lon2 - lon1));
        var U1 = Math.atan((1 - f) * Math.tan(this.toRad(lat1)));
        var U2 = Math.atan((1 - f) * Math.tan(this.toRad(lat2)));
        var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
        var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);

        var lambda = L, lambdaP, iterLimit = 100;
        do {
            var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
            var sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) +
                      (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
            if (sinSigma == 0) return 0;  // co-incident points
            var cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
            var sigma = Math.atan2(sinSigma, cosSigma);
            var sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
            var cosSqAlpha = 1 - sinAlpha * sinAlpha;
            var cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
            if (isNaN(cos2SigmaM)) cos2SigmaM = 0;  // equatorial line: cosSqAlpha=0 (§6)
            var C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
            lambdaP = lambda;
            lambda = L + (1 - C) * f * sinAlpha *
                      (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
        } while (Math.abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0);

        if (iterLimit == 0) return NaN  // formula failed to converge

        var uSq = cosSqAlpha * (a * a - b * b) / (b * b);
        var A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
        var B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
        var deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
                    B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
        var s = b * A * (sigma - deltaSigma);

        s = (Math.round(s) / 1000).toFixed(2); // round to 1mm precision
        return s;

    },
    toRad: function (deg) {
        return deg * Math.PI / 180;
    }
}
