﻿function getQueryStringParamValue(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function setQueryStringParamValue(url, parameterName, parameterValue) {
    var urlParts = url.split('?');
    var updatedUrl = urlParts[0];
    if (urlParts.length > 0) {
        var parameters = urlParts[1].split('&');
        updatedUrl += '?';
        for (var index = 0; index < parameters.length; index++) {
            if (index > 0) {
                updatedUrl += '&';
            }
            var paramSplits = parameters[index].split('=');
            var paramValue = paramSplits[1];
            if (paramSplits[0].toLowerCase() == parameterName.toLowerCase()) {
                paramValue = parameterValue;
            }
            updatedUrl += paramSplits[0] + '=' + paramValue;
        }
    }
    return updatedUrl;
}
function bindPrintURL(itemID) {
    var currentpageurl = window.location.href.toString();
    currentpageurl = currentpageurl.replace('#', '') + (currentpageurl.indexOf('?') == -1 ? '?' : '&') + 'cssclass=print';
    var updatedURL = setQueryStringParamValue(currentpageurl, "ItemID", itemID);
    if ($('#hlPrint').length > 0) {
        $('#hlPrint')[0].href = updatedURL;
    }
}

function printHtml(htmlContainerId, windowName, additionalInfo) {
    //additional info could be anything to write such as '<link href="/Style Library/Customer Core Styles/Styles/CSS/PrintRecipe.css" rel="Stylesheet" type="text/css" />'
    //set css to print media etc.        
    var htmlContainer = document.getElementById(htmlContainerId);
    if (htmlContainer == null) {
        return false;
    }

    if (windowName == undefined || windowName == null) {
        windowName = 'printWindow';
    }
    var printingWindow = window.open("about:blank");
    printingWindow.document.open();

    if (additionalInfo != undefined && additionalInfo != null) {
        printingWindow.document.write(additionalInfo);
    }

    printingWindow.document.write(htmlContainer.innerHTML);
    printingWindow.document.close();
    printingWindow.print();
}

/*------------Start Facebook functionality-----------------*/
var APPLICATION_ID = '271926969500513';
var accessToken = null;

var ownwerName, eventName, eventDescription, eventStartTime, eventEndTime, eventLocation, updated_Time, detailPageUrl;

function createEventInFacebook() {


    FB.getLoginStatus(function (response) {
        var accessToken = requestToken();
        if (!response.session) {
            login();
        }

        if (response.session != null) {
            var appAccessToken = response.session.access_token;
            // logged in and connected user, someone you know
            FB.api('me/events/', 'post', {
                "access_token": appAccessToken,
                "owner": {
                    "name": ownwerName
                },
                "name": eventName,
                "description": eventDescription,
                "start_time": eventStartTime,
                "end_time": eventEndTime,
                "location": eventLocation,
                "venue": "",
                "privacy": "OPEN",
                "updated_time": updated_Time
            }, function (response) {
            });
        }
    });

}

function requestToken() {
    if (window.location.hash.length == 0) {
        url = "https://www.facebook.com/dialog/oauth?client_id=" +
                     APPLICATION_ID + "&redirect_uri=" + window.location +
                     "&scope=create_event&response_type=token";
        window.open(url);
    }
    else {
        if (accessToken == null) {
            accessToken = window.location.hash.substring(1);
            accessToken = accessToken.substring(0, accessToken.indexOf('&expires_in='));
            graphUrl = "https://graph.facebook.com/me?" + accessToken +
                            "&callback=createEventInFacebook"

            //use JSON-P to call the graph
            var script = document.createElement("script");
            script.src = graphUrl;
            document.body.appendChild(script);
        }
    }

    return accessToken;
}

function login() {
    FB.api('/me', function (response) {
    });
}

function shareWithFacebook(url) {
    if (url == null) {
        u = location.href;
    }
    else {
        u = url;
    }
    t = document.title;
    window.open(
         'http://www.facebook.com/sharer.php?u=' +
         encodeURIComponent(u) + '&t=' + encodeURIComponent(t),
         'sharer',
         'toolbar=0,status=0,width=626,height=436');

    return false;
}
/*------------end Facebook functionality-----------------*/

/*-----function prepare json for all controls inside a specific control----*/
/*=====Generic Function Pass Control Id and Get its inout Control as json object '{controlname':controlValue}'====*/
function GetSubmitRequestData(MainDivCtrlId) {

    var returnVal = '';
    var inputItems = $('#' + MainDivCtrlId + ' :input');
    if (inputItems != null) {

        $(inputItems).each(function (index) {
            var jsonproperty = GetControlJSON(this);
            if (jsonproperty != '') {
                returnVal += jsonproperty;
            }
        });

        if (returnVal != '') {
            returnVal = returnVal + 'RequestType' + ":'SubmitForm'";  //.substr(0, returnVal.length - 1);
            returnVal = '{' + returnVal + '}';
            returnVal = eval('(' + returnVal + ')');
        }
    }

    return returnVal;
}

function GetControlJSON(ctrl) {

    var jsonNode = '';
    var element = $(ctrl);
    if (element.is(":radio") && element.is(":checked")) {
        jsonNode = element.attr('name') + ":'" + escape(element.val()) + "' ,";
    }
    else if (element.is(":checkbox")) {
        jsonNode = element.attr('name') + ":'" + escape(element.val()) + "' ,";
    }
    else if (element.is(":text")) {
        jsonNode = element.attr('name') + ":'" + escape(element.val()) + "' ,";
    }
    else if (element.is(":password")) {
        jsonNode = element.attr('name') + ":'" + escape(element.val()) + "' ,";
    }
    else if (element.is(":hidden")) {
        jsonNode = element.attr('name') + ":'" + escape(element.val()) + "' ,";

    }
    else if (element[0].type == "select-one") {

        jsonNode = element.attr('name') + ":'" + $(element).find("option:selected").val() + "' ,";
    }
    else if (element[0].type == "textarea") {

        jsonNode = element.attr('name') + ":'" + escape(element.val()) + "' ,";
    }

    return jsonNode;
}
/*-----function prepare json for all controls inside a specific control----*/
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";
    document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function dk_dsg_msd_Progress() {
    this.DisplayMessage = 'Loading please wait...';
    this.ImageUrl = '/Style%20Library/Customer Core Styles/Styles/Images/loader.gif';
    this.Container = '';
    this.top = 0;
    this.left = 0;

    this.triggerMonitoring = function () {
        $('body').click(function (e) {
            window.lastPageX = e.pageX;
            window.lastPageY = e.pageY;
        });

        $('body').keypress(function (e) {
            window.lastPageX = e.pageX;
            window.lastPageY = e.pageY;
        });
    };

    this.showProgress = function () {
        if (this.Container != null && this.Container != '') {
            var position = $(this.Container).position();
            var height = $(this.Container).height();
            var width = $(this.Container).width();

            $(this.Container).append($('<div id="divProgressContainer" class="dsg_sp_progressoverlaycontainer" ><div id="contantdiv" class="dsg_sp_controlcontainer"><img src="' + this.ImageUrl + '" alt="processing request" /><span>' + this.DisplayMessage + '</span></div></div>'));

            if (this.top != null && this.top > 0) {
                $(this.Container).find('#divProgressContainer').find('#contantdiv').css('top', this.top + 'px');
            }
            else {
                var pos = calculateCenter(this.Container, $(this.Container).find('#divProgressContainer'));
                if (pos != null && pos.length > 1) {
                    //top--pos[0]
                    //left--pos[1]
                    $(this.Container).find('#divProgressContainer').find('#contantdiv').css('top', pos[0] + 'px');
                }
            }

            if (this.left != null && this.left > 0) {
                $(this.Container).find('#divProgressContainer').find('#contantdiv').css('left', this.left + 'px');
            }
            else {
                var pos = calculateCenter(this.Container, $(this.Container).find('#divProgressContainer'));
                if (pos != null && pos.length > 1) {
                    //top--pos[0]
                    //left--pos[1]
                    $(this.Container).find('#divProgressContainer').find('#contantdiv').css('left', pos[1] + 'px');
                }
            }

            //$('#divProgressContainer').css('opacity', '0.5').css('background-color','black').css('position','aboslute').css('z-index','10000').css('top', position.top + 'px').css('left', position.left + 'px' ).css('width',width + 'px').css('height',height+'px');
            $(this.Container).find('#divProgressContainer').css('width', width + 'px').css('height', height + 'px');

        }
        else {
            $('body').append($('<div id="divProgressContainer" class="dsg_sp_progressoverlaycontainer"><div class="dsg_sp_controlcontainer"><img src="' + this.ImageUrl + '" alt="Processing"/><span >' + this.DisplayMessage + '</span></div></div>'));
            $('#divProgressContainer').css('top', window.lastPageY + 'px').css('left', window.lastPageX + 'px');
        }
    };

    this.hideProgress = function () {
        if (this.Container != null && this.Container != '') {
            $(this.Container).find("#divProgressContainer").remove();
        }
        else {
            $('body').find("#divProgressContainer").remove();
        }
    };

    this.setProgressContainerPosition = function (cTop, cLeft) {
        $(this.Container).find('#divProgressContainer').css({ top: cTop + 'px', left: cLeft + 'px' });
    };

    function calculateCenter(mainContainer, progressDiv) {
        try {
            var pos = [0, 0];
            var OverlayDivHeight = $(mainContainer).height();
            var OverlayDivwidth = $(mainContainer).width();
            var ProgressDivHeight = $(progressDiv).width();
            var ProgressDivWidth = $(progressDiv).height();

            if (OverlayDivHeight > 0) {
                pos[0] = (OverlayDivHeight / 2);
            }
            if (ProgressDivHeight > 0) {
                pos[0] = pos[0] - (ProgressDivHeight / 2);
            }
            pos[0] = pos[0] - 10;

            if (OverlayDivwidth > 0) {
                pos[1] = (OverlayDivwidth / 2) - 75;
            }

            return pos;
        }
        catch (error) {
            alert(error);
        }
    }
};


function getDanishDayName(dayNumber) {
    var dayName = '';
    switch (dayNumber) {
        case 0:
            dayName = 'søn';
            break;
        case 1:
            dayName = 'man';
            break;
        case 2:
            dayName = 'tir';
            break;
        case 3:
            dayName = 'ons';
            break;
        case 4:
            dayName = 'tor';
            break;
        case 5:
            dayName = 'fre';
            break;
        case 6:
            dayName = 'lør';
            break;
    }

    return dayName;
}
