//jquery code
var openTree = new Array();
     
$(document).ready(function(){        

    $("div#ajaxactive")
        .ajaxStart(function(){$(this).show();})
        .ajaxStop(function(){$(this).hide();})
        .ajaxError(function(request, settings){
             //$(this).append("<li>Error requesting page " + settings.url + "</li>");
             // $(this).show();
            });
            
    //load login screen
    manageDivs('ajaxform', 'user/show_login', -1, -1, '');
});

//for ajax forms - load appropiate ajax info
function load_ajaxform(opertype, oper, parentrecid, recid, successform)
{
    
    switch(oper)
    {     
        //User         
        case 'user/show_login':
            //user login                
            $('form#userlogin').ajaxForm({
                    type: "POST",
                    url: "user/checkLogin",
                    dataType: "json",
                    success: updateSuccess
            });
            break;          
        
        //Company
        case 'company/updateCompanyView/':
            $('form#updatecompanyform').ajaxForm({
                type: "POST",
                url: "company/updateCompany",
                dataType: "json",
                success: updateSuccess
            });
            $('#status').change(
                function(){
                    $('#company_status').val($("#status option:selected").val());
                });            
            break;
            
        //Project                
        case 'project/updateProjectView/':        
            $('form#updateprojectform').ajaxForm({
                    type: "POST",
                    url: "project/updateProject",
                    dataType: "json",
                    success: updateSuccess
            });
            $('#phase').change(
                function(){
                    $('#project_phase').val($("#phase option:selected").val());
                });            
            $('#status').change(
                function(){
                    $('#project_status').val($("#status option:selected").val());
                });            
            $('#contacts').change(
                function(){
                    $('#project_sponsor').val($("#contacts option:selected").val());
                });  
            $("#project_startdate,#project_enddate").datepicker({ 
                beforeShow: customRange, 
                showOn: "both", 
                buttonImage: "img/ui/calendar.gif", 
                buttonImageOnly: true 
            });                                                                               
            break;

        //Forum Topic                
        case 'forum/updateTopicView/':        
            $('form#updatetopicform').ajaxForm({
                    type: "POST",
                    url: "forum/updateTopic",
                    dataType: "json",
                    success: updateSuccess
            });
            break;

        //Forum Message
        case 'forum/updateMessageView/':  
            $('form#updatemessageform').ajaxForm({
                    type: "POST",
                    url: "forum/updateMessage",
                    dataType: "json",
                    success: updateSuccess
            });
            break;
            
        //Risk
        case 'risk/updateRiskView/':
            $('form#updateriskform').ajaxForm({
                    type: "POST",
                    url: "risk/updateRisk",
                    dataType: "json",
                    success: updateSuccess
            });
            $('#select_status').change(
                function(){
                    $('#risk_status').val($("#select_status option:selected").val());
                });            
            $('#select_potential').change(
                function(){
                    $('#risk_potential').val($("#select_potential option:selected").val());
                });            
            $('#select_impact').change(
                function(){
                    $('#risk_impact').val($("#select_impact option:selected").val());
                });            
            $('#select_assignedto').change(
                function(){
                    $('#risk_assignedto').val($("#select_assignedto option:selected").val());
                });            
            $("#tabsupdate > ul").tabs({ 
                selected: 0
            });
            break;
        case 'risk/viewRiskTable_byProject/':   
        case 'risk/viewRiskTable_byUser/': 
            
            var show_name = false;
            var data_type = 'byUser';
            if(oper == 'risk/viewRiskTable_byProject/') {
                show_name = true;
                data_type = 'byProject';
            }
          
            $("#flextable").flexigrid
            ({
                url: 'risk/get_json_projectrisks/' + data_type,
                dataType: 'xml',
                colModel : [
                    {display: 'ProjectID', name : 'projectid', hide: true, width : 40, sortable : true, align: 'center'},
                    {display: 'Project', name : 'project_name', hide: show_name, width : 120, sortable : true, align: 'left'},
                    {display: '#', name : 'id', width : 40, sortable : true, align: 'center'},
                    {display: 'name', name : 'name', width : 120, sortable : true, align: 'left'},
                    {display: 'status', name : 'risk_status', width : 80, sortable : true, align: 'left'},
                    {display: 'potential', name : 'risk_potential', width : 80, sortable : true, align: 'left'},
                    {display: 'impact', name : 'risk_impact', width : 80, sortable : true, align: 'left'},
                    {display: 'assigned to', name : 'risk_assignedto', width : 120, sortable : true, align: 'left'},
                    ],
                buttons : [
                    {name: 'Add', bclass: 'add', onpress : update},
                    {name: 'Edit', bclass: 'edit', onpress : update},
                    {name: 'Delete', bclass: 'delete', onpress : update},
                    {separator: true}
                    ],
                searchitems : [
                    {display: 'name', name : 'name'}
                    ],
                sortname: "name",
                selectid:  parentrecid,               
                sortorder: "asc",
                usepager: true,
                title: 'Risks',
                useRp: true,
                rp: 15,
                showTableToggleBtn: true,
                width: 700,
                height: 150
            });            
            break;

        //Task
        case 'task/updateTaskView/':
            $('form#updatetaskform').ajaxForm({
                    type: "POST",
                    url: "task/updateTask",
                    dataType: "json",
                    success: updateSuccess
            });
            $('#select_status').change(
                function(){
                    $('#task_status').val($("#select_status option:selected").val());
                });            
            $('#select_health').change(
                function(){
                    $('#task_health').val($("#select_health option:selected").val());
                });            
            $('#select_step').change(
                function(){
                    $('#task_step').val($("#select_step option:selected").val());
                });            
            $('#select_assignedto').change(
                function(){
                    $('#task_assignedto').val($("#select_assignedto option:selected").val());
                });            
            $("#tabsupdate > ul").tabs({ 
                selected: 0
            });                                                                    
            break;
            
        case 'task/viewTaskTable_byUser/':   
        case 'task/viewTaskTable_byProject/':   
            var show_name = false;
            var data_type = 'byUser';
            if(oper == 'task/viewTaskTable_byProject/') {
                show_name = true;
                data_type = 'byProject';
            }


            $("#flextable").flexigrid
            ({
                url: 'task/get_json_projecttasks/' + data_type,
                dataType: 'xml',
                colModel : [
                    {display: 'ProjectID', name : 'projectid', hide: true, width : 40, sortable : true, align: 'center'},
                    {display: 'Project', name : 'project_name', hide: show_name, width : 120, sortable : true, align: 'left'},
                    {display: '#', name : 'id', width : 40, sortable : true, align: 'center'},
                    {display: 'name', name : 'name', width : 120, sortable : true, align: 'left'},
                    {display: 'status', name : 'task_status', width : 80, sortable : true, align: 'left'},
                    {display: 'health', name : 'task_health', width : 80, sortable : true, align: 'left'},
                    {display: 'step', name : 'task_step', width : 80, sortable : true, align: 'left'},
                    {display: 'assigned to', name : 'task_assignedto', width : 120, sortable : true, align: 'left'},
                    ],
                buttons : [
                    {name: 'Add', bclass: 'add', onpress : update},
                    {name: 'Edit', bclass: 'edit', onpress : update},
                    {name: 'Delete', bclass: 'delete', onpress : update},
                    {separator: true}
                    ],
                searchitems : [
                    {display: 'name', name : 'name'}
                    ],
                sortname: "name",
                selectid:  parentrecid,               
                sortorder: "asc",
                usepager: true,
                title: 'Tasks',
                useRp: true,
                rp: 15,
                showTableToggleBtn: true,
                width: 700,
                height: 150
            });            
            break;


        //Contact                
        case 'contact/updateContactView/':        
            $('form#updatecontactform').ajaxForm({
                    type: "POST",
                    url: "contact/updateContact",
                    dataType: "json",
                    success: updateSuccess
            });
            $('#select_usertype').change(
                function(){
                    $('#contact_usertype').val($("#select_usertype option:selected").val());
                });            
            $('#select_status').change(
                function(){
                    $('#contact_status').val($("#select_status option:selected").val());
                });            
            $('#select_company').change(
                function(){
                    $('#contact_company_id').val($("#select_company option:selected").val());
                });   
            $("#tabsupdate > ul").tabs();         
            break;
        case 'contact/viewContactTable/': 
            $("#flextable").flexigrid
            ({
                url: 'contact/get_json_companycontacts',
                dataType: 'xml',
                colModel : [
                    {display: 'CompanyID', name : 'companyid', hide: true, width : 40, sortable : true, align: 'center'},
                    {display: 'ID', name : 'id', hide: true, width : 40, sortable : true, align: 'center'},
                    {display: 'first name', name : 'first_name', width : 120, sortable : true, align: 'left'},
                    {display: 'last name', name : 'last_name', width : 120, sortable : true, align: 'left'},
                    {display: 'phone', name : 'phone', width : 120, sortable : true, align: 'left'},
                    {display: 'company', name : 'company', width : 120, sortable : false, align: 'left'},
                    {display: 'username', name : 'username', width : 120, sortable : false, align: 'left'},
                    {display: 'status', name : 'status', width : 80, sortable : false, align: 'left'},
                    {display: 'user type', name : 'user_type', width : 80, sortable : false, align: 'left'},
                    ],
                buttons : [
                    {name: 'Add', bclass: 'add', onpress : update},
                    {name: 'Edit', bclass: 'edit', onpress : update},
                    {name: 'Delete', bclass: 'delete', onpress : update},
                    {separator: true}
                    ],
                searchitems : [
                    {display: 'first name', name : 'first_name'}
                    ],
                sortname: "last_name",
                selectid:  parentrecid,               
                sortorder: "asc",
                usepager: true,
                title: 'Contacts',
                useRp: true,
                rp: 15,
                showTableToggleBtn: true,
                width: 900,
                height: 150
            });            
            break;
    }
}

function load_simpletree()
{                  
    //simple tree
    simpleTreeCollection =     
    $('.simpleTree').simpleTree({        
        afterClick:function(node){
            var opertype = node.attr('opertype')
            var oper = node.attr('oper')
            var parentrecid = node.attr('parentrecid')
            var recid = node.attr('recid')
            var successform = node.attr('successform')
            manageDivs(opertype, oper, parentrecid, recid, successform);
        },
        afterDblClick:function(node){
        },
        afterMove:function(destination, source, pos){
        },
        afterAjax:function()
        {
        },
        animate:true
    });  //simple tree 
}

function save_simpletree_folderstatus()
{
    openTree = new Array();
    
    $('li.folder-open').each(function(i){
        openTree.push(this.id);
    });
    $('li.folder-open-last').each(function(i){
      openTree.push(this.id);
    });
}

//supporting functions    
//manage Divs
function manageDivs(opertype, oper, parentrecid, recid, successform) {
                   
    //perform action depending on div sent
    switch(opertype)
    {
        case 'ajaxform':
          $('#content')
                .load(oper, {}, function(){
                   load_ajaxform(opertype, oper, parentrecid, recid, successform);
                   //hide help div
                    $("div.detail").hide();

                    //show/hide detail div
                    $("div.showhide").click(function () {
                        $("div.detail").toggle();
                        });                                            
                   })
                .show();
          break;              
        case 'ajaxupdatetableform':          
          var parentid_str;  
          if(parentrecid == -1) {
            parentid_str = '';
          } else {
            parentid_str = '/' + parentrecid;
          }
          
          $('#tablecontent')
                .load(oper + recid + parentid_str, {}, 
                    function(){
                        load_ajaxform(opertype, oper, parentrecid, recid, successform);
                    })
                .show();
          break;    
        case 'ajaxupdateform':
          var parentid_str;  
          if(parentrecid == -1) {
            parentid_str = '';
          } else {
            parentid_str = '/' + parentrecid;
          }
          
          $('#content')            
                .load(oper + recid + parentid_str, {}, 
                    function(){
                        load_ajaxform(opertype, oper, parentrecid, recid, successform);

                       //hide help div
                        $("div.detail").hide();

                        //show/hide detail div
                        $("div.showhide").click(function () {
                            $("div.detail").toggle();
                        });                                            
                    })
                .show();
          break;    
        case 'displayform':
          $('#content').load(oper);   
          break;
        case 'updateform':            
            $('#content').load(oper + recid, {},
                function(){
                        //hide help div
                        $("div.detail").hide();

                        //show/hide detail div
                        $("div.showhide").click(function () {
                            $("div.detail").toggle();
                            });                                            
                })
                .show();   
          break;              
        case 'reportform':
            $('#content').load(oper + parentrecid);   
          break;              
        case 'deleteform':
            $("#content").load(oper + recid, {}, 
                function(){
                    $('#content').load(successform);
                    save_simpletree_folderstatus(); 
                    $("#menucontent").load('home/loadmenu', {}, function(){                       
                       load_simpletree();
                     });
             });
          break;              
        case 'deletetableform':
            $("#message").load(oper + recid, {}, 
                function(){
                    $('#tablecontent').html('<script type="text/javascript">$(".pReload").click(); </script>');
                });
          break;              
        default:
          //display error message
          $('#contentmessage').html('unknown oper ' + opertype + '/' + oper + '/' + parentrecid + '/' + recid + '/' + successform );
          break;
    }  // switch
}  //manageDivs    

function updateSuccess(data) {
    //refresh screen - this is done since just refreshing the menu does not work
    if(data.source == 'table') 
    {
        if(data.success == 'yes') {
            $('#message').html(data.message);    
            $('#tablecontent').html('<script type="text/javascript">$(".pReload").click(); </script>');
        }  else {
            $('#message').html(data.message);    
        }
    } else if(data.source == 'dbupdate') 
    {
        if(data.success == 'yes') {
            //display view
            manageDivs(data.opertype, data.oper, data.parentrecid, 
                data.recid, data.successform);
            
            //reload tree
            save_simpletree_folderstatus(); 
            $("#menucontent").load('home/loadmenu', {}, function(){
                    load_simpletree();
                 });
        }  else {
            $('#message').html(data.message);
        }
    } else if(data.source == 'login') 
    { 
        if(data.success == 'yes') {
            $('#message').html(data.message);    
            $('#toprightmessage').html(data.username + '/' + data.usertype);    
            $('#username').val(data.username);
            $('#usertype').val(data.usertype);
            $('#userid').val(data.userid);
            
            save_simpletree_folderstatus(); 
            $("#menucontent").load('home/loadmenu', {}, function(){
                    load_simpletree();
                 });
            $('#content').load('home/info');
        }  else {
            alert('no');
            $('#message').html(data.message);    
            $('#toprightmessage').html('not logged in');    
            $('#username').val('not logged in');
            $('#usertype').val('');
            $('#userid').val(-1);            
        }
    } else {    
        if(data.success == 'yes') {
            $('#message').html(data.message);    
            save_simpletree_folderstatus(); 
            $("#menucontent").load('home/loadmenu', {}, function(){
                    load_simpletree();
                 });
        }  else {
            $('#message').html(data.message);    
        }
    }
}                         