﻿// use togelLinks data as global for all WLs
var togelLinks = {
	"HK 4D": 'http://www.hk45pools.com',
    "HK TOTO": 'http://www.hk45pools.com',
    "HONGKONG": 'http://www.hk45pools.com',
    "SINGAPURA": 'https://www.singaporepools.com.sg',
    "SINGAPORE": 'https://www.singaporepools.com.sg',
    "JAPAN": 'http://www.japan4d.com',
    "TAIPEI": 'http://www.taipeipools.com',
    "MACAU": 'http://www.macau-lottery.com',
    "CAMBODIA": 'http://www.gdclottery.com'
}

function validateIPAddress(ipAddress) {
    return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipAddress)
}
function isValidLocalHost(host) {
    return (validateIPAddress(host) || host === 'localhost')
}
function popUpRegister(refCode) {
    window["isCheckedUserName"] = false;
    var location = window.location
    var url = location.origin
    var registerPage = "_View/Register.aspx"
    if (isValidLocalHost(location.host)) {
        url = getLocalHomeUrl()
        registerPage = refCode !== '' ? registerPage + '?ref=' : registerPage
    }
    else
        registerPage = refCode !== '' ? '/' + registerPage + '?ref=' : '/' + registerPage

    var registerWindow = window.open(url + registerPage + refCode, 'Register', 'width=645,height=700,toolbars=no,scrollbars=no,status=no,resizable=no');
    registerWindow.onbeforeunload = function () {
        //if (window["isCheckedUserName"]) {
        //    window.location.reload(true);
        //}
        //window.location.reload(true);
        var imgCaptcha = $('img[src*="public/img.aspx"]').eq(0)
        var src = imgCaptcha.attr('src')
        imgCaptcha.attr('src', src + "?r=" + new Date().getTime())
		if (imgCaptcha.length === 0)
			window.location.reload(true);
    }
    
}
function popupRegister(refCode, width = 645, height = 700) {
    window["isCheckedUserName"] = false;
    var location = window.location
    var url = location.origin
    var registerPage = "_View/Register.aspx"
    if (isValidLocalHost(location.host)) {
        url = getLocalHomeUrl()
        registerPage = refCode !== '' ? registerPage + '?ref=' : registerPage
    }
    else
        registerPage = refCode !== '' ? '/' + registerPage + '?ref=' : '/' + registerPage

    var registerWindow = window.open(url + registerPage + refCode, 'Register', `width=${width},height=${height},toolbars=no,scrollbars=no,status=no,resizable=no`);
    registerWindow.onbeforeunload = function () {
        //if (window["isCheckedUserName"]) {
        //    window.location.reload(true);
        //}
        //window.location.reload(true);
        var imgCaptcha = $('img[src*="public/img.aspx"]').eq(0)
        var src = imgCaptcha.attr('src')
        imgCaptcha.attr('src', src + "?r=" + new Date().getTime())
        if (imgCaptcha.length === 0)
            window.location.reload(true);
    }
}
function popUpNawala(url, w, h) {
    var location = window.location;
    var httpUrl = location.origin;
    if (url.indexOf('http') > -1)
        httpUrl = url
    else if (location.host == 'localhost')
        httpUrl = getLocalHomeUrl() + url
    else
        httpUrl += '/' + url
    window.open(httpUrl, 'Nawala Unblocker', 'width=' + w + ',height=' + h + ',toolbars=no,scrollbars=no,status=no,resizable=no');
}
function openMail() {
    var location = window.location;
    var mailPage = 'Public/Mail.aspx'
    var mailUrl = location.origin
    if (isValidLocalHost(location.host))
        mailUrl = getLocalHomeUrl() + mailPage
    else
        mailUrl += '/' + mailPage
    window.open(mailUrl, 'Mail Box', 'width=630,height=480,top=50,left=100,directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no');
}
function openLiveChat(url, w, h) {
    window.open(url, 'LiveChat', 'width=' + w + ',height=' + h + ',toolbars=no,scrollbars=no,status=no,resizable=no');
}
function popUpPromo(url, w, h) {
    var location = window.location;
    var httpUrl = location.origin;
    if (url.indexOf('http') > -1)
        httpUrl = url
    else if (location.host == 'localhost')
        httpUrl = getLocalHomeUrl() + url
    else
        httpUrl += '/' + url
    window.open(httpUrl, 'Promotion', 'width=' + w + ',height=' + h + ',toolbars=no,scrollbars=no,status=no,resizable=no');
}
function popupPromo(url, w, h) {
    var location = window.location;
    var httpUrl = location.origin;
    if (url.indexOf('http') > -1)
        httpUrl = url
    else if (location.host == 'localhost')
        httpUrl = getLocalHomeUrl() + url
    else
        httpUrl += '/' + url
    window.open(httpUrl, 'Promotion', 'width=' + w + ',height=' + h + ',toolbars=no,scrollbars=no,status=no,resizable=no');
}
function popupWindow(url, title, w, h) {
    var location = window.location;
    var httpUrl = location.origin;
    if (url.indexOf('http') > -1)
        httpUrl = url
    else if (location.host == 'localhost')
        httpUrl = getLocalHomeUrl() + url
    else
        httpUrl += '/' + url
    window.open(httpUrl, title, 'width=' + w + ',height=' + h + ',toolbars=no,scrollbars=no,status=no,resizable=no');
}

function changeBox(vLayout) {
    if (!vLayout) {
        document.getElementById('div1').style.display = 'none';
        document.getElementById('div2').style.display = '';
        document.getElementById('txtPassword').focus();
    }
    else {
        if(document.getElementById('Text1'))
            document.getElementById('Text1').style.display = 'none';

        if (document.getElementById('txtPasswordLabel'))
            document.getElementById('txtPasswordLabel').style.display = 'none';

        document.getElementById('txtPassword').style.display = '';
        document.getElementById('txtPassword').focus();
    }
}
function restoreBox(vLayout) {
    if (!vLayout) {
        if (document.getElementById('txtPassword').value == '') {
            document.getElementById('div1').style.display = '';
            document.getElementById('div2').style.display = 'none';
        }
    }
    else {
        if (document.getElementById('txtPassword').value == '') {
            if (document.getElementById('Text1'))
                document.getElementById('Text1').style.display = '';

            if (document.getElementById('txtPasswordLabel'))
                document.getElementById('txtPasswordLabel').style.display = '';

            document.getElementById('txtPassword').style.display = 'none';
        }
    }
}
function clearText(field) {
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}
function getLocalHomeUrl() {
    var localHomeUrl = window.location.href;
    //if (localHomeUrl.indexOf('Header') >= 0)
    //    localHomeUrl = localHomeUrl.split('Header')[0]
    return localHomeUrl.substr(0, localHomeUrl.lastIndexOf('/') + 1)
}
function getUrl() {
    return (isValidLocalHost(window.location.host) ? getLocalHomeUrl() : window.location.origin + '/') + 'pgajax.axd';
}

function fetchTogel(callback) {
    $.ajax({
        url: getUrl(),
        type: 'GET',
        data: { T: 'GetHasilTogel' },
        success: function (responseText) {
            try {
                var records = JSON.parse(responseText);
                callback(records)
            }
            catch (e) {
                callback(e)
            }
        }
    });
}
function fetchSlideImages(folderPath, callback) {
    $.ajax({
        url: location.href + '/pgajax.axd',
        type: 'GET',
        data: { T: 'GetSlideImages', folderPath: folderPath },
        success: function (responseText) {
            try {
                var records = JSON.parse(responseText);
                callback(records)
            }
            catch (e) {
                console.log(e)
                callback(e)
            }
        }
    });
}
function initMarquee(color, fontName) {
    setTimeout(function () {
        var location = window.location;
        var href = location.origin + '/'
        if (isValidLocalHost(location.host))
            href = getLocalHomeUrl()
        if (color == '' || color == undefined || color == null)
            color = '#fff'
        if (fontName == '' || fontName == undefined || fontName == null)
            fontName = 'euphemia'
        var message = document.getElementById('text-marquee').value.replace(/\n|\t/g, ' ')
        document.getElementById('div-marquee').innerHTML =
            '<marquee onmouseout="scrollDelay=1" onmouseover="scrollDelay=10000" scrolldelay="1" scrollamount="4"> <a class="Message" href="'
            + href + '_view/msglog.aspx" target="_blank" style="color:'
            + color + '; font-family:' + fontName + '; text-decoration:none">'
            + unescape(message) + '</a></marquee>';
    }, 1000)
}

function refreshCapcha(type, idCapchaImage) {
    switch (type) {
        case 'text':
            // todo 
            // send a ajax request to server gen new capcha code then assign to session
            break;
        case 'image':
            capchaImage = $('#' + idCapchaImage)
            capchaImage.attr('src', 'public/img.aspx?r=' + new Date().getTime())
            break;
    }
}
function getMailInfo() {
    $('#tdMail').html('<img width="15px" height="15px" src="Images/spinner.gif" />');
    $.ajax({
        url: 'pgajax.axd',    
        type: 'GET',
        data: { T: 'GetMail' },
        success: function (responseText) {
            var res = JSON.parse(responseText);
            var success = res.success;
            if (success) {
                $('#tdMail').html(decodeURIComponent(res.text));
            } else {
                $('#tdMail').html(`<a title="${res.text}" style="cursor:pointer">Mail (<span style="color:red !important;">Error</span>)</a>`);
            }
        }
    })
}

function convertDateTime(dateTimeStringISO8601) {
    const dateTime = new Date(dateTimeStringISO8601);

    const day = dateTime.getDate().toString().padStart(2, '0');
    const month = (dateTime.getMonth() + 1).toString().padStart(2, '0');
    const year = dateTime.getFullYear();
    const hour = dateTime.getHours().toString().padStart(2, '0');
    const minute = dateTime.getMinutes().toString().padStart(2, '0');
    const timeZoneOffset = -dateTime.getTimezoneOffset() / 60; // Switch sign
    const timeZoneOffsetString = timeZoneOffset >= 0 ? `+${timeZoneOffset}` : timeZoneOffset.toString();

    const formattedDateTime = `${day}/${month}/${year} ${hour}:${minute} GMT${timeZoneOffsetString}`;

    return formattedDateTime;
}
function fetchServerTime(gmtNumber, htmlId) {
    // gtmNumber: GMT+7
    fetch('https://worldtimeapi.org/api/timezone/Etc/' + gmtNumber)
        .then(response => response.json())
        .then(data => {
            $(htmlId).html(convertDateTime(data.datetime));
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

///////////////////////////// Handle PLACE_HOLDER for LOGIN form /////////////////////////////
/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/
(function ($) {
    $.fn.hint = function (blurClass) {
        if (!blurClass) {
            blurClass = 'blur';
        }

        return this.each(function () {
            // get jQuery version of 'this'
            var $input = $(this),

                // capture the rest of the variable to allow for reuse
                title = $input.attr('title'),
                $form = $(this.form),
                $win = $(window);

            function remove() {
                if ($input.val() === title && $input.hasClass(blurClass)) {
                    $input.val('').removeClass(blurClass);
                }
            }

            // only apply logic if the element has the attribute
            if (title) {
                // on blur, set value to title attr if text is blank
                $input.blur(function () {
                    if (this.value === '') {
                        $input.val(title).addClass(blurClass);
                    }
                }).focus(remove).blur(); // now change all inputs to title

                // clear the pre-defined text when form is submitted
                $form.submit(remove);
                $win.unload(remove); // handles Firefox's autocomplete
            }
        });
    };
})(jQuery);

// User for account header after login
var DC_Event = {};
var CFG_DCRefresh = '5';
function DC_STAKE(event) {
    if (+CFG_DCRefresh === 0) return;

    DC_Event = JSON.parse(sessionStorage.getItem("DC_Event")) || DC_Event;
    if (Object.keys(DC_Event).length) {
        if (DC_Event.Type == "STK") {
            if (Date.now() - DC_Event.Date < +CFG_DCRefresh * 1000) {
                $("body", parent.window.frames["fraMain"].document).addClass("animationFade").one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function () {
                    $(this).removeClass("animationFade");
                });
                event.preventDefault();
                return;
            }
            $("body").addClass('')
        }
    }

    DC_Event = { 'Type': 'STK', 'Date': Date.now() };
    sessionStorage.setItem("DC_Event", JSON.stringify(DC_Event));
}

function DC_STT(event) {
    if (+CFG_DCRefresh === 0) return;

    DC_Event = JSON.parse(sessionStorage.getItem("DC_Event")) || DC_Event;
    if (Object.keys(DC_Event).length) {
        if (DC_Event.Type == "STT_TW") {
            if (Date.now() - DC_Event.Date < +CFG_DCRefresh * 1000) {
                $("body", parent.window.frames["fraMain"].document).addClass("animationFade").one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function () {
                    $(this).removeClass("animationFade");
                });
                event.preventDefault();
                return;
            }
        }
    }

    DC_Event = { 'Type': 'STT_TW', 'Date': Date.now() };
    sessionStorage.setItem("DC_Event", JSON.stringify(DC_Event));
}

var isHeaderPage = () => window.location.pathname.split("/").pop().indexOf('Header.aspx') > -1;
$(function () {
    if (isHeaderPage()) {
        $('body').css('overflow', 'hidden')

        $('a[href="_norm/stake.aspx"').click(function (event) {
            DC_STAKE(event.originalEvent)
        })
        $('a[href="_norm/AccHistory.aspx"').click(function (event) {
            DC_STT(event.originalEvent)
        })
    }
    // find all the input elements with title attributes
    try {
        $('input[title!=""]').hint();
    } catch (err) {
        console.log(err)
    }
    
});