/* Minification failed. Returning unminified contents.
(846,70-71): run-time error JS1014: Invalid character: `
(846,71-76): run-time error JS1306: Invalid numeric literal: 500px
(846,76-77): run-time error JS1014: Invalid character: `
 */
////////////////////////////////////////////////////////////////////////////////
// JScript File
// NOTE!  This MUST NOT hold any JQuery related functions as they will fail.  Use the master_jq.js file for those functions.


////////////////////////////////////////////////////////////////////////////////
function ShowPolicy() {
    var url = '/popups/PrivacyPolicy.aspx';
    var oWnd = radopen(url, null);
    oWnd.setSize(700, 600);
}

function rwOpen(CloseMethod, URL, UniqueID, Title, SizeID, IsModal) {
    
	// Declare rad window object
	var oWnd = window.radopen(URL, UniqueID);

	// If Title parameter is not null, set a window title
	if (Title != null) {
		oWnd.set_title(Title);
	}

	// We will have few predefined sizes, SizeID = 1,2,3,4....etc....??
	if (SizeID != null) {

		// Default SizeID = 1
		var oWnd_W = 960;
		var oWnd_H = 540;

		if (SizeID == 2) {
			oWnd_W = 640;
			oWnd_H = 360;
		}

		if (SizeID == 3) {
			oWnd_W = 800;
			oWnd_H = 600;
		}

		// ... Add more sizes if needed ...

		oWnd.set_height(oWnd_H);
		oWnd.set_width(oWnd_W);
	}

	// If IsModal is sent to this routine, make popup window modal
	if (IsModal != null) {
		oWnd.set_modal(IsModal);
	}

	if (CloseMethod != null) {
		// Close Method handling
		if (CloseMethod == "refresh") {
			// If null, simply use parent.window.refresh()
			oWnd.add_close(rwCloseRefresh);
		}
		else {

			// Otherwise call custom javascript close method. 
			// Note that we should pass method name as object, without quotes around its name
			oWnd.add_close(CloseMethod);

			// To get circle closed on the parent page create a server side button ID="btn_Refresh"
			// Then put this line the CloseMethod client funtion: 
			// __doPostBack('<%=btn_Refresh.UniqueID%>', '');
			// Then in btn_Refresh_Click serverside event, add code for page refreshing
		}
	}
}

// Refresh parent window which has instantiated RadWindow
function rwCloseRefresh(oWnd, args) {
	oWnd.get_browserWindow().Refresh();
}

////////////////////////////////////////////////////////////////////////////////
// Rad Windows Popup loading functions
// used for opening rad window popup using default size and loading animation

var flagLoadingFinished = false;

// Pre cache image loading and make available for the page
var imgLoading = new Image();
imgLoading.id = "imgLoading";
imgLoading.src = "/assets/images/loading_popup.gif";


function closeDefaultRadWindow(WndName) {

    var manager = GetRadWindowManager();

    var oWnd = manager.getWindowByName(WndName);

    oWnd.close();

}

function openDefaultRadWindow(url, WndName, WndWidth, WndHeight, WndTitle) {

    var _wndWidth = 900;
    var _wndHeight = 700;

    if (WndWidth != undefined) _wndWidth = WndWidth;
    if (WndHeight != undefined) _wndHeight = WndHeight;

    flagLoadingFinished = false;

    var manager = GetRadWindowManager();

    var oWnd = manager.getWindowByName(WndName);

    if (oWnd == null) {
        //console.log('RadWindow \'' + WndName + '\' not found.');
        //return;
        var oWnd = radopen(url, WndName);
        if (WndTitle != undefined) {
            oWnd.set_title(WndTitle);
        }

        oWnd.set_centerIfModal(true);

        oWnd.setSize(_wndWidth, _wndHeight);

        oWnd.add_show(radWindowOnClientShow);
        oWnd.add_pageLoad(radWindowOnClientPageLoad);
        oWnd.add_close(radWindowOnClientClose);
        oWnd.add_resize(radWindowOnClientResize);
        oWnd.add_resizeStart(radWindowOnClientResize);
        oWnd.add_resizeEnd(radWindowOnClientResize);
        oWnd.set_minHeight(200);
        oWnd.set_minWidth(200);
    }
    else {
        if (WndTitle != undefined) {
            oWnd.set_title(WndTitle);
        }

        oWnd.set_centerIfModal(true);

        oWnd.setSize(_wndWidth, _wndHeight);

        oWnd.add_show(radWindowOnClientShow);
        oWnd.add_pageLoad(radWindowOnClientPageLoad);
        oWnd.add_close(radWindowOnClientClose);
        oWnd.add_resize(radWindowOnClientResize);
        oWnd.add_resizeStart(radWindowOnClientResize);
        oWnd.add_resizeEnd(radWindowOnClientResize);
        oWnd.set_minHeight(200);
        oWnd.set_minWidth(200);

        manager.open(url, WndName);
    }

}

function setImgPosition(sender, args) {

    contentCell = sender._contentCell;

    if (contentCell && imgLoading) {

        var xPos = (($(contentCell).width() + 15) / 2) - 50;
        var yPos = ((($(contentCell).height() + 55) / 2)) - 50;

        $(imgLoading).css('left', xPos);
        $(imgLoading).css('top', yPos);

    }

}

function radWindowOnClientResize(sender, args) {

    setImgPosition(sender, args);

}


function radWindowOnClientClose(sender, args) {

    sender.remove_close(radWindowOnClientClose);
    sender.setUrl("about:blank");

}

function radWindowOnClientPageLoad(sender, args) {

    sender.remove_resize(radWindowOnClientResize);
    sender.remove_resizeStart(radWindowOnClientResize);
    sender.remove_resizeEnd(radWindowOnClientResize);
    sender.remove_pageLoad(radWindowOnClientPageLoad);

    flagLoadingFinished = true;

    if (!imgLoading) return;

    $(imgLoading).css('display', 'none');
}

function radWindowOnClientShow(sender, args) {

    sender.center();
    sender.remove_show(radWindowOnClientShow);

    $objFrame = $("[name='" + sender.get_name() + "']");

    $objFrame.css('background-color', '#fdfdfd')

    if (flagLoadingFinished && $objFrame[0].src != 'about:blank') return;

    $(imgLoading).css('position', 'absolute');

    contentCell = sender._contentCell;

    if (contentCell && imgLoading) {

        contentCell.appendChild(imgLoading);

        $(imgLoading).css('display', '');

        setImgPosition(sender, args);

    }

}

////////////////////////////////////////////////////////////////////////////////
// JScript File
function addToPageLoadEvent(func) {
	var oldPageLoad = window.pageLoad;
	if (typeof window.pageLoad != 'function') {
		window.pageLoad = func;
	}
	else {
		window.pageLoad = function () {
			if (oldPageLoad) {
				oldPageLoad();
			}
			func();
		}
	}
}



var SSLFormAction = "";
function SecurePostback(ButtonID) {
	theForm.action = SSLFormAction;
	__doPostBack(ButtonID, '');
}

function NormalPostback(ButtonID) {
	__doPostBack(ButtonID, '');
}


////////////////////////////////////////////////////////////////////////////////
// UTILS

//Changes background color of the element passed as obj argument
function bgCC(obj, color) { //v1.1 by Project VII
	var b;
	if (!obj.style) {
		obj = findObj(obj);
	}
	b = (document.layers) ? obj : obj.style;
	b.backgroundColor = color
}

//Changes css class
function cCSS(obj, cssClass) { //v1.1 by Project VII
	if (!obj.className) {
		obj = findObj(obj);
	}
	obj.className = cssClass;
}

//Locates an object within a page, based on it's ID
function findObj(n, d) {
	var p, i, x;
	if (!d) d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0, p);
	}
	if (!(x = d[n]) && d.all) x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++) x = findObj(n, d.layers[i].document);
	if (!x && d.getElementById) x = d.getElementById(n);
	return x;
}

//Gets position of an element from the left
function DL_GetElementLeft(eElement) {
	var nLeftPos = eElement.offsetLeft; // initialize var to store calculations
	var eParElement = eElement.offsetParent; // identify first offset parent element
	while (eParElement != null) { // move up through element hierarchy
		nLeftPos += eParElement.offsetLeft; // appending left offset of each parent
		eParElement = eParElement.offsetParent; // until no more offset parents exist
	}
	return nLeftPos; // return the number calculated
}

//Gets position of an element from the top
function DL_GetElementTop(eElement) {
	var nTopPos = eElement.offsetTop; // initialize var to store calculations
	var eParElement = eElement.offsetParent; // identify first offset parent element
	while (eParElement != null) { // move up through element hierarchy
		nTopPos += eParElement.offsetTop; // appending top offset of each parent
		eParElement = eParElement.offsetParent; // until no more offset parents exist
	}
	return nTopPos; // return the number calculated
}

//Makes elemenent visible
function MakeVisible(elemID) {
	var g, b;
	if ((g = findObj(elemID)) != null) {
		b = (document.layers) ? g : g.style;
		b.visibility = "visible";
	}
}

//Makes elemenent invisible
function MakeInvisible(elemID) {
	var g, b;
	if ((g = findObj(elemID)) != null) {
		b = (document.layers) ? g : g.style;
		b.visibility = "hidden";
	}
}

function SetStyle(elemID, Attribute, Value) {
	var g, b;
	if ((g = findObj(elemID)) != null) {
		b = (document.layers) ? g : g.style;
		eval("b." + Attribute + "='" + Value + "'");
	}
}
function GetWinWidth() {
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return myWidth;
}
function GetWinHeight() {
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}

function DisableSubmitBtn(obj) {
	obj.disabled = true;
	obj.value = 'Processing...';
	obj.className = "FormButtonSubmitted";
	return true;
}
function DisableButton(obj) {
    obj.value = 'Processing...';
    obj.onclick = 'return false;';
}

function ToggleVisible(elemID, sender) {
	var g, b;
	if ((g = findObj(elemID)) != null) {
		b = (document.layers) ? g : g.style;
		if (b.display == "inline") {
			b.display = "none";
			sender.innerHTML = "show";
		}
		else {
			b.display = "inline";
			sender.innerHTML = "hide";
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// FLYOUT

// sfHover = function () {
// var sfEls = document.getElementById("navMain").getElementsByTagName("LI");
// for (var i = 0; i < sfEls.length; i++) {
// sfEls[i].onmouseover = function () {
// this.className += " sfhover";
// }
// sfEls[i].onmouseout = function () {
// this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
// }
// }
// }
// if (window.attachEvent) window.attachEvent("onload", sfHover);

//===============

//Locates an object within a page, based on it's ID
function findObj(n, d) {
	var p, i, x;
	if (!d) d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0, p);
	}
	if (!(x = d[n]) && d.all) x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++) x = findObj(n, d.layers[i].document);
	if (!x && d.getElementById) x = d.getElementById(n);
	return x;
}

//=========================

//Preloads an array of immages passed trough (usualy hover images)
function preloadImages() { //v3.0
	var d = document; if (d.images) {
		if (!d.MM_p) d.MM_p = new Array();
		var i, j = d.MM_p.length, a = preloadImages.arguments; for (i = 0; i < a.length; i++)
			if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
	}
}

//Restores an image that was changed on mouse over
function swapImgRestore() { //v3.0
	var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

//Changes an image on mouse over
function swapImage() { //v3.0
	var i, j = 0, x, a = swapImage.arguments;
	document.MM_sr = new Array;
	for (i = 0; i < (a.length - 2); i += 3)
		if ((x = findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

// Util function for whatever use
function SetStyle(elemID, Attribute, Value) {
	var g, b;
	if ((g = findObj(elemID)) != null) {
		b = (document.layers) ? g : g.style;
		eval("b." + Attribute + "='" + Value + "'");
	}
}

externalLinks();

function externalLinks() {
	if (!document.getElementsByTagName) {
		return;
	}

	var anchors = document.getElementsByTagName("a");
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		var relvalue = anchor.getAttribute("rel");

		if (anchor.getAttribute("href")) {
			var external = /external/;
			var relvalue = anchor.getAttribute("rel");
			if (external.test(relvalue)) {
				anchor.target = "_blank";
			}
		}
	}
}

window.onload = externalLinks;


////////////////////////////////////////////////////////////////////////////////
// TEXT FUNCTIONS

function textCounter(field, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
		alert('Your input text was too long and has been trimmed!');
	}
}

function TelerikEditor_OnClientLoad(editor, args) {
	//handles the right button click context menu appearing in firefox
	var toolAdapter = editor.get_toolAdapter();
	toolAdapter.isIE = false;

	//set the focus in the editor
	var editorObject = editor;
	setTimeout(function () {
		editorObject.setFocus();
	}, 10);
}

// limit number of words in the textbox
function LimitWordCount(textboxID, labelID, max) {
	if (document.getElementById(textboxID).value != '') {
		var split_words = document.getElementById(textboxID).value.split(' ');
		if (split_words.length > max) {
			var remain = '';
			for (var i = 0; i < max; i = i + 1) {
				if (split_words[i] != null) {
					if (i != max - 1)
						remain = remain + split_words[i] + ' ';
					else
						remain = remain + split_words[i];
				}
			}
			document.getElementById(textboxID).value = remain;
			alert('Your input text was too long and has been trimmed! Only ' + max + ' words allowed');
		}

		document.getElementById(labelID).innerHTML = document.getElementById(textboxID).value.split(' ').length;
	}
	else {
		document.getElementById(labelID).innerHTML = "0";
	}
}
// limit number of characters in the textbox
function LimitCharacterCount(textboxID, labelID, max) {
	if (document.getElementById(textboxID).value != '') {
		if (document.getElementById(textboxID).value.length > max) {
			document.getElementById(textboxID).value = document.getElementById(textboxID).value.substring(0, max);
			alert('Your input text was too long and has been trimmed! Only ' + max + ' characters allowed');
		}
		document.getElementById(labelID).innerHTML = document.getElementById(textboxID).value.length;
	}
	else {
		document.getElementById(labelID).innerHTML = "0";
	}
}


////////////////////////////////////////////////////////////////////////////////
// AJAX

function imagePopup(url) {
	if (typeof (url) != "object") {
		window.golarge = window.open("", "", "scrollbars=no,toolbar=no,menubar=no,screenX=30,screenY=30,left=30,top=30,height=400,width=420");
		window.golarge.document.open();
		window.golarge.document.writeln('<html>');
		window.golarge.document.writeln('<head>');
		window.golarge.document.writeln('<title></title>');
		window.golarge.document.writeln('</head>');
		window.golarge.document.write('<body>\n');
		window.golarge.document.write('<table width="100%" >\n');
		window.golarge.document.write('<tr><td class="AlignCenter"><img src="' + url + '" onLoad="opener.imagePopup(this);" alt="image popup" /><br/><a href="javascript:window.close();"><img src="/assets/images/button_closewindow.gif" vspace="8" border="0"></a></td></tr></table>\n');
		window.golarge.document.write('</body>\n');
		window.golarge.document.write('</html>\n');
		window.golarge.document.close();
	}
	else {
		if (document.layers)
			window.golarge.resizeTo(url.width, url.height);
		else
			window.golarge.resizeTo(url.width + 60, url.height + 100);
	}
}

var TelerikButton;
function TelerikOnRequestStart(sender, args) {
	TelerikButton = $("[name='" + args.get_eventTarget() + "']");
	TelerikButton.attr("disabled", true)
	document.body.style.cursor = "wait";
}
function TelerikOnResponseEnd(sender, args) {
	document.body.style.cursor = "default";
	TelerikButton.attr("disabled", false)
}

//////////////////////////////////////////////////////
// Initial and Load more functions in Image Gallery //
//////////////////////////////////////////////////////
var listurl = ''; // the ajax url been called

// Load initial item lists into Div with ID = ItemList
function LoadListInit(url, callback) {
	listurl = url;
	$('#ItemList').load(listurl, function () { callback(); });
}

// When click the button listmore, Load list content html into cache div with ID = LoadingCache.
function LoadListMore(callback) {
	size_li = $('#ItemList article').size();
	$('#LoadingCache').load(listurl + '&idx=' + size_li, function () { MoveCacheItemsToOutputContainer(); callback(); });
}

// Move cache content html into ItemList div.
function MoveCacheItemsToOutputContainer() {
	$('#ItemList').append($('#LoadingCache').html());
}

/* Cookie Handling */
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name, "", -1);
}


// Popup slider telerik window 
function OpenRadSliderWindow(url, width, height) {
	if (width == undefined) {
		width = 780;
	}
	if ($GlobalSetup.IsSliderPopupWindow) {
		var oWnd = radopen(url, "sliderwindow");
		oWnd.set_modal(true);
		// Add border less class for the popup telerik window
		oWnd._popupElement.className = oWnd._popupElement.className + " borderLessDialog";
		var $windowHeight = $(window).height();
		var $windowWidth = $(window).width();
		//oWnd.set_visibleTitlebar(false);
		oWnd.set_behaviors(Telerik.Web.UI.WindowBehaviors.Close);
		oWnd.setSize(20, $windowHeight);
		$('.borderLessDialog').css('left', $windowWidth - 20);
		$('.borderLessDialog').animate({ width: width, left: ($windowWidth - width) });
		return oWnd;
	}
	else {
		if (height == undefined) {
			height = $(window).height() - 100;
		}
		var oWnd = radopen(url, null);
		oWnd.setSize(width, height);
		oWnd.Center();
		return oWnd;
	}
}
;
// Modal popup class
// This is a Html5 and Css3 modal popup window, with injected javascript functions so that the popup window can be called by js with customized functions on the buttons OK and CANCEL.
/*
    e.g. 1 - customised popup window. can setup the popup text, buttons and return functions.
    var modalpopup = ModalPopup.createNew();        // required. create a new modal popup.
    modalpopup.IsShowButton_ModalCloser = false;    // optional. Top right close button. default is false
    modalpopup.IsShowButton_ModalBtnOK = true;      // optional. OK button. default is true
    modalpopup.IsShowButton_ModalBtnVIEW = false;   // optional. View button. default is false
    modalpopup.IsShowButton_ModalBtnCANCEL = true;  // optional. Cancel button. default is true
    modalpopup.Text_ModalBtnOK = 'OK';              // optional. Setup the text of the OK button.
    modalpopup.Text_ModalBtnVIEW = 'View Tildes';   // optional. Setup the text of the View button.
    modalpopup.Text_ModalBtnCANCEL = 'Cancel';      // optional. Setup the text of the Cancel button.
    modalpopup.setupText('ARE YOU SURE?', "Content text..."); // required. Setup the Subject and Content of the popup window.
    modalpopup.setupForm(ConfirmWS, null, null, null, ConfirmWSCancel, null);   // required, Setup the js function for each button. if no futher function, pass through null
    modalpopup.init();  // required
    modalpopup.open();  // optional. just a javascript way to open the modal popup

    e.g. 2 - popup a window. User need to click the OK button to run the following js function.
    ModalPopup.ModalPopupConfirmSimple(ActionConfirmed, null, 'Are you sure?', 'Click \'OK\' below to confirm your request.');
    function ActionConfirmed() {
        alert('Action confirmed.');
    }

    e.g. 3 - just popup a window, same as the js alert function
    ModalPopup.ModalPopupAlert("NOTE", "COMMING SOON.");

    e.g. 4 - show a loading popup window.
    ModalPopup.ModalLoadingGif('loading now...');

*/
var ModalPopup = {
    createNew: function () {

        // Initial the div
        if ($('#ModalPopup_Window').length && $('#ModalPopup_Window').length > 0) {
            // Top popup window template already exists
        }
        else {
            // The popup window template
            var MODALPOPUPWINDOWDIVHTML = '<a href="#ModalPopup_Window" class="ModalPopup_WindowLink"></a><div id="ModalPopup_Window" class="ModalPopup_ModalOuter">	<div><a href="#" title="Close Modal" class="ModalPopup_ModalCloser">X</a><h4 class="ModalPopup_ModalContentTitle"></h4><p class="ModalPopup_ModalContentHtml"></p><p style=" text-align:right;"><input type="button" id="ModalPopup_ModalBtnOK" class="FormButton ModalPopup_ModalBtnOK" value="OK" /> <input type="button" id="ModalPopup_ModalBtnVIEW" class="FormButton ModalPopup_ModalBtnVIEW" value="VIEW"/> <input type="button" id="ModalPopup_ModalBtnCANCEL" class="FormButton ModalPopup_ModalBtnCANCEL" value="Cancel"/></p></div></div>';
            $('body').append(MODALPOPUPWINDOWDIVHTML);
        }

        // initial the object
        var modalpopup = {};

        // The link text. Not be used in NG2
        modalpopup.OpenLink = '';
        // show or hide the x close button at top right of the modal window.
        modalpopup.IsShowButton_ModalCloser = false;
        // show or hide the OK button
        modalpopup.IsShowButton_ModalBtnOK = true;
        // show or hide the View button
        modalpopup.IsShowButton_ModalBtnVIEW = true;
        // show or hide the Cancel button
        modalpopup.IsShowButton_ModalBtnCANCEL = true;
        // OK Button text
        modalpopup.Text_ModalBtnOK = 'OK';
        // View Button text
        modalpopup.Text_ModalBtnVIEW = 'View Tildes';
        // Cancel Button text
        modalpopup.Text_ModalBtnCANCEL = 'Cancel';

        // setup the text content of the modal window
        // compulsory function
        modalpopup.setupText = function (ContentTitle, ContentHtml) {
            $('.ModalPopup_ModalContentTitle').html(ContentTitle);
            $('.ModalPopup_ModalContentHtml').html(ContentHtml);
        };

        // setup the function behide the buttons OK and Cancel.
        // compulsory function
        modalpopup.setupForm = function (BtnOKFunction, OKValue, BtnViewFunction, ViewValue, BtnCancelFunction, CancelValue) {
            // Check if there is already bind any click event, if yes, remove the previous click event.
            var objEvt = $._data($('#ModalPopup_ModalBtnOK')[0], 'events');
            if (objEvt && objEvt['click']) {
                $('#ModalPopup_ModalBtnOK').unbind();
            }
            
            var objEvt = $._data($('#ModalPopup_ModalBtnVIEW')[0], 'events');
            if (objEvt && objEvt['click']) {
                $('#ModalPopup_ModalBtnVIEW').unbind();
            }

            var objEvt = $._data($('#ModalPopup_ModalBtnCANCEL')[0], 'events');
            if (objEvt && objEvt['click']) {
                $('#ModalPopup_ModalBtnCANCEL').unbind();
            }

            // Bind click and keypress events
            $('#ModalPopup_ModalBtnOK').click(function () {
                modalpopup.close();
                if (typeof (BtnOKFunction) == 'function') {
                    BtnOKFunction(OKValue);
                }
            });
            $('#ModalPopup_ModalBtnVIEW').click(function () {
                modalpopup.close();
                if (typeof (BtnViewFunction) == 'function') {
                    BtnViewFunction(ViewValue);
                }
            });
            $('#ModalPopup_ModalBtnCANCEL').click(function () {
                modalpopup.close();
                if (typeof (BtnCancelFunction) == 'function') {
                    BtnCancelFunction(CancelValue);
                }
            });

        };

        // mouse leave the document
        modalpopup.leaveelement = function () {
            $(document).trigger('mouseleave');
        };

        // open the window
        modalpopup.open = function () {
            $('.ModalPopup_ModalOuter').css("opacity", "1");
            $('.ModalPopup_ModalOuter').css("display", "block");
        };

        // close the window
        modalpopup.close = function () {
            $('.ModalPopup_ModalOuter').css("opacity", "0");
            $('.ModalPopup_ModalOuter').css("display", "none");
            // Check if function exists
            if ($.isFunction($.fn.jqDestroy)) {
                $('.ModalPopup_ModalOuter').jqDestroy();
            }
        };

        // initial the modal
        // compulsory function
        modalpopup.init = function () {
            // Initial all buttons
            $('.ModalPopup_ModalCloser').click(function () {
                modalpopup.close();
            });
            if (modalpopup.OpenLink.length > 0) {
                $('.ModalPopup_WindowLink').show();
                $('.ModalPopup_WindowLink').html(modalpopup.OpenLink);
            }
            else {
                $('.ModalPopup_WindowLink').hide();
                $('.ModalPopup_WindowLink').html(modalpopup.OpenLink);
            }
            if (modalpopup.IsShowButton_ModalCloser) {
                $('.ModalPopup_ModalCloser').show();
            }
            else {
                $('.ModalPopup_ModalCloser').hide();
            }
            if (modalpopup.IsShowButton_ModalBtnOK) {
                $('.ModalPopup_ModalBtnOK').show();
            }
            else {
                $('.ModalPopup_ModalBtnOK').hide();
            }
            if (modalpopup.IsShowButton_ModalBtnVIEW) {
                $('.ModalPopup_ModalBtnVIEW').show();
            }
            else {
                $('.ModalPopup_ModalBtnVIEW').hide();
            }
            if (modalpopup.IsShowButton_ModalBtnCANCEL) {
                $('.ModalPopup_ModalBtnCANCEL').show();
            }
            else {
                $('.ModalPopup_ModalBtnCANCEL').hide();
            }
            $('.ModalPopup_ModalBtnOK').val(modalpopup.Text_ModalBtnOK);
            $('.ModalPopup_ModalBtnVIEW').val(modalpopup.Text_ModalBtnVIEW);
            $('.ModalPopup_ModalBtnCANCEL').val(modalpopup.Text_ModalBtnCANCEL);

            // make seperations
            if (modalpopup.IsShowButton_ModalBtnOK && modalpopup.IsShowButton_ModalBtnVIEW && modalpopup.IsShowButton_ModalBtnCANCEL) {
                $('.ModalPopup_ModalOuter').find('div').css('width', `500px`);
                //$('.ModalPopup_ModalBtnVIEW').after('<br />');
                //$('.ModalPopup_ModalBtnCANCEL').css('margin-top', '3px');
            }
        };

        // Initialize the document event listeners
        $(document).one("keydown", function (event) {
            // Check that modal is open
            if ($('#ModalPopup_Window').length && $('#ModalPopup_Window').length > 0) {
                if ($('#ModalPopup_Window').is(':visible')) {
                    // Check that enter key is pressed
                    if (event.keyCode === 13) {
                        // Always default to OK button first,
                        // Otherwise bind it to VIEW button
                        if (modalpopup.IsShowButton_ModalBtnOK) {
                            $('#ModalPopup_ModalBtnOK').focus(); // give focus
                            $('#ModalPopup_ModalBtnOK').click();
                        }
                        else if (modalpopup.IsShowButton_ModalBtnVIEW) {
                            $('#ModalPopup_ModalBtnVIEW').focus(); // give focus
                            $('#ModalPopup_ModalBtnVIEW').click();
                        }
                    }
                }
            }
        });

        // finish the class
        return modalpopup;
    },


    /* A standard easy function to replace the js confirm function */
    // obj is the butten or link in the html page.
    ModalPopupConfirm: function (obj, subject, str) {
        var isConfirmed = $('#' + obj.id).data("IsConfirmed");
            // console.log(obj.id + ' = ' + isConfirmed);
        if (isConfirmed == '1') {
            // console.log('confirmed=1 block.');
            $('#' + obj.id).data("IsConfirmed", '0');
            return true;
        }
        else {
            var modalpopup = ModalPopup.createNew();
            modalpopup.IsShowButton_ModalCloser = false;
            modalpopup.IsShowButton_ModalBtnOK = true;
            modalpopup.IsShowButton_ModalBtnVIEW = false;
            modalpopup.IsShowButton_ModalBtnCANCEL = true;
            modalpopup.setupText(subject, str);
            modalpopup.setupForm(ModalPopup.ModalPopupOKClick, obj.id, null, null, null, null);
            modalpopup.init();
            modalpopup.open();
            return false;
        }
    },

    ModalPopupOKClick: function(id) {
        //console.log('clicked ok.');
        $('#' + id).data("IsConfirmed", '1');
        if ($('#' + id)[0].tagName == 'A') {
            // works with asp.net linkbutton
            eval($('#' + id).attr('href'));
        }
        else {
            // works with asp.net button
            $('#' + id).trigger('click');
        }
    },

    /* A standard simple function to replace the js confirm function */
    ModalPopupConfirmSimple: function (functionname, parameter, subject, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = true;
        modalpopup.setupText(subject, str);
        modalpopup.setupForm(functionname, parameter, null, null, null, null);
        modalpopup.init();
        modalpopup.open();
    },

    /* A standard simple function to replace the js confirm function */
    ModalPopupConfirmOnlySimple: function (functionname, parameter, subject, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = false;
        modalpopup.setupText(subject, str);
        modalpopup.setupForm(functionname, parameter, null, null, null, null);
        modalpopup.init();
        modalpopup.open();
    },

    /* A standard simple function to replace the js confirm function */
    ModalPopupContinueSimple: function (functionname, parameter, subject, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.Text_ModalBtnOK = 'Continue';
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = true;
        modalpopup.setupText(subject, str);
        modalpopup.setupForm(functionname, parameter, null, null, null, null);
        modalpopup.init();
        modalpopup.open();
    },

    /* A custom button simple function to replace the js confirm function */
    ModalPopupSimple_CustomBtnOk: function (btnOKText, functionname, parameter, subject, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.Text_ModalBtnOK = btnOKText;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = true;
        modalpopup.setupText(subject, str);
        modalpopup.setupForm(functionname, parameter, null, null, null, null);
        modalpopup.init();
        modalpopup.open();
    },

    /* A standard easy function to replace the js confirm function */
    ModalPopupAlertSimple: function(functionname, parameter, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = false;
        modalpopup.setupText('ALERT', str);
        modalpopup.setupForm(functionname, parameter, null, null, null, null);
        modalpopup.init();
        modalpopup.open();
    },

    ModalPopupConfirmStandard: function (functionOKname, parameterOK, functionCancelname, parameterCancel, subject, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = true;
        modalpopup.setupText(subject, str);
        modalpopup.setupForm(functionOKname, parameterOK, null, null, functionCancelname, parameterCancel);
        modalpopup.init();
        modalpopup.open();
    },

    ModalPopupConfirmStandardCustomButton: function (functionOKname, parameterOK, textOK, functionCancelname, parameterCancel, textCancel, subject, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = true;
        modalpopup.Text_ModalBtnOK = textOK;
        modalpopup.Text_ModalBtnCANCEL = textCancel;
        modalpopup.setupText(subject, str);
        modalpopup.setupForm(functionOKname, parameterOK, null, null, functionCancelname, parameterCancel);
        modalpopup.init();
        modalpopup.open();
    },

    /* A standard simple function to replace the js alert function */
    ModalPopupAlert: function (subject, str) {
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = true;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = false;
        modalpopup.setupText(subject, str);
        modalpopup.setupForm(null, null, null, null, null, null);
        modalpopup.init();
        modalpopup.open();
	},

	/* A standard simple function to replace the js alert function */
	ModalPopupAlertWithOkFunction: function (functionnOKname, subject, str) {
		var modalpopup = ModalPopup.createNew();
		modalpopup.IsShowButton_ModalCloser = false;
		modalpopup.IsShowButton_ModalBtnOK = true;
		modalpopup.IsShowButton_ModalBtnVIEW = false;
		modalpopup.IsShowButton_ModalBtnCANCEL = false;
		modalpopup.setupText(subject, str);
		modalpopup.setupForm(functionnOKname, null, null, null, null, null);
		modalpopup.init();
		modalpopup.open();
	},

    /* Popup a Loading gif window */
    ModalLoadingGif: function(str){
        var modalpopup = ModalPopup.createNew();
        modalpopup.IsShowButton_ModalCloser = false;
        modalpopup.IsShowButton_ModalBtnOK = false;
        modalpopup.IsShowButton_ModalBtnVIEW = false;
        modalpopup.IsShowButton_ModalBtnCANCEL = false;
        modalpopup.setupText("", "<div style='text-align:center;'><img src='/assets/images/loading.gif' style='display:inline;'/><br> " + str + "</div>");
        modalpopup.setupForm(null, null, null, null, null, null);
        modalpopup.init();
        modalpopup.open();
    }

};
;
var logvalidation = {
	validate: function (sid) {
		try {
			var here = this;
			$('body').mouseover(function (e) {
				here.mouse_checking_over(here, e, sid);
			});

			$('body').bind('touchstart', function (e) {
				here.mouse_checking_touch(here, e, sid);
			});

			var needCheck = false;
			// Check existing cookie value
			var logValidateLastDate = this.get_cookie('logValidateLastDate');
			if (logValidateLastDate != null) {
				// Get the cookie value
				// Set needCheck to true only when day span > 1
				var hoursSpan = (new Date() - new Date(logValidateLastDate)) / (3600 * 1000); // check hours
				//console.log(hoursSpan);
				if (hoursSpan > 1) {
					needCheck = true;
				}
			}
			else {
				// Can not get cookie.
				// Try to set the cookie value first
				this.set_cookie('logValidateLastDate', new Date(), 30);
				// try to get cookie value.
				logValidateLastDate = this.get_cookie('logValidateLastDate');
				if (logValidateLastDate != null) {
					// Can get cookie value, need to check
					needCheck = true;
				}
				else {
					// Can not get cookie value, maybe it is a bot.
					needCheck = false;
				}
			}

			if (needCheck) {
				var pamas = {
					'sid': sid,
					'xtraInfo': ''
				};
				var that = this;
				logapi.Validate(pamas, function (data) {
					if (data.valid) {
						that.set_cookie('logValidateLastDate', new Date(), 30);
						//console.log('Set logValidateLastDate successfully');
					}
				});
			}
		}
		catch (error) {
			var pamas = {
				'sid': sid,
				'xtraInfo': error.message.substring(0, 99)
			};
			logapi.Validate(pamas, function (data) {
				if (!data.valid) {
					console.log('error');
				}
			});
		}
	},
	mouse_checking_over: function (that, e, sid) {
		try {
			if (window.MOUSECHECKINGLOCK == undefined) {
				window.MOUSECHECKINGLOCK = 1;
				var mousecheckinglog = that.get_cookie('logMouseCheckingLog');
				if (mousecheckinglog == null) {
					that.set_cookie('logMouseCheckingLog', new Date(), 30);
					mousecheckinglog = that.get_cookie('logMouseCheckingLog');
					if (mousecheckinglog != null) {
						var pamas = {
							'sid': sid,
							'xtraInfo': ('x:' + e.pageX + ',y:' + e.pageY)
						};
						logapi.Validate(pamas, function (data) {
							if (data.valid) {
								that.set_cookie('logMouseCheckingLog', new Date(), 30);
								//console.log('Set logMouseCheckingLog successfully');
							}
						});
					}
				}
			}
		}
		catch (error) {
			var pamas = {
				'sid': sid,
				'xtraInfo': error.message.substring(0, 99)
			};
			logapi.Validate(pamas, function (data) {
				if (!data.valid) {
					console.log('error');
				}
			});
		}
	},
	mouse_checking_touch: function (that, e, sid) {
		try {
			if (window.MOUSECHECKINGLOCK == undefined) {
				window.MOUSECHECKINGLOCK = 1;
				var mousecheckinglog = that.get_cookie('logMouseCheckingLog');
				if (mousecheckinglog == null) {
					that.set_cookie('logMouseCheckingLog', new Date(), 30);
					mousecheckinglog = that.get_cookie('logMouseCheckingLog');
					if (mousecheckinglog != null) {
						var pamas = {
							'sid': sid,
							'xtraInfo': ('touch_x:' + e.originalEvent.changedTouches[0].pageX + ',touch_y:' + e.originalEvent.changedTouches[0].pageY)
						};
						logapi.Validate(pamas, function (data) {
							if (data.valid) {
								that.set_cookie('logMouseCheckingLog', new Date(), 30);
								//console.log('Set logMouseCheckingLog successfully');
							}
						});
					}
				}
			}
		}
		catch (error) {
			var pamas = {
				'sid': sid,
				'xtraInfo': error.message.substring(0, 99)
			};
			logapi.Validate(pamas, function (data) {
				if (!data.valid) {
					console.log('error');
				}
			});
		}
	},
	set_cookie: function (name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";
	},
	get_cookie: function (name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	}
}

const logapi = {
	Validate: function (pamas, callback) {
		HTTP_LogValidation.get(APIRoute_LogValidation.Validate, pamas, callback);
	}
}

const APIRoute_LogValidation = {
	Validate: "/api/LogValidation/Validate"
}


const HTTP_LogValidation = {
	get: function (url, params, callback) {
		$.ajax({
			url: url,
			type: 'get',
			dataType: 'json',
			contentType: 'application/json',
			traditional: true,
			data: params
		}).then(function (res) {
			if (res.code == 200) {
				//console.log(res);
				if (callback) {
					callback(res.data);
				}
			}
			else {
				console.log(res.msg);
				if (ModalPopup) ModalPopup.ModalPopupAlert("ERROR", res.msg);
			}
		}, function (XMLHttpRequest, textStatus, errorThrown) {
			console.log('get data error');
			console.log(XMLHttpRequest.status);
			console.log(XMLHttpRequest.readyState);
			console.log(textStatus);
			alert('The service is unavailable. Please contact administrator.');
		});
	},
	post: function (url, params, callback) {
		$.ajax({
			url: url,
			type: 'post',
			dataType: 'json',
			contentType: 'application/json',
			traditional: true,
			data: params
		}).then(function (res) {
			if (res.code == 200) {
				//console.log(res);
				if (callback) {
					callback(res.data);
				}
			}
			else {
				console.log(res.msg);
				if (ModalPopup) ModalPopup.ModalPopupAlert("ERROR", res.msg);
			}
		}, function (XMLHttpRequest, textStatus, errorThrown) {
			console.log('get data error');
			console.log(XMLHttpRequest.status);
			console.log(XMLHttpRequest.readyState);
			console.log(textStatus);
			alert('The service is unavailable. Please contact administrator.');
		});
	}
}
;
