/*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var xhtml = "http://www.w3.org/1999/xhtml";

var GLOBAL_SERVICE_STRING = "GlobalAdmin";
var SERVER_ADMIN_STRING = "ServerAdmin";
var SERVICE_GROUP_ADMIN_STRING = "ServiceGroupAdmin";
var MODULE_ADMIN_STRING = "ModuleAdmin";
var LOGGING_SERVICE_STRING = "LoggingService";

var SECURITY_SCENARIO_CONFIG_ADMIN = "SecurityScenarioConfigAdmin";

var CRYPTO_ADMIN_STRING = "CryptoAdmin";
/*
@deprecate
*/
var RAMPART_INFLOW_CONFIG_ADMIN_STRING = "RampartInflowConfigAdmin";
/*
@deprecated
*/
var RAMPART_OUTFLOW_CONFIG_ADMIN_STRING = "RampartOutflowConfigAdmin";

var WSO2WSAS_SIGN_IN_STATUS = "WSO2WSAS_SIGN_IN_STATUS";

function init() {

    wso2.wsf.Util.initURLs();

    /*Initialize the XSLT cache*/
    wso2.wsf.XSLTHelper.init();
    /*initialize the dhtml history object*/
    initialize();
    /* If a vaild JSESSIONID is present refresh the login for the given domain */
    var jsessionId = wso2.wsf.Util.getCookie("JSESSIONID");
    if (jsessionId) {
        var ping = wsasPing();
        if (ping) {
            userName = wso2.wsf.Util.getCookie('userName');
            finishLogin();
        } else {
           wsasLogingHelper();
        }
    } else {
        wsasLogingHelper();
        //        document.formLogin.txtUserName.focus();
    }
}

function wsasLogingHelper() {
    userNameString =
    "<nobr><a href='about.html' target='_blank'>About</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='docs/index_docs.html' target='_blank'>Docs</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a id='logInA' href='#' onclick='javascript:wsasLogin(); return false;'>Sign In</a></nobr>";
    document.getElementById("meta").innerHTML = userNameString;
    var stat = wso2.wsf.Util.getCookie(WSO2WSAS_SIGN_IN_STATUS);
    if (stat && stat == "TRUE" && wso2.wsf.Util.getProtocol() == "https") {
        wso2.wsf.Util.deleteCookie(WSO2WSAS_SIGN_IN_STATUS);
        showLoginPage();
    } else {
        showGeneralHome();
    }
}

function wsasLogin() {
    /*Only for protocol determination*/
    var _tmpURL = locationString.substring(0, locationString.lastIndexOf('/'));
    if (_tmpURL.indexOf('https') == -1) {
        wso2.wsf.Util.setCookie(WSO2WSAS_SIGN_IN_STATUS, "TRUE");
        //Redirection to SSL will happen in follow,
        window.location = URL;
    } else {
        /*var loginDiv = document.getElementById('logincontainer');
        wso2.wsf.Util.showOnlyOneMain(loginDiv, true);*/
        showLoginPage();
    }
}

function wsasLoginCallback() {
    var isLogInDone = this.req.responseXML.getElementsByTagName("return")[0].firstChild.nodeValue;
    if (isLogInDone != "true") {
        loginFail();
        return;
    }
    userName = document.formWSASLogin.txtUserName.value;
    if (userName) {
        wso2.wsf.Util.setCookie("userName", userName);
    }

    /*initialize the dhtml history object*/
    initialize();
    /*Start login*/
    finishLogin();
}

function showForgotPassword(params) {
   wsasDivRendererHelper("forgotPassword", "login_helper.xsl", "divForgotPassword", params);
}

function showSignInHelp() {
   wsasDivRendererHelper("signInHelp", "login_helper.xsl", "divSignInHelp");
}

function showLoginPage() {
    wsasDivRendererHelper("wsasLogin", "login.xsl", "divFaq");
    document.formWSASLogin.txtUserName.focus();

}

function wsasDivRendererHelper(rootEleName, xslName, divName, params) {
    var tmpTransformationNode;
    /*
    The checking for the existance for window.XMLHttpRequest to figure out
    the browser and the functionality was dropped since the new version of
    IE has this object.
    */
    if (wso2.wsf.Util.isIE()) {
        tmpTransformationNode = new ActiveXObject("Microsoft.XmlDom");
        var sXml = "<"+rootEleName+"></"+rootEleName+">";
        tmpTransformationNode.loadXML(sXml);
    } else {
        tmpTransformationNode =
        document.implementation.createDocument("", rootEleName, null);
    }
    var objDiv = document.getElementById(divName);
    var xsltHelperObj = new wso2.wsf.XSLTHelper();
    xsltHelperObj.transform(objDiv, tmpTransformationNode, xslName, false, false, params);
    wso2.wsf.Util.showOnlyOneMain(objDiv, false);
}

/* changing css on runtime related to Menu Items*/

var selectedMenuItem = null;
var selectedMenuItemClass = null;

function renderSelectedMenuItem(obj, index) {
    if (obj != null && index) {
        if (selectedMenuItem != null) {
            selectedMenuItem.className = selectedMenuItemClass;
        }
        selectedMenuItem = obj;
        selectedMenuItemClass = selectedMenuItem.className;
        selectedMenuItem.className = MenuClassFactory.getClass(index);
    }

}

function renderGeneralHomeMenueExplicitly() {
    var obj = document.getElementById('menu_home_link_general_id');
    if (obj != null) {
        if (selectedMenuItem != null) {
            selectedMenuItem.className = selectedMenuItemClass;
        }
        selectedMenuItem = obj;
        selectedMenuItemClass = selectedMenuItem.className;
        selectedMenuItem.className = MenuClassFactory.getClass(0);
    }
}

function renderHomeMenuExplicitly() {
    var obj = document.getElementById('menu_home_link_id');
    if (obj != null) {
        if (selectedMenuItem != null) {
            selectedMenuItem.className = selectedMenuItemClass;
        }
        selectedMenuItem = obj;
        selectedMenuItemClass = selectedMenuItem.className;
        selectedMenuItem.className = MenuClassFactory.getClass(0);
    }
}

/*Object that uses to execute Second run of the '*' file upload method*/

function FileExcutor() {
}

/*Encounter for bug
FileExcutor.execute = foo; is the method should be called with extraStoreDirUUID(uuid);
*/
new FileExcutor();

/*This is the method that's gonna invoked by CertificateFileUploadExecutor for WS Call*/
function extraStoreDirUUID(uuid) {
    FileExcutor.execute(uuid);
}

/*
the method storeDiv(divName, isReloadDiv); when isReloadDiv is true,
div object is not added to the histry stack of the browser.

security.js is architectured in a way, that it will load from a main
div and populate other inner divs base on Web Service calls.

Thus, the method transformationWithoutHistory(xslFile,objDiv) will transform any
internal div without adding it to the browserstack

*/

function transformationWithoutHistory(xmlObj, xslFile, objDiv, params) {
    var xsltHelperObj = new wso2.wsf.XSLTHelper();
    xsltHelperObj.transform(objDiv, xmlObj, xslFile, false, false, params);
    wso2.wsf.Util.showOnlyOneMain(objDiv, true);

}

function showRestartServer(thisObj, index) {

    if (thisObj && index) {
        renderSelectedMenuItem(thisObj, index);
        gatherHistoryObject(thisObj.id, index);
    }

    /*
    restartServer with xsl
    */

    var tmpTransformationNode;

    if (window.XMLHttpRequest && !wso2.wsf.Util.isIE()) {
        tmpTransformationNode =
        document.implementation.createDocument("", "restartServer", null);
    } else if (window.ActiveXObject) {
        tmpTransformationNode = new ActiveXObject("Microsoft.XmlDom");
        var sXml = "<restartServer></restartServer>";
        tmpTransformationNode.loadXML(sXml);
    }
    var objDiv = document.getElementById("divRestartServer");
    wso2.wsf.Util.processXML(tmpTransformationNode, "restart_server.xsl", objDiv);
    wso2.wsf.Util.showOnlyOneMain(objDiv);

}

/*Menu rendering*/

function MenuClassFactory() {
}

/* indexes and elements have a one to one relationship*/
MenuClassFactory.classElements =
new Array(
        'menu_home_link_class_clicked',
        'menu_services_class_clicked',
        'menu_modules_class_clicked',
        'menu_security_class_clicked',
        'menu_transports_class_clicked',
        'menu_keystore_class_clicked',
        'menu_logs_class_clicked',
        'menu_restart_server_class_clicked',
        'menu_system_class_clicked',
        'menu_stat_class_clicked',
        'menu_log_class_clicked',
        'menu_tracer_class_clicked',
        'menu_axis_config_class_clicked',
        'menu_wsdl2code_class_clicked',
        'menu_item_class_clicked',
        'menu_item_class_wsdl2code_clicked', //15
        'menu_item_class_wsdlview_clicked',
        'menu_item_class_wsdlconverter_clicked',
        'menu_item_class_tryit_clicked',
        'menu_item_class_aarval_clicked',
        'menu_item_class_marval_clicked');
// 20

function getMenuFactoryClassElements(index) {
    return MenuClassFactory.classElements[index];
}

MenuClassFactory.getClass = getMenuFactoryClassElements;

/** A function that is called whenever the user
 presses the back or forward buttons. This
 function will be passed the newLocation,
 as well as any history data we associated
 with the location. */
function handleHistoryChange(newLocation, historyData) {
    var actDivName = newLocation.substring(3, newLocation.length);
    var shouldDisplay = false;
    var divId;
    var divIndex
    // This is done to stop the screen from jumping about.
    if (actDivName.indexOf("divHome") > -1) {
        showHomeMenu();
        return;
    }
    if (historyData != null) {
        var objValue = historyData.menuObj;
        if (objValue != undefined) {
            var divIdIndex = objValue.indexOf(":");

            divId = objValue.substring(0, divIdIndex);
            divIndex = objValue.substring(divIdIndex + 1, objValue.length);

            shouldDisplay = true;


        }

    }

    // lastHash from mf_ui; main.js
    if (shouldDisplay) {
        renderSelectedMenuItem(document.getElementById(divId), divIndex);
    }
    // This is must
    lastHash = newLocation;

    if (actDivName.indexOf("divListServiceGroups") > -1 && shouldDisplay) {
        startServices();

    } else if (actDivName.indexOf("divStatistics") > -1 && shouldDisplay) {
        monitorSystemMenu();
    } else {
        eval("wso2.wsf.Util.showOnlyOneMain(document.getElementById('" + actDivName + "'), true)");
    }
    return;

}


function gatherHistoryObject(objId, index) {
    mainMenuObjectId = objId;
    mainMenuObjectIndex = index;
}
/*
return false ; validation fails
return true ; validation passes
*/
function parseParameterName(value) {
    var regexParamName = /[<>"'&;]+/;

    if (regexParamName.test(value)) {
        return false;
    } else {
        return true;
    }
}
/**
 * stoppingRefreshingMethodsHook is an hook. 
 */
function stoppingRefreshingMethodsHook() {
    // initializing the showDiv variable
    clearInterval(showHomeInterval);
    showDivHome = false;
    showHomeInterval = 0;
    clearInterval(showDivInterval);
    showDivStatistics = false;
    showDivInterval = 0;
    // stoping refreshing methods from listService and listServiceGroup
    clearInterval(listServiceDataRequestInterval);
    showListServiceDataDiv = false;
    listServiceDataRequestInterval = 0;

    clearInterval(listServiceGroupsRequestInterval);
    showListServcieGroupDiv = false;
    listServiceGroupsRequestInterval = 0;

    clearInterval(showGraphDivInterval);
    showGraphDivHome = false;
    showGraphDivInterval = 0;
}