/*
 * These are some predefined glue listeners that you can
 *  modify to fit your application.
 *
 * This file should not placed in the /resources directory of your application
 * as that directory is for jmaki specific resources.
 */

// uncomment to turn on the logger
jmaki.debug = false;
// uncomment to show publish/subscribe messages
jmaki.debugGlue = false;

// map topic dojo/fisheye to fisheye handler
jmaki.subscribe("/dojo/fisheye*", function(args) {
    jmaki.log("glue.js : fisheye event");
 });

var rowId;
var selected_block_email;
var selected_block_type;
var selected_block_expiration_date;
var create_email_expiration_date;

// map topics ending with  /onSave to the handler
jmaki.subscribe("*onSelect", function(args) {
    jmaki.log("glue.js : onSelect request from: " + args.widgetId);
    if(args.widgetId == "MyFilterTable")
    {
        var mytableData2 = args.value;
        rowId = args.targetId;
        jmaki.log(jmaki.inspect(mytableData2)); //_inspectDepth, _currentDepth))
        selected_block_email = mytableData2.blocked_email;
        selected_block_type = mytableData2.block_type;
        selected_block_expiration_date = mytableData2.block_expiration_date;
        var verify = document.getElementById("removeRow");
        if(verify)
            verify.innerHTML = "Deleting Email: "+ selected_block_email;
        
        var blockedEmail = document.getElementById("blockedEmail");
        if(blockedEmail)
            blockedEmail.value = selected_block_email;
        
        
        var dtPicker;
        dtPicker = jmaki.getWidget("block_expiration_date");
        if(dtPicker)
        {
            //alert(selected_block_expiration_date);
            //alert(typeof selected_block_expiration_date);
            //var newDate = selected_block_expiration_date.replace(/\//g, "-");
            //alert(newDate);
            dtPicker.value = selected_block_expiration_date;
            //dtPicker.setNewDate(selected_block_expiration_date);
        }
        
        
        /*
        var block_expiration_date = document.getElementById("block_expiration_date");
        if(block_expiration_date)
            block_expiration_date.value = selected_block_expiration_date;
        */
        
        
        /*/
        var blockType = document.getElementByName("blockType");
        if(blockType)
            blockType.value = selected_block_type;*/
       
      if(selected_block_type == "Permanent")
      {
          document.getElementById("blockType_Permanent").checked = true;
      }
      else
      {
          document.getElementById("blockType_Temporary").checked = true;
      }
       
       
        
            //blockType.value = selected_block_type;
        
       
    }
    else if(args.widgetId == "block_expiration_date2")
    {
        create_email_expiration_date = args.value;
        jmaki.log("You picked the date of:" + args.value);
    }
    
    //if update is active, we need to populate the entry
    
    
    //jmaki.log(jmaki.inspect(mytableData2)); //_inspectDepth, _currentDepth))
    
    //var mytableData = jmaki.getWidget("MyFilterTable").value;
    //jmaki.log(jmaki.inspect(mytableData)); //_inspectDepth, _currentDepth))
    
});

function reloadURL()
{
  window.location.reload();
}


// find the row
function getRow(targetId) 
{
  for (var i=0; i < books.length; i++) 
  {
      for (var ii=0; ii < books[i].length; ii++) 
      {
          if (books[i][ii].id == targetId) return books[i][ii];
      }
  }
  return null;
}
  
function getSelectedEmail(targetId)
{
    jmaki.log("targetId = " + targetId);
    var mytableData = jmaki.getWidget("MyFilterTable").value;
    jmaki.log(jmaki.inspect(mytableData)); //_inspectDepth, _currentDepth))
    for (var i=0; i < mytableData.length; i++) 
    {
        if (mytableData[i].id == targetId) 
            return mytableData[i][1];
    }
    return null;
}

function emailcheck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID");
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail ID");
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail ID");
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail ID");
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail ID");
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail ID");
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail ID");
		    return false;
		 }

 		 return true;					
	}
function doCreate(){
    var opName = "create";
    
    var blockedEmail = document.getElementById("create_blockedEmail").value;
    if ((document.getElementById("create_blockedEmail").value==null)||(document.getElementById("create_blockedEmail").value==""))
    {
		alert("Please enter the sender's email address to block or suspend in the blocked email edit box");
		document.getElementById("create_blockedEmail").focus();
		return;
    }
    if(!emailcheck(blockedEmail))
    {
        document.getElementById("create_blockedEmail").value = "";
        document.getElementById("create_blockedEmail").focus();
        return;
    }
    var blockType;
    var blockTypeDisplay;
    var expiration_date_Display;
    var block_expiration_date = jmaki.getWidget("block_expiration_date2").getValue();
    if(document.create.create_blockType[0].checked == true)
    {
        blockType = "0";
        blockTypeDisplay = "Permanent";
        expiration_date_Display = "";
    }
    else
    {
        blockType = "1";
        blockTypeDisplay = "Temporary";
        expiration_date_Display = block_expiration_date;
    }
    //var blockType = document.getElementById("create_blockType").value;
    jmaki.log("blockType="+blockType);
    //var block_expiration_date = document.getElementById("block_expiration_date").value;
    
    //var block_expiration_date2 = jmaki.getWidget("block_expiration_date2").value;
    //var block_expiration_date2 = jmaki.getWidget("block_expiration_date2").getValue();
    //jmaki.log("picked the date:" +  block_expiration_date2);
    //jmaki.log("the expirartion date is:" + create_email_expiration_date);
       
    jmaki.doAjax({method: "POST",
        url: "SpamFilterServlet",
        content :  { blockedEmail: blockedEmail, blockType : blockType, block_expiration_date : block_expiration_date, opName: opName }, 
        callback: function(_req) {
            if (jmaki.trim(_req.responseText) == "SUCCESS")
            {
                jmaki.publish ('/MyFilterTable/addRow', {
                    value: {
                        blocked_email : blockedEmail,
                        block_type : blockTypeDisplay,
                        block_expiration_date : expiration_date_Display
                    }
                });
                document.forms.create.reset();
            }
            else
                alert ("error adding a row: "+_req.responseText);
        }
    });
        /*    
            
	    if(!tmp)  {
                 var a = jmaki.getWidget("dialog1");
                 a.setVisible(true);
            }  else {
	       var obj = eval("(" + tmp + ")");
                if ( opName == "create")
                     jmaki.publish('/table/addRow', obj);
		else {
		    jmaki.publish('/table/updateRow', obj);
	       }
	   }
        },
        onerror: function() {
                 var a = jmaki.getWidget("dialog1");
                 a.setVisible(true);            
                    } 
     });*/
     
}

function doDelete() {

    //jmaki.log("value "+document.getElementById("hidden").value);
    var opName = "delete";
    jmaki.log("trying to delete row id = " + rowId);
    jmaki.log("selected_email =  " + selected_block_email);
    //var selected_email = getSelectedEmail(rowId);
    
    
    //var authorId = rowId;  //set in onSelect
    
      jmaki.doAjax({method: "POST",
        url: "SpamFilterServlet",
        content :  { blockedEmail: selected_block_email, opName: opName },
        callback: function(_req) {
            jmaki.log("Get response back from server:" + _req.responseText);
            if (jmaki.trim(_req.responseText) == "SUCCESS")
            {
                 jmaki.publish ('/MyFilterTable/removeRow', { targetId: rowId});
            }
            else
                alert ("error removing a row: "+_req.responseText);
        }
    });
     
     jmaki.log("After calling doAjax")
     document.forms.remove.reset();
     var verify = document.getElementById("removeRow");
     verify.innerHTML = " ";
}

function doUpdate(){
    var opName = "update";
    
    //jmaki.log("value "+document.getElementById("hidden").value);
    
    jmaki.log("opName "+opName);
    var blockedEmail = document.getElementById("blockedEmail").value;
    //var blockType = document.getElementById("blockType").value;
    if ((document.getElementById("blockedEmail").value==null)||(document.getElementById("blockedEmail").value==""))
    {
		alert("Please enter the sender's email address to block or suspend in the blocked email edit box");
		document.getElementById("blockedEmail").focus();
		return;
    }
    if(!emailcheck(blockedEmail))
    {
        document.getElementById("blockedEmail").value = "";
        document.getElementById("blockedEmail").focus();
        return;
    }
    
    
    var block_expiration_date = jmaki.getWidget("block_expiration_date").getValue();
    
    var blockType;
    var blockTypeDisplay;
    var expiration_date_Display;
    if(document.getElementById("blockType_Permanent").checked)
    {
        blockType = "0";
        blockTypeDisplay = "Permanent";
        expiration_date_Display = "";
    }
    else
    {
        blockTypeDisplay = "Temporary";
        blockType = "1";
        expiration_date_Display = block_expiration_date;
    }
    //alert("blockType is:" + blockType);
    //var block_expiration_date = document.getElementById("block_expiration_date").value;
    
       
      jmaki.doAjax({method: "POST",
        url: "SpamFilterServlet",
        content :  { blockedEmail: blockedEmail, blockType : blockType, block_expiration_date : block_expiration_date, opName: opName },
        callback: function(_req) {
            if (jmaki.trim(_req.responseText) == "SUCCESS")
            {
                jmaki.publish ('/MyFilterTable/updateRow', {
                    targetId: rowId,
                    value: {
                        blocked_email : blockedEmail,
                        block_type : blockTypeDisplay,
                        block_expiration_date : expiration_date_Display
                    }
                });
            }
            else
                alert ("error updating: "+_req.responseText);
        }        
      });
      
      //reloadURL();
    
            /*
            var tmp = _req.responseText;
	    if(!tmp)  {                  
                 var a = jmaki.getWidget("dialog2");
                 a.setVisible(true);
            }  else {
	       var obj = eval("(" + tmp + ")");
                if ( opName == "create")
                     jmaki.publish('/table/addRow', obj);
		else {
		    jmaki.publish('/table/updateRow', obj);
	       }
	   }
            // handle any errors
        },
        onerror: function() {
                 var a = jmaki.getWidget("dialog2");
                 a.setVisible(true);
             }
     });*/
     //document.forms.update.reset();
     
}



jmaki.subscribe("/Main/button/AddRow", function(args) {
    jmaki.log("in /Main/button/AddRow");
    //var table = jmaki.getWidget("mytable");
    //table.addRow( ['', 'test@yahoo.com','1', '']);
    var row ={ user_name : 'user_must_exist',blocked_email: 'test@yahoo.com', block_type:'1', block_expiration_date:''};
    jmaki.publish("/Main/table/addRow",{value: row});
});

jmaki.subscribe("/Main/button/DeleteRow", function(args) {
    jmaki.log("in /Main/button/DeleteRow");
    jmaki.log(jmaki.insepect(args));
    var row = getRow(jmaki.getWidget("AllFilterTable"));
    if (row){
        jmaki.log("user_name=" + row.user_name + ", email="+ row.blocked_email);
        //window.location.href = row.url;
        //jmaki.log("in /Main/button/DeleteRow, user name = " + last_selected.value.user_name + ", email = " + last_selected.value.blocked_email);
      jmaki.doAjax({method: "POST",
      url: "deleteSpamEntry.jsp?user_name=" + encodeURIComponent(row.user_name)+"&email="+encodeURIComponent(row.blocked_email),
      callback: function(_req) 
      {
        //jmaki.publish('/Main/table/removeRow', { targetId: args.value.user_name });
        jmaki.publish('/Main/table/removeRow', { targetId: row });
      }
      });
    }


    
});

jmaki.subscribe("/Main/button/Update", function(args) {
    jmaki.log("in /Main/button/Update");
    jmaki.doAjax({method: "POST",
    url: "update.jsp?user_name=" + encodeURIComponent(args.value.user_name)+"&email="+encodeURIComponent(args.value.blocked_email)
    });
});


// map topics ending with  /onSave to the handler
jmaki.subscribe("*onSave", function(args) {
    jmaki.log("glue.js : onSave request from: " + args.id + " value=" + args.value);
});



// map topics ending with  /onSave to the handler
jmaki.subscribe("*onClick", function(args) {
    jmaki.log("glue.js : onClick request from: " + args.widgetId);
});

jmaki.subscribe("/LoginButton", function(args) {
    onLogin();
});

jmaki.subscribe("/SignupButton", function(args) {
    onSignup();
});

jmaki.subscribe("/LogOffButton", function(args) {
    onLogOff();
});

function onLogOff()
{
    var operation = "logoff";
    jmaki.doAjax({method: "POST",
    url: "LoginServlet"
    });
}
function onLogin()
{
    jmaki.log("onLogin get called.");
    var txtUserName = document.getElementById("txtUserName").value;
    var txtPassword = document.getElementById("txtPassword").value; 
    var operation = "login";
    jmaki.doAjax({method: "POST",
    url: "LoginServlet",
    content :{ txtUserName: txtUserName, txtPassword : txtPassword, operation : operation },
    callback: function(_req) 
        {
           if (jmaki.trim(_req.responseText) == "SUCCESS")
            {
                document.loginForm.submit();
            }
            else
                alert (_req.responseText);
        }
    });
}

function onSignup()
{
    jmaki.log("onSignup get called.");
    jmaki.log(document.getElementById("txtUserName"));
    var txtUserName = document.getElementById("txtUserName").value;
    var txtPassword = document.getElementById("txtPassword").value;
    jmaki.log("txtUserName = " + txtUserName);
    jmaki.log("txtPassword = " + txtPassword);
    var operation = "signup";
    jmaki.doAjax({method: "POST",
    url: "LoginServlet",
    content :{ txtUserName: txtUserName, txtPassword : txtPassword, operation : operation },
    callback: function(_req) 
        {
            //jmaki.publish('/Main/table/removeRow', { targetId: args.value.user_name });
            //jmaki.publish('/Main/table/removeRow', { targetId: row });
            if (jmaki.trim(_req.responseText) == "SUCCESS")
            {
                document.loginForm.submit();
            }
            else
                alert (_req.responseText);
        }
    });
}
  
