﻿var MAP_CONTAINER = 'GoogleMap';
var MAP_CONTAINER_CSS = 'GoogleMapContainer';
var MAP_DEFAULT_ZOOM = 7;
//var ERROR_LABEL_ID = 'ErrorMessageDialogDiv';
var GOOGLE_MAP_WRAPPER_DIV = 'GoogleMapWrapper';
var BUSY_INDICATOR_DIV = 'BusyIndicator';

var map = null;
var container = null;

function EnableSearchButton() {
    document.getElementById('Search_Button').disabled = false;
}

function DisableSearchButton() {
    document.getElementById('Search_Button').disabled = true;
}

function Initialize() {
    if (InitGoogleMap() == true) {
        map.setCenter(new GLatLng(ServerVariables.MAP_CENTER_DEFAULT_LATITUDE, ServerVariables.MAP_CENTER_DEFAULT_LONGITUDE), MAP_DEFAULT_ZOOM);
    }
}

function SetErrorMessage(message) {
    if ($('#' + ServerVariables.ErrorMessageDiv).length > 0 && message) {
        $('#' + ServerVariables.ErrorMessageDiv).css('display', 'block');
        
        if ($('#' + ServerVariables.ErrorMessageTextDiv).length > 0){
            $('#' + ServerVariables.ErrorMessageTextDiv).html(message);
        }
    }
}

function ClearErrorMessage() {
    if ($('#' + ServerVariables.ErrorMessageDiv).length > 0) {
        $('#' + ServerVariables.ErrorMessageDiv).css('display', 'none');

        if ($('#' + ServerVariables.ErrorMessageTextDiv).length > 0) {
            $('#' + ServerVariables.ErrorMessageTextDiv).html('');
        }
    }
}

function ShowBusyIndicator() {
    if($("#" + BUSY_INDICATOR_DIV).length > 0){
        $("#" + BUSY_INDICATOR_DIV).show();
    }
}

function HideBusyIndicator() {
    if ($("#" + BUSY_INDICATOR_DIV).length > 0) {
        $("#" + BUSY_INDICATOR_DIV).hide();
    }
}

function RegisterElementStyle(id, cssClassName) {
    if ($("#" + id).length > 0) {
        $("#" + id).addClass(cssClassName);
    }
}

function InitGoogleMap() {
    RegisterElementStyle(MAP_CONTAINER, MAP_CONTAINER_CSS);
    ClearErrorMessage();
    
    if (GBrowserIsCompatible()) {
        container = document.getElementById(MAP_CONTAINER);
        if (container) {
            if (!map) {
                map = new GMap2(container);
                map.enableScrollWheelZoom();
                map.addControl(new GLargeMapControl3D());
                map.addControl(new GMapTypeControl());
                return true;
            }
            else {
                return true;
            }
        }
    }
    
    return false;
}

function createPharmacyMarker(geoPoint) {
    if (!geoPoint.ChainLogoUrl) {
        geoPoint.ChainLogoUrl = resolveRootUrl() + "Images/Themes/Green/institution_default126bg.png";
    }

    var remark = "<div class=\"PharmacyListItem\">";
    if (geoPoint.RoundTheClock) {
        remark += "<div class=\"PharmacyListItemImage24h\">" +
                    "<img src=\"" + resolveRootUrl() + geoPoint.ChainLogoUrl + "\" height=\"68px\" width=\"128px\" /><br />" +
                    "<span class=\"RoundTheClock\">" + ServerVariables.Resources._LabelRoundTheClock + "</span><br />";
    } else {
        remark += "<div class=\"PharmacyListItemImage\">" +
                    "<img src=\"" + resolveRootUrl() + geoPoint.ChainLogoUrl + "\" height=\"68px\" width=\"128px\" /><br /><br /><br />";
    }

    if (geoPoint.PharmacyUrl != null) {
        remark += "</div>" +
              "<div class=\"PharmacyListItemText\">" +
              "<strong>" + geoPoint.PharmacyUrl + "</strong><br />" +
              ServerVariables.Resources._LabelAddress + "&nbsp;<strong>" + geoPoint.AddressLine1 + ", " + geoPoint.AddressLine2 + "</strong>";
    }
    else {
        remark += "</div>" +
              "<div class=\"PharmacyListItemText\">" +
              "<strong>" + geoPoint.Caption + "</strong><br />" +
              ServerVariables.Resources._LabelAddress + "&nbsp;<strong>" + geoPoint.AddressLine1 + ", " + geoPoint.AddressLine2 + "</strong>";
    }

    if (geoPoint.Phone && geoPoint.Phone !== "") {
        remark += "<br />" +
                ServerVariables.Resources._LabelPhone + "&nbsp;<strong>" + geoPoint.Phone + "</strong>";
    }

    if (geoPoint.WorkTime && geoPoint.WorkTime !== "") {
        remark += "<table class=\"wrpas\">" +
                  "<tr>" +
                  "<td class=\"wtimes\">" + ServerVariables.Resources._LabelWorkHours + "</td>" +
                  "<td>" +
                  "<table><tr><td>" + geoPoint.WorkTime + "</td></tr></table>" +
                  "</td>" +
                  "</tr>" +
                  "</table>";
    }

    if (geoPoint.WorkTime || geoPoint.RoundTheClock) {
        remark += "<table class=\"LineH22\">" +
                    "<tr><td>";
        if ((geoPoint.TimeToWorkInMinutes !== 0) &&
            (geoPoint.TimeToWorkInMinutes > 0)) {
            remark += "<img src=\"" + resolveRootUrl() + "Images/ClockOpen.png\" height=\"22px\" width=\"22px\" alt=\"\" /></td>";
            remark += "<td>" + ServerVariables.Resources._PharmacyOpenForFormat.replace("{0}", Math.floor(geoPoint.TimeToWorkInMinutes / 60)).replace("{1}", geoPoint.TimeToWorkInMinutes % 60);
        } else if (geoPoint.RoundTheClock) {
            remark += "<img src=\"" + resolveRootUrl() + "Images/ClockOpen.png\" height=\"22px\" width=\"22px\" alt=\"\" /></td>";
            remark += "<td>" + ServerVariables.Resources._PharmacyWorks24h;
        } else {
            remark += "<img src=\"" + resolveRootUrl() + "Images/ClockClosed.png\" height=\"22px\" width=\"22px\" alt=\"\" /></td>";
            remark += "<td>" + ServerVariables.Resources._PharmacyClosed;
        }

        remark += "</td></tr>";
        remark += "</table>";
    }

    remark += "<br /><INPUT type=\"textbox\" id=\"userAddressField\" class=\"input\" value=\""
        + ServerVariables.Resources._LabelYourAddress
        + "\" onFocus=\"if(this.value == '"
        + ServerVariables.Resources._LabelYourAddress
        +"') {this.value = '';}\" onBlur=\"if (this.value == '') {this.value = '"
        + ServerVariables.Resources._LabelYourAddress
        + "';}\" onkeydown=\"return disableEnterKey(event)\"/>";
    remark += "<a onclick=\"GetDirections('" + geoPoint.AddressLine1 + ", "
        + geoPoint.AddressLine2 + "')\" style=\"cursor: pointer;\" title=\""
        + ServerVariables.Resources._LabelShowTrack + "\">&nbsp;>></a>";
            
    remark += "<br />";
    remark += "</div>";

    var latlng = new GLatLng(geoPoint.Latitude, geoPoint.Longitude);
    if (latlng.lat() <= 0.0 ||
        latlng.lng() <= 0.0) {
        return null;
    }

    var marker = new GMarker(latlng, { title: geoPoint.Name });
    GEvent.addListener(marker, "click", function() {
        map.openInfoWindowHtml(latlng, remark);
    });

    return marker;
}

function ShowPoint() {
    ShowBusyIndicator();

    if (InitGoogleMap() == true) {
        PageMethods.set_path(getRootUrl());
        PageMethods.GetGeoPointById(function(geoPoint) {
            if (geoPoint) {
                var marker = createPharmacyMarker(geoPoint);
                map.addOverlay(marker);
                map.setCenter(marker.getLatLng(), 13);
            }
            else {
                map.setCenter(new GLatLng(ServerVariables.MAP_CENTER_DEFAULT_LATITUDE, ServerVariables.MAP_CENTER_DEFAULT_LONGITUDE), MAP_DEFAULT_ZOOM);
            }

            HideBusyIndicator();
        });
    }
}

function ShowAllPointsInTown(townId, regionId, chainId, isRoundTheClock, isWorkinOnly, timeToWork) {
    ShowBusyIndicator();
    
    if (InitGoogleMap() == true){
        map.clearOverlays();
        map.setCenter(new GLatLng(ServerVariables.MAP_CENTER_DEFAULT_LATITUDE, ServerVariables.MAP_CENTER_DEFAULT_LONGITUDE), MAP_DEFAULT_ZOOM);
        PageMethods.set_path(getRootUrl());
        PageMethods.GetAllPointsInTown(townId, regionId, chainId, isRoundTheClock, isWorkinOnly, timeToWork, resolveRootUrl(), function(list) {
            if (list &&
                (list.length > 0)) {

                var bounds = new GLatLngBounds();

                // add markers
                var count = 0;
                for (var i = 0; i < list.length; i++) {
                    var marker = createPharmacyMarker(list[i]);
                    if (marker) {
                        map.addOverlay(createPharmacyMarker(list[i]));
                        bounds.extend(marker.getLatLng());
                        count++;
                    }
                }

                // Center map or 
                // show error message if no markers were added.
                if (count > 0) {
                    map.setZoom(map.getBoundsZoomLevel(bounds));
                    map.setCenter(bounds.getCenter());
                }
                else {
                    SetErrorMessage(ServerVariables.Resources._PharmacyNotFound);
                }
            } else {
                SetErrorMessage(ServerVariables.Resources._PharmacyNotFound);
            }

            HideBusyIndicator();
        });
    }
}

function ShowAllPointsInRegion(regionId, chainId, isRoundTheClock, isWorkinOnly, timeToWork) {
    ShowBusyIndicator();

    if (InitGoogleMap() == true) {
        map.clearOverlays();
        map.setCenter(new GLatLng(ServerVariables.MAP_CENTER_DEFAULT_LATITUDE, ServerVariables.MAP_CENTER_DEFAULT_LONGITUDE), MAP_DEFAULT_ZOOM);
        PageMethods.set_path(getRootUrl());
        PageMethods.GetAllPointsInRegion(regionId, chainId, isRoundTheClock, isWorkinOnly, timeToWork, resolveRootUrl(), function(list) {
            if (list &&
                (list.length > 0)) {

                var bounds = new GLatLngBounds();

                // add markers
                var count = 0;
                for (var i = 0; i < list.length; i++) {
                    var marker = createPharmacyMarker(list[i]);
                    if (marker) {
                        map.addOverlay(createPharmacyMarker(list[i]));
                        bounds.extend(marker.getLatLng());
                        count++;
                    }
                }

                // Center map or 
                // show error message if no markers were added.
                if (count > 0) {
                    map.setZoom(map.getBoundsZoomLevel(bounds));
                    map.setCenter(bounds.getCenter());
                }
                else {
                    SetErrorMessage(ServerVariables.Resources._PharmacyNotFound);
                }
            } else {
                SetErrorMessage(ServerVariables.Resources._PharmacyNotFound);
            }

            HideBusyIndicator();
        });
    }
}

function ShowAllPointsFromArray(points) {
    if (points && points.length > 0) {
        ShowBusyIndicator();

        if (InitGoogleMap() == true) {
            map.clearOverlays();
            map.setCenter(new GLatLng(ServerVariables.MAP_CENTER_DEFAULT_LATITUDE, ServerVariables.MAP_CENTER_DEFAULT_LONGITUDE), MAP_DEFAULT_ZOOM);

            var bounds = new GLatLngBounds();

            // add markers
            var count = 0;
            for (var i = 0; i < points.length; i++) {
                var marker = createPharmacyMarker(points[i]);
                if (marker) {
                    map.addOverlay(createPharmacyMarker(points[i]));
                    bounds.extend(marker.getLatLng());
                    count++;
                }
            }

            // Center map or 
            // show error message if no markers were added.
            if (count == 1) {
                map.setZoom(13);
                map.setCenter(bounds.getCenter());
            }
            else if (count > 0) {
                map.setZoom(map.getBoundsZoomLevel(bounds));
                map.setCenter(bounds.getCenter());
            }
            else {
                SetErrorMessage(ServerVariables.Resources._PharmacyNotFound);
            }
        } else {
            SetErrorMessage(ServerVariables.Resources._PharmacyNotFound);
        }

        HideBusyIndicator();
    }
}

function ShowPharmacies() {
    ClearErrorMessage();

    if (ServerVariables.Pharmacies && ServerVariables.Pharmacies.length > 0) {
        ShowAllPointsFromArray(ServerVariables.Pharmacies);
        return;
    }

    var townId = document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_TownDropDownList").value;
    var regionId = document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_RegionDropDownList").value;
    var chainId = document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_PharmacyChainDropDownList").value;
    var rountTheClock = false;
    if (document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_RoundTheClockOnlyCheckBox")) {
        rountTheClock = document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_RoundTheClockOnlyCheckBox").checked;
    }
    var workingOnly = false;
    if (document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_WorkingOnlyCheckBox")) {
        workingOnly = document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_WorkingOnlyCheckBox").checked;
    }
    var timeToWork = -1;
    if (document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_TimeToWorkDropDownList")) {
        timeToWork = document.getElementById("ContentPlaceHolder1_Page_AsyncPlaceSelectorControl_Control_TimeToWorkDropDownList").value;
    }

    if (townId && regionId &&
        !isNaN(townId) && !isNaN(regionId)) {

        if (!chainId || isNaN(chainId)) {
            chainId = -1;
        }

        if (townId != -1) {
            ShowAllPointsInTown(townId, regionId, chainId, rountTheClock, workingOnly, timeToWork);
            CheckAndWritePlaceCookies(regionId, townId, chainId);
        }
        else if (townId == -1 && regionId != -1) {
            ShowAllPointsInRegion(regionId, chainId, rountTheClock, workingOnly, timeToWork);
            CheckAndWritePlaceCookies(regionId, townId, chainId);
        }
        else {
            if (regionId == -1) {
                SetErrorMessage(ServerVariables.Resources._ChoosRegion);
                map.clearOverlays();
                map.setCenter(new GLatLng(ServerVariables.MAP_CENTER_DEFAULT_LATITUDE, ServerVariables.MAP_CENTER_DEFAULT_LONGITUDE), MAP_DEFAULT_ZOOM);
            }
        }
    }
    else {
        SetErrorMessage(ServerVariables.Resources._PharmacyNotFound);
        map.clearOverlays();
        map.setCenter(new GLatLng(ServerVariables.MAP_CENTER_DEFAULT_LATITUDE, ServerVariables.MAP_CENTER_DEFAULT_LONGITUDE), MAP_DEFAULT_ZOOM);
    }
}

/*** cookies ***/
function CheckAndWritePlaceCookies(regionId, townId, chainId) {
    if (!regionId || !townId || !chainId ||
        isNaN(regionId) || isNaN(townId) || isNaN(chainId)) {
        return;
    }

    var regionValue = Get_Cookie('RegionId');
    var townValue = Get_Cookie('TownId');
    var chainValue = Get_Cookie('PharmacyChainId');

    if (regionValue && townValue && chainValue &&
        !isNaN(regionValue) && !isNaN(townValue) && !isNaN(chainValue)) {

        if (regionId != regionValue ||
            townId != townValue ||
            chainId != chainValue){
            
            Set_Cookie('RegionId', regionId, 30, '/', '', '');
            Set_Cookie('TownId', townId, 30, '/', '', '');
            Set_Cookie('PharmacyChainId', chainId, 30, '/', '', '');
        }
    }
    else {
        Set_Cookie('RegionId', regionId, 30, '/', '', '');
        Set_Cookie('TownId', townId, 30, '/', '', '');
        Set_Cookie('PharmacyChainId', chainId, 30, '/', '', '');
    }
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
}

function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');

        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

/*highlight v3
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>*/
jQuery.fn.highlight = function(pat) {
    if (pat) {
        function innerHighlight(node, pat) {
            var skip = 0;
            if (node.nodeType == 3) {
                var pos = node.data.toUpperCase().indexOf(pat);
                if (pos >= 0) {
                    var spannode = document.createElement('span');
                    spannode.className = 'highlight';
                    var middlebit = node.splitText(pos);
                    var endbit = middlebit.splitText(pat.length);
                    var middleclone = middlebit.cloneNode(true);
                    spannode.appendChild(middleclone);
                    middlebit.parentNode.replaceChild(spannode, middlebit);
                    skip = 1;
                }
            }
            else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
                for (var i = 0; i < node.childNodes.length; ++i) {
                    i += innerHighlight(node.childNodes[i], pat);
                }
            }
            return skip;
        }
        return this.each(function() {
            innerHighlight(this, pat.toUpperCase());
        });
    }
};

jQuery.fn.removeHighlight = function() {
    return this.find("span.highlight").each(function() {
        this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    }).end();
};

function highlightFragment(pattern) {
    if ($(".PackageIndexViewDiv").length > 0) {
        $(".PackageIndexViewDiv").highlight(pattern);
    }
    if ($(".GridView").length > 0) {
        $(".GridView").highlight(pattern);
    }
}

function logBannerClick(bannerId) {
    PageMethods.set_path(getRootUrl());
    PageMethods.LogBannerClick(bannerId, ServerVariables.IPAddress);
}

function logShortNewsClick(newsId) {
    PageMethods.set_path(getRootUrl());
    PageMethods.LogShortNewsClick(newsId, ServerVariables.IPAddress);
}

/* *** Save Feedback Message *** */
function SaveFeedbackMsg() {
    var url = document.location.href;
    var name = $('input[type=text]#Feedback_NameText').val();
    var email = $('input[type=text]#Feedback_EMailText').val();
    var msg = $('textarea#Feedback_MsgTextBox').val();

    if (msg) {
        try {
            PageMethods.set_path(getRootUrl());
            PageMethods.LogFeedbackMsg(url, ServerVariables.IPAddress, name, email, msg);
        }catch(Error){ }

        // clear dialog fields
        $('input[type=text]#Feedback_NameText').val("");
        $('input[type=text]#Feedback_EMailText').val("");
        $('textarea#Feedback_MsgTextBox').val("");        
    }
}

function ShowToggleAbleSubDivs(link) {
    if ($('.ToggleAbleSuperDiv > div').css('display') == 'none') {
        $('.ToggleAbleSuperDiv > div').show();
        $('#ImgInfoLeaflet').attr("src", resolveRootUrl() + "Images/Themes/Green/minus.png");
        $(link).attr("class", "linkToggle");
    }else{
        $('.ToggleAbleSuperDiv > div').hide();
        $('#ImgInfoLeaflet').attr("src", resolveRootUrl() + "Images/Themes/Green/plus.png");
        $(link).attr("class", "linkNormal");
    }
}

function ShowToggleAbleSubDivsChs(link) {
    if ($('.ToggleAbleSuperDivChs > div').css('display') == 'none') {
        $('.ToggleAbleSuperDivChs > div').show();
        $('#ImgInfoChs').attr("src", resolveRootUrl() + "Images/Themes/Green/minus.png");
        $(link).attr("class", "linkToggle");
    } else {
        $('.ToggleAbleSuperDivChs > div').hide();
        $('#ImgInfoChs').attr("src", resolveRootUrl() + "Images/Themes/Green/plus.png");
        $(link).attr("class", "linkNormal");
    }
}

function ToggleSubDiv(div) {
    if (div) {
        var parent = div.parentNode;
        var divs = parent.getElementsByTagName("div");
        var images = parent.getElementsByTagName("img");

        if (divs[0].style.display == 'none') {
            divs[0].style.display = 'block';
            images[0].src = resolveRootUrl() + "Images/Themes/Green/minus.png";
        }
        else {
            divs[0].style.display = 'none';
            images[0].src = resolveRootUrl() + "Images/Themes/Green/plus.png";
        }
    }
}

function ToggleSubDivInfo(div, ip, id, type, userType) {
    if (div) {
        var parent = div.parentNode;
        var divs = parent.getElementsByTagName("div");
        var links = parent.getElementsByTagName("a");
        var images = parent.getElementsByTagName("img");
        if (divs[0].style.display == 'none') {
            divs[0].style.display = 'block';
            links[0].setAttribute('class', 'linkToggle');
            //IE6
            links[0].setAttribute('className', 'linkToggle');
            images[0].src = resolveRootUrl() + "Images/Themes/Green/minus.png";
            PageMethods.set_path(getRootUrl());
            PageMethods.LogInfoRead(ip, id, type, userType);
        }
        else {
            divs[0].style.display = 'none';
            links[0].setAttribute('class', 'linkNormal');
            //IE6
            links[0].setAttribute('className', 'linkNormal');
            images[0].src = resolveRootUrl() + "Images/Themes/Green/plus.png";
        }
    }
}

function resolveRootUrl() {
    var rootURL = location.href;
    var baseURL = '';
    baseURL = location.protocol + '//' + document.location.hostname;
    if (rootURL.indexOf('localhost') != -1) {
        return baseURL + "/WebApp/";
    } else if (rootURL.indexOf('saugykla') != -1) {
        return baseURL + "/visivaistaibeta/";
    }else{
        return baseURL + "/";
    }
    return baseURL;
}

function showInformationDialog(image, message) {
    appName = navigator.appName;
    appVersion = navigator.appVersion;
    var screenHeight = 0;
    var screenWidth = 0;
    var vscroll = 0;
    if (appName.indexOf("Microsoft") > -1 && appVersion.indexOf("MSIE 6.0") > -1) {
        //IE6
        screenHeight = document.documentElement.clientHeight;
        screenWidth = document.documentElement.clientWidth;
        var posX = image.offsetLeft;
        var posY = image.offsetTop;
        var element = image.offsetParent;
        while (element.offsetTop > 0) {
            posY = posY + element.offsetTop;
            element = element.offsetParent;
        }
        element = image.offsetParent;
        while (element.offsetLeft > 0) {
            posX = posX + element.offsetLeft;
            element = element.offsetParent;
        }
        vscroll = document.documentElement.scrollTop;
        if (screenHeight - (posY - vscroll) >= $("#infoDialog").height()) {
            if (screenWidth - posX > $("#infoDialog").width()) {
                $("#infoDialog").css('left', posX + 10);
                $("#infoDialog").css('top', posY + 10);
            } else {
                $("#infoDialog").css('left', posX - $("#infoDialog").width());
                $("#infoDialog").css('top', posY + 10);
            }
        } else {
            if (screenWidth - posX > $("#infoDialog").width()) {
                $("#infoDialog").css('left', posX + 10);
                $("#infoDialog").css('top', posY - $("#infoDialog").height());
            } else {
                $("#infoDialog").css('left', posX - $("#infoDialog").width());
                $("#infoDialog").css('top', posY - $("#infoDialog").height() - 20);
            }
        }
        $("p#infoMessage").html(message);
        $("#infoDialog").show();
    } else {
        //Other browsers
        screenHeight = $(window).height();
        screenWidth = $(window).width();
        var img = $(image);
        var pos = img.offset();
        vscroll = document.documentElement.scrollTop;
        if (vscroll == 0) {
            vscroll = document.body.scrollTop;
        }
        if (screenHeight - (pos.top - vscroll) >= $("#infoDialog").height()) {
            if (screenWidth - pos.left > $("#infoDialog").width()) {
                $("#infoDialog").css('left', pos.left + 10);
                $("#infoDialog").css('top', pos.top + 10);
            } else {
                $("#infoDialog").css('left', pos.left - $("#infoDialog").width());
                $("#infoDialog").css('top', pos.top + 10);
            }
        } else {
            if (screenWidth - pos.left > $("#infoDialog").width()) {
                $("#infoDialog").css('left', pos.left + 10);
                $("#infoDialog").css('top', pos.top - $("#infoDialog").height());
            } else {
                $("#infoDialog").css('left', pos.left - $("#infoDialog").width());
                $("#infoDialog").css('top', pos.top - $("#infoDialog").height());
            }
        }
        $("p#infoMessage").html(message);
        $("#infoDialog").show();
    }
}

function hideInformationDialog() {
    $("#infoDialog").hide();
}

function Top5HideShowSubstances() {
    var elem = document.getElementById("Top5Substances");
    if (elem.style.display == "none") {
        elem.style.display = "block";
    } else {
        elem.style.display = "none";
    }
}

function Top5HideShowPharmacies() {
    var elem = document.getElementById("Top5Pharmacies");
    if (elem.style.display == "none") {
        elem.style.display = "block";
    } else {
        elem.style.display = "none";
    }
}

//TreeView
function CheckChildNodes(evt) {
    var src = window.event != window.undefined ? window.event.srcElement : evt.target;
    var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
    if (isChkBoxClick) {
        var parentTable = GetParentByTagName("table", src);
        var nxtSibling = parentTable.nextSibling;
        //tikrinam ar gretimas kaimynas nera NULL ir yra elementas
        if (nxtSibling && nxtSibling.nodeType == 1)
        {
            //tikrinam ar elementas turi vaiku
            if (nxtSibling.tagName.toLowerCase() == "div")
            {
                //pazymim/atzymim vaikus
                CheckUncheckChildren(parentTable.nextSibling, src.checked);
            }
        }
        //pazymim/atzymim tevus
        CheckUncheckParents(src, src.checked);
    }
}

function CheckUncheckChildren(childContainer, check) {
    var childChkBoxes = childContainer.getElementsByTagName("input");
    var childChkBoxCount = childChkBoxes.length;
    for (var i = 0; i < childChkBoxCount; i++) {
        childChkBoxes[i].checked = check;
    }
}

function CheckUncheckParents(srcChild, check) {
    var parentDiv = GetParentByTagName("div", srcChild);
    var parentNodeTable = parentDiv.previousSibling;

    if (parentNodeTable) {
        var checkUncheckSwitch;

        if (check)
        {
            var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
            if (isAllSiblingsChecked)
                checkUncheckSwitch = true;
            else
                return;
        }
        else
        {
            checkUncheckSwitch = false;
        }

        var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
        if (inpElemsInParentTable.length > 0) {
            var parentNodeChkBox = inpElemsInParentTable[0];
            parentNodeChkBox.checked = checkUncheckSwitch;
            CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
        }
    }
}

function AreAllSiblingsChecked(chkBox) {
    var parentDiv = GetParentByTagName("div", chkBox);
    var childCount = parentDiv.childNodes.length;
    for (var i = 0; i < childCount; i++) {
        if (parentDiv.childNodes[i].nodeType == 1)
        {
            if (parentDiv.childNodes[i].tagName.toLowerCase() == "table") {
                var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
                if (!prevChkBox.checked) {
                    return false;
                }
            }
        }
    }
    return true;
}

function GetParentByTagName(parentTagName, childElementObj) {
    var parent = childElementObj.parentNode;
    while (parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
        parent = parent.parentNode;
    }
    return parent;
}

/* Updating MyCartList */

function onUpdating() {
    screenHeight = $(window).height();
    screenWidth = $(window).width();
    vscroll = document.documentElement.scrollTop;
    if (vscroll == 0) {
        vscroll = document.body.scrollTop;
    }
    document.getElementById("LoadingPopupDiv").style.display = "block";
    $("#LoadingPopupDiv").css("height", $(document).height());
    $("#LoadingPopupDiv > div").css("left", (screenWidth / 2) - ($("#LoadingPopupDiv > div").width() / 2));
    $("#LoadingPopupDiv > div").css("top", (screenHeight / 2) - ($("#LoadingPopupDiv > div").height() / 2) + vscroll);
}

function onUpdated() {
    document.getElementById("LoadingPopupDiv").style.display = "none";
}

/* Text limit for MultiLine TextBox */
function isMaxLength(txtBox, maxlength) {
    if (txtBox.value.length > maxlength) {
        txtBox.value = txtBox.value.substring(0, maxlength);
        SetErrorMessage(ServerVariables.Resources._ErrorSymbolsLimit + maxlength);
    }
    txtBox.scrollTop = txtBox.scrollHeight * 5;
}

/* DiseasesTree append substances */
function SubstancesPopulate(icd, depth, element) {
    var selector = "Substances_" + icd;
    if (document.getElementById(selector) != null) {
        $(document.getElementById(selector)).remove();
    } else {
    PageMethods.set_path(getRootUrl());
    PageMethods.GetSubstancesPopulate(icd, depth,
            function(list) {
                $(element).parent().append(list);
            });
    }
}

/* DiseasesTree append packages */
function PackagesPopulate(link) {
    var parent = $(link).parent();
    var children = parent.children("ul");
    if ($(children).is(":visible")) {
        $(children).hide();
    } else {
        $(children).show();
    }
}

/* Floating side banner (E position) */
$(document).ready(function() {
    if ($("#AdvertisingDiv").children().size() > 1 && $(window).width() >= 1400) {
        var $scrollingDiv = $("#AdvertisingDiv");
        $scrollingDiv.css('top', ($(window).height() + $(window).scrollTop() - $scrollingDiv.height() - 5));

        $(window).scroll(function() {
            $scrollingDiv.stop()
                .animate({ "top": ($(window).height() + $(window).scrollTop()
                    - $scrollingDiv.height() - 5) + "px"
                }, "fast");
        });
    }
    else {
        $("#AdvertisingDiv").hide();
    }
    CheckAllBoxes();
});

function CloseSideBanner() {
    $("#AdvertisingDiv").hide();
}

/* Clears text fields in table */
function ClearFields(button) {
    $(':input:not(:submit)', $(button).parents("table")).val('');
}

/* Closes Error message in the top of the page */
function HideFloatingInformation() {
    $("#ErrorMessageDiv").slideUp("slow");
}

function ClickSearchButton() {
    $("#Search_Button").click();
}

function ScrollToTop() {
    scroll(0, 0);
    return false;
}

function CheckAllBoxes() {
    var headerChk = $(".typeCheckboxMain input");
    var itemChk = $(".typeCheckbox input");
    headerChk.bind("click", function() {
        itemChk.each(function() { this.checked = headerChk[0].checked; })
    });
    itemChk.bind("click", function() {
            headerChk[0].checked = false;
    });
}

function CheckChildBoxes(id) {
    var title = $("#" + id + " > input");
    var children = $("#" + id + "Child > input");
    for (i = 0; i < children.length; i++) {
        children[i].checked = title[0].checked;
    }
}

function UncheckParentBoxes(id, item) {
    var title = $("#" + id + " > input");
    if (item.checked == false) {
        title[0].checked = item.checked;
    } else {
        var all = true;
        var children = $("#" + id + "Child > input");
        for (i = 0; i < children.length; i++) {
            if (children[i].checked == false) {
                all = false;
            }
        }
        if (all) {
            title[0].checked = true;
        }
    }
}

function MyCartCookieAdd(Id) {
    var list = Get_Cookie('MyDrugList');
    if (list != null) {
        if (list.indexOf(Id) == -1) {
            list = list + "_" + Id;
            Set_Cookie('MyDrugList', list, 30, '/', '', '');
        }
    }
    else {
        list = "_" + Id;
        Set_Cookie('MyDrugList', list, 30, '/', '', '');
    }
}

function MyCartCookieRemove(Id) {
    var list = Get_Cookie('MyDrugList');
    if (list != null) {
        if (list.indexOf(Id) != -1) {
            list = list.replace('_' + Id, '')
            Set_Cookie('MyDrugList', list, 30, '/', '', '');
        }
    }
}

function MyCartCookieClear() {
    Set_Cookie('MyDrugList', '', 30, '/', '', '');
}

function userCreateMPE() {
    $find('ConfirmModalPopupExtender').show();
    document.getElementById('ContentPlaceHolder1_ConfirmEmailTextBox').value =
        document.getElementById('ContentPlaceHolder1_Page_EMailTextBox').value;
}

function RxAdsMPEHide() {
    $find('AskQuestionModalPopupExtender').hide();
}

function RxAdsCreateMPE(id) {
    $find('AskQuestionModalPopupExtender').show();
    document.getElementById('ContentPlaceHolder1_HiddenTextBox').value = id;
}

function userCreateMPEHide() {
    $find('ConfirmModalPopupExtender').hide();
    document.getElementById('ContentPlaceHolder1_Page_EMailTextBox')
        .style.backgroundColor = "pink";
}

function diseasesTreeMPE(id) {
    document.body.scroll = "no";
    document.body.style.overflow = "hidden";
    document.getElementById('__EVENTTARGET').value = id;
    __doPostBack('ContentPlaceHolder1_PackageDetailsUserControl_PackageDetailsPanel', id);
    $find('PackageDetailsPopupExtender').show();
}

function diseasesTreeMPEHide() {
    document.body.scroll = "yes";
    document.body.style.overflow = "scroll";
    $find('PackageDetailsPopupExtender').hide();
}

function PreviousPartMPE(id, id2) {
    document.body.scroll = "no";
    document.body.style.overflow = "hidden";
    document.getElementById('__EVENTTARGET').value = id + "_" + id2;
    __doPostBack('ContentPlaceHolder1_PreviousCasePartControl_PreviousPartsUpdatePanel', id + "_" + id2);
    $find('PreviousPartPopupExtender').show();
}

function PreviousPartMPEHide() {
    document.body.scroll = "yes";
    document.body.style.overflow = "scroll";
    $find('PreviousPartPopupExtender').hide();
}

function GetDirections(toAddress) {
    var fromAddress = document.getElementById("userAddressField").value;
    var link = "http://maps.google.com/maps?saddr=\"" + fromAddress + "\"&daddr=\"" + toAddress + "\"";
    window.open(link, '_blank');
}

function disableEnterKey(e) {
    if (event.which == 13 || event.keyCode == 13) {
        return false;
    }
}

function LogRxAdVideo(id, user) {
    PageMethods.set_path(getRootUrl());
    PageMethods.LogAdVideoClick(id, user);
}

function SelectSelectedPackage(item) {
    var radio = $(item).parent().siblings("input").get(0);
    $(radio).attr("checked", "checked");
    __doPostBack('ctl00$ContentPlaceHolder1$PackageSelector_Control$AddPackageLinkButton', '');
}

function RemoveSelectedPackage(item) {
    var radio = $(item).parent().siblings("input").get(0);
    $(radio).attr("checked", "checked");
    __doPostBack('ctl00$ContentPlaceHolder1$PackageSelector_Control$RemovePackageLinkButton', '');
}

function getRootUrl() {
    var url = window.location.href;
    var baseUrl = url.substring(0, url.indexOf('/', 23));
    return baseUrl + "/Default.aspx";
}

function getPlainRootUrl() {
    var url = window.location.href;
    var baseUrl = url.substring(0, url.indexOf('/', 23));
    return baseUrl;
}

/* List B Packages populate */
function ListBPackagesPopulate(substanceId, element) {
    var selector = "ListBPackages_" + substanceId;
    if (document.getElementById(selector) != null) {
        $(document.getElementById(selector)).remove();
    } else {
        PageMethods.set_path(getRootUrl());
        PageMethods.GetPackageBySubstanceIdListB(substanceId, getPlainRootUrl(),
            function(list) {
                $(element).parent().parent().after(list);
            });
    }
}

function showPackageVideos() {
    $("#ContentPlaceHolder1_DiseaseVideosDiv").css('display', 'block');
}

function ShowConsultancies(id, element) {
    var selector = "Consultancies_" + id;
    if (document.getElementById(selector) != null) {
        $(document.getElementById(selector)).remove();
    } else {
        PageMethods.set_path(getRootUrl());
        PageMethods.PopulateConsultancies(id, getPlainRootUrl(),
            function(list) {
                $(element).parent().parent().parent().parent().after(list);
            });
    }
}

function ShowDiseaseConsultancies(id) {
    var selector = "#Consultancies_" + id;
    if ($(selector).css('display') == 'none') {
        $(selector).show();
    } else {
        $(selector).hide();
    }
}

function ScrollDivToLetter(e) {
    var unicode = e.charCode ? e.charCode : e.keyCode;
    var letter = "";
    switch (unicode) {
        case 187: letter = "Ž"; break;
        case 107: letter = "Ž"; break;
        case 49: letter = "Ą"; break;
        case 50: letter = "Č"; break;
        case 51: letter = "Ę"; break;
        case 52: letter = "Ė"; break;
        case 53: letter = "Į"; break;
        case 54: letter = "Š"; break;
        case 55: letter = "Ų"; break;
        case 56: letter = "Ū"; break;
        default: letter = String.fromCharCode(e.charCode ? e.charCode : e.keyCode); break;
    }
    var obj = $('#NewsWriteTagsId').find('td > label').filter(function(index) {
        return $(this).text().search(letter) == 0;
    }).first();
    if (obj.text() != '') {
        $('#NewsWriteTagsId').scrollTop(0);
        $('#NewsWriteTagsId').scrollTop(
            obj.position().top - 877
        );
    }
}

function ShowBlogComments() {
    if ($('#BlogItemComments').css('display') == 'none') {
        $('#BlogItemComments').css('display', 'block');
    } else {
        $('#BlogItemComments').css('display', 'none');
    }
}

function DrawWeightGraph(chartTitle, height, days, user) {
    chartTitle = chartTitle + ' (' + days + ')';
    PageMethods.set_path(getRootUrl());
    PageMethods.GetUserWeightDate(user, days, function(rez) {
        if (rez != '') {
            var maxLine = [];
            var minLine = [];
            var max = 25 * ((height / 100) * (height / 100));
            var min = 18 * ((height / 100) * (height / 100));
            for (var i = 0; i < rez.length; i++) {
                maxLine.push([rez[i][0], max]);
                minLine.push([rez[i][0], min]);
            }
            $('#userChart').empty();
            var plot1 = $.jqplot('userChart', [rez, maxLine, minLine], {
                title: chartTitle,
                axes: {
                    xaxis: {
                        renderer: $.jqplot.DateAxisRenderer,
                        tickOptions: {
                            formatString: '%Y-%m-%d'
                        }
                    },
                    yaxis: {
                        tickOptions: {
                            formatString: '%.2f'
                        },
                        min: 0,
                        max: 250
                    }
                }, 
                fillBetween: {
                    series1: 1,
                    series2: 2,
                    color: "rgba(153, 235, 153, 0.5)",
                    baseSeries: 0,
                    fill: true
                },
                highlighter: {
                    show: true,
                    sizeAdjust: 10
                },
                cursor: {
                    show: false
                }, 
                legend: { show: true, location: 'ne' },
                series: [
                  {
                      color: '#CC0000',
                      lineWidth: 2,
                      markerOptions: { style: 'filleddimaond' },
                      label: ServerVariables.YourWeightTitle
                  },
                  {
                      color: '#00CC00',
                      lineWidth: 2,
                      showMarker: false,
                      label: ServerVariables.MaxWeightTitle
                  },
                  {
                      color: '#00A800',
                      lineWidth: 2,
                      showMarker: false,
                      label: ServerVariables.MinWeightTitle
                  }
              ]
            });
        }
    });
}

function showDrugsUsageCalendar(userId) {
    PageMethods.set_path(getRootUrl());
    PageMethods.GetUserDrugsUsage(userId, function(rez) {
        var myObject = eval('([' + rez + '])');
        $('#calendar').fullCalendar({
            header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' },
            buttonText: {
                today: ServerVariables._calendarToday,
                month: ServerVariables._calendarMonth,
                day: ServerVariables._calendaryDay,
                week: ServerVariables._calendarWeek
            },
            monthNames: [
                ServerVariables._calendarJanuary,
                ServerVariables._calendarFebruary,
                ServerVariables._calendarMarch,
                ServerVariables._calendarApril,
                ServerVariables._calendarMay,
                ServerVariables._calendarJune,
                ServerVariables._calendarJuly,
                ServerVariables._calendarAugust,
                ServerVariables._calendarSeptember,
                ServerVariables._calendarOctober,
                ServerVariables._calendarNovember,
                ServerVariables._calendarDecember],
            monthNamesShort: [
                ServerVariables._calendarJanuaryShort,
                ServerVariables._calendarFebruaryShort,
                ServerVariables._calendarMarchShort,
                ServerVariables._calendarAprilShort,
                ServerVariables._calendarMayShort,
                ServerVariables._calendarJuneShort,
                ServerVariables._calendarJulyShort,
                ServerVariables._calendarAugustShort,
                ServerVariables._calendarSeptemberShort,
                ServerVariables._calendarOctoberShort,
                ServerVariables._calendarNovemberShort,
                ServerVariables._calendarDecemberShort],
            dayNames: [
                ServerVariables._calendarSunday,
                ServerVariables._calendarMonday,
                ServerVariables._calendarTuesday,
                ServerVariables._calendarWednesday,
                ServerVariables._calendarThursday,
                ServerVariables._calendarFriday,
                ServerVariables._calendarSaturday],
            dayNamesShort: [
                ServerVariables._calendarSundayShort,
                ServerVariables._calendarMondayShort,
                ServerVariables._calendarTuesdayShort,
                ServerVariables._calendarWednesdayShort,
                ServerVariables._calendarThursdayShort,
                ServerVariables._calendarFridayShort,
                ServerVariables._calendarSaturdayShort],
            timeFormat: { '': 'H:mm' },
            axisFormat: 'H:mm',
            minTime: 0,
            maxTime: 24,
            allDayText: ServerVariables._calendarWholeDay,
            firstDay: 1,
            defaultView: 'agendaWeek',
            theme: true,
            events: myObject,
            eventClick: function(calEvent, jsEvent, view) {
                $(this).qtip("hide");
                var $radios = $('input:radio[name=used]');

                if (calEvent.className == 'calendarNot') {
                    $radios.filter('[value=0]').attr('checked', true);
                } else {
                    $radios.filter('[value=1]').attr('checked', true);
                }

                $('#ContentPlaceHolder1_calendarDialog').dialog({
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog("close");
                            var changed = $('input[name=used]:checked').val();
                            PageMethods.set_path(getRootUrl());
                            var gmtHours = -calEvent.start.getTimezoneOffset() / 60;
                            var newTime = new Date(calEvent.start.setHours(calEvent.start.getHours() + gmtHours));
                            if (calEvent.className == 'calendarNot' && changed == 1) {
                                PageMethods.SaveUserDrugUsed(calEvent.start, calEvent.id);
                                calEvent.backgroundColor = '#80E680';
                                calEvent.borderColor = '#80E680';
                                calEvent.className = 'calendarDone';
                            } else if (calEvent.className == 'calendarDone' && changed == 0) {
                                PageMethods.RemoveUserDrugUsed(calEvent.start, calEvent.id);
                                calEvent.backgroundColor = '#FF8080';
                                calEvent.borderColor = '#FF8080';
                                calEvent.className = 'calendarNot';
                            }
                            calEvent.start = new Date(calEvent.start.getFullYear(),
                                    calEvent.start.getMonth(),
                                    calEvent.start.getDate(),
                                    calEvent.start.getHours() - gmtHours,
                                    calEvent.start.getMinutes());
                            calEvent.end = new Date(calEvent.end.getFullYear(),
                                    calEvent.end.getMonth(),
                                    calEvent.end.getDate(),
                                    calEvent.end.getHours(),
                                    calEvent.end.getMinutes())
                            $('#calendar').fullCalendar('refetchEvents');
                        }
                    }
                });
            },
            eventRender: function(event, element) {
                element.qtip({
                    content: event.description
                });
            }
        });
    });
}
