﻿
/**************************************** t3-tw Login Use ***************************************************/
var authenticationHandler = function() {
    var _self = this;
    var _headers = new Array();

    var _paramNames = new Array();
    var _paramValues = new Array();

    var _soapMessage;

    var _url = "http://webservice.t3-tw.com/Login/Login.asmx";
    var _xmlnamespace = "http://webservice.t3-tw.com/Login";

    var _onValid;
    var _onLeave;
    var _onInvalidId;
    var _onInvaliedPassword;
    var _onError;
    var _onBlock;

    this.send = function(soapAction) {
        var fs = xmlHttpRequest.getFlash();

        function callback(varName) {
            var response = fs.GetVariable(varName);
            _self.responseText = response;
            if (_self.onload) {
                _self.onload();
            }
        }
        this.createHeader(soapAction);

        fs.XmlHttp(_url, CallbackManager.registerCallback(callback), _soapMessage, _headers, "text/xml; charset=utf-8");
    };
    this.createHeader = function(soapAction) {
        _headers.push("Cache-Control");
        _headers.push("public, no-cache, max-age=0");

        _headers.push("Pragma");
        _headers.push("public, no-cache");

        _headers.push("expires");
        _headers.push("0");

        _headers.push("SOAPAction");
        _headers.push(soapAction);
    };
    this.createSoapMessage = function(methodName) {
        var strEnvelope = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
		"<soap:Body><" + methodName + " xmlns=\"" + _xmlnamespace + "\">";

        for (i = 0; i < _paramNames.length; i++) {
            strEnvelope += "<" + _paramNames[i] + ">" + _paramValues[i] + "</" + _paramNames[i] + ">";
        }

        return strEnvelope + "</" + methodName + "></soap:Body></soap:Envelope>";
    };

    this.requestLogin = function(id, password, onValid, onLeave, onInvalidId, onInvaliedPassword, onError) {
        _paramNames[0] = "userId";
        _paramNames[1] = "password";

        _paramValues[0] = id;
        _paramValues[1] = password;

        if (!this.isfunction(onValid, "onValid")
			|| !this.isfunction(onLeave, "onLeave")
			|| !this.isfunction(onInvalidId, "onInvalidId")
			|| !this.isfunction(onInvaliedPassword, "onInvaliedPassword")
			|| !this.isfunction(onError, "onError")) {
            return;
        }
        _onValid = onValid;
        _onLeave = onLeave;
        _onInvalidId = onInvalidId;
        _onInvaliedPassword = onInvaliedPassword;
        _onError = onError;
        _soapMessage = this.createSoapMessage("SetLogin");

        this.onload = this.responseLogin;
        this.send(_xmlnamespace + "/SetLogin");
    };
    this.requestLogout = function(onload) {
        _soapMessage = this.createSoapMessage("SetLogout");
        this.onload = (onload == null) ? this.responseLogout : onload;
        this.send(_xmlnamespace + "/SetLogout");
    };
    this.isfunction = function(functionObj, parameterName) {
        if (functionObj == null || typeof (functionObj) != 'function') {
            alert(parameterName + "- Please specify the script function");
            return false;
        }
        else
            return true;
    };
    this.responseLogin = function() {
        var response = _self.responseText;




        if (response == 'undefined') {
            _onError.call(response);
            return false;
        }
        var res = this.createXMLFromString(response);

        switch (this.getNodeFromXML(res, 'Flag')) {
            case "0":
                var loginUser = {
                    key: this.getNodeFromXML(res, 'Key'),
                    id: this.getNodeFromXML(res, 'ID'),
                    //	name:	res.getElementsByTagName('Name')[0].text,
                    //	nick:	res.getElementsByTagName('Nick')[0].text,
                    email: this.getNodeFromXML(res, 'UserMail'),
                    token: this.getNodeFromXML(res, 'Token'),
                    status: this.getNodeFromXML(res, 'UserAgree')
                }
                _onValid.call(this, loginUser); //location.reload();
                this.loginStatus(loginUser.status);
                break;
            case "1":
                _onLeave.call();
                break;
            case "201":
                _onInvalidId.call();
                break;
            case "202":
                _onInvaliedPassword.call(this, this.getNodeFromXML(res, 'ID'));
                break;
            case "203":
                _onError.call(this, '帳號已被鎖定!');
                break;
            default: //case "100":
                _onError.call(this, this.getNodeFromXML(res, 'ID'));
                break;
        }
    };

    this.loginStatus = function(status) {
        switch (status) {
            case "N":
                var url = "http://webservice.t3-tw.com/policy/UserAgree.aspx";
                window.location.replace(url);
                break;
            default:
                break;
        }
    };

    this.createXMLFromString = function(message) {
        var xmlDocument;
        var xmlParser;
        if (window.ActiveXObject) {   //IE
            xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
            xmlDocument.async = false;
            xmlDocument.loadXML(message);
        } else if (window.XMLHttpRequest) {   //Firefox, Netscape
            xmlParser = new DOMParser();
            xmlDocument = xmlParser.parseFromString(message, 'text/xml');
        } else {
            return null;
        }
        return xmlDocument;
    };
    this.getNodeFromXML = function(xml, node) {
        return (xml.getElementsByTagName(node)[0].firstChild == null) ? "" : xml.getElementsByTagName(node)[0].firstChild.nodeValue;
    };
    this.responseLogout = function() {
        var response = _self.responseText;



        if (response != 'undefined') {
            location.reload();
        }
    };
}
var currentAuthenticationHandler;
/*
id : User Id
password : encrypted password
onValid : When valied members is the processing function handler, parameter : login user joson object
onLeave : When leave members is the processing function handler
onInvalidId : When wrong id members is the processing function handler
onInvaliedPassword : When wrong password members is the processing function handler, parameter : id
onError : When exception is the processing function handler, parameter : exception message
*/
function RequestLogin(id, password, onValid, onLeave, onInvalidId, onInvaliedPassword, onError) {
    currentAuthenticationHandler = new authenticationHandler();
    currentAuthenticationHandler.requestLogin(id, password, onValid, onLeave, onInvalidId, onInvaliedPassword, onError);
};

/*
onloadFunction : When processing is complete, sign out of the function is being processed(If you do not value, page reload)
*/
function RequestLogout(onload) {
    currentAuthenticationHandler = new authenticationHandler();
    currentAuthenticationHandler.requestLogout(onload);
};

