﻿var _highlightSuggestionIndex = -2; 
var _highlightDiv = null;
var _selectedIndex = -1; 
var _divObject = null;

function DisplayWord() 
{
  if(_selectedIndex > -1) 
  { 
  var selectedWord = document.getElementById("Display").childNodes[_selectedIndex].nodeValue; 
  document.getElementById("txtAuto").value = selectedWord; 
  }
  else 
  {    
    document.getElementById("txtAuto").value = ""; 
  }  
  // Hide the DIV Element 
  document.getElementById("Display").style.visibility = "hidden";
}


function SearchWord_CallBack(response)
{
    var word = response.d;
    if(response != null && word != null)
    {
        document.getElementById("Display").style.visibility = "visible";
        document.getElementById("Display").innerHTML = 
                    word.substring(0,word.length - 2);
    }
}

function Highlight(index) 
{
    if(index < 0) return;    
    completeList = document.getElementById("Display"); 
    if(index > completeList.childNodes.length) return;
    _selectedIndex = index; 
    if(completeList) 
    {       
        var divValue = document.getElementById("Display").childNodes[index].nodeValue;         
        document.getElementById("txtAuto").value = divValue;     
    }
 
}

function Hover(t){
    t.style.backgroundColor = "#ebf6fd";
}
function HoverOff(t){
    t.style.backgroundColor = "#fff";
};
function Accept(t){
   var elem = document.getElementById("txtAuto") 
   //value from display box
   elem.value = t.innerHTML;
   ar = Array();
   ar = t.id.split(":");
   SendForCampaign(ar[1]);
   //set hidden campaign value
   $('#ctl00_body_hidcampaignid').val(ar[1]);
   //DisplayWord() 
   document.getElementById("Display").style.visibility = "hidden"; 
}

function GetCampaignData_CallBack(response){
    var jso = response.d
    var val = eval(jso)
    
    //option defaults
   
    var resOptions = {
    0 : 'Simple',
    1 : 'Complex'
    };
    $('#ctl00_body_responsetype').empty();
    $.each(resOptions, function(val, text) {
        $('#ctl00_body_responsetype').append(
            $('<option></option').val(val).html(text)
        );
    });
    
    var staOptions = {
    0 : 'Inactive',
    1 : 'Active'
    };
    $('#ctl00_body_status').empty();
    $.each(staOptions, function(val, text) {
        $('#ctl00_body_status').append(
            $('<option></option').val(val).html(text)
        );
    });


    
    FillFields(val[0].Campaign,val[0].Username,val[0].Password,val[0].RuleID,val[0].Status,val[0].ResponseType);
    SendForRules(val[0].RuleID);
   
}

function FillFields(campaign,username,password,rule,status,response){
    if(campaign != ""){
        document.getElementById("ctl00_body_cmname").value = campaign
    }
    if(username != ""){
        document.getElementById("ctl00_body_username").value = username
    }
    if(password != ""){  
        document.getElementById("ctl00_body_password").value = password
    }
    if(status != ""){
        if(status == true){
            document.getElementById("ctl00_body_status").selectedIndex = 1
        }
        else{
            document.getElementById("ctl00_body_status").selectedIndex = 0
        }        
    }
    if(response != ""){
        document.getElementById("ctl00_body_responsetype").selectedIndex = response
    }    
               
}
function SwitchThis(on,off){
    if(document.getElementById(on).style.display == 'none'){
        document.getElementById(on).style.display = 'block'
        document.getElementById(off).style.display = 'none'
        
    }
    else if(document.getElementById(on).style.display == 'block'){
        document.getElementById(on).style.display = 'none'
        document.getElementById(off).style.display = 'block'
    }
    return false;
}
function Validate(){
    return true
}
function Toggle(id){
    var t = document.getElementById(id)
    if(t.style.display == 'none'){
        t.style.display = 'block'
    }
    else{t.style.display = 'none'}
    return false
}
function ClearAll(form){
    if(form == "admin"){
        $('#txtAuto').val("")
        $('#ctl00_body_cmname').val("")
        $('#ctl00_body_username').val("")
        $('#ctl00_body_password').val("")
        $('#ctl00_body_cpassword').val("")  
        $('#ctl00_body_hidcampaignid').val("");
        $('#ctl00_body_rule').empty();
        $('#ctl00_body_responsetype').empty();
        $('#ctl00_body_status').empty();
    }
    return false
}
//not sure if im using this 
function SelectThis(t){
    document.getElementById(t.id)
}
function SearchWord(pressevent,keyValue)
{
    var charCode = (pressevent.which)? pressevent.which : (event.keyCode);
    
    // Send to the Server Side Method to get the string
    if(charCode >=65 && charCode <=90 || 
       charCode >= 97 && charCode <=122) {
        Handler(keyValue)
    }

    // if the backspace key (8) is pressed and 48 is for the delete button
    else if(charCode == 8 || charCode == 48)
    {
        // Reset the count
        _highlightSuggestionIndex = -2;
        Handler(keyValue)
    }

    // when the down arrow key is pressed
    else if(charCode == 40)
    {
        if((_highlightSuggestionIndex+2) <= 
            document.getElementById("Display").childNodes.length)
        {
            _highlightSuggestionIndex = _highlightSuggestionIndex + 2;
        }

        Highlight(_highlightSuggestionIndex);
    }

    // When the up arrow key is pressed
    else if(charCode == 38)
    {
        if((_highlightSuggestionIndex-2) >= 0) {
            _highlightSuggestionIndex = _highlightSuggestionIndex -2;
        }
        Highlight(_highlightSuggestionIndex);
    }
}
function Handler(keyValue) {
    $.ajax({
        type: "POST",
        url: "WebService.asmx/Search",
        data: "{a : '" + $('#txtAuto').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {SearchWord_CallBack(result);},
        error: function(request, status, errorThrown) {
            ReturnSaved(result)
        }
    });
}
function SendForCampaign(id) {
    $.ajax({
        type: "POST",
        url: "WebService.asmx/GetCampaignData",
        data: "{campaignid : '" + id + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {GetCampaignData_CallBack(result);},
        error: function(request, status, errorThrown) {
            ReturnSaved(result)
        }
    });
}
function SendForRules(sel) {
    $.ajax({
        type: "POST",
        url: "WebService.asmx/JSONWriteRules",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {FillRules(result,sel);},
        error: function(request, status, errorThrown) {
            ReturnSaved(result)
        }
    });
}
function FillRules(result,sel){
    var res = eval(result.d);
    var rule = document.getElementById("ctl00_body_rule")
    var i=0;
    $('#ctl00_body_rule').empty();
    for(i in res){
        var opnew = document.createElement('option');
        opnew.text = res[i].RuleName
        opnew.value = res[i].RuleID
        if(res[i].RuleID == sel){
            opnew.selected = true;
        }
        try{
            rule.add(opnew,null);
        }
        catch(ex){
            rule.add(opnew);
        }
    }
    ShowEditPage();
}


function Save(){
    $.ajax({
        type: "POST",
        url: "WebService.asmx/Save",
        data: "{campaignid : '" + $('#ctl00_body_hidcampaignid').val() + "',accountid : '" + 
        1 + "',ruleid : '" + $('#ctl00_body_rule').val() + "',campaign : '" + $('#ctl00_body_cmname').val() + 
        "',username : '" + $('#ctl00_body_username').val() + "',password : '" + $('#ctl00_body_password').val() + "',responsetype : '" + 
        $('#ctl00_body_responsetype').val()  + "',debugmode : '" + 1 + "',status : '" + $('#ctl00_body_status').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {ReturnSaved(result);},
        error: function(request, status, errorThrown) {
            ReturnSaved(result);
        }
    });
}

function ReturnSaved(res){
    $('#msg').css("visibility","visible");
    $('#msg').css("color","red");
    if(res.d == "succ-add"){
        $('#msg').text("Account has been successfully created.");
        ClearAll("admin");
        HideEdit();
    }
    else if(res.d == "err-add"){
        $('#msg').text("There was a problem creating the account. Please try again.");
    }
    else if(res.d == "succ-edit"){
        $('#msg').text("Account has been successfully updated.");
        ClearAll("admin");
        HideEdit();
    }  
    else if(res.d == "err-edit"){
        $('#msg').text("There was a problem updating the account. Please try again.");
    }     
    else{
        $('#msg').text("An error has occured. Please try again.")
    } 
}


function randomPassword()
{
  length = 6
  chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  pass = "";
  for(x=0;x<length;x++)
  {
    i = Math.floor(Math.random() * 64);
    pass += chars.charAt(i);
  }
  return pass;
}

$(document).ready(function() {
    if($('#ctl00_body_rid').val() != ""){
        //makes the row that was clicked on highlighted after post back from server
        var id = $('#ctl00_body_rid').val();
        var row = $('#'+id);
        row.removeClass('click-row');
        row.addClass('click-row-on');
        //add name over repeater based on the value in the clicked td
        //var name = row.find("td").eq(1).html();  
        //$('#rule-name').text(name);
    }
    if(document.getElementById('ctl00_body_sdate')){dp_cal  = new Epoch('epoch_popup','popup',document.getElementById('ctl00_body_sdate'));}
	if(document.getElementById('ctl00_body_edate')){p_cal  = new Epoch('epoch_popup','popup',document.getElementById('ctl00_body_edate'));}
	$('#les-cal').click(function(){
	   dp_cal.toggle()
	}),
	$('#led-cal').click(function(){
	   p_cal.toggle()
	}),
	$('#les-cal').hover(function(){
	   $(this).css("cursor","pointer");
	}),
	$('#led-cal').hover(function(){
	   $(this).css("cursor","pointer");
	}),	
    $('#txtAuto').focus(function(){
        this.select();
    }),
    $('#ctl00_body_save').click(function(){
        Save();
        return false;
    }),
	$('#ctl00_body_clear').click(function(){
        ShowAddPage()
        return false;
    }),    
	$('#show-rule').click(function(){
       $('#newrule').slideToggle("slow"); 
       return false;      
    })
    ,
	$('.click-row').hover(
	 function(){
	    if($(this).css("backgroundColor") != "rgb(246, 246, 246)")
            $(this).css("backgroundColor","#F3F3F3");  
    },
    function(){
        if($(this).css("backgroundColor") != "rgb(246, 246, 246)")
            $(this).css("backgroundColor","#FFF");    
    }),
    $('.click-row').find('td:eq(1)').click(function(){   
        $('#ctl00_body_rid').val($(this).parent().attr("id"))
        __doPostBack('RepeaterviewRuleSelect',$(this).parent().attr("id") ); 
    }),
    $('.click-row').find('td:eq(0)').click(function(){   
        $('#ctl00_body_rid').val($(this).parent().attr("id"))
    }),    
    $('.click-row').find('td:eq(1)').hover(function(){
        $(this).css("cursor","pointer");
    }),   
    $('#add-account').click(function(){
        if($(this).html() == '[ + ] Add Account'){
            $(this).text('[ - ] Add Account');
        }
        else{
            $(this).text('[ + ] Add Account');
        }
        $('#add-rules').slideToggle('slow');
        return false;
    });        
});

function ShowAddPage(){
    SetAddName();
    ClearAll("admin");
    HideEdit();
}
function ShowEditPage(){
    $('.rule-bloc').css("visibility","visible")
    SetEditName();
    $('#msg').text("");
}

function HideEdit(){
    $('.rule-bloc').css("visibility","hidden")
}
function SetEditName(){
    $('#td-account').html('Edit Account');
}
function SetAddName(){
    $('#td-account').html('Add Account');
}
