﻿// JScript File

var currentPage = "currentProtection";   // default page
var lastPage = "";

function $(id) { return document.getElementById(id); }
function $event(ev) { return ev = ev || window.event; }
function $target(ev) { return ev.target || ev.srcElement; }
function $create(tag, id, cls, htm) { var elem = document.createElement(tag); if (id) elem.id = id; if (cls) elem.className = cls; if (htm) elem.innerHTML = htm; return elem; }
function $setText(target, text)
{
    if (target.innerText != null)
        target.innerText = text;
    else
        target.textContent = text;
}

function $getText(target)
{
    if (target.innerText != null)
        return target.innerText;
    else
        return target.textContent;
}

function display(id, flag)
{
    if (typeof (id) !== "object")
        var obj = document.getElementById(id);
    else
        obj = id;

    if (obj)
    {
        if (flag)
        {
            obj.style.display = "";
            //obj.style.display = "block";
            obj.style.visibility = "visible";
        }
        else
        {
            obj.style.display = "none";
            obj.style.visibility = "hidden";
        }
    }
}

function checkEnterKey(ev, functionToCall)
{
    if (getCharCode(ev) == 13)
    {
        eval(functionToCall);
        return false;
    }
}


function trim(string)
{
    if (string)
        return string.replace(/^\s+|\s+$/g, "");
    else
        return null;
}


function getCharCode(e)
{
    var characterCode;   //literal character code will be stored in this variable

    if (window.event)
        characterCode = window.event.keyCode;     //IE
    else
        characterCode = e.which;    //firefox

    return characterCode;
}


function encodeText(text)
{
    if (text != null && text != "")
    {
        text = escape(text);
        text = text.replace(/\+/g, "%2B");
        text = text.replace(/ /g, "+");
        text = text.replace(/\//g, "%2F");
        text = text.replace(/@/g, "%40");
    }
    
    return text;
}

function decodeText(text)
{
    
    if (text != null && text != "")
    {
        text = text.toString();
        text = text.replace(/\+/g, " ");
        text = text.replace(/%2B/g, "+");
        text = text.replace(/%2F/g, "/");
        text = text.replace(/%40/g, "@");
        text = unescape(text);
    }
    
    return text;
}

function validateEmail(email)
{
    if (email)
    {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        return reg.test(email);
    }

    return false;
}

function toggleDisplay(obj)
{
    if (obj.style.display != "none")
        display(obj, false)
    else
        display(obj, true);
}


function help(icon, title, body)
{
    var hicon = document.getElementById("helpicon");
    var hTitle = document.getElementById("helptextTitle");
    var hBody = document.getElementById("helptextBody");

    hicon.style.backgroundImage = "url(images/" + icon + ")";
    hTitle.innerHTML = title;

    hBody.innerHTML = body;
}

function showSettings(pcId, pcName, protectionStatus)
{
    var postData = "pcId=" + pcId + "&pcName=" + pcName + "&protectionStatus=" + protectionStatus;
    var loader = new ajaxLoader();
    showImage("mainBody");
    loader.onLoadComplete = function()
    {
        var container = $("mainBody");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
        setRHSContent("currentProtection");
        adjustContentHeight();
    };
    loader.post("settings.aspx", null, postData);
}


function showActivityLogs(pcId, pcName, protectionStatus)
{
    var postData = "pcId=" + pcId + "&pcName=" + pcName + "&protectionStatus=" + protectionStatus;
    var loader = new ajaxLoader();
    showImage("mainBody");
    loader.onLoadComplete = function()
    {
        var container = $("mainBody");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
        setRHSContent("recentApps");
        currentPage = "recentApps";
    };
    loader.post("activityLogs.aspx", null, postData);
}

function loadMainBody(page)
{
    currentPage = page;
    var loader = new ajaxLoader();
    showImage("mainBody");
    loader.onLoadComplete = function()
    {
        var container = $("mainBody");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);

        adjustContentHeight();

    };
    loader.post(page + ".aspx", null, null);

}

function showProfile()
{
    var loader = new ajaxLoader();
    showImage("mainBody");
    loader.onLoadComplete = function()
    {
        var container = $("mainBody");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
        setRHSContent("personalInfo");
        currentPage = "personalInfo";
    };
    loader.post("profile.aspx", null, null);
}

function toggleRecentList()
{
    var recentList = $('applicationsList');
    toggleDisplay(recentList);

    if (recentList.style.display == "none")
        $("recentAppsText").innerHTML = "+";
    else
        $("recentAppsText").innerHTML = "-";

}

function setRHSContent(menuTitle)
{
    //    if (menuTitle == currentPage)
    //        return;
    var loader = new ajaxLoader();
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        var container = $("rhsContent");
        if (container)
        {
            var tool = $create("div", "content", '', loader.responseHTML);
            container.innerHTML = "";
            container.appendChild(tool);
            setSelectedMenuItem(menuTitle);
            adjustContentHeight();
        }
    };
    loader.post(menuTitle + ".aspx", null, null);
}


function getSelectedRadioValue(radios)
{
    var value = null;

    for (var i = 0; i < radios.length; i++)
    {
        if (radios[i].checked)
        {
            value = radios[i].value;
            break;
        }
    }

    return value;
}

//function toggleListSelect()
//{
//    var s4kEnabled = $("s4kEnabled").checked;
//    if (s4kEnabled)
//    {
//        $("listSettingRow").style.visibility = "visible";
//        $("listSettingRow").style.display = "block";
//    }
//    else
//    {
//        $("listSettingRow").style.visibility = "hidden";
//        $("listSettingRow").style.display = "none";

//        var oldListSetting = $("oldListSetting").value;
//        var whiteList = $("whiteList");

//        var blackList = $("blackList");

//        if (whiteList.value == oldListSetting)
//        {
//            whiteList.checked = true;
//        }
//        else
//            blackList.checked = true;
//    }


//}

function checkCategoriesChange()
{
    var oldprotectedCategories = $("oldProtectedCategories").value;
    var protectedCategories = 0;
    var categories = document.getElementsByName("webCategory");
    for (i = 0; i < categories.length; i++)
    {
        if (categories[i].checked)
            protectedCategories = protectedCategories | categories[i].value;
    }

    if (oldprotectedCategories == protectedCategories)
    {
        updateControlsDiv.style.display = "none";
        updateControlsDivDisabled.style.display = "block";
    }
    else
    {
        updateControlsDiv.style.display = "block";
        updateControlsDivDisabled.style.display = "none";
    }
}




var blockerModeFlag = false;
var activityLogFlag = false;
var ageRatingFlag = false;
var msgBeepsFlag = false;

function checkSettingsChange()
{
    var check = false;

    var maxAgeRating = $("maxAgeRating").options[$("maxAgeRating").selectedIndex].value;
    var oldMaxAgeRating = $("oldMaxAgeRating").value;
    
    if (maxAgeRating != oldMaxAgeRating)
    {
        check = true;
        ageRatingFlag = true;
    }

    var oldProtectionStatus = $("oldProtectionStatus").value;
    var protection = getSelectedRadioValue(document.getElementsByName("s4KProtection"));
    
   
    
    if (oldProtectionStatus != protection)
    {
        check = true;
        blockerModeFlag = true;
    }

    
//    var oldListSetting = $("oldListSetting").value;
//    var listSetting = getSelectedRadioValue(document.getElementsByName("listSetting"));

//    if (oldListSetting != listSetting)
//    {
//        check = true;
//        blockerModeFlag = true;
//    }

    var logEnabled = $("logEnabled").checked;
    
    var log = 0;
    if (logEnabled)
        log = 1;
        
    var oldActivityLog = $("oldActivityLog").value;

    if (oldActivityLog != log)
    {
        check = true;
        activityLogFlag = true;
    }
    
  var msgBeepsEnabled = $("msgBeepsEnabled").checked;
    
    var msgBeeps = 0;
    if (msgBeepsEnabled)
        msgBeeps = 1;
        
    var oldMsgBeeps = $("oldMsgBeeps").value;

    if (oldMsgBeeps != msgBeeps)
    {
        check = true;
        msgBeepsFlag = true;
    }
 

    var updateControlsDiv = $("updateControlsDiv");
    var updateControlsDivDisabled = $("updateControlsDivDisabled");

    if (check)
    {
        updateControlsDiv.style.display = "block";
        updateControlsDivDisabled.style.display = "none";
    }
    else
    {
        updateControlsDiv.style.display = "none";
        updateControlsDivDisabled.style.display = "block";
    }

    return check;
}



function updateBlockerSettings(pcName)
{

    var s4kEnabled = $("s4kEnabled");

    var protection = getSelectedRadioValue(document.getElementsByName("s4KProtection"));

    var logEnabled = $("logEnabled").checked;

    var msgBeepsEnabled = $("msgBeepsEnabled").checked;

    var listSetting = 64 //  getSelectedRadioValue(document.getElementsByName("listSetting")); // whitelist

    var maxAgeRating = $("maxAgeRating").options[$("maxAgeRating").selectedIndex].value;

    var protectionstatus = 1;
    var log = 0;
    var msgBeeps = 0;
    if (protection == 4)
    {
        if (!confirm("Disabling Safe4Kidz Protection will leave " + pcName + " vunerable!\nAre you sure?"))
        {
            protection = 1;
        }
    }

    if (logEnabled)
        log = 1;
    
    if (msgBeepsEnabled)
        msgBeeps = 1;
        
    var postData = "";
    var seperator = "";

    if (blockerModeFlag)
    {
        postData = "protection=" + protection + "&listSetting=" + listSetting;
        seperator = "&";
        blockerModeFlag = false;
    }

    if (activityLogFlag)
    {
        postData += seperator + "logEnabled=" + log;
        seperator = "&";
        activityLogFlag = false;
    }
    
    if (msgBeepsFlag)
    {
        postData += seperator + "msgBeepsEnabled=" + msgBeeps;
        seperator = "&";
        msgBeepsFlag = false;
    }

    if (ageRatingFlag)
    {
        postData += seperator + "maxAgeRating=" + maxAgeRating;
        ageRatingFlag = false;
    }
    
    postData += "&action=blockerSettings";

    var loader = new ajaxLoader();
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        var container = $("rhsContent");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
    };
    loader.post("updateSettings.aspx", null, postData);

}

function protectPC(pcId, pcName)
{

/*
    var freeSlots = $("freeSlots").value;   // protectedPcCount
    if (freeSlots == 0)
    {
        if (confirm("\"" + pcName + "\" cannot be added to the protection list!\nYou can only protect a max of 3 PCs per license!\n press ok if you want to buy more licenses"))
        {
            window.open("http://www.safe4kidz.com/buyNow.aspx", "", "", false);

        }

        return false;
    }

    else
    {
        var postData = "pcId=" + pcId + "&action=protect";
        var loader = new ajaxLoader();
        showImage("mainBody");

        loader.onLoadComplete = function()
        {
            loadMainBody('managePCs')
        };
        loader.post("savePCInfo.aspx", null, postData);
    }
    
    
    */
    alert("To allocate a product key,complete the Safe4Kidz registration on \"" + pcName + "\" ");
}




function setSelectedMenuItem(menuTitle)
{
    var oldMenuItem = $(currentPage);
    var currentMenuItem = $(menuTitle);
    //debugMsg(currentPage +"->"+ menuTitle);
    if (oldMenuItem && currentMenuItem)
    {
        oldMenuItem.className = "leftMenuItem";
        currentMenuItem.className = "leftMenuItemSelected";
        currentPage = menuTitle;
    }
    
}


function saveAccessTime(action, restrictionId)
{
    var daysSelected = 0;
    var protectionToken = 0;
    var description = $("description");
    var days = document.getElementsByName("days");

    var check = true;

    for (var i = 0; i < days.length; i++)
    {
        if (days[i].checked)
        {
            daysSelected = daysSelected | days[i].value;
        }
    }

    if (daysSelected == 0)
    {
        document.getElementById("activeDaysPreText").innerHTML = "=>";
        document.getElementById("activeDaysText").style.color = "red";
        document.getElementById("activeDaysPostText").innerHTML = "Select a Day to allow access on";

        check = false;
    }
    else
    {
        document.getElementById("activeDaysPreText").innerHTML = "&nbsp;";
        document.getElementById("activeDaysText").style.color = "black";
        document.getElementById("activeDaysPostText").innerHTML = "&nbsp;";
    }

    var startTimeHour = document.getElementById("startTimeHour").selectedIndex;
    var endTimeHour = document.getElementById("endTimeHour").selectedIndex;
    var startTimeMinute = document.getElementById("startTimeMinute").selectedIndex;
    var endTimeMinute = document.getElementById("endTimeMinute").selectedIndex;

    if (startTimeHour > endTimeHour)
    {
        document.getElementById("endTimePreText").innerHTML = "=>";
        document.getElementById("endTimeText").style.color = "red";
        document.getElementById("endTimePostText").innerHTML = "End Time less than Start Time";
        check = false;
    }
    else if (startTimeHour == endTimeHour)
    {
        if (startTimeMinute == endTimeMinute)
        {
            document.getElementById("endTimePreText").innerHTML = "=>";
            document.getElementById("endTimeText").style.color = "red";
            document.getElementById("endTimePostText").innerHTML = "End Time the same as Start Time";
            check = false;
        }
        else if (startTimeMinute > endTimeMinute)
        {
            document.getElementById("endTimePreText").value = "=>";
            document.getElementById("endTimeText").style.color = "red";
            document.getElementById("endTimePostText").innerHTML = "End Time less than Start Time";
            check = false;
        }
        else
        {
            document.getElementById("endTimePreText").innerHTML = "&nbsp;";
            document.getElementById("endTimeText").style.color = "black";
            document.getElementById("endTimePostText").innerHTML = "&nbsp;";
        }
    }
    else
    {
        document.getElementById("endTimePreText").innerHTML = "&nbsp;";
        document.getElementById("endTimeText").style.color = "black";
        document.getElementById("endTimePostText").innerHTML = "&nbsp;";
    }
    document.getElementById("actionsPreText").innerHTML = "&nbsp";

    if (description.value == "")
    {
        document.getElementById("descriptionPreText").value = "=>";
        document.getElementById("descriptionText").style.color = "red";
        document.getElementById("descriptionPostText").innerHTML = "Description cant be blank";
        check = false;
    }
    else
    {
        document.getElementById("descriptionPreText").value = "&nbsp;";
        document.getElementById("descriptionText").style.color = "black";
        document.getElementById("descriptionPostText").innerHTML = "&nbsp;";
    }

    if (check)
    {


        var restrictions = document.getElementsByName("restrictions");

        for (var i = 0; i < restrictions.length; i++)
        {
            if (restrictions[i].checked)
            {
                var options = document.getElementsByName(restrictions[i].value);

                for (var j = 0; j < 2; j++)
                {
                    if (options[j].checked)
                        protectionToken = protectionToken | options[j].value;
                }
            }
        }
        
        var allowWebSite = $("allowWebsites");
        var allowCards = $("allowCards");

        if(allowWebSite.checked)
        {
                if (allowCards.checked)
                    protectionToken = protectionToken | allowCards.value;
        }
        
        if (protectionToken == 0)
        {
            document.getElementById("actionsPreText").innerHTML = "=>";

            document.getElementById("activeDaysText").style.color = "red";
            document.getElementById("activeDaysPostText").innerHTML = "Please select the action you will allow during this Access Time";
        }
        else
        {
            var loader = new ajaxLoader();
            var postData = "&selectedDays=" + daysSelected + "&protectionToken=" + protectionToken
                                    + "&description=" + encodeText(description.value)
                                    + "&startTimeHour=" + startTimeHour
                                    + "&startTimeMinute=" + (startTimeMinute * 5)
                                    + "&endTimeHour=" + (endTimeHour)
                                    + "&endTimeMinute=" + (endTimeMinute * 5)
                                    + "&action=" + action;

            if (action != "add")
                postData += "&restrictionId=" + $("restrictionId").value;

            showImage("rhsContent");

            loader.onLoadComplete = function()
            {
                var container = $("rhsContent");
                var tool = $create("div", "content", '', loader.responseHTML);
                container.innerHTML = "";
                container.appendChild(tool);
                currentPage = "accessTimes";
            };
            loader.post("saveAccessTime.aspx", null, postData);
        }
    }
    else
        return;

}


function saveCategories()
{
    var categories = document.getElementsByName("webCategory");
    var protectedCategories = 0;

    for (i = 0; i < categories.length; i++)
    {
        if (categories[i].checked)
            protectedCategories = protectedCategories | categories[i].value;
    }

    var loader = new ajaxLoader();
    var postData = "protectedCategories=" + protectedCategories + "&action=categories";
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        var container = $("rhsContent");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
        setRHSContent("websiteCategories");
    };
    loader.post("updateSettings.aspx", null, postData);


}


function deleteProtectedApp(objId, appName, defaultApp)
{
    var check = false;

    if (defaultApp)
        check = confirm("Are you sure Restore " + decodeText(appName) + " to the Default setting?");
    else
        check = confirm("Are you sure you want to remove " + decodeText(appName) + " from the protected list?");
    
    if(check)
    {

        var loader = new ajaxLoader();
        var postData = "objId=" + objId + "&action=delete";
        showImage("rhsContent");
        loader.onLoadComplete = function()
        {
            var container = $("rhsContent");
            var tool = $create("div", "content", '', loader.responseHTML);
            container.innerHTML = "";
            container.appendChild(tool);
        };
        loader.post("saveProtectedApp.aspx", null, postData);
    }
}


function protectApplication(exeName, description, companyName, objId)
{

    var loader = new ajaxLoader();
    var postData = "exeName=" + exeName + "&description=" + description + "&companyName=" + companyName + "&objId=" + objId + "&action=protect";
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        var container = $("rhsContent");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
        setRHSContent("recentApps");
        //alert(decodeText(exeName) + " has been added to the protection list.");
    };
    loader.post("saveProtectedApp.aspx", null, postData);

}

function addProtectedApplication()
{

    var exeName = $("exeName");
    var description = $("description");
    var protectionType = $("protectionType").options[$("protectionType").selectedIndex].value;
    
    var accessTimeString = "";
    
    if (protectionType == 5)       // 5 -> accessTimes
    {
        var daysSelected = 0;
        var protectionToken = 0;
        var description = $("description");
        var days = document.getElementsByName("days");
        var accessTimeProtectionType = $("accessTimeProtectionType").options[$("accessTimeProtectionType").selectedIndex].value; ;
        var check = true;

        for (var i = 0; i < days.length; i++)
        {
            if (days[i].checked)
            {
                daysSelected = daysSelected | days[i].value;
            }
        }

        if (daysSelected == 0)
        {
            document.getElementById("activeDaysPreText").innerHTML = "=>";
            document.getElementById("activeDaysText").style.color = "red";
            document.getElementById("activeDaysPostText").innerHTML = "Select a Day to allow access on";

            check = false;
        }
        else
        {
            document.getElementById("activeDaysPreText").innerHTML = "&nbsp;";
            document.getElementById("activeDaysText").style.color = "black";
            document.getElementById("activeDaysPostText").innerHTML = "&nbsp;";
        }

        var startTimeHour = document.getElementById("startTimeHour").selectedIndex;
        var endTimeHour = document.getElementById("endTimeHour").selectedIndex;
        var startTimeMinute = document.getElementById("startTimeMinute").selectedIndex;
        var endTimeMinute = document.getElementById("endTimeMinute").selectedIndex;

        if (startTimeHour > endTimeHour)
        {
            document.getElementById("endTimePreText").innerHTML = "=>";
            document.getElementById("endTimeText").style.color = "red";
            document.getElementById("endTimePostText").innerHTML = "End Time less than Start Time";
            check = false;

        }
        else if (startTimeHour == endTimeHour)
        {
            if (startTimeMinute == endTimeMinute)
            {
                document.getElementById("endTimePreText").innerHTML = "=>";
                document.getElementById("endTimeText").style.color = "red";
                document.getElementById("endTimePostText").innerHTML = "End Time the same as Start Time";
                check = false;

            }
            else if (startTimeMinute > endTimeMinute)
            {
                document.getElementById("endTimePreText").value = "=>";
                document.getElementById("endTimeText").style.color = "red";
                document.getElementById("endTimePostText").innerHTML = "End Time less than Start Time";
                check = false;

            }
            else
            {
                document.getElementById("endTimePreText").innerHTML = "&nbsp;";
                document.getElementById("endTimeText").style.color = "black";
                document.getElementById("endTimePostText").innerHTML = "&nbsp;";
            }
        }
        else
        {
            document.getElementById("endTimePreText").innerHTML = "&nbsp;";
            document.getElementById("endTimeText").style.color = "black";
            document.getElementById("endTimePostText").innerHTML = "&nbsp;";
        }

        if (description.value == "")
        {
            document.getElementById("descriptionPreText").value = "=>";
            document.getElementById("descriptionText").style.color = "red";
            document.getElementById("descriptionPostText").innerHTML = "Description cant be blank";
            check = false;
        }
        else
        {
            document.getElementById("descriptionPreText").value = "&nbsp;";
            document.getElementById("descriptionText").style.color = "black";
            document.getElementById("descriptionPostText").innerHTML = "&nbsp;";
        }

        if (!check)
            return;

        accessTimeString = "0@" + startTimeHour + "@" + startTimeMinute +
                     "@" + endTimeHour + "@" + endTimeMinute +
                      "@" + daysSelected + "@" + Math.pow(2, accessTimeProtectionType) + "@" + description.value + "$";

    }



    var loader = new ajaxLoader();
    var postData = "exeName=" + encodeText(exeName.value) + "&description=" + encodeText(description.value) + "&action=add&accessTimeString=" + accessTimeString + "&protectionType=" + Math.pow(2, protectionType);
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        var container = $("rhsContent");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
        setRHSContent("applications");
        //alert(decodeText(exeName.value) + " has been added to the protection list.");
    };
    loader.post("saveProtectedApp.aspx", null, postData);

}



function saveProtectedApp(action, objId, defaultApp)
{
    var protectionType = $("protectionType").options[$("protectionType").selectedIndex].value;
    var postData = "";
    var accessTimeString = "";
    var description = "";
    
    
    if (action == "edit")
    {

        objId = $("editObjId").value;
        //action = $("editAction").value;
        description = $("appDescription");

        defaultApp = ($("editDefaultApp").value === 'true');
        if (defaultApp)
        {
            //action = "add";
            exeName = $("editExeName").value;
            description = $("editAppDescription").value;
        }
    }
    
    if (protectionType == 5)       // 5 -> accessTimes
    {
        var daysSelected = 0;
        var protectionToken = 0;
        var accessTimeDescription = $("description");
        var days = document.getElementsByName("days");
        var accessTimeProtectionType = $("accessTimeProtectionType").options[$("accessTimeProtectionType").selectedIndex].value; ;
        var check = true;

        for (var i = 0; i < days.length; i++)
        {
            if (days[i].checked)
            {
                daysSelected = daysSelected | days[i].value;
            }
        }

        if (daysSelected == 0)
        {
            document.getElementById("activeDaysPreText").innerHTML = "=>";
            document.getElementById("activeDaysText").style.color = "red";
            document.getElementById("activeDaysPostText").innerHTML = "Select a Day to allow access on";

            check = false;
        }
        else
        {
            document.getElementById("activeDaysPreText").innerHTML = "&nbsp;";
            document.getElementById("activeDaysText").style.color = "black";
            document.getElementById("activeDaysPostText").innerHTML = "&nbsp;";
        }

        var startTimeHour = document.getElementById("startTimeHour").selectedIndex;
        var endTimeHour = document.getElementById("endTimeHour").selectedIndex;
        var startTimeMinute = document.getElementById("startTimeMinute").selectedIndex;
        var endTimeMinute = document.getElementById("endTimeMinute").selectedIndex;

        if (startTimeHour > endTimeHour)
        {
            document.getElementById("endTimePreText").innerHTML = "=>";
            document.getElementById("endTimeText").style.color = "red";
            document.getElementById("endTimePostText").innerHTML = "End Time less than Start Time";
            check = false;

        }
        else if (startTimeHour == endTimeHour)
        {
            if (startTimeMinute == endTimeMinute)
            {
                document.getElementById("endTimePreText").innerHTML = "=>";
                document.getElementById("endTimeText").style.color = "red";
                document.getElementById("endTimePostText").innerHTML = "End Time the same as Start Time";
                check = false;

            }
            else if (startTimeMinute > endTimeMinute)
            {
                document.getElementById("endTimePreText").value = "=>";
                document.getElementById("endTimeText").style.color = "red";
                document.getElementById("endTimePostText").innerHTML = "End Time less than Start Time";
                check = false;

            }
            else
            {
                document.getElementById("endTimePreText").innerHTML = "&nbsp;";
                document.getElementById("endTimeText").style.color = "black";
                document.getElementById("endTimePostText").innerHTML = "&nbsp;";
            }
        }
        else
        {
            document.getElementById("endTimePreText").innerHTML = "&nbsp;";
            document.getElementById("endTimeText").style.color = "black";
            document.getElementById("endTimePostText").innerHTML = "&nbsp;";
        }

        if (accessTimeDescription.value == "")
        {
            document.getElementById("descriptionPreText").value = "=>";
            document.getElementById("descriptionText").style.color = "red";
            document.getElementById("descriptionPostText").innerHTML = "Description cant be blank";
            check = false;
        }
        else
        {
            document.getElementById("descriptionPreText").value = "&nbsp;";
            document.getElementById("descriptionText").style.color = "black";
            document.getElementById("descriptionPostText").innerHTML = "&nbsp;";
        }

        if (!check)
            return;

        accessTimeString = objId + "@" + startTimeHour + "@" + startTimeMinute +
                     "@" + endTimeHour + "@" + endTimeMinute +
                      "@" + daysSelected + "@" + Math.pow(2, accessTimeProtectionType) + "@" + accessTimeDescription.value + "$";

    }

    
    
    postData = "objId=" + objId + "&protectionType=" + Math.pow(2, protectionType) + "&accessTimeString=" + accessTimeString + "&action=" + action + "&description=" + encodeText(description.value);

    if (defaultApp)
        postData += "&defaultApp=1&exeName=" + exeName + "&description=" + description;
        
    var loader = new ajaxLoader();
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        setRHSContent("applications");
        //backToAppsList();
    };
    loader.post("saveProtectedApp.aspx", null, postData);
    adjustContentHeight();
    
}

function saveWebsite(tableId, action, objId, index )
{
    var postData = "objId="+objId+"&action="+action;
    var accessMode = null, websiteURL = null, newAgeRating = null;
    var commit = true;
    var urlChange = false, protectionChange= false; ageRatingChange = false;

    var protectionText = new Array('Unknown', 'Allowed', 'Blocked', 'Challenge', 'Check Language');
    var url = null, protection = null, ageRating = null;

    
    
    
    
    switch(action)
    {
        case 'delete':
            url = trim($getText($("urlText_" + index)));
            if (!confirm("Are you sure you want to delete " + url + " from the Protected Websites"))
                return;
            break;

        case 'reject':
            url = trim($getText($("pnUrlText_" + index)));
            if (!confirm("Are you sure you want to reject " + url))
                return;
            break;

        case 'edit':
            commit = false;
            url = trim($getText($("urlText_" + index)));
            protection = getIndexInArray(protectionText, $getText($("accessModeText_" + index)));
            ageRating = $getText($("ageRatingsText_" + index)).replace("+", "");
            
            accessMode = $getSelObjVal($("accessModeSelector_" + index));
            websiteURL = trim($("urlTextInput_" + index).value);
            newAgeRating = $getSelObjVal($("ageRatingsTextSelector_" + index));

            websiteURL = websiteURL.replace("http://", "");
            websiteURL = websiteURL.replace("https://", "");
            websiteURL = websiteURL.replace("www.", "");
            
            if (protection != accessMode)
            {
                commit = true;
                protectionChange = true;
                postData += "&accessMode=" + accessMode;
            }

            if (url != websiteURL)
            {
                commit = true;
                urlChange = true;
                postData += "&websiteURL=" +websiteURL;
            }

            if (ageRating != newAgeRating)
            {
                commit = true;
                ageRatingChange = true;
                postData += "&ageRating=" + newAgeRating;
            }

            break;
    
            default : break;
    }

    if (commit)
    {            
        var loader = new ajaxLoader();
        //    showImage("rhsContent");

        
        loader.onLoadComplete = function()
        {

            if (loader.responseHTML == "false")
                alert("Some error has occurred. Pleae Try again later.");
            else
            {
                switch(action)
                {
                    case 'approve':
                    case 'reject':
                    case 'delete':
                        var tbl, tblRow;

                        if (tableId == "ap")
                        {
                             tbl = $("approvedURLsTable");
                             tblRow = $("apRw_" + index);
                         }
                         else
                         {
                             tbl = $("pendingURLsTable");
                             tblRow = $("pnRw_" + index);
                         }

                        var rw = tblRow.nextSibling;
                        tblRow.parentNode.removeChild(tblRow);
                        
                       //tbl.deleteRow(index);

                        if (tbl.rows.length == 1)  // table is empty
                        {
                            var tBody = tbl.firstChild;
                            var newTR = $create("tr");
                            var newTD = document.createElement('td');
                            newTD.innerHTML = 'No URL in List';
                            newTR.appendChild(newTD);
                            tBody.appendChild(newTR);
                        }
                        else
                       {
                       while(rw)
                            {
                                if (rw.className == "blueRow")
                                    rw.className = "whiteRow";
                                else
                                    rw.className = "blueRow";
                                rw = rw.nextSibling;
                                    
                            }
                        }
                        
                        
                        break;


                    case 'edit':
                            
                            if (urlChange)
                            {
                                $setText($("urlText_"+index), websiteURL);
                            }

                            if (protectionChange)
                            {
                                $setText($("accessModeText_" + index), protectionText[accessMode]);
                            }
                           
                            if (ageRatingChange)
                            {
                                $setText($("ageRatingsText_" + index), newAgeRating+"+");
                            }

                            //tableId, action, objId, index, url , protection, ageRating

                            var editLink = $("startEdit_" + index);   // editWebsite<%=count %>, <%=protection %>, <%=ageRating %>
                            var saveLink = $("saveEdit_" + index);     // saveWebsite('ap', 'edit', 2, 1, 'mysite1.com3', 1, 3)
                            
                            cancelEditWebsite(index);
                            
                        break;
                
                }
            
                //setRHSContent("websites");
            }
            
            //backToAppsList();
        };
        loader.post("saveWebsite.aspx", null, postData);
    }
    else
        cancelEditWebsite(index);
}

function editWebsite(index)
{

    var urlText = $("urlText_"+index);
    var urlTextInput = $("urlTextInput_" + index);
    
    urlTextInput.value = $getText(urlText);
    
    var accessModeText = $("accessModeText_"+index);
    var accessModeSelector = $("accessModeSelector_" + index);

    var protectionText = new Array('Unknown', 'Allowed', 'Blocked', 'Challenge', 'Check Language');
    
    var protection = $getText(accessModeText);
    
    var ageRatingsText = $("ageRatingsText_" + index);
    var ageRatingsTextSelector = $("ageRatingsTextSelector_" + index);

    var ageRating = $getText(ageRatingsText).replace("+", "");

    $setSelObjVal(accessModeSelector, getIndexInArray(protectionText, protection) );
    $setSelObjVal(ageRatingsTextSelector, ageRating);

    var editControl = $("editControl_" + index);
    var saveCancelControl = $("saveCancelControl_" + index);

    display(urlText, false);
    display(urlTextInput, true);
    
    display(accessModeText, false);
    display(accessModeSelector, true);

    display(ageRatingsText, false);
    display(ageRatingsTextSelector, true);

    display(editControl, false);
    display(saveCancelControl, true);
}

 function getIndexInArray(arrayObj, val)
 {
     if(arrayObj && val)
     {
        for(var i=0; i< arrayObj.length; i++)
        {
            if(arrayObj[i] == val)
            return i;
        }
     }
     return -1;
 }

function cancelEditWebsite(index)
{
    var urlText = $("urlText_" + index);
    var urlTextInput = $("urlTextInput_" + index);
    
    var accessModeText = $("accessModeText_" + index);
    var accessModeSelector = $("accessModeSelector_" + index);

    var ageRatingsText = $("ageRatingsText_" + index);
    var ageRatingsTextSelector = $("ageRatingsTextSelector_" + index);

    var editControl = $("editControl_" + index);
    var saveCancelControl = $("saveCancelControl_" + index);

    display(urlTextInput, false);
    display(urlText, true);

    display(accessModeSelector, false);
    display(accessModeText, true);

    display(ageRatingsTextSelector, false);
    display(ageRatingsText, true);

    display(saveCancelControl, false);
    display(editControl, true);
    
}


function togglechangePassword(check)
{
    var infoTable = $("userInfoTable");
    var changePasswordTable = $("changePasswordTable");

    var txtArray = new Array("oldPass", "newPass", "reTypeNewPass");

    if (check)
    {
        for (var i = 0; i < txtArray.length; i++)
            $(txtArray[i]).value = "";
    }


    display(changePasswordTable, check);
    display(infoTable, !check);

    display("changePasswordControls", check);
    display("mainControls", !check);

    return false;
}
function saveNewPassword()
{
    var oldPass = $("oldPass");

    if (oldPass.value == "")
    {
        alert("Empty Password");
        oldPass.focus();
        return false;
    }



    var newPass = $("newPass");
    var reTypeNewPass = $("reTypeNewPass");

    if (newPass.value != reTypeNewPass.value)
    {
        alert("Passwords do Not Match!");
        return false;
    }

    var postData = "oldPass=" + oldPass.value + "&newPass=" + newPass.value + "&action=pass";
    var loader = new ajaxLoader();
    var check = "";

    loader.onLoadComplete = function()
    {
        check = loader.responseHTML;
        if (check == "false")
        {
            alert("Old Password Incorrect!");
            oldPass.select();
            oldPass.focus();
        }
        else
        {
            togglechangePassword(false);
            alert("New Password Saved!");
        }

    };
    loader.post("editPersonalInfo.aspx", null, postData);

}

function toggleEditPersonalInfo(check)
{
    var txtArray = new Array("emailTxt", "firstNameTxt", "lastNameTxt", "editControls");
    var spanArray = new Array("emailSpan", "firstNameSpan", "lastNameSpan", "mainControls");
    for (var i = 0; i < txtArray.length; i++)
    {
        display(txtArray[i], check);
        display(spanArray[i], !check);
    }

    if (check)
    {
        for (var i = 0; i < txtArray.length - 1; i++)
        {
            $(txtArray[i]).value = $getText($(spanArray[i]));
        }

        $(txtArray[0]).select();
        $(txtArray[0]).focus();
    }

    return false;
}

function savePersonalInfo()
{
    var loader = new ajaxLoader();
    var email = $("emailTxt");
    var firstName = $("firstNameTxt");
    var lastName = $("lastNameTxt");

    var postData = "email=" + email.value + "&firstName=" + firstName.value + "&lastName=" + lastName.value + "&action=info";

    loader.onLoadComplete = function()
    {
        var txtArray = new Array("emailTxt", "firstNameTxt", "lastNameTxt");
        var spanArray = new Array("emailSpan", "firstNameSpan", "lastNameSpan");

        for (var i = 0; i < txtArray.length; i++)
        {
            $setText($(spanArray[i]), $(txtArray[i]).value);
        }
        toggleEditPersonalInfo(false);

        $setText($("userFName"), firstName.value);

    };
    loader.post("editPersonalInfo.aspx", null, postData);

}


//function editProtectedApp(objId, appName, protection, accessTimeString)
//{
//    var loader = new ajaxLoader();
//    var postData = "objId=" + objId + "&appName=" + appName + "&protectionType=" + protection + "&accessTimeString=" + accessTimeString;
//    showImage("rhsContent");
//    loader.onLoadComplete = function()
//    {
//        var container = $("rhsContent");
//        var tool = $create("div", "content", '', loader.responseHTML);
//        container.innerHTML = "";
//        container.appendChild(tool);
//        $("appName").innerHTML = decodeText(appName);
//        $("protectionType").selectedIndex = protection   // Math.log(protection) / Math.log(2);    // temp working fix: need to improvise to reduce calculation
//        $("protectionType").focus();

//        if (protection == 5)    // 5 -> access times only
//        {
//            preFillAppAccessTimesInfo(accessTimeString);
//        }
//    };
//    loader.post("editProtectedApp.aspx", null, postData);
//}

//function editDefaultProtectedApp(objId, exeName, description)
//{
//    var loader = new ajaxLoader();
//    //var postData = "objId=" + objId + "&appName=" + appName + "&protectionType=" + protection + "&accessTimeString=" + accessTimeString;
//    var postData = "objId=" + objId + "&exeName=" + exeName + "&protectionType=2&description=" + description + "&defaultApp=1";
//    
//    showImage("rhsContent");
//    loader.onLoadComplete = function()
//    {
//        var container = $("rhsContent");
//        var tool = $create("div", "content", '', loader.responseHTML);
//        container.innerHTML = "";
//        container.appendChild(tool);
//        $("appName").innerHTML = decodeText(exeName);
//        $("protectionType").selectedIndex = 2   // Math.log(protection) / Math.log(2);    // temp working fix: need to improvise to reduce calculation
//        $("protectionType").focus();
//       
//    };
//    loader.post("editProtectedApp.aspx", null, postData);
//}

function editProtectedApp(objId, appName, protection, isDefaultApp, accessTimeString, description)
{
    var appsList = $("appsLists");
    var editApp = $("editApp");

    display(appsList, false);
    display(editApp, true);

    display("appAccessTime", false);
    clearAppAccessTimesInfo();
    
    $("editObjId").value = objId;
    $("editAction").value = "edit" ;
    $("editDefaultApp").value = isDefaultApp;
    
    $("editExeName").value = decodeText(appName);
    $("editAppDescription").value = decodeText(description);
    $("editAppAccessTimeString").value = accessTimeString;
    
//  var editAction = $("editAction").value;
//  var editObjId = $("editObjId").value;
//  var editDefaultApp = $("editDefaultApp").value;
//  var editExeName = $("editExeName").value;
//  var editAppDescription = $("editAppDescription").value;

    if (protection == 5)    // 5 -> access times only
    {
        preFillAppAccessTimesInfo(accessTimeString);
        $("protectionType").selectedIndex = 3;
    }
    else
        $("protectionType").selectedIndex = protection;

    var appNameField = $("appName");
    var decodeAppName = decodeText(appName);
    
    $setText(appNameField, decodeAppName);
    appNameField.title = decodeAppName;
   
    
    $("appDescription").value =  decodeText(description);
    
    $("protectionType").focus();

}

function backToAppsList()
{
    var appsList = $("appsLists");
    var editApp = $("editApp");

    display(editApp , false);
    display(appsList, true);
}



function preFillAppAccessTimesInfo(accessTimeString)
{
    var accessTimeData = accessTimeString.split(/@|\$/);
    $("protectionType").selectedIndex = 3;
    display("appAccessTime", true);

    $("startTimeHour").selectedIndex = accessTimeData[1];
    $("startTimeMinute").selectedIndex = accessTimeData[2];

    $("endTimeHour").selectedIndex = accessTimeData[3];
    $("endTimeMinute").selectedIndex = accessTimeData[4];
    $("description").value = accessTimeData[7];
    $("accessTimeProtectionType").selectedIndex = Math.log(accessTimeData[6]) / Math.log(2);

    var daysStored = accessTimeData[5];

    var daysList = { NONE: 0, Sunday: 1, Monday: 2, Tuesday: 4, Wednesday: 8, Thursday: 16, Friday: 32, Saturday: 64 };

    if ((daysStored & daysList.Sunday) != 0)
    {
        $("sun").checked = "checked";
    }

    if ((daysStored & daysList.Monday) != 0)
    {
        $("mon").checked = "checked";
    }

    if ((daysStored & daysList.Tuesday) != 0)
    {

        $("tue").checked = "checked";
    }

    if ((daysStored & daysList.Wednesday) != 0)
    {
        $("wed").checked = "checked";
    }

    if ((daysStored & daysList.Thursday) != 0)
    {
        $("thu").checked = "checked";

    }

    if ((daysStored & daysList.Friday) != 0)
    {
        $("fri").checked = "checked";
    }

    if ((daysStored & daysList.Saturday) != 0)
    {
        $("sat").checked = "checked";
    }


}


function clearAppAccessTimesInfo()
{
    $("protectionType").selectedIndex = 0;
    $("startTimeHour").selectedIndex = 0;
    $("startTimeMinute").selectedIndex = 0;

    $("endTimeHour").selectedIndex = 0;
    $("endTimeMinute").selectedIndex = 0;
    $("description").value = "";
    $("accessTimeProtectionType").selectedIndex = 0;

    $("sun").checked = false;    
    $("mon").checked = false;
    $("tue").checked = false;
    $("wed").checked = false;
    $("thu").checked = false;
    $("fri").checked = false;
    $("sat").checked = false;
}




function deleteRestriction(restrictionId, startTime, endTime)
{

    if (confirm("Are you sure you want to delete restriction " + startTime + " to " + endTime + "?"))
    {
        var postData = "restrictionId=" + restrictionId + "&action=delete"; ;

        var loader = new ajaxLoader();
        showImage("rhsContent");
        loader.onLoadComplete = function()
        {
            var container = $("rhsContent");
            var tool = $create("div", "content", '', loader.responseHTML);
            container.innerHTML = "";
            container.appendChild(tool);
        };
        loader.post("saveAccessTime.aspx", null, postData);
    }
}

function updateRestriction(restrictionId, startTimeHour, startTimeMinute, endTimeHour, endTimeMinute, days, restrictionType)
{
    var postData = "restrictionId=" + restrictionId +
                    "&startTimeHour=" + startTimeHour + "&startTimeMinute=" + startTimeMinute +
                     "&endTimeHour=" + endTimeHour + "&endTimeMinute=" + endTimeMinute +
                      "&days=" + days + "&restrictionType=" + restrictionType +
                        "&action=update";

    var loader = new ajaxLoader();
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        var container = $("rhsContent");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
    };
    loader.post("accessTimeInterface.aspx", null, postData);
}

function editRestriction(restrictionId, startTimeHour, startTimeMinute, endTimeHour, endTimeMinute, days, restrictionType, description)
{
    var postData = "restrictionId=" + restrictionId +
                    "&startTimeHour=" + startTimeHour + "&startTimeMinute=" + startTimeMinute +
                     "&endTimeHour=" + endTimeHour + "&endTimeMinute=" + endTimeMinute +
                      "&days=" + days + "&restrictionType=" + restrictionType +
                      "&description=" + description +
                        "&action=edit";

    var loader = new ajaxLoader();
    showImage("rhsContent");
    loader.onLoadComplete = function()
    {
        var container = $("rhsContent");
        var tool = $create("div", "content", '', loader.responseHTML);
        container.innerHTML = "";
        container.appendChild(tool);
        preFillAccessTimesInfo();
    };
    loader.post("editAccessTime.aspx", null, postData);
}


function preFillAccessTimesInfo()
{
    $("startTimeHour").selectedIndex = $("startTimeHour_oldVal").value;
    $("startTimeMinute").selectedIndex = $("startTimeMinute_oldVal").value / 5;

    $("endTimeHour").selectedIndex = $("endTimeHour_oldVal").value;
    $("endTimeMinute").selectedIndex = $("endTimeMinute_oldVal").value / 5;
    $("description").value = decodeText($("description_old").value);
    var daysStored = $("days_oldVal").value;
    var restrictionType = $("restrictionType_oldVal").value;

    var daysList = { NONE: 0, Sunday: 1, Monday: 2, Tuesday: 4, Wednesday: 8, Thursday: 16, Friday: 32, Saturday: 64 };

    if ((daysStored & daysList.Sunday) != 0)
    {
        $("sun").checked = "checked";
    }

    if ((daysStored & daysList.Monday) != 0)
    {
        $("mon").checked = "checked";
    }

    if ((daysStored & daysList.Tuesday) != 0)
    {

        $("tue").checked = "checked";
    }

    if ((daysStored & daysList.Wednesday) != 0)
    {
        $("wed").checked = "checked";
    }

    if ((daysStored & daysList.Thursday) != 0)
    {
        $("thu").checked = "checked";

    }

    if ((daysStored & daysList.Friday) != 0)
    {
        $("fri").checked = "checked";
    }

    if ((daysStored & daysList.Saturday) != 0)
    {
        $("sat").checked = "checked";
    }

    //    var allowCards = $("allowWebsites");

    //    if ((restrictionType & allowCards.value) != 0)
    //    {
    //        allowCards.checked = "checked";

    //    }

    var allowWebsites = $("allowWebsites");
    var allWebsites = $("allWebsites");
    var webAccessTime = $("webAccessTime");
    var allowCards = $("allowCards");
    
    if ((restrictionType & allWebsites.value) != 0)
    {
        allWebsites.checked = "checked";
        allowWebsites.checked = "checked";
        allowCards.disabled = false;
        
        if ((restrictionType & allowCards.value) != 0)
        {
            allowCards.checked = "checked";
        }

    }
    else if ((restrictionType & webAccessTime.value) != 0)
    {
        allowCards.disabled = false;
        webAccessTime.checked = "checked";
        allowWebsites.checked = "checked";
        
        if ((restrictionType & allowCards.value) != 0)
        {
            allowCards.checked = "checked";
        }
    }

    var allowApps = $("allowApps");
    var allApplications = $("allApplications");
    var appAccessTime = $("appAccessTime");

    if ((restrictionType & allApplications.value) != 0)
    {
        allApplications.checked = "checked";
        allowApps.checked = "checked";
    }
    else if ((restrictionType & appAccessTime.value) != 0)
    {
        appAccessTime.checked = "checked";
        allowApps.checked = "checked";
    }


    adjustRadios();
}

function removePC(pcId, pcName)
{
//   if (confirm("Are you sure you want to remove \"" + pcName + "\" from the protected list?"))
    if (confirm("Releasing the product key will leave \"" + pcName + "\" unprotected,\nInstall/Register Safe4kidz to protect it again "))
    {
        var postData = "pcId=" + pcId + "&action=remove";
        var loader = new ajaxLoader();
        showImage("mainBody");

        loader.onLoadComplete = function()
        {
            loadMainBody('managePCs');
        };
        loader.post("savePCInfo.aspx", null, postData);
    }
}


function toggleRadios(name, status)
{
    var radios = document.getElementsByName(name);

    for (var i = 0; i < radios.length; i++)
    {
        radios[i].disabled = !status;
    }
}

function toggleAllowWebsites(name, status)
{
    toggleRadios(name, status);
    
    toggleAllowCards(status);
}

function toggleAllowCards(status)
{
    var allowCards = $("allowCards");
    allowCards.disabled = !status;
}


function selectAllCheckboxes()
{
    var checkBoxes = document.getElementsByTagName("input");

    for (var i = 0; i < checkBoxes.length; i++)
    {
        checkBoxes[i].checked = "checked";
    }
}

function deselectAllCheckboxes()
{
    var checkBoxes = document.getElementsByTagName("input");

    for (var i = 0; i < checkBoxes.length; i++)
    {
        checkBoxes[i].checked = false;
    }

}

function adjustRadios()
{
    toggleRadios('webSelection', document.getElementById("allowWebsites").checked)
    toggleRadios('appSelection', document.getElementById("allowApps").checked);
}



function getWindowSize()
{
    var width = height = 0;
    var marginLeft = document.body.style.marginLeft;

    if (marginLeft == null || marginLeft == undefined || marginLeft == "")
    {
        marginLeft = document.body.leftMargin;

        if (marginLeft == undefined)
            marginLeft = "0px";
    }

    var marginRight = document.body.style.marginRight;

    if (marginRight == null || marginRight == undefined || marginRight == "")
    {
        marginRight = document.body.rightMargin;

        if (marginRight == undefined)
            marginRight = "0px";
    }

    var marginTop = document.body.style.marginTop;

    if (marginTop == null || marginTop == undefined || marginTop == "")
    {
        marginTop = document.body.topMargin;

        if (marginTop == undefined)
            marginTop = "0px";
    }

    var marginBottom = document.body.style.marginRight;

    if (marginBottom == null || marginBottom == undefined || marginBottom == "")
    {
        marginBottom = document.body.bottomMargin;

        if (marginBottom == undefined)
            marginBottom = "0px";
    }

    var marginWidth = Number(marginLeft.replace('px', '')) + Number(marginRight.replace('px', ''));
    var marginHeight = Number(marginTop.replace('px', '')) + Number(marginBottom.replace('px', ''));

    if (typeof (window.innerWidth) == 'number')
    {
        //Non-IE
        width = window.innerWidth;
        height = window.innerHeight;
    }

    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    }

    else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }

    width -= marginWidth;
    height -= marginHeight;

    return { width: width, height: height };

}


function setAppAccessTime()
{

    var optionSelected = $("protectionType").options[$("protectionType").selectedIndex].value;
    var appAccessTime = $("appAccessTime");
    if (optionSelected == 5)        // accessTimes
    {
        toggleDisplay(appAccessTime);
    }
    else
        if (appAccessTime.style.display != "none")
        toggleDisplay(appAccessTime);


}


function adjustContentHeight()
{
    var screenHeight = getWindowDim();

    var headerHeight = $("header").offsetHeight;

    var occupiedHeight = $("header").offsetHeight;

    var footer = $("footer");
    var footerHeight = footer.offsetHeight;

    switch (currentPage)
    {
        case "currentProtection":
        case "websiteCategories":
        case "accessTimes":
        case "applications":
            var content = $("mainBody");
            if (content)
            {
                //content.style.height = Math.max(300, (screenHeight.height - 380)) + "px";
                //document.body.style.height = Math.max(screenHeight.height - 380, content.offsetHeight + 300) + "px";
            }
            break;


        case "managePCs":
            //var protectionTable = $("protectonTableList");
            //var content = $("mainBody");
            //if (protectionTable)
            //{
            //protectionTable.style.height = Math.max(100, (screenHeight.height - protectionTable.offsetTop - footerHeight-10)) + "px";
            //}
            //document.body.style.height = screenHeight.height + 'px';
            break;

        case "recentApps":
        case "webSitesLogs":
        case "appsLogs":
            
//            var appLogList = $("applicationsList");
//            if (appLogList)
//            {
//                screenHeight = getWindowSize();
//                appLogList.style.height = Math.max(100, (screenHeight.height - 400)) + "px";
//            }

            //document.body.style.height = screenHeight.height + 30 + 'px';
            break;
        default:
            //document.body.style.height = screenHeight.height  + 'px';
            break;

    }

    occupiedHeight += $("contentBody").offsetHeight;

    var scrollHeight = document.documentElement.scrollHeight;

    //$debugMsg(occupiedHeight);
    footer.style.top = Math.max(occupiedHeight + footerHeight, screenHeight.height - footerHeight) + 'px';
    footer.style.width = Math.max( document.body.scrollWidth, 1200) + "px";
    header.style.width = Math.max( document.body.scrollWidth, 1200) + "px";
}

function adjustFooterPos()
{

    var screenDim = getWindowDim();
    var spacer = $("spacer");
    var contentBodyHeight = $("contentBody").offsetHeight;
    
    var headerHeight = $("header").offsetHeight;
    var footer = $("footer");
    var footerHeight = footer.offsetHeight;
    
    var occupiedHeight = headerHeight + contentBodyHeight + footerHeight;
    
    var availibleHeight = screenDim.height;
    
    var offset = availibleHeight - occupiedHeight;
    
    if(offset>0)
        spacer.style.height = (offset - 1) + "px";
    
}


function toggleAddLicense()
{
    var currentLicensesDiv = $("currentLicenses");
    var addMoreLicenseDiv = $("newLicense");
    
    $setText($("errorText"), " ");
    $("newLicenseKey").value = "";
    
    toggleDisplay(currentLicensesDiv);
    toggleDisplay(addMoreLicenseDiv);
    

}


function saveNewLicense()
{
    var newLicense = $("newLicenseKey");

    if (validateLicenseKey(newLicense))
    {
        var postData = "license=" + newLicense.value;
        var loader = new ajaxLoader();
        //showImage("rhsContent");

        loader.onLoadComplete = function()
        {

            var result = loader.responseHTML;

            if (result != "")
            {
                $setText($("errorText"), result);
                newLicense.focus();
                newLicense.select();
                return false;
            }
            else
            //toggleAddLicenses();
                setRHSContent('licenses');

        };
        loader.post("manageLicenses.aspx", null, postData);

    }
}


function validateLicenseKey(license)
{
    var result = false, licenseKey = license.value;
    if (licenseKey == "")
    {
        $setText($("errorText"), "Please Enter a Product Key");
        license.focus();
        return false;
    }

    if (!validateLicenseKeyForm(licenseKey))
    {
        $setText($("errorText"), "Invalid Product Key!");
        license.focus();
        return false
    }
    
    
    return true;
}

function validateLicenseKeyForm(licenseKey)
{
    var re = /^\w{4}\-\w{4}-\w{4}-\w{4}-\w{4}-\w{4}-\w{4}-\w{4}$/;
    return (re.test(licenseKey));
}

function debugMsg(debugMSG)
{
    $setText($("debugSpan"), debugMSG);
}

function getWindowDim()
{
    var width = height = 0;


    if (typeof (window.innerWidth) == 'number')
    {
        //Non-IE
        width = window.innerWidth;
        height = window.innerHeight;
    }

    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    }

    else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }

    return { width: width, height: height };

}

function showUserApps()
{
    var userAppsTable = $("userAppsTable");
    var defaultAppsTable = $("defaultAppsTable");

    display(defaultAppsTable, false);
    display(userAppsTable, true);

//    var uatopMenu = $("userDefinedTopMenu");
//    var datopMenu = $("defaultAppsTopMenu");

//    datopMenu.className = "topMenuUnselected";
//    uatopMenu.className = "topMenuSelected";
    $("appViewSelector").selectedIndex = 0;
  
    $("addApp").style.visibility = "visible";
    adjustContentHeight();
}

function showDefaultApps()
{
    var userAppsTable = $("userAppsTable");
    var defaultAppsTable = $("defaultAppsTable");

    display(userAppsTable, false);
    display(defaultAppsTable, true);

//    var uatopMenu = $("userDefinedTopMenu");
//    var datopMenu = $("defaultAppsTopMenu");

//    uatopMenu.className = "topMenuUnselected";
//    datopMenu.className = "topMenuSelected";
    $("appViewSelector").selectedIndex = 1;
    $("addApp").style.visibility = "hidden";
    adjustContentHeight();
}

function setAppView()
{
    var selectedView = $("appViewSelector").options[$("appViewSelector").selectedIndex].value;

    if (selectedView == 1)
        showUserApps();
    else
        showDefaultApps();
}

function setURLView()
{

    var selectedView = $getSelObjVal($("urlViewSelector"));

    if (selectedView == 1)
        showApprovedURLs();
    else
        showPendingURLs();
}

function showApprovedURLs()
{
    var approvedURLsTable = $("approvedURLsTable");
    var pendingURLsTable = $("pendingURLsTable");

    display(approvedURLsTable, true);
    display(pendingURLsTable, false);

    adjustContentHeight();
}

function showPendingURLs()
{
    var approvedURLsTable = $("approvedURLsTable");
    var pendingURLsTable = $("pendingURLsTable");

    display(approvedURLsTable, false);
    display(pendingURLsTable, true);

    adjustContentHeight();
}


function mouserHoverOn(obj) 
{
    obj.className = obj.className +"_Hover";
}

function mouseHoverOff(obj)
{
    var originalClass = obj.className.replace("_Hover", "");
    obj.className = originalClass;
}


function $getSelObjVal(selObj)
{
    var selectedVal = selObj.options[selObj.selectedIndex].value;
    return selectedVal;
}

function $setSelObjVal(selObj, val)
{
    var objCount = selObj.options.length;
    for (var i = 0; i < objCount; i++)
    {
        if (selObj.options[i].value == val)
        {
            selObj.selectedIndex = i;
            return true;
            break;
        }
    }
    return false;
}

function $debugMsg(debugMSG)
{
    $insertDebugDiv();
    $setText($("debugSpan"), debugMSG);
}

function $insertDebugDiv()
{
    var debugDiv = $("debugDiv");
    if (debugDiv)
        return;

    debugDiv = $create("div", "debugDiv", "", "");
    debugDiv.style.zIndex = 10000;
    var debugSpan = $create("span", "debugSpan", "", "S4K Debug Info");
    debugDiv.appendChild(debugSpan);

    var debugStyle = debugDiv.style;

    debugStyle.cssText = "color:white;background-color:#d18034; position:fixed; top:0px; left:40%; padding:5px; border:solid 1px black;";

    document.body.appendChild(debugDiv);

}

function selectRadio(radioID)
{
    $(radioID).checked=true;
}

function createXmlObject(xmlResponse)
{
    var doc = null;
    var result = false;
    var browserType = "";
    
    // code for IE
    if (window.ActiveXObject)
    {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = "false";
        doc.loadXML(xmlResponse);
        
        var err = doc.parseError;

        if (err.errorCode == 0)
            result = true;
            
        browserType = "ie";
    }
    // code for Mozilla, Firefox, Opera, etc.
    else
    {
        var parser = new DOMParser();
        doc = parser.parseFromString(xmlResponse,"text/xml");
        
        if (doc.documentElement.nodeName != "parsererror")
            result = true;
            
        browserType = "other";
    }
    
    return { xmlDoc: doc, browser: browserType, validXml: result };
}
