var radEditor;
var divEditor;
var divEditorContent;
var radCallbackId;
var radEditorDock;
var fixedToolbarAdded = false;
var fToolBar = null;
var EditorControlMap = Array();

window.status = '';
//Use this method to compare dates. The
//following variables can be used :  
//startDateFieldID, 
//startHourFieldID,
//startMinuteFieldID
//endDateFieldID -- Manditory,
//endHourFieldID, 
//endMinuteFieldID
function onResponseEnd(sender, arguments) {
    var dt1 = new Date()
    window.status = "Content saved at " + dt1.toLocaleTimeString();
};
function onRequestStart(sender, arguments) {
    window.status = "Saving content...";
};
function textCounter(field, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    }
}
function validateCheckboxes(sender, args) {
    var itemInGroupSelected = false;
    //var hiddenfield = document.getElementById(sender.getAttribute("controltovalidate")).value;
	
	var hiddenfield = document.getElementById(sender.controltovalidate).value;
	





    while (hiddenfield.indexOf("-") > -1) {
        hiddenfield = hiddenfield.replace('-', '_');
    }
    var guidArray = hiddenfield.split(',');
    var inputfields = document.getElementsByTagName('input');
    for (var i = 0; ((i < inputfields.length) && (itemInGroupSelected == false)); i++) {
        if (inputfields[i].type == "checkbox") {
            var checkboxInGroup = false;
            for (var l = 0; ((l < guidArray.length) && (checkboxInGroup == false)); l++) {
                if (inputfields[i].id.indexOf(guidArray[l]) > -1) {
                    checkboxInGroup = true;
                    if (inputfields[i].checked == true) {
                        itemInGroupSelected = true;
                    }
                }
            }
        }
    }
    if (itemInGroupSelected) {
        args.IsValid = true;
    }
    else {
        args.IsValid = false;
    }
}
function AddZeros(number, requiredLength) {
    number = number.toString();
    while (number.length < requiredLength) {
        number = "0" + number;
    }
    return number;
}
function fileDownload(applicationPath, fieldInstanceId, coState) {
    var fileDownloadURL = applicationPath + "/admin/filedownload.aspx?fieldId=" + fieldInstanceId;
    fileDownloadURL = fileDownloadURL.replace("//", "/");
    if (coState != undefined)
        fileDownloadURL = fileDownloadURL + "&coState=" + coState;
    window.open(fileDownloadURL, "workflowpopup", "directories=no,height=100,width=100,location=no,menubar=no,resizable=yes,status=no,titlebar=no,toolbar=no,scrollbars=no");
}

function datesValidation(source, clientside_arguments) {
    var localDateFormat = "yyyy mm dd HH:mm:ss"
    if (typeof (dateFormat) != "undefined") {
        localDateFormat = dateFormat;
        if ((localDateFormat.indexOf("H") == -1) && (localDateFormat.indexOf("h") == -1)) {
            localDateFormat = localDateFormat + " HH:mm:ss";
        }
    }

    var startDate = "";
    var endDate = "";
    var startHour;
    var startMinute;
    var endHour;
    var endMinute;
    //---------------------------------------------------------------
    //StartDate
    if (typeof startDateFieldID != "undefined") {
        var startDateField = document.getElementById(startDateFieldID + "_dateInput_text");
        startDate = startDateField.value;
    }
    //else
    //    startDate = (new Date()).getFullYear() + "/" + ((new Date()).getMonth()+1) + "/" + (new Date()).getDate();
    //EndDate 
    var endDateField;
    if (typeof endDateFieldID != "undefined") {
        endDateField = document.getElementById(endDateFieldID + "_dateInput_text");
        endDate = endDateField.value;
    }
    else {
        clientside_arguments.IsValid = true;
        return;
    }
    //StartHour
    if (typeof startHourFieldID != "undefined") {
        var startHourField = document.getElementById(startHourFieldID);
        startHour = startHourField.item(startHourField.selectedIndex).text;
    }
    else
        startHour = "00";
    //StartMinute
    if (typeof startMinuteFieldID != "undefined") {
        var startMinuteField = document.getElementById(startMinuteFieldID);
        startMinute = startMinuteField.item(startMinuteField.selectedIndex).text;
    }
    else
        startMinute = "00";
    //EndHour
    if (typeof endHourFieldID != "undefined") {
        var endHourField = document.getElementById(endHourFieldID);
        endHour = endHourField.item(endHourField.selectedIndex).text;
    }
    else
        endHour = "00";
    //EndMinute
    if (typeof endMinuteFieldID != "undefined") {
        var endMinuteField = document.getElementById(endMinuteFieldID);
        endMinute = endMinuteField.item(endMinuteField.selectedIndex).text;
    }
    else
        endMinute = "00";

    var startDateTime
    if (startDate == "") {
        startDateTime = DateTimeParseExact((new Date()).getFullYear() + "/" + ((new Date()).getMonth() + 1) + "/" + (new Date()).getDate() + " " + startHour + ":" + startMinute + ":00", "yyyy/MM/dd HH:mm:ss");
    }
    else {
        startDateTime = DateTimeParseExact(startDate.toString() + " " + startHour + ":" + startMinute + ":00", localDateFormat)
    }
    var endDateTime = DateTimeParseExact(endDate.toString() + " " + endHour + ":" + endMinute + ":00", localDateFormat)

    //var startDateTime = new Date(startDate.toString() + " " + startHour + ":" + startMinute+":00");
    //var endDateTime =   new Date(endDate.toString() + " " + endHour + ":" + endMinute+":00");
    if (endDateTime < startDateTime) {
        endDateField.focus();
        clientside_arguments.IsValid = false;
    }
    else {
        clientside_arguments.IsValid = true;
    }
    //---------------------------------------------------------------
    //StartDate
    if (typeof startDateFieldID != "undefined") {
        var startDateField = document.getElementById(startDateFieldID + "_dateInput_text");
        startDate = startDateField.value;
    }
    else
        startDate = ((new Date()).getDate() + " " + monthNames[(new Date()).getMonth()] + " " + (new Date()).getYear()) //(new Date()).getFullYear() + "/" + AddZeros(((new Date()).getMonth()+1),2) + "/" + AddZeros((new Date()).getDate(),2);
    //EndDate 
    var endDateField = document.getElementById(endDateFieldID + "_dateInput_text");
    endDate = endDateField.value;
    //StartHour
    if (typeof startHourFieldID != "undefined") {
        var startHourField = document.getElementById(startHourFieldID);
        startHour = startHourField.item(startHourField.selectedIndex).text;
    }
    else
        startHour = "00";
    //StartMinute
    if (typeof startMinuteFieldID != "undefined") {
        var startMinuteField = document.getElementById(startMinuteFieldID);
        startMinute = startMinuteField.item(startMinuteField.selectedIndex).text;
    }
    else
        startMinute = "00";
    //EndHour
    if (typeof endHourFieldID != "undefined") {
        var endHourField = document.getElementById(endHourFieldID);
        endHour = endHourField.item(endHourField.selectedIndex).text;
    }
    else
        endHour = "00";
    //EndMinute
    if (typeof endMinuteFieldID != "undefined") {
        var endMinuteField = document.getElementById(endMinuteFieldID);
        endMinute = endMinuteField.item(endMinuteField.selectedIndex).text;
    }
    else
        endMinute = "00";


    var startDateTime;
    var endDateTime;

    startDateTime = new Date(startDate + " " + startHour + ":" + startMinute + ":00");

    endDateTime = new Date(endDate + " " + endHour + ":" + endMinute + ":00");
    if (endDateTime < startDateTime) {
        endDateField.focus();
        clientside_arguments.IsValid = false;
    }
    else {
        clientside_arguments.IsValid = true;
    }
}

//Used for text area maxLength
function textboxMultilineMaxNumber(txt, maxLen) {
    try {
        if (maxLen > 0 && txt.value.length > (maxLen - 1)) {
            var cont = txt.value;
            txt.value = cont.substring(0, (maxLen - 1));
            return false;
        };
    } catch (e) {
    }
}

//Specifically for checking Live/Archive dates
function workflowDatesValidation(source, clientside_arguments) {
    var localDateFormat = "yyyy mm dd HH:mm:ss"
    if (typeof (dateFormat) != "undefined") {
        localDateFormat = dateFormat;
        if ((localDateFormat.indexOf("H") == -1) && (localDateFormat.indexOf("h") == -1)) {
            localDateFormat = localDateFormat + " HH:mm:ss";
        }
    }
    var startDate = "";
    var endDate = "";
    var startHour;
    var startMinute;
    var endHour;
    var endMinute;
    if (typeof workflowNeverArchiveFieldID != "undefined") {
        var workflowNeverArchiveField = document.getElementById(workflowNeverArchiveFieldID);
        if (workflowNeverArchiveField.checked) {
            clientside_arguments.IsValid = true;
            return;
        }
    }

    //StartDate
    if (typeof workflowStartDateFieldID != "undefined") {
        var startDateField = document.getElementById(workflowStartDateFieldID + "_dateInput_text");
        startDate = startDateField.value;
    }
    //else
    //    startDate = (new Date()).getFullYear() + "/" + ((new Date()).getMonth()+1) + "/" + (new Date()).getDate();
    //EndDate 
    var endDateField;
    if (typeof workflowEndDateFieldID != "undefined") {
        endDateField = document.getElementById(workflowEndDateFieldID + "_dateInput_text");
        endDate = endDateField.value;
    }
    else {
        clientside_arguments.IsValid = true;
        return;
    }
    //StartHour
    if (typeof workflowStartHourFieldID != "undefined") {
        var startHourField = document.getElementById(workflowStartHourFieldID);
        startHour = startHourField.item(startHourField.selectedIndex).text;
    }
    else
        startHour = "00";
    //StartMinute
    if (typeof workflowStartMinuteFieldID != "undefined") {
        var startMinuteField = document.getElementById(workflowStartMinuteFieldID);
        startMinute = startMinuteField.item(startMinuteField.selectedIndex).text;
    }
    else
        startMinute = "00";
    //EndHour
    if (typeof workflowEndHourFieldID != "undefined") {
        var endHourField = document.getElementById(workflowEndHourFieldID);
        endHour = endHourField.item(endHourField.selectedIndex).text;
    }
    else
        endHour = "00";
    //EndMinute
    if (typeof workflowEndMinuteFieldID != "undefined") {
        var endMinuteField = document.getElementById(workflowEndMinuteFieldID);
        endMinute = endMinuteField.item(endMinuteField.selectedIndex).text;
    }
    else
        endMinute = "00";

    var startDateTime
    if (startDate == "") {
        startDateTime = DateTimeParseExact((new Date()).getFullYear() + "/" + ((new Date()).getMonth() + 1) + "/" + (new Date()).getDate() + " " + startHour + ":" + startMinute + ":00", "yyyy/MM/dd HH:mm:ss");
    }
    else {
        startDateTime = DateTimeParseExact(startDate.toString() + " " + startHour + ":" + startMinute + ":00", localDateFormat)
    }
    var endDateTime = DateTimeParseExact(endDate.toString() + " " + endHour + ":" + endMinute + ":00", localDateFormat)

    //var startDateTime = new Date(startDate.toString() + " " + startHour + ":" + startMinute+":00");
    //var endDateTime =   new Date(endDate.toString() + " " + endHour + ":" + endMinute+":00");
    if (endDateTime < startDateTime) {
        endDateField.focus();
        clientside_arguments.IsValid = false;
    }
    else {
        clientside_arguments.IsValid = true;
    }
}


//Use this method to debug an object's properties
function debug(obj, root) {
    var debugString = "";
    var counter = 0;
    var lines = 0;
    var charIndex = 0;
    for (property in obj) {

        debugString += root + "." + property + "=" + obj[property] + "\n";
        counter++;
        while (debugString.indexOf("\n", charIndex) > -1) {
            lines++;
            charIndex = debugString.indexOf("\n", charIndex) + 1;
        }
        if (lines > 20) {
            alert(debugString);
            counter = 0;
            debugString = "";
        }
        lines = 0;
        charIndex = 0;
    }
    alert(debugString);
}


/* This function needs to be called with a small delay after the page loads, to make sure that the fixed toolbar placeholder is created */
function MoveFixedToolbar() {
    //alert(fToolBar);
    if (fToolBar == null) {
        //Get reference to any of the editor objects on the page.
        var editor = radEditor.Id;

        //Get a reference to the Fixed placeholder object and move it to its new location
        //var fixedToolbar1 = document.getElementById("RadEditorRelativeToolbarHolder"); 
        fToolBar = document.getElementById("RadEditorRelativeToolbarHolder");
        //alert(fToolBar);
        //fToolBar.className = "";
        if (fToolBar.parentNode.Id != "div_toolbar") {
            fToolBar.parentNode.removeChild(fToolBar);
            fixedToolbarAdded = true;
            var newPlaceholder = document.getElementById("div_toolbar");
            newPlaceholder.appendChild(fToolBar);
        }
    }

    //window.setTimeout(focusEditor, 300); 
    //alert(newPlaceholder.innerHTML);      
}

function focusEditor() {
    window.focus();
    radEditor.SetFocus();
    radEditorDock.Show();
    radEditorDock.Hide();
    radEditorDock.Show();
}

var divHid;
var radEditId;
var timerToolbar;

function cancelEditor() {
    return OnClientCancel(radEditor);
}

function setEditorVisible(divEditorId, divContentId, divOriginalContentId, editorId, callbackId, pencilId) {
    radCallbackId = callbackId;
    radEditor = GetRadEditor(editorId);
    var cArea = radEditor.GetContentArea();
    var dddd = document.getElementById(radEditor.Id.replace('editor1', 'divContent'));
    var topBar = document.getElementById(radEditor.Id.replace('ctl001', 'Topctl00'));
    var actualContent = document.getElementById(radEditor.Id.replace('ctl001', 'RadEContentHolderctl00'));
    ToggleVisibility(topBar);
    radEditor.SetSize(dddd.offsetWidth, dddd.offsetHeight + 55);
    //divEditor = divEditorId;
    //divEditorContent = divContentId;
    var divOriginalContent = document.getElementById(divOriginalContentId)
    divOriginalContent.value = radEditor.GetHtml();

    divOriginalContent.style.display = "none";
    ShowHideObjects(divEditorId, divContentId);

    //actualContent.focus();

    divHid = document.createElement('div');
    divHid.Id = "divHid";
    divHid.innerHTML = "aaa";
    document.getElementById('dHid').appendChild(divHid);
    document.getElementById(pencilId).style.display = "none";

    //window.setTimeout("focusEditor()", 50)
}

function focusEditor() {
    radEditor.SetFocus();
}

function FindEditorControlMapIndex(editorId) {
    var index = -1;
    for (var i = 0; ((i < EditorControlMap.length) && (index == -1)); i++) {
        if (EditorControlMap[i][0] == editorId) {
            index = i;
        }
    }
    return index;
}

function divEditorID(index) { return EditorControlMap[index][1]; }
function divContentID(index) { return EditorControlMap[index][2]; }
function divOriginalContentID(index) { return EditorControlMap[index][3]; }
function editPenID(index) { return EditorControlMap[index][4]; }

function OnClientCancel(editor) {
    var ControlMapIndex = FindEditorControlMapIndex(editor.Id);
    var close = true;
    radEditor = GetRadEditor(editor.Id);
    divOriginalContent = document.getElementById(divOriginalContentID(ControlMapIndex));
    var originalData = divOriginalContent.value; //document.getElementById(divOriginalContentID(ControlMapIndex)).innerHTML;
    if (originalData != radEditor.GetHtml()) {
        close &= confirm('You have unsaved changes. Click OK to lose these changes or Cancel to continue editing.');
    }
    if (close) {
        document.getElementById(editPenID(ControlMapIndex)).style.display = "block";
        if (isFullScreen) {
            radEditorScreen = GetRadEditor(editor.Id);
            radEditorScreen.Fire("ToggleScreenMode");
        }
        window.focus();
        ShowHideObjects(divContentID(ControlMapIndex), divEditorID(ControlMapIndex));
        radEditor.SetHtml(divOriginalContent.value);
        radEditor = null;
        divEditor = null;
        //hide editor toolbar
        try {
            document.getElementById(divContentID(ControlMapIndex)).click();
        }
        catch (e) { }
        divEditorContent = null;
        radCallbackId = null;
        originalData = null;
    }
    CheckinContent();
    return false;
}

function OnClientSubmit(editor) {
    radEditor = null;
    divEditor = null;
    divEditorContent = null;
    radCallbackId = null;
    CheckinContent();
}
function resizeContentArea(editor) {
    if (editor.InitialHeight == -1) {
        editor.InitialHeight = editor.Document.body.clientHeight;
    }

    var ie = document.all ? true : false;
    var oDoc = editor.Document;
    var targetHeight = ie ? oDoc.body.scrollHeight : oDoc.documentElement.scrollHeight;

    if (targetHeight > editor.InitialHeight) {
        var theIFrame = document.getElementById("RadEContentIframe" + editor.Id);
        theIFrame.style.height = parseInt(targetHeight) + "px";
        if (!ie) editor.SetSize(editor.GetWidth(), targetHeight); //FireFox bug, TD does not decrease height   

    }
}

var theEditor;

function OnClientLoad(editor) {

    var iframe = document.getElementById(editor.Id);
    var newPlaceholder = document.getElementById("div_toolbar2");
    theEditor = editor;


    var theIFrame = document.getElementById("RadEContentIframe" + editor.Id);
    theIFrame.allowTransparency = true;

    var theMainEditorTable = document.getElementById("RadEWrapper" + editor.Id);

    var theParentEl = theMainEditorTable.parentNode.parentNode;
    var theContentArea = editor.GetContentArea();

    editor.AttachEventHandler("onkeyup",
        function(e) {
            setSizeAfterEdit(editor);

        }
    );
    editor.AttachEventHandler("onkeydown",
        function(e) {
            setSizeAfterEdit(editor);
        }
    );
    editor.AttachEventHandler("blur", function() {
        restorePoint = editor.CreateRestorePoint();
    });

    var resizeFnRef = function anon() { setSizeAfterEdit(editor) };
    editor.AttachEventHandler("RADEVENT_SEL_CHANGED", resizeFnRef)

    // This removes scrollbars

    for (var attr in theParentEl.currentStyle) {
        theContentArea.style[attr] = theParentEl.currentStyle[attr];
    }



    /*telerik code */

    editor.InitialHeight = -1;

    editor.GetContentArea().style.overflow = "hidden";
    editor.Document.body.scroll = "no";

    var resizeFnRef = function anon() { resizeContentArea(editor) };
    //NdK - Commented out on 2008-04-25 to fix funny behaviour in editor     
    //editor.AttachEventHandler("RADEVENT_SEL_CHANGED", resizeFnRef);

    editor.AttachEventHandler("keydown", resizeFnRef)

}
var timerPaste;
var radEditorPaste;
var restorePoint = null;
function OnClientCommandExecuted(editor, commandName, oTool) {
    if ("InsertTable" == commandName) {
        //get a reference to the editor content area using the GetContentArea method
        var cArea = editor.GetContentArea();
        //get all TABLE elements in the content area
        var tables = cArea.getElementsByTagName("TABLE");
        for (var i = 0; i < tables.length; i++) {
            var oTable = tables[i];
            //Check if this table existed before the InsertTable executed.
            if (!IsObjectInArray(oTable, curTables)) {
                //set the table widht to 100%
                oTable.style.width = "100%";
            }
        }
    }

    switch (commandName) {

        case 'Paste':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'PasteFromWord':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'PasteAsHtml':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'PastePlainText':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'Cut':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'ToggleScreenMode':
            {
                if (isFullScreen)
                    isFullScreen = false;
                else
                    isFullScreen = true;
            }
        case 'Undo':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }
        case 'Redo':
            {
                radEditorPaste = GetRadEditor(editor.Id);
                timerPaste = window.setInterval(setSizeAfterPaste, 500);
                break;
            }

    }
}
//-------------------------------------------------------------------------
function setSizeAfterPaste() {
    divHid.innerHTML = radEditorPaste.GetHtml();

    if (!isFullScreen)
        radEditorPaste.SetSize(radEditorPaste.Width, divHid.offsetHeight + 60);

    window.clearInterval(timerPaste);
    divHid.innerHTML = "";
}
//-------------------------------------------------------------------------
function setSizeAfterEdit(editor) {
    radEditor = GetRadEditor(editor.Id);
    if (divHid == null)//When the page first loads, then then divHid does not exist yet.
    {
        return
    }
    divHid.innerHTML = radEditor.GetHtml();

    if (!isFullScreen)
        radEditor.SetSize(radEditor.Width, divHid.offsetHeight + 60);
    divHid.innerHTML = "";
}
//-------------------------------------------------------------------------
function ToggleVisibility(fieldId) {
    try {
        if (document.getElementById(fieldId)) {
            document.getElementById(fieldId).style.display =
	            document.getElementById(fieldId).style.display == "block" ? "none" : "block";
        }
    }
    catch (error) {
        if (document.getElementById(fieldId)) {
            document.getElementById(fieldId).style.display =
	            document.getElementById(fieldId).style.display == "block" ? "none" : "block";
        }
    }
}
//show and hide objects by ID
function ShowHideObjects(fieldShow, fieldHide) {
    try {
        if (document.getElementById(fieldShow))
        { document.getElementById(fieldShow).style.display = "block"; }
        if (document.getElementById(fieldHide))
        { document.getElementById(fieldHide).style.display = "none"; }
    }
    catch (error) {
        if (document.getElementById(fieldShow))
        { document.getElementById(fieldShow).style.display = "block"; }
        if (document.getElementById(fieldHide))
        { document.getElementById(fieldHide).style.display = "none"; }
    }
}

function launchWin(url, w, h) {
    return launchWin(url, w, h, "RadWindow1");
}
function launchWin(url, w, h, windowName) {
    windowName = windowName + "";
    if (windowName == "undefined")
        windowName = "RadWindow1";

    var oManager = GetRadWindowManager();
    var oWnd = oManager.GetWindowByName(windowName);
    oWnd.SetSize(w, h);
    oWnd.SetUrl(url);
    oWnd.Show();
    oManager = null;
    oWnd = null;
    return false;
}
function launchRadWindow(url, w, h, windowName, windowTitle) {
    windowName = windowName + "";
    if (windowName == "undefined")
        windowName = "RadWindow1";

    if (windowTitle == "undefined")
        windowTitle = "Page Properties";

    var oManager = GetRadWindowManager();
    var oWnd = oManager.GetWindowByName(windowName);
    oWnd.SetSize(w, h);
    oWnd.SetTitle(windowTitle);
    oWnd.SetUrl(url);
    oWnd.Show();
    oManager = null;
    oWnd = null;
    return false;
}
function CloseRadWindow() {
    if (GetRadWindow() != null) {
        GetRadWindow().Close();
    }
}
//-------------------------------------------------------------------------
function CloseWindowRefresh() {
    CloseRadWindow();
    GetRadWindow().BrowserWindow.document.location.href = GetRadWindow().BrowserWindow.document.location.href + "&refresh=true";
}

function scrollableWindowOpen(url, width, height) {
    var winl = (screen.width - width) / 2;
    var wint = (screen.height - height) / 2;
    window.open(url, '_blank', 'directories=no, fullscreen=no, height=' + height + ', width=' + width + ', location=no, menubar=no, resizable=no, scrollbars=yes, status=no, titlebar=no, toolbar=no, top=' + wint + ', left=' + winl + '', 'bReplace=false');
}
function clickButton(e, buttonid) {
    var bt = document.getElementById(buttonid);
    if (typeof bt == 'object') {
        if (is_ie) {
            if (event.keyCode == 13) {
                bt.click();
                return false;
            }
        }
        if (is_nav) {
            if (e.keyCode == 13) {
                bt.click();
                return false;
            }
        }
    }
}
//function to add events to be fired when a page loads
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function AddAltTagToFileInput(radUpload, arg) {
    try {
        var file = GetFile(arg.FileInputField.value);
        arg.FileInputField.alt = file;
        arg.FileInputField.title = file;
    }
    catch (err) { }
}
function GetFile(obj) {
    var filePath;
    var filePathArray;
    var file;
    filePath = obj;
    filePathArray = filePath.split("\\");
    file = filePathArray[filePathArray.length - 1];
    return file;
}
function ValidateRadioButtons(validator, args) {
    var txtValidate = document.getElementById(validator.attributes["targetcontrol"].nodeValue);
    if (txtValidate.value.length == 0) {
        args.IsValid = false;
        var radio = document.getElementById(validator.attributes["focuscontrol"].nodeValue);
        radio.focus();
    }
    else {
        args.IsValid = true;
    }
}
function ValidateManditoryUpload(validator, args) {
    var radUpload = GetRadUpload(validator.attributes["targetcontrol"].nodeValue);
    var fileInputs = radUpload.GetFileInputs();
    var emptyFieldFlag = false;
    for (var i = 0; i < fileInputs.length; i++) {
        //If at least one empty input field exists   
        //the emptyFieldFlag is being raised   
        if (fileInputs[i].value.length == 0) {
            emptyFieldFlag = true;
            fileInputs[i].focus();
            break;
        }
    }
    //Checks whether there is an empty field   
    if (emptyFieldFlag) {
        args.IsValid = false;
        //radUpload.focus();
    }
    else args.IsValid = true;
}
function ValidateFileExtention(source, arguments) {
    var radUpload = GetRadUpload(source.attributes["targetcontrol"].nodeValue);
    arguments.IsValid = radUpload.ValidateExtensions();
}

function DateTimeParseExact(sourceDate, sourceDateFormat) {

    var formatIndex = 0;
    var dateIndex = 0;
    var testString;
    var date = new Date();
    var monthsLong = ";January;February;March;April;May;June;July;August;September;October;November;December";
    var monthsShort = ";Jan;Feb;Mar;Apr;May;Jun;Jul;Aug;Sep;Oct;Nov;Dec";
    var daysLong = ";Monday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday";
    var daysShort = ";Mon;Tue;Wed;Thu;Fri;Sat;Sun";

    var year = -1;
    var month = -1;
    var day = -1;
    var hour = -1;
    var minute = -1;
    var second = -1;
    var time = "";

    //Replace long months
    if (sourceDateFormat.indexOf("MMMM") != -1) {
        sourceDateFormat = sourceDateFormat.replace("MMMM", "M");
        var array = monthsLong.split(';');
        var replaced = false;
        for (var i = 1; ((i < array.length) && (!replaced)); i++) {
            if (sourceDate.indexOf(array[i]) != -1) {
                sourceDate = sourceDate.replace(array[i], i);
                replaced = true;
            }
        }
    }
    //Replace short months
    if (sourceDateFormat.indexOf("MMM") != -1) {
        sourceDateFormat = sourceDateFormat.replace("MMM", "M");
        var array = monthsShort.split(';');
        var replaced = false;
        for (var i = 1; ((i < array.length) && (!replaced)); i++) {
            if (sourceDate.indexOf(array[i]) != -1) {
                sourceDate = sourceDate.replace(array[i], i);
                replaced = true;
            }
        }
    }
    //Replace long days
    if (sourceDateFormat.indexOf("dddd") != -1) {
        sourceDateFormat = sourceDateFormat.replace("dddd", "");
        var array = daysLong.split(';');
        var replaced = false;
        for (var i = 1; ((i < array.length) && (!replaced)); i++) {
            if (sourceDate.indexOf(array[i]) != -1) {
                sourceDate = sourceDate.replace(array[i], "");
                replaced = true;
            }
        }
    }

    //Replace short days
    if (sourceDateFormat.indexOf("ddd") != -1) {
        sourceDateFormat = sourceDateFormat.replace("ddd", "");
        var array = daysShort.split(';');
        var replaced = false;
        for (var i = 1; ((i < array.length) && (!replaced)); i++) {
            if (sourceDate.indexOf(array[i]) != -1) {
                sourceDate = sourceDate.replace(array[i], "");
                replaced = true;
            }
        }
    }
    while (formatIndex < sourceDateFormat.length) {
        if (sourceDateFormat.substr(formatIndex, 4) == "yyyy") {
            year = parseInt(sourceDate.substr(dateIndex, 4), 10);
            formatIndex = formatIndex + 4;
            dateIndex = dateIndex + 4;
        }
        else if (sourceDateFormat.substr(formatIndex, 2) == "yy") {
            year = parseInt("20" + sourceDate.substr(dateIndex, 2), 10);
            formatIndex = formatIndex + 2;
            dateIndex = dateIndex + 2;
        }
        else if (sourceDateFormat.substr(formatIndex, 2) == "MM") {
            month = parseInt(sourceDate.substr(dateIndex, 2), 10);
            formatIndex = formatIndex + 2;
            dateIndex = dateIndex + 2;
        }
        else if (sourceDateFormat.substr(formatIndex, 2) == "dd") {
            day = parseInt(sourceDate.substr(dateIndex, 2), 10);
            formatIndex = formatIndex + 2;
            dateIndex = dateIndex + 2;
        }
        else if ((sourceDateFormat.substr(formatIndex, 2) == "HH") || (sourceDateFormat.substr(formatIndex, 2) == "hh")) {
            hour = parseInt(sourceDate.substr(dateIndex, 2), 10);
            formatIndex = formatIndex + 2;
            dateIndex = dateIndex + 2;
        }
        else if (sourceDateFormat.substr(formatIndex, 2) == "mm") {
            minute = parseInt(sourceDate.substr(dateIndex, 2), 10);
            formatIndex = formatIndex + 2;
            dateIndex = dateIndex + 2;
        }
        else if (sourceDateFormat.substr(formatIndex, 2) == "ss") {
            second = parseInt(sourceDate.substr(dateIndex, 2), 10);
            formatIndex = formatIndex + 2;
            dateIndex = dateIndex + 2;
        }
        else if (sourceDateFormat.substr(formatIndex, 2) == "tt") {
            time = sourceDate.substr(dateIndex, 2);
            formatIndex = formatIndex + 2;
            dateIndex = dateIndex + 2;
        }
        else if (sourceDateFormat.substr(formatIndex, 1) == "M") {
            formatIndex = formatIndex + 1;
            if ((sourceDate.charCodeAt(dateIndex + 1) >= 48) && (sourceDate.charCodeAt(dateIndex + 1) <= 57)) {
                month = parseInt(sourceDate.substr(dateIndex, 2), 10);
                dateIndex = dateIndex + 2;
            }
            else {
                month = parseInt(sourceDate.substr(dateIndex, 1), 10);
                dateIndex = dateIndex + 1;
            }
        }
        else if (sourceDateFormat.substr(formatIndex, 1) == "d") {
            formatIndex = formatIndex + 1;
            if ((sourceDate.charCodeAt(dateIndex + 1) >= 48) && (sourceDate.charCodeAt(dateIndex + 1) <= 57)) {
                day = parseInt(sourceDate.substr(dateIndex, 2), 10);
                dateIndex = dateIndex + 2;
            }
            else {
                day = parseInt(sourceDate.substr(dateIndex, 1), 10);
                dateIndex = dateIndex + 1;
            }
        }
        else if ((sourceDateFormat.substr(formatIndex, 1) == "H") || (sourceDateFormat.substr(formatIndex, 1) == "h")) {
            formatIndex = formatIndex + 1;
            if ((sourceDate.charCodeAt(dateIndex + 1) >= 48) && (sourceDate.charCodeAt(dateIndex + 1) <= 57)) {
                hour = parseInt(sourceDate.substr(dateIndex, 2), 10);
                dateIndex = dateIndex + 2;
            }
            else {
                hour = parseInt(sourceDate.substr(dateIndex, 1), 10);
                dateIndex = dateIndex + 1;
            }
        }
        else if (sourceDateFormat.substr(formatIndex, 1) == "m") {
            formatIndex = formatIndex + 1;
            if ((sourceDate.charCodeAt(dateIndex + 1) >= 48) && (sourceDate.charCodeAt(dateIndex + 1) <= 57)) {
                minute = parseInt(sourceDate.substr(dateIndex, 2), 10);
                dateIndex = dateIndex + 2;
            }
            else {
                minute = parseInt(sourceDate.substr(dateIndex, 1), 10);
                dateIndex = dateIndex + 1;
            }
        }
        else if (sourceDateFormat.substr(formatIndex, 1) == "s") {
            formatIndex = formatIndex + 1;
            if ((sourceDate.charCodeAt(dateIndex + 1) >= 48) && (sourceDate.charCodeAt(dateIndex + 1) <= 57)) {
                second = parseInt(sourceDate.substr(dateIndex, 2), 10);
                dateIndex = dateIndex + 2;
            }
            else {
                second = parseInt(sourceDate.substr(dateIndex, 1), 10);
                dateIndex = dateIndex + 1;
            }
        }
        else {
            formatIndex = formatIndex + 1;
            dateIndex = dateIndex + 1;
        }
    }
    if (time.length > 0) {
        if ((time == "AM") && (hour == 12))
            hour = 0;
        else if (time == "PM")
            hour = hour + 12;
    }

    if (year == -1)
        date.setFullYear(1900);
    else
        date.setFullYear(year);

    if (month == -1)
        date.setMonth(0);
    else
        date.setMonth(month - 1);

    if (day == -1)
        date.setDate(1);
    else
        date.setDate(day);

    if (hour == -1)
        date.setHours(0);
    else
        date.setHours(hour);

    if (minute == -1)
        date.setMinutes(0);
    else
        date.setMinutes(minute);

    if (second == -1)
        date.setSeconds(0);
    else
        date.setSeconds(second);
    return date;
}