<?xml version="1.0" encoding="UTF-8" ?>
<Module>
    <ModulePrefs title="Account Recovery">
        <Require feature="pubsub-2"/>
    </ModulePrefs>
    <Content type="html" view="default">
        <![CDATA[

        <link rel="stylesheet" type="text/css" href="js/ui/css/main.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jquery-ui-1.12.1.custom.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jqueryui-themeroller.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/dialog.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-theme.css">

	    <script src="js/jquery.min.js" type="text/javascript"></script>
	    <script type="text/javascript" src="serverinfo.jag"></script>
        <script>
            var headID = document.getElementsByTagName("head")[0];
            var cssNode = document.createElement('link');
            cssNode.type = 'text/css';
            cssNode.rel = 'stylesheet';
            cssNode.href = PROXY_CONTEXT_PATH + '/portal/gadgets/account-recovery/js/ui/font-awesome/css/font-awesome.min.css';
            headID.appendChild(cssNode);
        </script>
	<script>
		$(function() {
			$('.max_view').click(function() {
				 gadgets.Hub.publish('org.wso2.is.dashboard', {
                            msg : 'A message from User profile',
                            id: "account_recovery .expand-widget"
                        });
			});
		});
	</script>

	    <div class='icon-rotate-left icon-rotate-left-dashboard icon-marketing-styles'></div>
        <p>Update account recovery challenge questions.</p>
        <p><a class='btn btn-default max_view' href=''>View details</a></p>
        ]]>
    </Content>

    <Content type="html" view="home">
        <![CDATA[
	    <script type="text/javascript" src="/portal/csrf.js"></script>
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="js/main.js"></script>
        <script type="text/javascript" src="js/modal.js"></script>
        <script type="text/javascript" src="js/gadget.js"></script>
        <script type="text/javascript" src="serverinfo.jag"></script>

        <link rel="stylesheet" type="text/css" href="js/ui/css/main.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-theme.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-missing.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/dialog.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jquery-ui-1.12.1.custom.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jqueryui-themeroller.css">

        <script>
            var headID = document.getElementsByTagName("head")[0];
            var cssNode = document.createElement('link');
            cssNode.type = 'text/css';
            cssNode.rel = 'stylesheet';
            cssNode.href = PROXY_CONTEXT_PATH + '/portal/gadgets/account-recovery/js/ui/font-awesome/css/font-awesome.min.css';
            headID.appendChild(cssNode);
        </script>

        <script type="text/javascript">
            var cookie = null;
            var json = null;
            var userName = null;
            var serverUrl = window.location.host + PROXY_CONTEXT_PATH;

            $(function WindowLoad(event) {
                url = 'wss://' + serverUrl + '/dashboard/session_manager.jag';
                ws = new WebSocket(url);

                ws.onopen = function () {
                    console.log("web Socket onopen. ");
                    ws.send("First Message open");
                };
                //send message to server
                //   setTimeout(function () {
                //     ws.send("First Message - - -");
                //}, 50);

                //event handler for the message event in the case of text frames
                ws.onmessage = function (event) {
                    var obj = $.parseJSON(event.data);
                    cookie = obj.cookie;
                    userName = obj.user;
                    reloadGrid();
                    if (cookie != null) {
                        var str = PROXY_CONTEXT_PATH + "/portal/gadgets/account-recovery/index.jag";

                        $.ajax({
                            type:"POST",
                            url:str,
                            data: {cookie : cookie, user : userName}

                        })
                                .done(function (data) {
                                    json = $.parseJSON(data);
                                    drawPage();

                                })
                                .fail(function () {
                                    console.log('error');

                                })
                                .always(function () {
                                    console.log('completed');
                                });
                    }
                };
                ws.onclose = function () {
                    console.log("web Socket onclose. ");
                };
            });

            function submitUpdate() {
                var str = PROXY_CONTEXT_PATH + "/portal/gadgets/account-recovery/controllers/account_recovery/edit_finish.jag";
                $.ajax({
                    url:str,
                    type:"POST",
                    data:$('#gadgetForm').serialize() + "&profileConfiguration=default" + "&cookie=" + cookie + "&user=" + userName
                })
                        .done(function (data) {
			//message({content:'Successfully updated the recovery questions',type:'info', cbk:function(){} });
            		cancel();

                        })
                        .fail(function () {

			message({content:'Error While updated the recovery questions',type:'error', cbk:function(){} });
			console.log('error');

                        })
                        .always(function () {
                            console.log('completed');
                        });

            }

            function drawPage() {
       var qID = 0;
       var isAns = false;
       var sorted = [];
       for(var key in json){
          sorted.push(key);
       }
       sorted.sort();
        var body = "    <div id=\"questionSets\" class=\"col-lg-12 content-section\">\n";
       for(var i=0;i<sorted.length;i++){
          var questionSet = json[sorted[i]];
          var questionSetId = sorted[i];
          var locale = questionSet[0].locale; // locale within a questionSet are same.
          var setId = sorted[i].split("/").pop();
          body = body + "<fieldset>\n" +
               "                <input type=\"hidden\" name=\"qid[]\" value=\""+setId+"\"/>\n" +
               "                <input type=\"hidden\" name=\"challengeId_"+setId+"\" value=\""+questionSetId+"\"/>\n" +
               "                <input type=\"hidden\" name=\"locale_"+setId+"\" value=\""+locale+"\"/>\n" +
               "                <legend>Challenge Question Set ID : "+setId+"</legend>\n" +
               "                <div class=\"control-group\">\n" +
               "                    <label class=\"control-label\" for=\"q"+setId+"\">Challenge Question <span class=\"required\">*</span></label>\n" +
               "                    <div class=\"controls\">\n" +
               "                        <select id=\"q"+setId+"\" name=\"question_"+setId+"\" class=\"input-xxlarge\">\n" ;
               for (var j=0;j<questionSet.length;j++){

                      if (questionSet[j].selected == 'true')   { isAns = true; qID = j;
       body = body +  "<option name=\"q\" selected=\"selected\" value=\""+questionSet[j].question+"\">"+questionSet[j].question+"</option>\n";

                  } else {
       body = body +  "<option name=\"q\" value=\""+questionSet[j].question+"\">"+questionSet[j].question+"</option>\n";

                     }
                 }
       body = body +  "                        </select>\n" +
               "                    </div>\n" +
               "                </div>\n" +
               "                <div class=\"control-group\">\n" +
               "                    <label class=\"control-label\" for=\"q"+setId+"answer\">Your Answer <span class=\"required\">*</span></label>\n" +
               "                    <div class=\"controls\">\n";
                if(isAns){
       body = body +  "                        <input type=\"password\" name=\"ans_"+setId+"\" class=\"input-xxlarge\" value=\""+questionSet[qID].answer+"\" />\n" ;
                } else {
       body = body +  "                        <input type=\"password\" name=\"ans_"+setId+"\" class=\"input-xxlarge\" value=\"\" />\n" ;
               }
       body = body +        "                    </div>\n" +
               "                </div>\n" +
               "            </fieldset>\n";
       }
        body = body + "            <div class=\"control-group\">\n" +
               "                <div class=\"controls\">\n" +
               "                    <input type=\"button\" class=\"btn btn-primary\" value=\"Update\" onclick=\"validate();\"/>\n" +
               "                    <input type=\"button\" class=\"btn btn-default btn-cancel\" value=\"Cancel\" onclick=\"cancel();\"/>\n" +
               "                </div>\n" +
               "            </div>\n" +
               "    </div>" ;


                output = body;
                $("#gadgetBody").empty();
                $("#gadgetBody").append(output);
            }

function cancel(){
           gadgets.Hub.publish('org.wso2.is.dashboard', {
                        msg:'A message from User profile',
                        id:"account_recovery  .shrink-widget"
           });

}


function validate() {
    var element = "<div class=\"modal fade\" id=\"messageModal\">\n" +
        "  <div class=\"modal-dialog\">\n" +
        "    <div class=\"modal-content\">\n" +
        "      <div class=\"modal-header\">\n" +
        "        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>\n" +
        "        <h3 class=\"modal-title\">Modal title</h4>\n" +
        "      </div>\n" +
        "      <div class=\"modal-body\">\n" +
        "        <p>One fine body&hellip;</p>\n" +
        "      </div>\n" +
        "      <div class=\"modal-footer\">\n" +
        "      </div>\n" +
        "    </div>\n" +
        "  </div>\n" +
        "</div>";
    $("#message").append(element);

    var collection = document.getElementById('questionSets').getElementsByTagName('INPUT');
    for (var x=0; x < collection.length; x++) {
      if (collection[x].type.toUpperCase() == 'PASSWORD') {
        var collection_number = collection[x].name;
        collection_number = collection_number.replace("ans_", "");
        if (validateEmpty(collection[x]).length > 0) {
          var msg = "Challenge Question Set " + collection_number + " is required";
          message({content:msg, type:'warning', cbk:function () {
          } });
          return false;
        }
      }
    }
    submitUpdate();

}

function validateEmpty(fldelement) {
    var fld = fldelement;
    var error = "";
    var value = fld.value;
    if (value.length == 0) {
        error = fld.name + " ";
        return error;
    }
    value = value.replace(/^\s+/, "");
    if (value.length == 0) {
        error = fld.name + "(contains only spaces) ";
        return error;
    }
    return error;
}
        </script>


        <form id="gadgetForm" class="form-horizontal">
            <div id="gadgetBody"></div>
	    <div id="message"></div>
        </form>

        ]]>
    </Content>
</Module>
