/// <reference path="jQuery/jquery-1.6.1.js"/>

function pauseComputing(milliseconds)
{
    var InitMilliseconds = new Date().getMilliseconds();
    var WaitToMilliseconds = InitMilliseconds + milliseconds;

    var sum = InitMilliseconds;

    var preMilli = sum;

    while (sum <= WaitToMilliseconds)
    {
        var newMilli = new Date().getMilliseconds();

        if (newMilli < preMilli)
            sum = sum + ((newMilli + 1000 - preMilli));
        else
            sum = sum + ((newMilli - preMilli));

        preMilli = newMilli;
    }
}

function ShowAddressInfo(addressLink)
{
    var hiddenAddressLink = GetElementByTagAndSearchText("input", "hiddenAddressLinkField")

    if (hiddenAddressLink)
    {
        hiddenAddressLink.value = addressLink;

        ClickElementWithTagAndID("input", "hiddenAddressLinkButton");
    }
}

function EnableControl(enable, controlID)
{
    if (controlID)
        $get(controlID).disabled = !enable;
}

function DisableEnableAllControls(disable)
{
    try
    {
        if (disable && !allowDisableControls)
            return;
    }
    catch (e) { }

    var controlList = document.getElementsByTagName("input");

    for (var index = 0; index < controlList.length; index++)
    {
        if (controlList[index])
        {
            if (controlList[index].type == "image")
            {
                controlList[index].disabled = disable;
            }
            else if (controlList[index].type == "hidden")
            {
                // Do nothing!
            }
            else
            {
                controlList[index].disabled = disable;
            }
        }
    }

    controlList = document.getElementsByTagName("select");

    for (var index = 0; index < controlList.length; index++)
    {
        if (controlList[index])
            controlList[index].disabled = disable;
    }

    allControlsAreDisabled = disable;
}


function ShowTask(taskId)
{
    window.open('/tasks/ShowTask.aspx?TaskLink=' + taskId, 'ShowTask', 'toolbar=0, location=0, fullsize=0, status=0, menubar=0, scrollbars=1, resizable=0, screenX=10, screenY=10, top=10, left=10, width=900, height=710');
}

function OpenQhelp(url)
{
    var size = "toolbar=0, location=0, fullsize=0, status=0, menubar=0, scrollbars=1, resizable=1, screenX=10, screenY=10, top=10, left=10, width=1070, height=710";

    window.open(url, 'Qhelp', size);

}

function GetElementByTagAndSearchText(tag, searchText)
{
    var tagList = document.getElementsByTagName(tag);

    for (var index = 0; index < tagList.length; index++)
    {
        if (tagList[index].id)
        {
            if (tagList[index].id.indexOf(searchText) > -1)
            {
                return tagList[index];
            }
        }
        else if (tagList[index].name)
        {
            if (tagList[index].name.indexOf(searchText) > -1)
            {
                return tagList[index];
            }
        }
    }
    return null;
}

function GetChildElementBySearchText(parent, searchText)
{
    for (var index = 0; index < parent.childNodes.length; index++)
    {
        if (parent.childNodes[index].id)
        {
            if (parent.childNodes[index].id.indexOf(searchText) > -1)
            {
                return parent.childNodes[index];
            }
        }
        else if (parent.childNodes[index].name)
        {
            if (parent.childNodes[index].name.indexOf(searchText) > -1)
            {
                return parent.childNodes[index];
            }
        }
    }
    return null;
}

function CountSelectedItems(listboxid)
{
    var listbox = GetElementBy(listboxid);
    var selectCounter = 0;

    for (var index = 0; index < listbox.length; index++)
    {
        if (listbox[index].selected)
            selectCounter++;
    }
    return selectCounter;
}

function GetElementsByTagAndType(tag, typeName)
{
    var tagList = document.getElementsByTagName(tag);

    var resultList = new ArrayList();

    for (var index = 0; index < tagList.length; index++)
    {
        if (tagList[index].type == typeName)
        {
            resultList.Add(tagList[index]);
        }
    }

    return resultList.ToArray();
}

function GetElementByTagAndTypeAndSearchText(tag, typeName, searchText)
{
    var tagList = document.getElementsByTagName(tag);

    for (var index = 0; index < tagList.length; index++)
    {
        if (tagList[index].type)
        {
            if (tagList[index].type == typeName)
            {
                if (tagList[index].id)
                {
                    if (tagList[index].id.indexOf(searchText) > -1)
                    {
                        return tagList[index];
                    }
                }
                else if (tagList[index].name)
                {
                    if (tagList[index].name.indexOf(searchText) > -1)
                    {
                        return tagList[index];
                    }
                }
            }
        }
    }
    return null;
}

var tempIsChecked = null;
function CheckAllBy(checkAllBox, searchId)
{
    var checkboxArray = GetAllCheckboxArray();

    for (var index = 0; index < checkboxArray.length; index++)
    {
        if (checkboxArray[index].name.indexOf(searchId) > -1)
        {
            if (!checkboxArray[index].disabled)
            {
                if (checkAllBox)
                    checkboxArray[index].checked = checkAllBox.checked;
                else
                {
                    if (tempIsChecked == null)
                        tempIsChecked = !checkboxArray[index].checked;

                    checkboxArray[index].checked = tempIsChecked;
                }
            }
        }
    }

    tempIsChecked = null;
}

function GetAllCheckboxArray()
{
    var inputList = document.getElementsByTagName("input");

    var checkboxList = new ArrayList();

    for (var index = 0; index < inputList.length; index++)
    {
        if (inputList[index].type == "checkbox")
        {
            checkboxList.Add(inputList[index]);
        }
    }

    return checkboxList.ToArray();
}

function EnableDisableImageButtonID(imageButtonID, enable)
{
    EnableDisableImageButton(GetElementBy(imageButtonID), enable);
}

function EnableDisableImageButton(imageButton, enable)
{
    if (imageButton == null)
        return;

    var src = imageButton.src;

    if (enable && src.search(/_Disabled/gi) != -1)
    {
        src = src.replace(/_Disabled/i, '');

        imageButton.disabled = false;
        imageButton.style.cursor = 'auto';
    }
    else if (!enable && src.search(/_MouseOver/gi) != -1)
    {
        var indexOfPeriod = src.lastIndexOf(".");

        var fileName = src.substring(0, indexOfPeriod);
        fileName = fileName.replace(/_MouseOver/i, '');

        var extension = src.substring(indexOfPeriod);

        src = fileName + '_Disabled' + extension;

        imageButton.disabled = true;
        imageButton.style.cursor = 'default';
    }
    else if (!enable && src.search(/_Disabled/gi) == -1)
    {
        var indexOfPeriod = src.lastIndexOf(".");
        var fileName = src.substring(0, indexOfPeriod);
        var extension = src.substring(indexOfPeriod);

        src = fileName + '_Disabled' + extension;

        imageButton.disabled = true;
        imageButton.style.cursor = 'default';
    }

    imageButton.src = src;
}

function OnMouseOverHyperLink(hyperLink)
{
    if (hyperLink == null)
        return;

    for (var index = 0; index < hyperLink.childNodes.length; index++)
    {
        var child = hyperLink.childNodes[index];

        if (child.src)
        {
            OnMouseOver(child);
        }
    }
}

function OnMouseOutHyperLink(hyperLink)
{
    if (hyperLink == null)
        return;

    for (var index = 0; index < hyperLink.childNodes.length; index++)
    {
        var child = hyperLink.childNodes[index];

        if (child.src)
        {
            OnMouseOut(child);
        }
    }
}

function OnMouseOverID(imageButtonID)
{
    OnMouseOver(GetElementBy(imageButtonID));
}

function OnMouseOver(imageButton)
{
    if (imageButton == null)
        return;
    if (imageButton.disabled)
        return;

    var src = imageButton.src;

    if (src.search(/_MouseOver/gi) == -1 && src.search(/_Disabled/gi) == -1)
    {
        var indexOfPeriod = src.lastIndexOf(".");
        var fileName = src.substring(0, indexOfPeriod);
        var extension = src.substring(indexOfPeriod);

        src = fileName + '_MouseOver' + extension;
    }

    imageButton.src = src;
}

function OnMouseOutID(imageButtonID)
{
    OnMouseOut(GetElementBy(imageButtonID));
}

function OnMouseOut(imageButton)
{
    if (imageButton == null)
        return;
    if (imageButton.disabled)
        return;

    var src = imageButton.src;

    if (src.search(/_MouseOver/gi) != -1)
    {
        src = src.replace(/_MouseOver/i, '');
    }

    imageButton.src = src;
}

function GetElementBy(id)
{
    if (document.all)
        return document.all[id];
    else
        return document.getElementById(id);
}

function GetASCIIcode(e)
{
    e = (e) ? e : ((window.event) ? event : null);

    if (e)
    {
        return (e.charCode) ? e.charCode :
					((e.keyCode) ? e.keyCode :
						((e.which) ? e.which : 0));
    }
    else
        return 0;
}

function GetCharFromCode(charCode)
{
    return String.fromCharCode(charCode);
}

function UpdateTextSize(newSize)
{
    var divList = document.getElementsByTagName("div");

    for (var index = 0; index < divList.length; index++)
    {
        var name = divList[index].className;

        if (name == "articleBody" || name == "sFrameBoxRight")
            divList[index].style.fontSize = newsize + "px";

        if (name == "articleDateTime")
            divList[index].style.fontSize = (newsize - 2) + "px";

        if (name == "articleTitle")
            divList[index].style.fontSize = (newsize + 2) + "px";
    }
}

function ChangeFooterValue(text)
{
    var textBox = GetElementByTagAndSearchText("input", "hiddenUserIdFooter");

    if (textBox)
    {
        alert('ChangeFooterValue(text) = ' + text);

        textBox.value = text;

        DoPostBack();
    }
}

function FireQuserControlCustomEvent(text, elementId)
{
    var textBox = document.getElementById(elementId);

    textBox.value = text;

    DoPostBack();
}

function DoPostBack()
{
    var theform = document.getElementsByTagName("form")[0];

    theform.submit();
}

function DoSubmit()
{
    var theform = document.getElementsByTagName("form")[0];

    theform.submit();
}

function ClickElementWithTagAndID(tag, id)
{
    var element = GetElementByTagAndSearchText(tag, id);

    if (element)
    {
        jQuery(element).click();
    }
}

function ClickChildElementWithID(parent, childID)
{
    var element = GetChildElementBySearchText(parent, childID);

    if (element)
    {
        jQuery(element).click();
    }
}

function OnUnloadEventHandler()
{
    if (event.clientY < 0)
    {
        var checkBox = GetElementBy("hiddenCheckBoxUnloadEvent");

        checkBox.checked = true;

        DoPostBack();
    }
}

function DeleteTaskComment(commentId)
{
    var deleteBox = GetElementBy("hiddenDeleteCommentLink");

    deleteBox.value = commentId;
}

function UpdateTaskComment(commentId)
{
    var updateBox = GetElementByTagAndSearchText("input", "hiddenUpdateCommentLink");
    var newCommentBox = GetElementByTagAndSearchText("textarea", "txtAddComment");
    var commentBox = GetElementByTagAndSearchText("textarea", "CommentBox" + commentId);

    newCommentBox.value = commentBox.value;
    updateBox.value = commentId;
}

function OpenCloseDivElementBySpan(spanElement, openCloseDiv, hiddenInputId, openText, closeText)
{
    var hiddenSearch = GetElementByTagAndSearchText("input", hiddenInputId);

    if (hiddenSearch.value == openText)
    {
        OpenDivElement(openCloseDiv);
        hiddenSearch.value = closeText;
        spanElement.innerHtml = closeText + "Close" + hiddenSearch;
    }
    else
    {
        CloseDivElement(openCloseDiv);
        hiddenSearch.value = openText;
        spanElement.innerHtml = openText + "Open" + hiddenSearch;
    }
}

function OpenCloseDivElement(divId)
{
    var div = GetElementByTagAndSearchText("div", divId);

    if (div && div.style && div.style.display == "none")
    {
        OpenDivElement(divId);
    }
    else
    {
        CloseDivElement(divId);
    }
}

function OpenCloseDivElementBy(showBox, openCloseDiv, openText, closeText)
{
    var div = GetElementByTagAndSearchText("div", openCloseDiv);

    if (div)
    {
        if (showBox.value == openText)
        {
            OpenDiv(div);
            showBox.value = closeText;
        }
        else
        {
            CloseDiv(div);
            showBox.value = openText;
        }
    }
}

function OpenDiv(div)
{
    if (div && div.style)
        div.style.display = "inline";
}

function CloseDiv(div)
{
    if (div && div.style)
        div.style.display = "none";
}

function OpenDivElement(divId)
{
    var div = GetElementByTagAndSearchText("div", divId);

    if (div && div.style)
        div.style.display = "inline";
}

function CloseDivElement(divId)
{
    var div = GetElementByTagAndSearchText("div", divId);

    if (div && div.style)
        div.style.display = "none";
}


function OpenCloseDivElementAndSetHiddenText(divId, hiddenInputValueField, hiddenText)
{
    var div = GetElementByTagAndSearchText("div", divId);

    if (div && div.style && div.style.display == "none")
    {
        OpenDivElementAndSetHiddenText(divId, hiddenInputValueField, hiddenText);
    }
    else
    {
        CloseDivElementAndSetHiddenText(divId, hiddenInputValueField, "");
    }
}

function OpenDivElementAndSetHiddenText(divId, hiddenInputValueField, hiddenText)
{
    var div = GetElementByTagAndSearchText("div", divId);
    var hiddenInput = GetElementByTagAndSearchText("input", hiddenInputValueField);

    if (div && div.style)
        div.style.display = "inline";

    if (hiddenInput)
        hiddenInput.value = hiddenText;
}

function CloseDivElementAndSetHiddenText(divId, hiddenInputValueField, hiddenText)
{
    var div = GetElementByTagAndSearchText("div", divId);
    var hiddenInput = GetElementByTagAndSearchText("input", hiddenInputValueField);

    if (div && div.style)
        div.style.display = "none";

    if (hiddenInput)
        hiddenInput.value = hiddenText;
}

function SetDefaultCursor()
{
    var controlList = document.getElementsByTagName("*");

    for (var index = 0; index < controlList.length; index++)
    {
        if (controlList[index] && controlList[index].style)
        {
            controlList[index].style.cursor = "default";
        }
    }
}

//Hides all select boxes inside the given element
function HideSelectBoxes(parentElementId)
{
    var parentElement = document.getElementById(parentElementId);

    if (parentElement)
        HideSelectBoxesRecursive(parentElement);

}

//Hides all select boxes inside the given element
function HideSelectBoxesRecursive(parentElement)
{
    if (parentElement.nodeType == 1)
    {
        if (parentElement.tagName == "SELECT")
        {
            parentElement.style.display = 'none';
        }

        var childElement = parentElement.firstChild;

        while (childElement)
        {
            HideSelectBoxesRecursive(childElement);
            childElement = childElement.nextSibling;
        }
    }
}

//Shows all select boxes inside the given element
function ShowSelectBoxes(parentElementId)
{
    var parentElement = document.getElementById(parentElementId);

    if (parentElement)
        ShowSelectBoxesRecursive(parentElement);
}

//Shows all select boxes inside the given element
function ShowSelectBoxesRecursive(parentElement)
{
    if (parentElement.nodeType == 1)
    {
        if (parentElement.tagName == "SELECT")
        {
            parentElement.style.display = 'block';
        }

        var childElement = parentElement.firstChild;

        while (childElement)
        {
            ShowSelectBoxesRecursive(childElement);
            childElement = childElement.nextSibling;
        }
    }
}

//Disables form controls inside the given element, and dims the background
function DisableAndDim(parentElementId, backgroundCssClass)
{

    DisableFormControls(parentElementId);

    var parentElement = document.getElementById(parentElementId);


}




//Disables form controls inside the given element
function DisableFormControls(parentElementId)
{
    var parentElement = document.getElementById(parentElementId);

    if (parentElement)
        DisableFormControlsRecursive(parentElement);
}

//Disables form controls inside the given element
function DisableFormControlsRecursive(parentElement)
{
    if (parentElement.nodeType == 1)
    {

        if (parentElement.tagName == "SELECT")
            parentElement.disabled = true;


        if (parentElement.tagName == "INPUT")
            parentElement.disabled = true;


        var childElement = parentElement.firstChild;

        while (childElement)
        {
            DisableFormControlsRecursive(childElement);
            childElement = childElement.nextSibling;
        }
    }
}
//Enables form controls inside the given element, and undims the background
function EnableAndUnDim(parentElementId)
{
    EnableFormControls(parentElementId);

}

//Enables form controls inside the given element
function EnableFormControls(parentElementId)
{
    var parentElement = document.getElementById(parentElementId);

    if (parentElement)
        EnableFormControlsRecursive(parentElement);
}

//Enables form controls inside the given element
function EnableFormControlsRecursive(parentElement)
{
    if (parentElement.nodeType == 1)
    {

        if (parentElement.tagName == "SELECT")
            parentElement.disabled = false;


        if (parentElement.tagName == "INPUT")
            parentElement.disabled = false;


        var childElement = parentElement.firstChild;

        while (childElement)
        {
            EnableFormControlsRecursive(childElement);
            childElement = childElement.nextSibling;
        }
    }
}

function ShowMessageTextBox(form, text)
{
    if (form)
    {
        var messageBox = document.createElement('div');

        messageBox.innerText = text;

        messageBox.style.position = 'absolute';
        messageBox.style.left = '10px';
        messageBox.style.top = '10px';
        messageBox.style.height = '200px';
        messageBox.style.width = '200px';
        messageBox.style.backgroundColor = '#FFFFFF';
        messageBox.style.zIndex = 20000;

        form.appendChild(messageBox);
    }
}

function CountDownCallBack(searchButtonId)
{
    ResetCountDown();

    var searchButton = document.getElementById(searchButtonId);

    if (searchButton)
    {
        jQuery(searchButton).click();
    }
}


//function DisableButtonID(buttonId)
//{
//    var button = jQuery(buttonId);

//    if (button.length != 0)
//        DisableButton(button);

//    //    if (button.length != 0)
//    //        button.attr("disabled", "disabled");
//}

function DisableButton(button)
{
    var jButton = jQuery(button);

    // If the button is disabled the jButton.length is 0
    if (jButton.length != 0)
    {
//        if (jButton.is(":visible"))
//        {
//            var impersonatorButton = jQuery(jButton.clone());

//            impersonatorButton.attr("id", jButton.attr("id") + "___impersonator");

//            jQuery(jButton.parent).insertBefore(impersonatorButton);

//            jButton.hide();
//        }

        jButton.attr("disabled", "disabled");

        return false;
    }

    // if no jQuery object, try find the dom element
    var buttonControl = GetElementBy(button);

    if (buttonControl)
    {
//        if (buttonControl.style.display == '')
//        {
//            var impersonatorButton = buttonControl.cloneNode(false);

//            impersonatorButton.id = buttonControl.id + "___impersonator";
//            impersonatorButton.disabled = true;

//            buttonControl.parentNode.insertBefore(impersonatorButton, buttonControl);
//            buttonControl.style.display = 'none';
//        }

        buttonControl.disabled = false;
    }
}

//function EnableButtonID(buttonId)
//{
//    var button = jQuery(buttonId); //  GetElementBy(buttonId);

//    if (button.length != 0)
//        EnableButton(button);

//    //    if (button.length != 0)
//    //        button.removeAttr("disabled");
//}

function EnableButton(button)
{
    var jButton = jQuery(button);

    // If the button is disabled the jButton.length is 0
    if (jButton.length != 0 || jButton.is(":disabled"))
    {
        jButton.removeAttr("disabled");

//        if (!jButton.is(":visible"))
//        {
//            var impersonatorButton = jQuery(jButton.attr("id") + "___impersonator");

//            if (impersonatorButton.length != 0)
//                jQuery(impersonatorButton.parent).remove(impersonatorButton);

//            jButton.show();
//        }

        return false;
    }

    // if no jQuery object, try find the dom element
    var buttonControl = GetElementBy(button);

    if (buttonControl)
    {
//        if (buttonControl.style.display == 'none')
//        {
//            var impersonatorButton = $get(buttonControl.id + "___impersonator");

//            if (impersonatorButton != null)
//                impersonatorButton.removeNode(true);

//            buttonControl.style.display = '';
//        }

        buttonControl.disabled = false;
    }
}

//function DisableButton(button)
//{
//    if (button.style.display == '')
//    {
//        var impersonatorButton = button.cloneNode(false);

//        impersonatorButton.id = button.id + "___impersonator";
//        impersonatorButton.disabled = true;

//        button.parentNode.insertBefore(impersonatorButton, button);
//        button.style.display = 'none';
//    }
//}

//function EnableButton(button)
//{
//    if (button.style.display == 'none')
//    {
//        var impersonatorButton = $get(button.id + "___impersonator");

//        if (impersonatorButton != null)
//            impersonatorButton.removeNode(true);

//        button.style.display = '';
//    }
//}

function removeHTMLTags(input)
{
    var output = input.replace(/&(lt|gt);/g,
                    function (strMatch, p1)
                    {
                        return (p1 == "lt") ? "<" : ">";
                    });

    return output.replace(/<\/?[^>]+(>|$)/g, "");
}

function GetLastMonday(date)
{
    while (date.getDay() != 1)
    {
        // subtract a day from the date
        date.setDate(date.getDate() - 1);
    }

    return date;
}

function GetFirstDayInMonth(date)
{
    var newDate = new Date(date.getFullYear(), date.getMonth(), 1);

    return newDate;
}

function GetLastDayInMonth(date)
{
    var newDate = new Date(date.getFullYear(), date.getMonth(), 10);

    newDate = newDate.AddDays(30);

    newDate = GetFirstDayInMonth(newDate);

    return newDate.AddDays(-1);
}

function GetTimeDiff(date1, date2)
{
    dt1 = new Date(date1);
    dt2 = new Date(date2);

    var diff;

    if (dt1 > dt2)
    {
        diff = new Date(dt1 - dt2);
    }
    else
    {
        diff = new Date(dt2 - dt1);
    }

    return diff;
}

function GetHoursDiff(date1, date2)
{
    return MillisecondsToDurationInHours(GetTimeDiff(date1, date2).getTime());
}

//Convert milliseconds to 0000:00:00.00 [hhhh:mm:ss.cc] string format
function MillisecondsToDurationText(milliseconds)
{
    var hms = "";
    var dtm = new Date();

    dtm.setTime(milliseconds);

    var h = "000" + Math.floor(milliseconds / 3600000);
    var m = "0" + dtm.getMinutes();
    var s = "0" + dtm.getSeconds();
    var cs = "0" + Math.round(dtm.getMilliseconds() / 10);

    hms = h.substr(h.length - 4) + ":" + m.substr(m.length - 2) + ":";
    hms += s.substr(s.length - 2) + "." + cs.substr(cs.length - 2);

    return hms;
}

//Convert milliseconds to hours #0.00 [#h.mm] number format (Float)
function MillisecondsToDurationInHours(milliseconds)
{
    return milliseconds / 3600000;
}

function GetTimeText(hours)
{
    if (hours == 0.0)
        return " ";

    var preSign = "";

    if (hours < 0)
    {
        hours = Math.abs(hours);

        preSign = "-";
    }

    var seconds = hours * 3600;

    var h = Math.floor(seconds / 3600);
    var m = Math.round((seconds - (h * 3600)) / 60);

    if (m < 10)
        return preSign + h + ":0" + m;
    else
        return preSign + h + ":" + m;
}


function ConvertToDateTime(dateTimeString, usFormat)
{
    // Checks for the following valid date formats:
    // DD/MM/YY  DD-MM-YY  DD/MM/YYYY  DD-MM-YYYY And MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY

    // Checks if time is in HH:MM:SS format.
    // The seconds are optional.

    if (!IsDateTimeValid(dateTimeString, usFormat)) return null;

    var matchArray = dateTimeString.match(dateTimePat);

    // Parse date into variables
    var day = matchArray[1];
    var month = matchArray[3];
    var year = matchArray[4];

    if (usFormat)
    {
        day = matchArray[3];
        month = matchArray[1];
        year = matchArray[4];
    }

    var hour = matchArray[6];
    var minute = matchArray[7];
    var second = matchArray[9];

    var returnDate = new Date();

    returnDate = new Date(year, month - 1, day, hour, minute, second);

    return returnDate;
}

var dateTimePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})(\s|T)(\d{1,2}):(\d{2})(:(\d{2}))?$/; // requires 4 digit year

function IsDateTimeValid(dateTimeString, usFormat)
{
    // Checks for the following valid date formats:
    // DD/MM/YY  DD-MM-YY  DD/MM/YYYY  DD-MM-YYYY And MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY

    // Checks if time is in HH:MM:SS format.
    // The seconds are optional.

    var matchArray = dateTimeString.match(dateTimePat); // is the format ok?

    if (matchArray == null)
    {
        alert(dateTimeString + " Date is not in a valid format.")
        return false;
    }

    // Parse date into variables
    var day = matchArray[1];
    var month = matchArray[3];
    var year = matchArray[4];

    if (usFormat)
    {
        day = matchArray[3];
        month = matchArray[1];
        year = matchArray[4];
    }

    var hour = matchArray[6];
    var minute = matchArray[7];
    var second = matchArray[9];

    if (second == "") { second = null; }

    if (hour < 0 || hour > 23)
    {
        alert("Hour must be between 1 and 23.");
        return false;
    }
    if (minute < 0 || minute > 59)
    {
        alert("Minute must be between 0 and 59.");
        return false;
    }
    if (second != null && (second < 0 || second > 59))
    {
        alert("Second must be between 0 and 59.");
        return false;
    }

    if (month < 1 || month > 12)
    { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }
    if (day < 1 || day > 31)
    {
        alert("Day must be between 1 and 31.");
        return false;
    }
    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31)
    {
        alert("Month " + month + " doesn't have 31 days!")
        return false;
    }
    if (month == 2)
    { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));

        if (day > 29 || (day == 29 && !isleap))
        {
            alert("February " + year + " doesn't have " + day + " days!");
            return false;
        }
    }

    return true;
}

function IsDateValid(dateString, usFormat)
{
    // Checks for the following valid date formats:
    // DD/MM/YY  DD-MM-YY  DD/MM/YYYY  DD-MM-YYYY And MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY

    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // requires 4 digit year

    var matchArray = dateString.match(datePat); // is the format ok?

    if (matchArray == null)
    {
        alert(dateString + " Date is not in a valid format.")
        return false;
    }

    // Parse date into variables
    var day = matchArray[1];
    var month = matchArray[3];
    var year = matchArray[4];

    if (usFormat)
    {
        day = matchArray[3];
        month = matchArray[1];
        year = matchArray[4];
    }

    if (month < 1 || month > 12)
    { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }
    if (day < 1 || day > 31)
    {
        alert("Day must be between 1 and 31.");
        return false;
    }
    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31)
    {
        alert("Month " + month + " doesn't have 31 days!")
        return false;
    }
    if (month == 2)
    { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap))
        {
            alert("February " + year + " doesn't have " + day + " days!");
            return false;
        }
    }

    return true;
}

function IsTimeValid(timeString)
{
    // Checks if time is in HH:MM:SS format.
    // The seconds are optional.

    var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?$/;

    var matchArray = timeString.match(timePat);

    if (matchArray == null)
    {
        alert("Time is not in a valid format.");
        return false;
    }

    var hour = matchArray[1];
    var minute = matchArray[2];
    var second = matchArray[4];

    if (second == "") { second = null; }

    if (hour < 0 || hour > 23)
    {
        alert("Hour must be between 1 and 23.");
        return false;
    }
    if (minute < 0 || minute > 59)
    {
        alert("Minute must be between 0 and 59.");
        return false;
    }
    if (second != null && (second < 0 || second > 59))
    {
        alert("Second must be between 0 and 59.");
        return false;
    }

    return true;
}

function GetDateDifference(dateString1, dateString2)
{
    date1 = new Date();
    date2 = new Date();
    diff = new Date();

    if (isValidDate(dateform.firstdate.value) && isValidTime(dateform.firsttime.value))
    { // Validates first date 
        date1temp = new Date(dateform.firstdate.value + " " + dateform.firsttime.value);
        date1.setTime(date1temp.getTime());
    }
    else return false; // otherwise exits

    if (isValidDate(dateform.seconddate.value) && isValidTime(dateform.secondtime.value))
    { // Validates second date 
        date2temp = new Date(dateform.seconddate.value + " " + dateform.secondtime.value);
        date2.setTime(date2temp.getTime());
    }
    else return false; // otherwise exits

    // sets difference date to difference of first date and second date

    diff.setTime(Math.abs(date1.getTime() - date2.getTime()));

    timediff = diff.getTime();

    weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
    timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

    days = Math.floor(timediff / (1000 * 60 * 60 * 24));
    timediff -= days * (1000 * 60 * 60 * 24);

    hours = Math.floor(timediff / (1000 * 60 * 60));
    timediff -= hours * (1000 * 60 * 60);

    mins = Math.floor(timediff / (1000 * 60));
    timediff -= mins * (1000 * 60);

    secs = Math.floor(timediff / 1000);
    timediff -= secs * 1000;

    dateform.difference.value = weeks + " weeks, " + days + " days, " + hours + " hours, " + mins + " minutes, and " + secs + " seconds";

    return false;
}

Date.prototype.ToShortDateString = function (culture)
{
    var day = this.getDate();
    var month = this.getMonth() + 1;
    var year = this.getFullYear();

    var dayString = "";
    var monthString = "";

    if (day < 10)
        dayString = "0" + day;
    else
        dayString = day;

    if (month < 10)
        monthString = "0" + month;
    else
        monthString = month;


    var shortDateString = "";

    switch (culture)
    {
        case "da-DK":
            shortDateString = dayString + "-" + monthString + "-" + year;
            break;
        default:
            shortDateString = dayString + "-" + monthString + "-" + year;
            break;
    }

    return shortDateString;
}



Date.prototype.DummyDate = function ()
{
    return new Date(1980, 0, 1);
}

Date.prototype.EqualsDummyDate = function ()
{
    return (this < new Date(1980, 0, 2));
}

Date.prototype.AddMinutes = function (minutes)
{
    var returnDate = new Date(this);

    returnDate.setMinutes(this.getMinutes() + minutes);

    return returnDate;
}

Date.prototype.AddHours = function (hours)
{
    var returnDate = new Date(this);

    returnDate.setHours(this.getHours() + hours);

    return returnDate;
}

Date.prototype.AddDays = function (days)
{
    var returnDate = new Date(this);

    returnDate.setDate(this.getDate() + days);

    return returnDate;
}

Date.prototype.AddMonths = function (months)
{
    var returnDate = new Date(this);

    returnDate.setMonth(this.getMonth() + months);

    if (returnDate.getMonth() == this.getMonth())
    {
        if (months < 0)
        {
            returnDate = GetFirstDayInMonth(returnDate).AddDays(-1);
        }
    }
    else if (months > 0)
    {
        var prevMonth = (returnDate.getMonth() == 0) ? 11 : returnDate.getMonth() - 1;

        if (prevMonth != this.getMonth())
        {
            // 2 month ahead!

            returnDate = GetFirstDayInMonth(returnDate).AddDays(-1);
        }
    }

    if (this.getDate() == GetLastDayInMonth(this).getDate())
    {
        // Set the new month to the last day.
        returnDate = GetLastDayInMonth(returnDate);
    }

    return returnDate;
}

Date.prototype.GetHoursFromMidnight = function ()
{
    var midnightDate = new Date(this.getFullYear(), this.getMonth(), this.getDate());

    return GetHoursDiff(this, midnightDate) * -1;
}

Date.prototype.GetHoursToMidnight = function ()
{
    var midnightDate = new Date(this.getFullYear(), this.getMonth(), this.getDate());

    midnightDate = midnightDate.AddDays(1);

    return GetHoursDiff(this, midnightDate);
}

Date.prototype.GetMidnightDate = function ()
{
    var midnightDate = new Date(this.getFullYear(), this.getMonth(), this.getDate());

    return midnightDate;
}

Date.prototype.MinDate = function ()
{
    var minDate = new Date(1980, 1, 1);

    return minDate;
}

Date.prototype.MaxDate = function ()
{
    var maxDate = new Date(2099, 1, 1);

    return maxDate;
}


String.prototype.TryParseInt = function (defaultValue)
{
    if (this.length == 0)
        return 0;

    var startIndex = 0;

    for (var i = 0; i < this.length; i++)
    {
        if (this.charAt(i) != "0")
        {
            startIndex = i;
            break;
        }
    }

    var newString = this.substring(startIndex);

    var parseResult = parseInt(newString);

    if (parseResult == "NaN")
    {
        if (defaultValue == null)
            return 0;
        else
            return defaultValue;
    }

    return parseResult;
}

String.prototype.TryParseBool = function ()
{
    if (this == "True" || this == "true" || this == "1")
        return true;

    return false;
}

String.prototype.startsWith = function (prefix)
{
    return this.indexOf(prefix) === 0;
}



String.prototype.endsWith = function (suffix)
{
    return this.match(suffix + "$") == suffix;
}


// æ = %E6 ø = %F8 å = %E5 Æ = %C6 Ø = %D8 Å = %C5 

function ParameterValue(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 results[1];
}

function BaseUrl()
{
    var url = location.href;

    while (SlashCount(url) > 2)
    {
        url = url.substring(0, url.lastIndexOf('/'));
    }

    return url;
}

function SlashCount(str)
{
    try
    {
        return RegexCountMatches("/", str);
    }
    catch (e)
    {
        return 0;
    }
}

function LineBreakCount(str)
{
    try
    {
        return ((str.match(/[^\n]*\n[^\n]*/gi).length));
    }
    catch (e)
    {
        return 0;
    }
}


// Regular Expression Validator START

function CheckRegex(f, ptrn, txt)
{
    var pattern = f.elements[ptrn].value;
    var source = f.elements[txt].value;

    if (pattern.length == 0)
    {
        alert("You must enter a pattern to use.");
        return;
    }

    try
    {
        var matches = ExtractMatches(pattern, source, "g");

        //alert( "There were " + matches.length + " matches." ) ;
        if (matches.length == 1)
        {
            str = "<font color=green>There was " + matches.length + " match.</font>";
            for (var i = 0; i < matches.length; i++)
            {
                str += "<br />Match " + (i + 1) + ": " + matches[i].Text;
            }
            document.all['result'].innerHTML = str;
        } else if (matches.length > 0)
        {
            str = "<font color=green>There were " + matches.length + " matches.</font>";
            for (var i = 0; i < matches.length; i++)
            {
                str += "<br />Match " + (i + 1) + ": " + matches[i].Text;
            }
            document.all['result'].innerHTML = str;
        } else
        {
            document.all['result'].innerHTML = "<font color=red>There were " + matches.length + " matches.</font>";
        }
    }
    catch (ex)
    {
        alert(ex.message);
    }
}

function RegexCountMatches(pattern, text)
{
    try
    {
        var matches = ExtractMatches(pattern, text, "g");

        return matches.length;
    }
    catch (ex)
    {
        alert(ex.message);
    }
}

function ExtractMatches(pattern, text, ig)
{
    var reg = null;

    if (ig != null)
        reg = new RegExp(pattern, ig);
    else
        reg = new RegExp(pattern);

    var results = new Array();

    var arr = reg.exec(text)

    while (arr != null)
    {
        var match = new Match();
        match.Text = arr[0];

        for (var i = 1; i < arr.length; i++)
        {
            match.Groups[i - 1] = arr[i];
        }

        results[results.length] = match;
        arr = reg.exec(text);
    }

    return results;
}


function Match()
{
    this.Text = null;
    this.Groups = new Array();
}

// Regular Expression Validator END


function CountVisibleDataItems(dataItems)
{
    var count = 0;

    for (var i = 0; i < dataItems.length; i++)
    {
        if (dataItems[i].get_visible())
            count++;
    }

    return count;
}

function RadGridSetSelectedRow(radGrid, selectedIndex)
{
    //    // get_itemIndexHierarchical() start at 1 NOT 0 SOMETIME!!!
    //    --selectedIndex;

    try
    {
        if (radGrid.get_masterTableView().get_dataItems().length > selectedIndex)
        {
            radGrid.get_masterTableView().clearSelectedItems();

            if (radGrid.get_masterTableView().get_dataItems()[selectedIndex].get_visible())
            {
                radGrid.get_masterTableView().get_dataItems()[selectedIndex].set_selected(true);
                return;
            }
        }
    }
    catch (Error) { }
}

// Start Default RadComboBox OnClient Event functions **********************************************************

var RadComboBox_Requesting = false;

function RadComboBox_ItemsRequesting(sender, eventArgs)
{
    if (RadComboBox_Requesting)
    {
        eventArgs.set_cancel(true);
        return false;
    }
    else
    {
        RadComboBox_Requesting = true;
    }

    if (sender.get_text().length == 0)
    {
        eventArgs.set_cancel(true);
        RadComboBox_Requesting = false;
        return;
    }

    var context = eventArgs.get_context();

    if (context["NumberOfItems"] > 0 && sender.get_endOfItems())
    {
        eventArgs.set_cancel(true);
        RadComboBox_Requesting = false;
        return;
    }

    context["SearchText"] = sender.get_text();
}

function RadComboBox_SelectedIndexChanged(sender, eventArgs)
{
    if (eventArgs.get_item() == null)
    {
        return false;
    }

    var hasChanged = (GetLink(sender) != eventArgs.get_item().get_value());

    if (hasChanged)
    {
        SetLink(sender, eventArgs.get_item().get_value());
        SetText(sender, eventArgs.get_item().get_text());
    }

    RadComboBox_Requesting = false;
}

function RadComboBox_ItemsRequested(sender, eventArgs)
{
    RadComboBox_Requesting = false;

    if (sender.get_items().get_count() == 1)
    {
        sender.get_items().getItem(0).select();
    }
}

function RadComboBox_DropDownOpening(sender, eventArgs)
{
    if (sender.get_text().length == 0)
    {
        sender.set_text("*");
    }
    else if (sender.get_text().startsWith("Alle ") && sender.get_text().endsWith("..."))
    {
        sender.set_text("*");
    }
}

function RadComboBox_Focus(sender, eventArgs)
{
    SetText(sender, sender.get_text());
}

function RadComboBox_Blur(sender, eventArgs)
{
    var text = GetText(sender);

    if (text != null)
        sender.set_text(text);
}

// ComboBox.ID + '_Link' or '_Text'
// Used by CopyTask, DataImport, TimeSetting
// Get and Set Link or Text in RadComboBox Hidden
function GetLink(control)
{
    return GetHiddenValue(control, '_Link')
}

function GetText(control)
{
    return GetHiddenValue(control, '_Text')
}

function GetHiddenValue(control, postName)
{
    var hiddenControl = GetHiddenClientControl(control, postName);

    if (hiddenControl != null)
        return hiddenControl.value;
    else
        return "";
}

function SetLink(control, link)
{
    SetHiddenValue(control, '_Link', link)
}

function SetText(control, text)
{
    SetHiddenValue(control, '_Text', text)
}

function SetHiddenValue(control, postName, value)
{
    var hiddenControl = GetHiddenClientControl(control, postName);

    if (hiddenControl != null)
        hiddenControl.value = value;
}

function GetHiddenClientControl(control, postName)
{
    var hiddenControl = $get(GetControlID(control) + postName);

    if (hiddenControl == null)
    {
        hiddenControl = jQuery('<input type="hidden" id="' + GetControlID(control) + postName + '" />');

        hiddenControl.appendTo('body');

        hiddenControl = $get(GetControlID(control) + postName);
    }

    return hiddenControl;
}

function GetControlID(control)
{
    if (control._uniqueId == null)
        return "";

    var uniqueID = control._uniqueId;

    var lastIndexOfS = uniqueID.lastIndexOf("$") + 1;

    if (lastIndexOfS == 0)
        return "";

    return uniqueID.substring(lastIndexOfS);
}

// End RadComboBox functions **************************************************************

// Debug Logger
function DebugLog(message, header)
{
    if (jQuery('#DebugLog').length == 0)
    {
        jQuery('<div id="DebugLog"></div>').appendTo('body');
    }

    if (header != null)
    {
        jQuery('#DebugLog').append('<br/>' + header + '<br/>');
    }

    jQuery('#DebugLog').append(message + '<br/>');
}
