﻿//This file defines methods for accessing the currently logged in user. Most of
//these are static convience methods.
var User = {}
var loginDialogId = null;
//Returns the currently logged in user. Use this method rather than attempting to
//get the global attribute
User.getCurrentUser = function() {
  return window.bucappuser;
}

//Sets the currently logged in user. The passed in
//object should have an attribute called 'user' with
//the correct values
User.setCurrentUser = function(user) {
  var logoutUser = false;
  var newUser = user;
  if (is(newUser)){
    if (is(newUser.dialogId))
    {
      $('#'+newUser.dialogId).remove();
    }
    if (is(newUser.user)) {
      window.bucappuser = newUser.user;  
    } else {
     window.bucappuser = newUser;  
    }
  } else {
    //If we are setting the user to null
    //and there is a valid user then send logout
    //reuqest to server
    if (window.bucappuser != null) logoutUser = true;
    window.bucappuser = null;
  } 
  
  User.apply();
  if (logoutUser) User.doLogout();    
}

//Applies all user settings
User.apply = function() {  
  User.applyMenuSecurity();
}

//Convience method that checks for role
//access for the currently logged in user
User.isInRole = function(role) {
  var user = User.getCurrentUser();
  if (is(user) && is(user.roles))
  {
    return user.roles[role] === true;
  }
  return false;
}

//Convience method to check if logged in user exists
User.valid = function() {
  var user = User.getCurrentUser();
  if (is(user))
  {
    return true;
  }
  return false;  
}

//Applies security settings to the main menu
//options for the currently logged in user
User.applyMenuSecurity = function() {
    if (!User.valid()) {
        //Hide the no data filter from winter routes
        $("#tsWinerRow_NO_DATA").css({ "display": "none" })
        //Hide Admin options
        $("#adminToolsShade").css({ "display": "none" })

        //Hide wind direction filter from public                       
        $("#windParent").css({ display: "none" })
        $("#windChild").css({ display: "none" })

        //Hide disaster incident filte from public
        $("#disasterFilter").css({ display: "none" })

        //Hide traffic device display from public view
        $("#trafficDevice").css({ display: "none" })
        $("#trafficDeviceChild").css({ display: "none" })

        //Hide traffic segment editor from public view                                            
        $("#trafficSpeedAdminFunctions").css({ "display": "none" });

        //Hide FMS Region select box from public view
        $("#fmsRegionsDropdown").css({ "display": "none" })

        //Hide the private rwis options from public
        //disable the click since there are no child options        
        $("#imgRwisParent").unbind("click");

        //Change plus/minus icon to blank image
        $("#imgRwisParent").attr("src", "images/treeBlank.gif");

        //Change to public icon
        $("#rwisParentIcon").attr("src", "images/iconsAndPins/purple_triangle.gif");

        //hide child items
        $("#rwisChild").css({ display: "none" })

        //Hide HAR Beacons from public
        $("#harBeacon").css({ display: "none" })
        $("#harBeaconChild").css({ display: "none" })
        
    } else {
        //Show wind direction filter to internal users
        showRow($("#windParent"));
        showRow($("#windChild"));

        //Show disaster incident filter to internal users
        showRow($("#disasterFilter"));

        //Show the no data filter for winter routes to internal
        showRow($("#tsWinerRow_NO_DATA"));

        //Show rwis to internal        
        //enable the click since there are child options now
        $("#imgRwisParent").click(function() { $("#tsLink_rwis").trigger("click") });
        //Add the plus icon to 
        $("#imgRwisParent").attr("src", "images/treePlus.gif");

        //Change to internal parent icon
        $("#rwisParentIcon").attr("src", "images/iconsAndPins/green_triangle.gif");
        //Show the child options
        showRow($("#rwisChild"));

        //Display Admin options selectivly
        $("#adminToolsShade").css({ "display": "block" })


        if (User.isInRole("APP-BUC-Road Activity Editor")) {
            $("#roadActivityAdminFunctions").css({ "display": "block" })
        } else {
            $("#roadActivityAdminFunctions").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-Winter Route Editor")) {
            $("#winterAdminFunctions").css({ "display": "block" })
        } else {
            $("#winterAdminFunctions").css({ "display": "none" })
        }

        //if we should show FMS Region dropdown box
        var viewFMSMessageBox = false;

        //Camera stuff
        var viewCameraSelections = false;

        if (User.isInRole("APP-BUC-WebCamera Editor")) {
            viewCameraSelections = true;
        } else {
            $("#addCamera").css({ "display": "none" })
            $("#editCamera").css({ "display": "none" })
            $("#deleteCamera").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-Camera Controller")) {
            viewCameraSelections = true;
        } else {
            $("#controlCamera").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-Camera Viewer")) {
            viewCameraSelections = true;
        } else {
            $("#viewCamera").css({ "display": "none" })
            $("#viewCameraBank").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-Camera Tour Editor")) {
            viewCameraSelections = true;
        } else {
            $("#editCameraTours").css({ "display": "none" })
        }

        if (viewCameraSelections) {
            viewFMSMessageBox = true;
            $("#cameraAdminFunctions").css({ "display": "block" })
        } else {
            $("#cameraAdminFunctions").css({ "display": "none" })
        }


        //DMS stuff
        var viewSignSelections = false;

        if (User.isInRole("APP-BUC-DMS Operator")) {
            viewSignSelections = true;
        } else {
            $("#editMessageSign").css({ "display": "none" })
            $("#viewMultipleMessageSigns").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-DMS Travel Time Editor")) {
            viewSignSelections = true;
        } else {
            $("#manageMessageSign").css({ "display": "none" })
            $("#createMultipleSignView").css({ "display": "none" })
            $("#editMultipleSignView").css({ "display": "none" })
            $("#deleteMultipleSignView").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-DMS Administrator")) {
            viewSignSelections = true;
        } else {
            $("#addMessageSign").css({ "display": "none" })
            $("#deleteMessageSign").css({ "display": "none" })
        }

        if (viewSignSelections) {
            viewFMSMessageBox = true;
            $("#messageSignAdminFunctions").css({ "display": "block" })
        } else {
            $("#messageSignAdminFunctions").css({ "display": "none" })
        }

        //HAR stuff
        var viewHarSelections = false;

     if (User.isInRole("APP-BUC-HAR Operator")) {
            viewHarSelections = true;
        } else {
            $("#editHar").css({ "display": "none" })
            $("#viewMultipleHar").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-HAR Travel Time Editor")) {
            viewHarSelections = true;
        } else {
            $("#manageHar").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-HAR Administrator")) {
            viewHarSelections = true;
        } else {
            $("#addHar").css({ "display": "none" })
            $("#deleteHar").css({ "display": "none" })
            $("#addHarBeacon").css({ "display": "none" })
            $("#manageHarBeacon").css({ "display": "none" })
            $("#deleteHarBeacon").css({ "display": "none" })
        }

        if (viewHarSelections) {
            viewFMSMessageBox = true;            
            $("#harAdminFunctions").css({ "display": "block" })
        } else {
            $("#harAdminFunctions").css({ "display": "none" })
        }

        if (User.isInRole("APP-BUC-Traffic Speed Segment Editor")) {
            viewFMSMessageBox = true;
            $("#trafficSpeedAdminFunctions").css({ "display": "block" })
        } else {
            $("#trafficSpeedAdminFunctions").css({ "display": "none" })
        }


        if (User.isInRole("APP-BUC-Travel Time Segment Editor")) {
            viewFMSMessageBox = true;
            $("#travelSegmentsAdminFunctions").css({ "display": "block" })
        } else {
            $("#travelSegmentsAdminFunctions").css({ "display": "none" })
        }        


        if (viewFMSMessageBox)
            $("#fmsRegionsDropdown").css({ "display": "block" })
        else
            $("#fmsRegionsDropdown").css({ "display": "none" })

        //Traffic Device Display
        //Show the traffic device display to priveleged viewers
        if (User.isInRole("APP-BUC-Traffic Speed Viewer")) {
            showRow($("#trafficDevice"));
            showRow($("#trafficDeviceChild"));
        } else {
            $("#trafficDevice").css({ display: "none" })
            $("#trafficDeviceChild").css({ display: "none" })
        }


        //HAR Beacons
     if ((User.isInRole("APP-BUC-HAR Administrator")) || (User.isInRole("APP-BUC-HAR Operator"))) {
            showRow($("#harBeacon"));
            showRow($("#harBeaconChild"));
        } else {
            $("#harBeacon").css({ display: "none" })
            $("#harBeaconChild").css({ display: "none" })
        }        
    }
}

//Logs out the current user
User.doLogout = function(){
    $.getJSON('ajax/login/LogOut.aspx', function(resp) {
      //Ignore response
    });
}


//Loads the current user from the server
User.loadCurrentUser = function(){
    $.getJSON('ajax/login/GetCurrentUser.aspx', function(resp) {        
        User.setCurrentUser(resp.user);
    });
    return User.getCurrentUser();
}



//Debug function that displays attributes for the currently
//logged in user in an alert box
User.displayUser = function() {
    var user = User.getCurrentUser();
    var msg = "user [";
   if ((typeof user  != "undefined") && (user != null))
    {
        msg += objToString(user);
    } else {
      msg = "No user is currently logged in."
    }
    msg += "]";    
    alert(msg);
}

function objToString(obj)
{
    var msg = "";
    var first = true;    
    for (prop in obj){
      var value = obj[prop];
      if (first) {
        msg += prop + " [";
        first = false;
      } else {
        msg += ", " + prop + " [";
      }
      
      if (typeof value == "object"){
         msg += objToString(value);
      } else {
         msg += value;
      }
      
      msg += "]";
    }
    return msg;
}

/*
Firefox will not display table rows correctly using display: block have to
use display: table-row (this is standards compliant). IE on the other hand 
requires display: block (non-standard)
*/
function showRow(el) {
    if ($.browser.msie) {
        el.css({ display: "block" })
    }
    else {
        el.css({ display: "table-row" })
    }                        
}


/*
 Login prompt dialog functions
*/
function showLoginPrompt() {
    var dialogId = Math.floor(Math.random() * 23423);
    var dialog = '#' + dialogId;
    loginDialogId = dialog;
    
    var iframeSrc = LOGIN_URL + '?doLoginPrompt=true&dialogId=' + dialogId;
    
    // once the user clicks the ok button an event on the page needs to be fired in order for the
    // next window to be created and their selected data be populated
    var frameName = "frame_" + dialogId;
    
    var cancelBtn = function() {
        $(dialog).remove();
        loginDialogId = null;
    }    
    
    var params = {
        id: dialogId,
        h: 150,
        w: 350,
        title: 'Login - BuckeyeTraffic',
        buttons:[{ "id":"btnCancel", "value":"Cancel", "click":cancelBtn }],        
        body: {type: 'iframe', src: iframeSrc}};
    
    var d = new DialogBox(params);
}

//------------------------------------------------------------------------------------------------------------
function doPromptForLogin()
{    
   try
   {
      if (!User.valid())
      {
        showLoginPrompt();
      }
   }catch(e){}
    return false;
}
//------------------------------------------------------------------------------------------------------------
function doLogUserOut()
{
    try
    {
      if (User.valid())
      {
          User.setCurrentUser(null);
          closeWindows();  //from buckeyetrafficfunctions
      }
    }catch(e){}
    return false;    
}


function is(obj){
  return (typeof obj != "undefined" && obj != null);
}

