﻿/// <reference path="jquery.js" />
/// <reference path="jquery-ui-1.7.2.custom.min.js" />


function Impersonate(id)
{
    $.ajax({
              type: "GET",
              url: "../Home/Impersonate?id="+id,
              dataType: "text",
              global:false,
              cache:false,
              success: function(data)
              {
                  //ShowAlert(data);
              },
              error: function(data)
              {
                  ShowAlert("Cannot impersonate this user at this time, please contact the site administrator.");
              }
            });
};

       
/* Client Side Pagination functions */  
function ChangePage(page)
{
    var totalResults = $('#CaseListTable').attr("TotalResults");
    var totalPages = 0;
    if(totalResults %30 == 0)
        totalPages = totalResults/30;
    else
        totalPages = parseInt(totalResults/30) + 1;
    //update page number background
    $('a.pageNum').each(function()
    {
        if($(this).attr("value") != page.toString())
        {
            $(this).removeClass('selected').addClass('notSelected');
        }
        else
        {
            $(this).removeClass('notSelected').addClass('selected');
        }
        
        if(parseInt($(this).attr("value")) > totalPages-1)
            $(this).hide();
        else
            $(this).show();
    });
    
    
    //updateTable
    var currentPage = page;
    if(currentPage+1 == totalPages)
        $('#nextLink').find('img').hide();
    else
        $('#nextLink').find('img').show();
        
    if(currentPage == 0)
        $('#previousLink').find('img').hide();
    else
        $('#previousLink').find('img').show();
     
        
    var numPerPage = 30;

    $('.paginated').find('tbody .visible').hide()
        .slice(currentPage * numPerPage, (currentPage + 1) * numPerPage)
          .show();
    
    UpdateSummary(page,totalResults);
    
    
};

function NextClick()
{
    var totalResults = $('#CaseListTable').attr("TotalResults");
    var totalPage = parseInt(totalResults/30+1);
    var page = 0;
    $('a.pageNum').each(function()
    {
        if($(this).hasClass("selected"))
        {
            page = parseInt($(this).attr("value"))+1;
            
        }
    });
   
    
    if(page>totalPage-1)
        return;
    
    //switch to the next 10 pages view
    if(page%10 == 0)
    {
        $('a.pageNum').each(function()
        {
            $(this).attr("value",parseInt($(this).attr("value"))+10);
            if(parseInt($(this).attr("value")) < totalPage)
            {
                this.innerHTML = parseInt($(this).attr("value"))+1;
                $(this).unbind('click');
                $(this).click(function()
                {
                    ChangePage(parseInt($(this).attr("value"))); 
                });
            }
            else
            {
                $(this).unbind('click');
                this.innerHTML = "";
            }
        });    
        
    }   
    ChangePage(page);    
}

function PreviousClick()
{
    var totalResults = $('#CaseListTable').attr("TotalResults");
    var page = 0;
    $('a.pageNum').each(function()
    {
        if($(this).hasClass("selected"))
        {
            page = parseInt($(this).attr("value"))-1;
            
        }
    });
   
    
    if(page<0)
        return;
    
    //switch to the next 10 pages view
    if(page%10 == 9)
    {
        $('a.pageNum').each(function()
        {
            $(this).attr("value",parseInt($(this).attr("value"))-10);
            this.innerHTML = parseInt($(this).attr("value"))+1;
            $(this).unbind('click');
            $(this).click(function()
            {
                ChangePage(parseInt($(this).attr("value"))); 
            });
        });    
        
    }   
    ChangePage(page);    
}

function UpdateSummary(page)
{
     var totalResults = $('#CaseListTable').attr("TotalResults");
     var totalPages = 0;
     if(totalResults %30 == 0)
         totalPages = totalResults/30;
     else
         totalPages = parseInt(totalResults/30) + 1;
        
     var currentPage = page + 1;
     $("#PageSum").attr("innerHTML","Page &nbsp;"+currentPage.toString()+"&nbsp;of&nbsp;"+totalPages);
     var start = page*30+1;
     var end = totalResults;
     if((page+1)*30 < totalResults)
     {
         end = (page+1)*30;    
     }
     $("#ResultsSum").attr("innerHTML","&nbsp;"+start.toString()+"&nbsp;-&nbsp;" + end.toString()+"&nbsp;of&nbsp;"+totalResults);    
}

function SortBy(column)
{ 
    $table = $('.paginated');
    
    var firstrow =  $table.find('tbody > tr:eq(0)').get();
    var rows = $table.find('tbody .visible').get();
    
    var count = 0;
    var asc = 1;
    $.each(firstrow,function(index, row)
    {      
        $('th',row).each(function(col)
        {
            var imgSrc = $(this).find('a > img').attr("src");
            if(col == column)
            {
                if(imgSrc=='undefined' || imgSrc == "" || imgSrc == "../images/Sort-down-blue.png")
                {
                    $(this).find('a > img').attr("src","../images/sort-up-blue.png");
                    
                }
                else
                {
                    $(this).find('a > img').attr("src","../images/Sort-down-blue.png"); 
                    asc = 0; 
                }
                $(this).find('a > img').show();
            }
            else
            {
                $(this).find('a > img').hide(); 
            }
        })
    })
    
    $.each(rows, function(index, row) 
    {
        if(column == 0)
        {
            if($(row).children('td').eq(0).children('img').attr("alt") == "Bug")
                row.sortKey = 1;
            else if($(row).children('td').eq(0).children('img').attr("alt") == "Feature")
                row.sortKey = 2;
            else
                row.sortKey = 3;
        }
        else if(column == 1) //compare the numbers
        { 
            row.sortKey = parseInt($(row).children('td').eq(column).text());
        }
        else if(column == 5) //compare dates
            row.sortKey = new Date(($(row).children('td').eq(column).attr("value")));
        else
            row.sortKey = $(row).children('td').eq(column).text().toUpperCase()
       
        count ++; 
    })
    
    if(asc == 1)
    {
        rows.sort(function(a, b) {
                if (a.sortKey < b.sortKey) return -1
                if (a.sortKey > b.sortKey) return 1
                return 0
        })
    }
    else
    {
         rows.sort(function(a, b) {
                if (a.sortKey < b.sortKey) return 1
                if (a.sortKey > b.sortKey) return -1
                return 0
        })   
    }
    
    
    $.each(rows, function(index, row) {
            $table.children('tbody').append(row)
            row.sortKey = null
    })
    
    ChangePage(0);
    RedrawBackgound('.paginated');
    
}

//filters as checkbox list
function ShowHideListFilters(list,checkList,tableName,colName)
{
    var pos = $('#'+colName).position();
    var selectAll = true;
    if($('#FilterDiv').attr("value") == "0")
    {
        $('#FilterDiv').css('visibility','visible');
        $('#FilterDiv').css('position','absolute');
        $('#FilterDiv').css('left',pos.left);
        $('#FilterDiv').css('top',pos.top+10);
       
        
        //remove old rows
        $('#FilterDivTable').find('tbody > tr').remove();
        
        //add new rows
        var cbList = list.split(',');
        var checkedList = checkList.split(',');
        for(var i=0 ;i<cbList.length; i++)
        {
            var row = '<tr style="background-color:#6699CC"><td><input onclick="UncheckSelectAllFilters()" class="filterCB" type="checkbox" ';
            if(checkedList[i] == "true")
                row += ' checked="checked" value="'+cbList[i]+'"/></td><td><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">'+cbList[i]+'</label></td></tr>';
            else
            {
                row += ' value="'+cbList[i]+'"/></td><td><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">'+cbList[i]+'</label></td></tr>';
                selectAll = false;  
            }
            $('#FilterDivTable').children('tbody').append(row);
        }
        
        $('#FilterSelectAllLabel').show();
        $('#FilterListSelectAll').show();
        $('#FilterListSelectAll').attr("checked",selectAll);
               
        $('#FilterDiv').show();
        $('#FilterInnerDiv').show();
        $('#FilterDiv').attr("value", "0.5");
        $('#FilterDiv').attr("tableName",tableName);
        $('#FilterDiv').attr("colName",colName);
        $('#FilterSubmit').unbind('click');
        $('#FilterSubmit').click(function()
        {
            FilterListSubmit(); 
        });
    }
    else
    {
        $('#FilterDiv').css('visibility','hidden');
        $('#FilterInnerDiv').hide();
        $('#FilterDiv').hide();
        $('#FilterDiv').attr("value", "0");    
    }
    
    

}

//filters as datepickers
function ShowHideRangeFilters(list,checkList,tableName,colName)
{
    var pos = $('#'+colName).position();
    var selectAll = true;
    if($('#FilterDiv').attr("value") == "0")
    {
        $('#FilterDiv').css('visibility','visible');
        $('#FilterDiv').css('position','absolute');
        $('#FilterDiv').css('left',pos.left);
        $('#FilterDiv').css('top',pos.top+10);
       
        
        //remove old rows
        $('#FilterDivTable').find('tbody > tr').remove();
        
        var cbList = list.split(',');
        var checkedList = checkList.split(',');
        
        //add new rows
        var fromRow = '<tr style="background-color:#6699CC">'+
                      '<td align="right"><label for="InputFrom" style="font-family:Arial, Helvetica, sans-serif; font-size:11px">From:</label></td>'+
                      '<td><input type="text" id="InputFrom" style="width:110px; border:solid medium Silver" /></td></tr>';
        var toRow = '<tr style="background-color:#6699CC">' + 
                    '<td align="right"><label for="InputTo" style="font-family:Arial, Helvetica, sans-serif; font-size:11px">To:</label></td>'+
                    '<td><input type="text" id="InputTo" style="width:110px; border:solid medium Silver" /><td></tr>';
       
        var emptyRow = '<tr><td colspan ="2">&nbsp;</td></tr>';
        
        var last7Radio = '<tr><td colspan="2" ><input type="radio" name="preRange" id="radio7" onclick="ChangeRange(7)" /><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">Last 7 days</label></td><tr>';
        var last30Radio = '<tr><td colspan="2" ><input type="radio" name="preRange" id="radio30" onclick="ChangeRange(30)" /><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">Last 30 days</label></td><tr>';
        
        $('#FilterDivTable').children('tbody').append(fromRow);
        $('#FilterDivTable').children('tbody').append(toRow);
        $('#FilterDivTable').children('tbody').append(emptyRow);
        $('#FilterDivTable').children('tbody').append(last7Radio);
        $('#FilterDivTable').children('tbody').append(last30Radio);
        

        $('#InputFrom').datepicker(
        {
            onSelect: function()
            {
                $('#radio7').attr("checked",false);
                $('#radio30').attr("checked",false);
            }
        });
        
        $('#InputTo').datepicker(
         {
            onSelect: function()
            {
                $('#radio7').attr("checked",false);
                $('#radio30').attr("checked",false);
            }
        });
        
        $('#InputFrom').attr("value",cbList[0]);
        $('#InputTo').attr("value",cbList[1]);
        

        if(checkedList[0] == "true")
        {
            $('#radio7').attr("checked",true); 
        }
        else if(checkedList[1] == "true")
        {
            $('#radio30').attr("checked",true);
        }
        

        $('#FilterSelectAllLabel').hide();
        $('#FilterListSelectAll').hide();
               
        $('#FilterDiv').show();
        $('#FilterInnerDiv').show();
        $('#FilterDiv').attr("value", "0.5");
        $('#FilterDiv').attr("tableName",tableName);
        $('#FilterDiv').attr("colName",colName);
        $('#FilterSubmit').unbind('click');
        $('#FilterSubmit').click(function()
        {
            FilterRangeSubmit(); 
        });
    }
    else
    {
        $('#FilterDiv').css('visibility','hidden');
        $('#FilterInnerDiv').hide();
        $('#FilterDiv').hide();
        $('#FilterDiv').attr("value", "0");    
    }
    
    

}

function ShowHideCaseFilters(colName)
{
    var pos = $('#'+colName).position();
    var list = "";
    var checkList = "";
    
    if(colName == "category")
    {
        list =  "Inquiry,Bug,Feature";
        checkList = $('#FilterDiv').attr("categoryCheckList");
    }
    else if(colName == "status")
    {
        list = "Closed,Active";
        checkList = $('#FilterDiv').attr("statusCheckList");
    }

    var selectAll = true;
    if($('#FilterDiv').attr("value") == "0")
    {
        $('#FilterDiv').css('visibility','visible');
        $('#FilterDiv').css('position','absolute');
        $('#FilterDiv').css('left',pos.left);
        $('#FilterDiv').css('top',pos.top+10);
       
        
        //remove old rows
        $('#FilterDivTable').find('tbody > tr').remove();
        
        //add new rows
        var cbList = list.split(',');
        var checkedList = checkList.split(',');
        for(var i=0 ;i<cbList.length; i++)
        {
            var row = '<tr style="background-color:#6699CC"><td><input class="filterCB" type="checkbox" onclick="UncheckSelectAllFilters()"';
            if(checkList.indexOf(cbList[i]) >= 0)
                row += ' checked="checked" value="'+cbList[i]+'"/></td><td><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">'+cbList[i]+'</label></td></tr>';
            else
            {
                row += ' value="'+cbList[i]+'"/></td><td><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">'+cbList[i]+'</label></td></tr>';
                selectAll = false;  
            }
            $('#FilterDivTable').children('tbody').append(row);
        }
        
        $('#FilterSelectAllLabel').show();
        $('#FilterListSelectAll').show();
        $('#FilterListSelectAll').attr("checked",selectAll);
               
        $('#FilterDiv').show();
        $('#FilterInnerDiv').show();
        $('#FilterDiv').attr("value", "0.5");
        $('#FilterDiv').attr("colName",colName);
        $('#FilterDiv').attr("tableName","CaseTable");
        $('#FilterSubmit').unbind('click');
        $('#FilterSubmit').click(function()
        {
            FilterCaseSubmit(colName); 
        });
    }
    else
    {
        $('#FilterDiv').css('visibility','hidden');
        $('#FilterInnerDiv').hide();
        $('#FilterDiv').hide();
        $('#FilterDiv').attr("value", "0");    
    }
    
    

}

//filters as datepickers
function ShowHideCaseRangeFilters(colName)
{
    var pos = $('#'+colName).position();
    var selectAll = true;
    if($('#FilterDiv').attr("value") == "0")
    {
        $('#FilterDiv').css('visibility','visible');
        $('#FilterDiv').css('position','absolute');
        $('#FilterDiv').css('left',pos.left);
        $('#FilterDiv').css('top',pos.top+10);
       
        
        //remove old rows
        $('#FilterDivTable').find('tbody > tr').remove();
        

        //add new rows
        var fromRow = '<tr style="background-color:#6699CC">'+
                      '<td align="right"><label for="InputFrom" style="font-family:Arial, Helvetica, sans-serif; font-size:11px">From:</label></td>'+
                      '<td><input type="text" id="InputFrom" style="width:110px; border:solid medium Silver" /></td></tr>';
        var toRow = '<tr style="background-color:#6699CC">' + 
                    '<td align="right"><label for="InputTo" style="font-family:Arial, Helvetica, sans-serif; font-size:11px">To:</label></td>'+
                    '<td><input type="text" id="InputTo" style="width:110px; border:solid medium Silver" /><td></tr>';
       
        var emptyRow = '<tr><td colspan ="2">&nbsp;</td></tr>';
        
        
        var last7Radio = '<tr><td colspan="2" ><input type="radio" name="preRange" id="radio7" onclick="ChangeRange(7)" /><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">Last 7 days</label></td><tr>';
        var last30Radio = '<tr><td colspan="2" ><input type="radio" name="preRange" id="radio30" onclick="ChangeRange(30)" /><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">Last 30 days</label></td><tr>';
        var allRadio = '<tr><td colspan="2" ><input type="radio" name="preRange" id="radioAll" onclick="ChangeRange(-1)" /><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">All</label></td><tr>';
        
        $('#FilterDivTable').children('tbody').append(fromRow);
        $('#FilterDivTable').children('tbody').append(toRow);
        $('#FilterDivTable').children('tbody').append(emptyRow);
        $('#FilterDivTable').children('tbody').append(last7Radio);
        $('#FilterDivTable').children('tbody').append(last30Radio);
        $('#FilterDivTable').children('tbody').append(allRadio);
        

        $('#InputFrom').datepicker(
        {
            onSelect: function()
            {
                $('#radio7').attr("checked",false);
                $('#radio30').attr("checked",false);
                $('#radioAll').attr("checked",false);
            }
        });
        
        $('#InputTo').datepicker(
         {
            onSelect: function()
            {
                $('#radio7').attr("checked",false);
                $('#radio30').attr("checked",false);
                $('#radioAll').attr("checked",false);
            }
        });
        
        var range = $('#FilterDiv').attr("dateRangeList");
        if(range !== "All")
        {
            range = range.split(',');
        
            $('#InputFrom').attr("value",range[0]);
            $('#InputTo').attr("value",range[1]);
            
            var fromDate = new Date(range[0]);
            var toDate = new Date(range[1]);
            var today = new Date();
            
            fromDate.setHours(0,0,0,0);
            toDate.setHours(0,0,0,0);
            today.setHours(0,0,0,0);
         
            var last7 = false;
            if(today-toDate == 0 && today-fromDate == (1000*60*60*24)*7)
                last7 = true;
            
            var last30 = false;    
            if(today-toDate == 0 && today-fromDate == (1000*60*60*24)*30)
                last30 = true;
                
            if(last7)
            {
                $('#radio7').attr("checked",true); 
            }
            else if(last30)
            {
                $('#radio30').attr("checked",true);
            }
        }
        else
            $('#radioAll').attr("checked",true);    
        

        $('#FilterSelectAllLabel').hide();
        $('#FilterListSelectAll').hide();
               
        $('#FilterDiv').show();
        $('#FilterInnerDiv').show();
        $('#FilterDiv').attr("value", "0.5");
        $('#FilterDiv').attr("colName",colName);
        $('#FilterSubmit').unbind('click');
        $('#FilterSubmit').click(function()
        {
            FilterCaseRangeSubmit(); 
        });
    }
    else
    {
        $('#FilterDiv').css('visibility','hidden');
        $('#FilterInnerDiv').hide();
        $('#FilterDiv').hide();
        $('#FilterDiv').attr("value", "0");    
    }
    
    

}

function FilterListSubmit()
{
    var str = "";
    $('.filterCB').each(function()
    {
        if(this.checked == true)
        {
            str += encodeURI(this.value);
            str += ",";
        }
    }
    );
    
    var tableName = $('#FilterDiv').attr("tableName");
    var colName = $('#FilterDiv').attr("colName");
     
    $.ajax({
          type: "GET",
          url: "../Home/"+tableName,
          dataType: "html",
          data: "filter="+colName+"&conditions="+str,
          success: function(data)
          {
              $('#FilterDiv').css('visibility','hidden');
              $('#ajaxTable').attr("innerHTML",data);
              $('#FilterDiv').attr("value","0");
              $('#FilterDiv').hide();  
          },
          error: function(data)
          {
              ShowAlert("Cannot use this filter at this time, please contact the site administrator.");
          }
        });
    
}

function FilterRangeSubmit()
{
    var fromStr = $('#InputFrom').attr("value");
    var toStr = $('#InputTo').attr("value");
    
    //check date format
    var dateformat = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/;
    if(!dateformat.test(fromStr))
    {
        ShowAlert("From Date should be of format MM/DD/YYYY, please re-enter");
        return;
    }
    if(!dateformat.test(toStr))
    {
        ShowAlert("To Date should be of format MM/DD/YYYY, please re-enter");
        return;
    }
    
    var fromDate = new Date(fromStr);
    var toDate = new Date(toStr);
   
   if(fromDate > toDate)
   {
        ShowAlert("From Date is after To Date, please re-enter");
        return;   
   }
    
    var str = fromStr + ","+ toStr;
    
    var tableName = $('#FilterDiv').attr("tableName");
    var colName = $('#FilterDiv').attr("colName");
     
    $.ajax({
          type: "GET",
          url: "../Home/"+tableName,
          dataType: "html",
          data: "filter="+colName+"&conditions="+str,
          success: function(data)
          {
              $('#FilterDiv').css('visibility','hidden');
              $('#ajaxTable').attr("innerHTML",data);
              $('#FilterDiv').attr("value","0");
              $('#FilterDiv').hide();  
          },
          error: function(data)
          {
              ShowAlert("Cannot use this filter at this time, please contact the site administrator.");
          }
        });
        
}

function FilterCaseSubmit(colName)
{
    var results = "";
    $('.filterCB').each(function()
    {
        if(this.checked)
        {
            results += encodeURI(this.value)+',';
        }
    }
    ); 
    
    if(results != "")
       results = results.substring(0,results.length-1);
       
    if(colName == "category")
    {
        $('#FilterDiv').attr("categoryCheckList",results);
    }
    else if(colName == "status")
    {
        $('#FilterDiv').attr("statusCheckList",results);
    }


    FilterCaseCommonSubmit();
        
}



function FilterCaseRangeSubmit()
{
    var fromStr = $('#InputFrom').attr("value");
    var toStr = $('#InputTo').attr("value");
    var allChecked = $('#radioAll').attr("checked");
    var count = 0; 
    
    if(allChecked != true)
    {
        //check date format
        var dateformat = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/;
        if(!dateformat.test(fromStr))
        {
            ShowAlert("From Date should be of format MM/DD/YYYY, please re-enter");
            return;
        }
        if(!dateformat.test(toStr))
        {
            ShowAlert("To Date should be of format MM/DD/YYYY, please re-enter");
            return;
        }
        
        var fromDate = new Date(fromStr);
        var toDate = new Date(toStr);
        var newToDate = new Date(toDate.getTime()+1000*60*60*24);
      
        if(fromDate > toDate)
        {
            ShowAlert("From Date is after To Date, please re-enter");
            return;   
        }
        
        $('#FilterDiv').attr("dateRangeList",(fromDate.getMonth()+1)+"/"+fromDate.getDate().toString()+"/"+fromDate.getFullYear().toString()+","+(toDate.getMonth()+1)+"/"+toDate.getDate().toString()+"/"+toDate.getFullYear().toString());
        
    }
    else
         $('#FilterDiv').attr("dateRangeList","All");
    
    FilterCaseCommonSubmit();
         
}

function FilterCaseCommonSubmit()
{
    var count = 0;
    var dateRange = $('#FilterDiv').attr("dateRangeList");
    var fromDate = new Date();
    var toDate = new Date();
    var newToDate = new Date();
    
    if(dateRange != "All")
    {
        dateRange = dateRange.split(',');
        fromDate = new Date(dateRange[0]);
        toDate = new Date(dateRange[1]);
        newToDate = new Date(toDate.getTime()+1000*60*60*24);
    }
    
    
        
    //Apply other filters
    var query1 = $('#FilterDiv').attr("categoryCheckList");

    var query2 = $('#FilterDiv').attr("statusCheckList");
    
    var query = "";
    
    if(query1 == "" || query2 == "")
        query = "";
    else
    {
        if(query1.indexOf(',') > 0)
            query1 = query1.replace(/,/gi,"|");
        if(query2.indexOf(',') > 0)
            query2 = query2.replace(/,/gi,"|");
         
        query = '('+query1+') & (' + query2 + ')'; 
    }
    
    $table = $('.paginated');     
    var rows = $table.find('tbody > tr:gt(0)').get();
    
    $.each(rows, function(index, row) 
    {
        var cat = $(row).children('td').eq(0).children('img').attr("alt");
        var sta = $(row).children('td').eq(4).text();
        var openDateStr = $(row).children('td').eq(5).attr("value");
        var openDate = new Date(openDateStr);
        
        if(sta.indexOf("Closed") >= 0)
            sta = "Closed";
        else
            sta = "Active";
        
        if(dateRange != "All")
        {
            if(query1.indexOf(cat) < 0 || query2.indexOf(sta) < 0 || newToDate-openDate <= 0 || fromDate-openDate > 0)
                $(this).hide().removeClass('visible');
            else
            {
                $(this).show().addClass('visible') ;
                count++;
            }
        }
        else
        {
            if(query1.indexOf(cat) < 0 || query2.indexOf(sta) < 0)
                $(this).hide().removeClass('visible');
            else
            {
                $(this).show().addClass('visible') ;
                count++;
            } 
        }
    });  
    
    $('#CaseListTable').attr("TotalResults",count);
    ChangePage(0);
    
    $('#FilterDiv').attr("value","0");
    $('#FilterDiv').hide();
    $('#FilterDiv').css('visibility','hidden');     
    
    RedrawBackgound('CaseListTable');
}


function ChangeRange(days)
{
    if(days == -1)
    {
        $('#InputFrom').attr("value","");
        $('#InputTo').attr("value","");    
    }
    else
    {
        var today = new Date();
        var utcTime = today.getTime();
        var sevenDaysAgo =new Date(utcTime - days*24*3600000);
        $('#InputFrom').datepicker();
        $('#InputTo').datepicker();
        $('#InputFrom').attr("value",(sevenDaysAgo.getMonth()+1)+"/"+sevenDaysAgo.getDate().toString()+"/"+sevenDaysAgo.getFullYear().toString());
        $('#InputTo').attr("value",(today.getMonth()+1)+"/"+today.getDate().toString()+"/"+today.getFullYear().toString());
    }
}

function SelectAllFilters()
{
    if($('#FilterListSelectAll').attr("checked"))
    {
        $('.filterCB').each(function()
        {
           this.checked = true;
        }
        );       
    }
    else
    {
        $('.filterCB').each(function()
        {
           this.checked = false;
        }
        );      
    }
}

function UncheckSelectAllFilters()
{
     $('.filterCB').each(function()
        {
           if(!this.checked)
           {
               $('#FilterListSelectAll').attr("checked",false);
               return;
           }
        }
      );   
    
       
}

function ShowAlert(message)
{
    window.parent.$('#AlertDialog').dialog('destroy');
    window.parent.$('#AlertDialog').attr("innerHTML","<p>"+message+"</p>");
    InitAlert();
	    
}

function InitAlert()
{
    window.parent.$('#AlertDialog').dialog({
			bgiframe: true,
			height: 140,
			modal: true
			
		}); 
}



function ShowHideAnouncements()
{
    if($('#ShowAnouncementsLink').attr("show") == "0")
    {
        $('#ShowAnouncementsLink').attr("inneHTML","- View All Previous Announcements");
        $('#ShowAnouncementsLink').attr("show","1");
        $('#PreviousAnouncementsDiv').show('slow');
    }
    else
    {
        $('#ShowAnouncementsLink').attr("innerHTML","+ View All Previous Announcements");
        $('#ShowAnouncementsLink').attr("show","0");
        $('#PreviousAnouncementsDiv').hide('slow');
    }
          
}

function ShowHidePeople(companyid)
{
    
    if($('#Company'+companyid).attr("show") == "0")
    {
        $('#Company'+companyid).attr("show","1");
        $('#Company'+companyid).find('img').attr('src','../images/security_close.png');
        $(".Users"+companyid).each(function()
        {
            if(!$(this).is(".deleted"))
                $(this).show();
        });
        
    }
    else
    {
        $('#Company'+companyid).attr("show","0");
        $('#Company'+companyid).find('img').attr("src","../images/security_expand.png");
        $(".Users"+companyid).hide();
    }
}

function ShowHideAll()
{    
    if($('#ShowHideAllLink').attr("show") == "0")
    {
        $('#ShowHideAllLink').attr("show","1");
        $('#ShowHideAllLink').find('img').attr('src','../images/security_close.png');
        $('.SecurityCompany').each(function()
        {
            $(this).children('td').eq(0).find('a>img').attr('src','../images/security_close.png');
        });
        $(".Users").each(function()
        {
            if(!$(this).is(".deleted"))
                $(this).show();
        });
        
    }
    else
    {
        $('#ShowHideAllLink').attr("show","0");
        $('#ShowHideAllLink').find('img').attr("src","../images/security_expand.png");
        $('.SecurityCompany').each(function()
        {
            $(this).children('td').eq(0).find('a>img').attr('src','../images/security_expand.png');
        });
        $(".Users").hide();
    }
}



function SecuritySortBy(column)
{ 
    $table = $('#SecurityListTable');
    
    var firstrow =  $table.find('tbody > tr:eq(0)').get();
    var rows = $table.find('tbody > tr:gt(0)').get();
    
    var count = 0;
    var asc = 1;
    $.each(firstrow,function(index, row)
    {      
        $('th',row).each(function(col)
        {
            var imgSrc = $(this).find('a > img').attr("src");
            if(col == column)
            {
                if(imgSrc == "" || imgSrc == "../images/Sort-down-blue.png")
                {
                    $(this).find('a > img').attr("src","../images/sort-up-blue.png");
                    
                }
                else
                {
                    $(this).find('a > img').attr("src","../images/Sort-down-blue.png"); 
                    asc = 0; 
                }
                $(this).find('a > img').show();
            }
            else
            {
                $(this).find('a > img').hide(); 
            }
        })
    })
    
    $.each(rows, function(index, row) 
    {
     
        row.sortKey = $(row).children('td').eq(column).text().toUpperCase()
       
        count ++; 
    })
    
    if(asc == 1)
    {
        rows.sort(function(a, b) {
                if (a.sortKey < b.sortKey) return -1
                if (a.sortKey > b.sortKey) return 1
                return 0
        })
    }
    else
    {
         rows.sort(function(a, b) {
                if (a.sortKey < b.sortKey) return 1
                if (a.sortKey > b.sortKey) return -1
                return 0
        })   
    }
    
    $.each(rows, function(index, row) {
            $table.children('tbody').append(row)
            row.sortKey = null
    })
   
    
}


function RedrawBackgound(tableName)
{
    var rows;
    
    //tablename is a class
    if(tableName.toString().indexOf('.') == 0)
        $table = $(tableName);
    else
        $table = $('#'+tableName);
    
    rows = $table.find('tbody .visible').get();
        
    var i=0;
    
    $.each(rows, function(index, row) 
    {
        if(i%2 == 0)
            $(this).addClass('alt');
        else
            $(this).removeClass('alt');  
        i++;  
            
    })
    
}

function ShowHideSecurityFilters(colName)
{
    var pos = $('#'+colName).position();
    var checkList = "";
    var cbList = new Array();
    if(colName == "accManager")
    {
        var rows = $('#SecurityListTable').find('.SecurityCompany').get();
        $.each(rows, function(index, row) 
        {
            var accManagerName = $(row).children('td').eq(8).text();
           
            if(cbList.toString().indexOf(accManagerName)<0)
                cbList.push(accManagerName);
            
        });
        
        checkList = $('#SecurityListTable').attr("accManagerCheckList");
    }
    else if(colName == "status")
    {
        cbList.push("Active");
        cbList.push("Inactive");
        checkList = $('#SecurityListTable').attr("statusCheckList");
    }

    var selectAll = true;
    if($('#FilterDiv').attr("value") == "0")
    {   
        $('#FilterDiv').css('visibility','visible');
        $('#FilterDiv').css('position','absolute');
        $('#FilterDiv').css('left',pos.left);
        $('#FilterDiv').css('top',pos.top+10);
       
        
        //remove old rows
        $('#FilterDivTable').find('tbody > tr').remove();
        
        //add new rows
        
        for(var i=0 ;i<cbList.length; i++)
        {
            var row = '<tr style="background-color:#6699CC"><td><input class="filterCB" type="checkbox" onclick="UncheckSelectAllFilters()"';
            if(checkList.indexOf(cbList[i]) < 0)
                row += ' checked="checked" value="'+cbList[i]+'"/></td><td><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">'+cbList[i]+'</label></td></tr>';
            else
            {
                row += ' value="'+cbList[i]+'"/></td><td><label style="font-family:Arial, Helvetica, sans-serif; font-size:11px">'+cbList[i]+'</label></td></tr>';
                selectAll = false;  
            }
            $('#FilterDivTable').children('tbody').append(row);
        }
        
        $('#FilterSelectAllLabel').show();
        $('#FilterListSelectAll').show();
        $('#FilterListSelectAll').attr("checked",selectAll);
               
        $('#FilterDiv').show();
        $('#FilterInnerDiv').show();
        $('#FilterDiv').attr("value", "0.5");
        $('#FilterDiv').attr("colName",colName);
        $('#FilterDiv').attr("tableName","CaseTable");
        $('#FilterSubmit').unbind('click');
        $('#FilterSubmit').click(function()
        {
            SecurityFilterSubmit(colName); 
        });
    }
    else
    {
        $('#FilterDiv').css('visibility','hidden');
        $('#FilterInnerDiv').hide();
        $('#FilterDiv').hide();
        $('#FilterDiv').attr("value", "0");    
    }
    
}

function SecurityFilterSubmit(colName)
{
    var uncheckedList = "";
    var colNo = 0;
    $('.filterCB').each(function()
    {
       if(!this.checked)
       {
           uncheckedList += encodeURI(this.value)+',';
       }    
    });
    
    var rows = $('#SecurityListTable').find('tbody > tr:gt(0)').get();
    
    if(colName == "accManager")
    {
        $('#SecurityListTable').attr("accManagerCheckList",uncheckedList);
        colNo = 8;
    }
    else
    {
        $('#SecurityListTable').attr("statusCheckList",uncheckedList);
        colNo = 10;
    }
    
    $.each(rows, function(index, row) 
    {
        var colText = $(row).children('td').eq(colNo).text();
       
        if(uncheckedList.indexOf(colText) >=0)
           $(row).hide();
        else
        {    var type = $(row).children('td').eq(1).find('img').attr('alt');
             if(type == "company")
                 $(row).show();  
        }
        
    });
    
    $('#FilterDiv').css('visibility','hidden');
    $('#FilterDiv').hide();
  
}

function UpdateDownload(sqlid,fileID)
{
     $.ajax({
          type: "GET",
          url: "../Home/FileDownload?sqlid="+sqlid+"&fileid="+fileID,
          dataType: "html",
          success: function(data)
          {
              return false; 
          },
          error: function(data)
          {
              
              //ShowAlert("Cannot use this filter at this time, please contact the site administrator.");
          }
        });
}

function DeleteFile(sqlid)
{
     $('#DeleteDialog').dialog({
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			close: function()
			{
			    $('#DeleteDialog').dialog('destroy');
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
				},
				'Delete': function() {
					$(this).dialog('close');
					$.ajax({
                    type: "GET",
                    async: false,
                    url: "../Home/DeleteFile?sqlid="+sqlid,
                    dataType: "html",
                    success: function(data)
                    {
                        $('#ajaxTable').attr("innerHTML",data);
                        ShowAlert("File has been deleted successfully.");
                    },
                    error: function(data)
                    {
                        ShowAlert("Cannot delete file at this time, please contact the site administrator.");
                        
                    }
                
                    });
				}
			}
		});
}

function DeleteUser(sqlid,username)
{    
     $('#DeleteDialog').dialog({
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			close: function()
			{
			    $('#DeleteDialog').dialog('destroy');
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
				},
				'Delete': function() {
					$(this).dialog('close');
					$.ajax({
                    type: "GET",
                    async: false,
                    url: "../Home/DeleteUser?sqlid="+sqlid,
                    dataType: "html",
                    success: function(data)
                    {
                         var rows = $('#SecurityListTable').find('tr:gt(0)').get();
                         
                         $.each(rows, function(index, row) 
                         {
                             if($(row).children('td').eq(5).text() == username)
                             {
                                 $(row).addClass('deleted');
                                 $(row).hide();
                             }
                                      
                         });
                        ShowAlert("This user has been deleted successfully.");
                    },
                    error: function(data)
                    {
                        ShowAlert("Cannot delete file at this time, please contact the site administrator.");
                        
                    }
                
                    });
				}
			}
		});
}


function DeleteCompany(sqlid,companyname)
{    
     $('#DeleteDialog').dialog({
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			close: function()
			{
			    $('#DeleteDialog').dialog('destroy');
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
				},
				'Delete': function() {
					$(this).dialog('close');
					$.ajax({
                    type: "GET",
                    async: false,
                    url: "../Home/DeleteCompany?sqlid="+sqlid,
                    dataType: "html",
                    success: function(data)
                    {
                         var rows = $('#SecurityListTable').find('tr:gt(0)').get();
                         
                         $.each(rows, function(index, row) 
                         {
                             if($(row).children('td').eq(4).text() == companyname)
                             {
                                 $(row).addClass('deleted');
                                 $(row).hide();
                             }
                                      
                         });
                        ShowAlert("This company and its users have been deleted successfully.");
                    },
                    error: function(data)
                    {
                        ShowAlert("Cannot delete file at this time, please contact the site administrator.");                       
                    }
                
                    });
				}
			}
		});
}


//New Pop-up Window
function ShowPopup(name,left,top)
{
    window.parent.$('#'+name).css('left',left)
    window.parent.$('#'+name).css('top',top);
    window.parent.$('#'+name).css('position','absolute');
    window.parent.$('#'+name).show('slow');    
}  

function HidePopup(name)
{
    window.parent.$('#'+name).hide('slow');   
}


function ShowForgetPassword()
{
    var pos = $('#forgot').position();
    ShowPopup('ForgetPasswordDiv',pos.left,pos.top);
}

function HideForgetPassword()
{
    HidePopup('ForgetPasswordDiv');
}

function SendForgetPasswordEmail()
{
    var email = $("#forgetemail").attr("value");   
    
    if(email == "")
        ShowAlert("Email address cannot be empty.");     
    else   
        forgetPassword(email);
}

function forgetPassword(email)
{
     
     $('#submitemail').attr("disabled","diabled");
     $.ajax({
          type: "GET",
          url: "../Home/ForgetPasswordSubmit?FPEmail="+email,
          dataType: "text",
          global:false,
          cache:false,
          success: function(data)
          {
              ShowAlert(data);
              $("#submitemail").removeAttr("disabled"); 
              $("#forgetemail").attr("value","");
              if(data == "New Password has been sent to your email address.")
                  HideForgetPassword();   
          },
          error: function(data)
          {
              ShowAlert("Cannot send new password at this time, please contact the site administrator.");             
          }
        });
};

function ShowAddAnnoucement()
{
    var pos = $('#AddAnnoucementLink').position();
    ShowPopup('AnnoucememntFrame',pos.left,pos.top);    
}

function AddAnnoucement()
{
    var title= $("#title").attr("value");
    var content = $("#content").attr("value"); 
    var image= $("#imageLink").attr("value");
    var link= $("#link").attr("value");


    if(title == "")
    {
        ShowAlert("Title is empty, please re-enter.");
        return;
    }
    if(content == "" )
    {
        ShowAlert("Content is empty, please re-enter.");
        return; 
    }
    if(title.length > 100)
    {
        ShowAlert("Title cannot exceed 100 characters");
        return;
    }
    if(content.length > 1024)
    {
        ShowAlert("Content cannot exceed 1024 characters");
        return;
    }
    
    
    $('#AnnouncementForm').submit();
    
    ShowAlert("Adding new annonuncement succeeded."); 
   
    HideAddAnnouncement();
    refreshAnnouncement();
    
};

function HideAddAnnouncement()
{
    HidePopup('AnnoucememntFrame');
}

function refreshAnnouncement()
{
     //refresh anouncement list
        $.ajax({
            type: "GET",
            async: false,
            url: "../Home/Anouncements",
            dataType: "html",
            success: function(data)
            {
                window.parent.$('#AjaxAnnouncements').attr('innerHTML',data);
                window.parent.$('#PreviousAnouncementsDiv').hide();   
            },
            error: function(data)
            {
                ShowAlert("Cannot refresh announcements list at this time, please contact the site administrator.");
            }
              
            
        
        });


};

function deleteAnouncement(no)
{
    $('#DeleteDialog').dialog({
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			close: function()
			{
			    $('#DeleteDialog').dialog('destroy');
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
				},
				'Delete': function() {
					$(this).dialog('close');
					$.ajax({
                    type: "GET",
                    async: false,
                    url: "../Home/Anouncements?Delete="+no,
                    dataType: "html",
                    success: function(data)
                    {
                        window.parent.$('#AjaxAnnouncements').attr('innerHTML',data);
                        window.parent.$('#PreviousAnouncementsDiv').hide();
                        ShowAlert("Announcement has been deleted successfully.");
                    },
                    error: function(data)
                    {
                        ShowAlert("Cannot refresh announcements list at this time, please contact the site administrator.");
                        
                    }
                
                    });
				}
			}
		});
    
   
    
}

function clearAnouncement()
{
    $('#title').attr("value","");
    $('#content').attr("value","");
    $('#imageLink').attr("value","");
    $('#link').attr("value","");
   
};


function ShowChangePassword()
{
    var pos1 = $('#ChangePasswordLink').position();
    var pos2 = $('#company_info').position();
    ShowPopup('ChangePasswordDiv',pos1.left+pos2.left,pos1.top+pos2.top);
};

function HideChangePassword()
{
    HidePopup('ChangePasswordDiv');
}

function ChangePasswordSubmit()
{
    var oldPass = $("#oldpass").attr("value");
    var newPass = $("#newpass").attr("value"); 
    var newPassConfirm= $("#newpass_confirm").attr("value");


    if(oldPass == "")
    {
        ShowAlert("The old password is empty, please re-enter.");
        return;
    }
    if(newPass == "" )
    {
        ShowAlert("The new password is empty, please re-enter.");
        return; 
    }
    if(newPassConfirm == "" )
    {
        ShowAlert("The confirm new password is empty, please re-enter.");
        return; 
    }
    if(newPass != newPassConfirm)
    {
        ShowAlert("The confirm new password doesn't match the new password, please re-enter.");
        return;    
    }

    changePassword(oldPass,newPass,newPassConfirm); 
}


function changePassword(oldPass,newPass,newPassConfirm)
{
     $('#submitchangepass').attr("disabled","diabled");
     $.ajax({
              type: "GET",
              url: "../Home/ChangePassword?ClientOldPassword="+oldPass+"&ClientNewPassword="+newPass+"&ConfirmNewPassword="+newPassConfirm,
              dataType: "text",
              global:false,
              cache:false,
              success: function(data)
              {
                  ShowAlert(data);
                  $('#submitchangepass').removeAttr("disabled");
                  $("#oldpass").attr("value","");
                  $("#newpass").attr("value","");
                  $("#newpass_confirm").attr("value","");
                  
                  if(data == "Your password has been successfully updated. It will take effects next time you login.")
                      HideChangePassword();
                  
              },
              error: function(data)
              {
                  ShowAlert("Cannot change password at this time, please contact the site administrator.");
              }
            });

};

/*Knowledge Base*/
function ClearDocumentDiv()
{
    $('#documentId').removeAttr('value');  
    $('#folderId').removeAttr('value');
    $('#sectionName').text('');
    $('#title').removeAttr('value');
    $('#text').removeAttr('value');
    $('#urlLink').removeAttr('value'); 
    $('#fileLink').removeAttr('value');  
}
function ShowAddDocument(tableIndex, tableName,docId)
{
    ClearDocumentDiv();
    var pos = $('#addDocumentLink_'+tableIndex).position();
    $('#folderName').text(tableName);
    if(docId)
    {
        $('#documentId').attr('value',docId);  
        //ajax pull out data 
         
    }
    $('#folderId').attr("value",tableIndex);
    $('#sectionName').text(tableName);
    $('#UpdateBtn').hide();
    $('#AddBtn').show(); 
    ShowPopup('AddDocumentDiv',pos.left,pos.top);    
}

function ShowUpdateDocument(tableIndex,tableName,docTitle,docType,docDescription,docId)
{
    ClearDocumentDiv();
    var pos = $('#editDocumentLink_'+docId).position();
    $('#folderName').text(tableName);
    $('#documentId').attr('value',docId);  
    $('#folderId').attr("value",tableIndex);
    $('#sectionName').text(tableName);
    $('#title').attr('value',decodeURIComponent(docTitle));
   
    if(docType == 1)
    {
        $('#fileLink').attr('disabled','disabled');
        $('#radioFile').removeAttr('checked'); 
        $('#urlLink').attr('disabled','disabled');
        $('#radioUrl').removeAttr('checked'); 
        $('#text').removeAttr('disabled');
        $('#radioText').attr('checked','checked');
        
        $('#text').attr('value',decodeURIComponent(docDescription));
    }
    else if(docType == 2)
    {
        $('#text').attr('disabled','disabled');
        $('#radioText').removeAttr('checked'); 
        $('#urlLink').attr('disabled','disabled'); 
        $('#radioUrl').removeAttr('checked'); 
        $('#fileLink').removeAttr('disabled');  
        $('#radioFile').attr('checked',true);
    }
    else if(docType== 0)
    {
        $('#text').attr('disabled','disabled');
        $('#radioText').removeAttr('checked'); 
        $('#fileLink').attr('disabled','disabled');
        $('#radioFile').removeAttr('checked');
        $('#urlLink').removeAttr('disabled'); 
        $('#radioUrl').attr('checked','checked');
        $('#urlLink').attr('value',decodeURIComponent(docDescription));
    }
    
    $('#UpdateBtn').show();
    $('#AddBtn').hide();   
    
    ShowPopup('AddDocumentDiv',pos.left,pos.top);    
}

function AddDocument(update)
{
    var title= $("#title").attr("value");
 
    if(title == "")
    {
        ShowAlert("Title cannot be empty.");
        return;
    }
    if(title.length > 250)
    {
        ShowAlert("Title cannot exceed 250 characters");
        return;
    }
    
    if($('#radioText').attr('checked') == true)
    {
        if($('#text').attr('value') == "")
        {
            ShowAlert("Text cannot be empty.");
            return;
        }
    }
    if($('#radioFile').attr('checked') == true )
    {
        if(update == 0)
        {
            if($('#fileLink').val() == "")
            {
                ShowAlert("No File is selected.");
                return;
            } 
        }
    }
    if($('#radioUrl').attr('checked') == true )
    {
        if($('#urlLink').attr('value') == "")
        {
            ShowAlert("URL cannot be empty.");
            return; 
        }
    }
    
    $("#title").attr("value",encodeURIComponent($("#title").attr("value")));
    $('#text').attr('value',encodeURIComponent($('#text').attr('value')));
    
    $('#AddDocumentForm').submit();
    
    
   
    HideAddDocument();
    
    
};

function HideAddDocument()
{
    HidePopup('AddDocumentDiv');
}

function refreshDocument(tableIndex)
{
     //refresh anouncement list
        $.ajax({
            type: "GET",
            async: false,
            url: "../Home/KnowledgeBaseContent",
            dataType: "html",
            success: function(data)
            {
                window.parent.$('#AjaxKnowledgeBase').attr('innerHTML',data);
            },
            error: function(data)
            {
                ShowAlert("Cannot refresh Knowledge Base at this time, please contact the site administrator.");
            }

        });


};


function deleteDocument(no)
{
    $('#DeleteDialog').dialog({
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			close: function()
			{
			    $('#DeleteDialog').dialog('destroy');
			},
			buttons: {
				Cancel: function() {
					$(this).dialog('close');
				},
				'Delete': function() {
					$(this).dialog('close');
					$.ajax({
                    type: "GET",
                    async: false,
                    url: "../Home/KnowledgeBaseContent?Delete="+no,
                    dataType: "html",
                    success: function(data)
                    {
                        window.parent.$('#AjaxKnowledgeBase').attr('innerHTML',data);
                       
                        ShowAlert("Item has been deleted successfully.");
                    },
                    error: function(data)
                    {
                        ShowAlert("Cannot refresh Knowledge Base at this time, please contact the site administrator.");
                        
                    }
                
                    });
				}
			}
		});

}

function moveUpDocument(no)
{
    $.ajax({
            type: "GET",
            async: false,
            url: "../Home/KnowledgeBaseContent?moveup="+no,
            dataType: "html",
            success: function(data)
            {
                window.parent.$('#AjaxKnowledgeBase').attr('innerHTML',data);
            },
            error: function(data)
            {
                ShowAlert("Cannot refresh Knowledge Base at this time, please contact the site administrator.");
                
            }
            });
}

function moveDownDocument(no)
{
    $.ajax({
            type: "GET",
            async: false,
            url: "../Home/KnowledgeBaseContent?movedown="+no,
            dataType: "html",
            success: function(data)
            {
                window.parent.$('#AjaxKnowledgeBase').attr('innerHTML',data);

            },
            error: function(data)
            {
                ShowAlert("Cannot refresh Knowledge Base at this time, please contact the site administrator.");
                
            }
            });
}


/*Mass Email Function*/
function ShowMassEmail()
{
    var pos = $('#MassEmailLink').position();
    ShowPopup('MassEmailDiv',pos.left-400,pos.top);       
}

function HideMassEmail()
{
    HidePopup('MassEmailDiv');
}

function EmailCompanyClicked()
{
    $('#cbAllCompanies').removeAttr('checked');
}

function AllCompanyClicked()
{
    if($('#cbAllCompanies').attr('checked') == true)
    {
        $('input:checkbox').each (function() 
         {
             $(this).attr('checked','checked');
         });  
    }
    else  
    {
         $('input:checkbox').each (function() 
         {
             $(this).removeAttr('checked');
         });  
    }
}

function GenerateEmails(InputParms)
{
    var companies = "";
    var users = 0;
    
    $('input:checkbox').each (function() 
    {
        if(this.checked == true && $(this).attr('id') != "cbAllCompanies")
        {
            companies += "" + $(this).attr('value')+",";
        }
    }); 
    
    
    if($('#AdminRadio').attr('checked') == true)
        users = 1;
    
    $.ajax({
            type: "GET",
            async: false,
            url: "../Home/GetEmails?user="+users+"&company="+companies,
            dataType: "html",
            success: function(data)
            {
                window.parent.$('#ResultsString').attr('innerHTML',data);
            },
            error: function(data)
            {
                ShowAlert("Cannot generate email list at this time, please contact the site administrator.");
                
            }
            });

}

function htmlEncode(str)
{
    while(str.indexOf('&') >=0)
        str = str.replace('>','&amp;');
    while(str.indexOf('<') >=0)
        str = str.replace('<','&lt;');
        
    while(str.indexOf('>') >=0)
        str = str.replace('>','&gt;');
    
    while(str.indexOf(' ') >=0)
        str = str.replace(' ','&nbsp;');
    
    while(str.indexOf('\r\n') >=0)
        str = str.replace('\r\n','<br/>');
    
    while(str.indexOf('\n') >=0)
        str = str.replace('\n','<br/>');
    
    return str;
}
















































