// Google Analitics part -> initialization //
(function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
//ga('create', 'UA-112186487-1', 'auto');//DM token= UA-112186487-1 cahange ga token as required 
ga('create', 'UA-112186487-1', {
    cookieFlags: 'max-age=7200;secure;samesite=None'
});
ga('send', 'pageview');

function sendEventToGoogleAnalytics(eventcategoryname, eventactionname, eventlabel) {
    ga('send', { 'hitType': 'event', 'eventCategory': eventcategoryname, 'eventAction': eventactionname, 'eventLabel': eventlabel });
}
//--------------------------------------------

//Qibla compass part starts ********************
var img = null,
    needle = null,
    ctx = null,
    degrees = 0;
var canvas = null;
var maxNeedleAngle = null;
var timeInterval = null;

//detects device sreen type
function detectScreenType() {
    global.DeviceScreenType = "PC";
    if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) ||
        navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) ||
        navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i)) {
        global.DeviceScreenType = "Mobile";
    }

    if (navigator.userAgent.match(/Android/i)) {
        if (!navigator.userAgent.match(/Mobile/i)) {
            global.DeviceScreenType = "AndroidTablet";
        }
        global.DeviceScreenType = "Android";

    }
    if (navigator.userAgent.match(/ipad/i)) {
        global.DeviceScreenType = "Ipad";
    }
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
        global.DeviceScreenType = "Iphone";
    }


}

function reloadHappinessMeter() {
    //document.getElementById("IFrameHappiness").src = "https://portal.dm.gov.ae/HappinessMeterDMClient/HappinessProccessor?type=2&lang=en&appId=Makani";
    sendEventToGoogleAnalytics("Happiness Meter", "Happiness Meter Click", "English");
    ////document.getElementById("IFrameHappiness").contentWindow.location.reload(); 

    var windowSize = {
        width: 500,
        height: 500,
    };

    var windowLocation = {
        left: (window.screen.availLeft + (window.screen.availWidth / 2)) - (windowSize.width / 2),
        top: (window.screen.availTop + (window.screen.availHeight / 2)) - (windowSize.height / 2)
    };
    var params = 'scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,width=' + windowSize.width + ',height=' + windowSize.height + ',,left=' + windowLocation.left + ',top=' + windowLocation.top + '';
    window.open("https://portal.dm.gov.ae/HappinessMeterDMClient/HappinessProccessor?type=2&lang=en&appId=Makani", "hapinessmeterWindowName", params);

}
//gets current browser location & set angle to qibla compass pointer
function setQiblaCompass() {
    //reset degrees to zero if you need rotation on each call  event else delete reset zeroi in lubna implementation.
    degrees = 0;
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, null, {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        });
    } else {
        //set to default location if can't read current location
        setAngleToCompassPointer(0, 0);
    }
}
function showPosition(position) {
    setAngleToCompassPointer(position.coords.latitude, position.coords.longitude);
    if (typeof vm !== 'undefined') {
        vm.compassAvailable = true;
    }

}
function setAngleToCompassPointer(currentlatitude, currentlongitude) {
    //set DM location, if current location is null
    if (!currentlatitude && !currentlongitude) {
        currentlatitude = 25.26452971;
        currentlongitude = 55.31196410;
    }
    //p1 is current deivce location
    var p1 = {
        x: currentlatitude,
        y: currentlongitude
    };

    //p2 for saudi qibla static location  
    var p2 = {
        x: 19.9211423,
        y: 40.4489672
    };
    global.currentDevicelatitude = currentlatitude;
    global.currentDeviceLongitude = currentlongitude;
    // angle in radians
    // var angleRadians = Math.atan2(p2.y - p1.y, p2.x - p1.x);

    // angle in degrees
    var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;
    maxNeedleAngle = (angleDeg + 360) % 360;
    initQiblaCompass();

    if (global.currentDevicelatitude && global.currentDeviceLongitude) {
        vm.routingsearch_model0 = "Your Location";
        //vm.SetRoutingLatLongData('routingsearch_model0', [global.currentDeviceLongitude, global.currentDevicelatitude]);
        vm['routingsearch_model0_latlong_data'] = 'current';

        //addDraggableMarker("", global.currentDevicelatitude, global.currentDeviceLongitude, true, true);
        addDraggableMarker("", global.currentDevicelatitude, global.currentDeviceLongitude, false, true, false);

        if (!getParameterByName("m") && !getParameterByName("sn")) {
            map.setCenter({ lat: global.currentDevicelatitude, lng: global.currentDeviceLongitude });
            if (global.DeviceScreenType === "PC")
                map.setZoom(global.pcZoom);
            else
                map.setZoom(global.mobileZoom);
        }
    }
}

function ResizeDetailDIvWidth() {
    AvailableScreenWidth = window.innerWidth;
    if (AvailableScreenWidth <= 500) {
        setTimeout(function () {
            document.getElementById("SearchDetailCard").style.width = AvailableScreenWidth + 'px';
        }, 200);

    }
}
function ResizeRoutingDIvWidth() {
    AvailableScreenWidth = window.innerWidth;
    if (AvailableScreenWidth <= 500) {
        setTimeout(function () {
            document.getElementById("RoutingDiv").style.width = AvailableScreenWidth + 'px';
        }, 200);

    }
}
function initQiblaCompass() {
    // Grab the compass element
    canvas = document.getElementById('compass');

    // Canvas supported?
    if (canvas.getContext('2d')) {
        ctx = canvas.getContext('2d');

        // Load the needle image
        needle = new Image();
        needle.src = global.hostAddress + '/Images/needle.png'; //set compass needle image path here

        // Load the compass image
        img = new Image();
        img.src = global.hostAddress + '/Images/compass.png';  //set compass image path here
        img.onload = imgLoaded();
    }
    else {
        alert("Canvas not supported!");
    }
}

function imgLoaded() {

    timeInterval = setInterval(drawCompass, 80);
}
function drawCompass() {
    //  Rotate around this point
    if (degrees <= (maxNeedleAngle + 15)) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // Draw the compass onto the canvas
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        // Save the current drawing state
        ctx.save();

        // Now move across and down half the
        //  ctx.translate(canvas.width/2, canvas.height/2.3);       
        ctx.translate(canvas.width / 2, canvas.height / 2.3);
        ctx.rotate(degrees * (Math.PI / 180));
        ctx.translate(-(canvas.width / 2), -(canvas.height / 2.3));
        // Draw the image back and up
        ctx.drawImage(needle, 0, 0, canvas.width, canvas.height);

        // Restore the previous drawing state
        ctx.restore();
        // Increment the angle of the needle by 5 degrees
        degrees += 15;

    } else {
        clearInterval(timeInterval);
    }
}

//Quibla direction ends

//48.8733641244471,= 2.294754032045603;
//Street level functionalities
function getStreetLevelPreview(targetContainerId, latitude, longitude) {
    var streetPrvwHolder = document.createElement("div");
    streetPrvwHolder.id = "_StreetPrvwHolder";

    //var targetContainer = document.getElementById(targetContainerId);
    var targetContainer = targetContainerId;
    if (targetContainer.hasChildNodes()) {

        targetContainer.removeChild(targetContainer.lastChild);
    }

    targetContainer.appendChild(streetPrvwHolder);

    var maptypes = platform.createDefaultLayers();
    platform.configure(H.map.render.panorama.RenderEngine);
    platform.configure(H.map.render.panorama.RenderEngine);

    var streetMap = new mapsjs.Map(streetPrvwHolder, maptypes.normal.map,
        {
            center: { lat: latitude, lng: longitude },
            zoom: 19,
            engineType: H.Map.EngineType.PANORAMA
        });


}
//street level full view 
function getStreetLevelView(targetContainerId, latitude, longitude) {

    var streetPrvwHolder = document.createElement("div");
    streetPrvwHolder.id = "_StreetViewHolder";

    var targetContainer = document.getElementById(targetContainerId);
    if (targetContainer.contains(document.getElementById("_StreetViewHolder"))) {
        targetContainer.getElementById("_StreetViewHolder").remove();
        //streetPrvwHolder.remove();
    }
    targetContainer.appendChild(streetPrvwHolder);


    var maptypes = platform.createDefaultLayers();
    platform.configure(H.map.render.panorama.RenderEngine);
    var streetMap = new mapsjs.Map(document.getElementById("_StreetViewHolder"), maptypes.normal.map,
        {
            center: { lat: latitude, lng: longitude },
            zoom: 19,
            engineType: H.Map.EngineType.PANORAMA
        });

    H.map.render.panorama.RenderEngine.getClosestPanoramas(
        { lat: latitude, lng: latitude }, function (panoramaData) {
            if (panoramaData.length) {

                // Set map center to the location of the first available panorama:
                streetMap.setCenter(panoramaData[0].position);

                // Switch to to the panorama engine to show the panorama:
                streetMap.setEngineType(H.Map.EngineType.PANORAMA);
            }
        });

    var StreetMapEvents = new H.mapevents.MapEvents(streetMap);
    var StreetMapbehavior = new H.mapevents.Behavior(StreetMapEvents);
}
