﻿// Global Script for all Pages on Manager EdPortal.com
var DefaultMsgBoxTitle  = "Edportal.com";
var DefaultMsgBoxWidth  = 350;
var DefaultMsgBoxHeight = 125;
var TimeoutUrl = '/logout.aspx?timeout=1';
var reset_session = null;
var AjaxFolderPanel = null, AjaxWebsiteNavPanel = null;
var MyWebsiteUrl = null;
var MyProfileUrl = null;
var WebsiteModuleUrl = 'website.aspx';
var ResourcesModuleUrl = '/public/edresources.aspx';
var ManagerModuleUrl = 'manager.aspx';
var MyProfileModuleUrl = 'profile.aspx';

function cfm( t, m, cb, w, h, el ){
    w = ( w ) ? w : DefaultMsgBoxWidth;
    h = ( h ) ? h : DefaultMsgBoxHeight;
    return radconfirm(m, cb, w, h, el, t);    
}

function alt(t, m, w, h, cb){
    w = ( w ) ? w : DefaultMsgBoxWidth;
    h = ( h ) ? h : 'auto';
    //cb = (cb) ? cb : function() { this.hide(false); }
    var win = radalert(m, w, h, t);
    win.ClientCallBackFunction = cb;    
    return win;
    //var props = {'Title':t,'Width':w,'Height':h, 'Buttons':MsgButtonTypes.Ok,'CallBackFunction':cb};
    //return Dialog.Show(m,props);
}

function prmt(t,m,cb,w,h, el){
    w = ( w ) ? w : DefaultMsgBoxWidth;
    h = ( h ) ? h : DefaultMsgBoxHeight;
    return radprompt(m, cb, w, h, el, t);    
}

function LoadModule( mod ){
    var url = ManagerModuleUrl;
    switch( mod ){
        case 'website':
            url = WebsiteModuleUrl; 
            break;
        case 'myprofile':
            url = MyProfileModuleUrl; 
            break;
        case 'edresources':
            url = ResourcesModuleUrl;
            break;                     
    }
    location.replace(url);
    return false;
}
function EdTimeout(){
    location.replace( TimeoutUrl );
}        
function EdTimeoutWarning( timeleft ){
    cfm('Timeout Warning', 'Your session will timeout in '+ timeleft +' minutes.  Click "Yes" to renew your session.', Warning_Callback);
}
function Warning_Callback( result ){
    if( result )
        RefreshSession();
}

// get content window
function GetWindow( name ){
    var WindowManager = GetRadWindowManager();
    return WindowManager.GetWindowByName( name );        
}  

function ModuleWindow_Closed(){
    try{
        // reloads the content grid
        if( ReloadContent )
            setTimeout('ReloadContent("rebind");', 500);
    } catch ( e ) {}
}

function ShowWindow( name, cid, qs ){    
    var radwin = GetWindow( '_ModuleWindow' );
    var url    = ManagerUrls[ name ];
    if( cid )
        url += '&ContentID='+ cid;
    if( qs )
        url += qs;
    // set url
    radwin.SetUrl( url );
    radwin.Show();        
    //if( name.toLowerCase() == 'page' )
    var height = f_clientHeight();
    var width  = f_clientWidth();
    radwin.SetSize( (width-100), height );
    radwin.Center();
    radwin.OnClientClose = ModuleWindow_Closed;
    // resets the Timeout script, so it doesn't keep popping up    
    if( reset_session )
        reset_session();
    return radwin;
}
function moduleOver( div ){
    if( div.className )
        div.className = 'dashicon_over';
    if( div.style )
        div.style.cursor = 'pointer';
}
function moduleOut ( div ){
    if( div.className )
        div.className = 'dashicon';
    if( div.style )
        div.style.cursor = 'default';
}
function forgotPassword(){
    ShowWindow('ForgotPassword');
}
function LoginErrorWin_Close(){}
function Login_Init(){
    ShowLoader('LoginStatus','Checking user credentials....');
    return true;
}        
function Login_Callback( obj ){
    HideLoader('LoginStatus');
    if( obj.LoginOk ){
        updateDiv('LoginStatus','Loading account information....');
        location.replace( obj.Url );
    } else {
        // failed to login
        alt('Login Failed', obj.Message);                
    }
}      
function ChangePassword_Init(){
    ShowLoader('PasswordStatus','Trying to change your password....');
    return true;
}
function ChangePassword_Callback( obj ){
     HideLoader('PasswordStatus');
    if( obj.Success )
        alt( 'Change Password', obj.Message );
}
function SecurityQuestionSave_Callback( obj ){
    HideLoader('SecurityQuestionSaveStatus');
    if( obj.SecurityQuestionResponse )
        alt('Security Questions', obj.SecurityQuestionResponse );
}
function SecurityQuestionSave_Init( obj ){
    ShowLoader('SecurityQuestionSaveStatus', 'Updating your security questions...');
    return true;
}
function LoadSecurityQuestion_Init(){
    ShowLoader('ForgotPasswordQuestion','Loading your security questions....');
    return true;
}
function LoadSecurityQuestion_Callback( obj ){
    HideLoader('ForgotPasswordQuestion');
    if( obj.ResponseCode )
        updateDiv('SecurityQuestion_Text', obj.ResponseCode);   
   // show the question     
   toggleEl('SecurityQuestions');
}
function ForgotPassword_Init(){
    ShowLoader('ResetPasswordStatus', 'Confirming your identity....');
    return true;
}
function ForgotPassword_Callback( obj ){
    HideLoader('ResetPasswordStatus');
    if( obj.Message )
        alt(null, obj.Message); 
}
function MyProfileUpdate_Init(){
    ShowLoader('ProfileUpdateStatus','Updating your profile....');
    return true;
}
function MyProfileUpdate_Callback(){
    HideLoader('ProfileUpdateStatus');
    alt('Profile Update', 'Your profile has been successfully updated.');    
}
function WebsiteUpdate_Complete(){
    HideLoader('WebsiteUpdateStatus');
    alt('Website Information', 'Your website has been updated successfully.');
    //LoadModule('Website');
}
function WebsiteUpdate_Init(){
    ShowLoader('WebsiteUpdateStatus', 'Updating your website....');
    return true;
}
function ThemeUpdate_Init(){
    ShowLoader('ThemeUpdateStatus', 'Updating your website....');
    return true;
}
function ThemeUpdate_Complete(){
    HideLoader('ThemeUpdateStatus');
    alt('Website Information', 'Your website has been updated successfully.');    
}
function WebsiteDesignerOption_Change( optionItem ){
    if( !optionItem )
        return;        
    var img = el( optionItem.Attributes.ImagePreviewClientID );
    if( img )
        img.src = optionItem.Attributes.ImageUrl;
}
var dataGrid = null, ControlUniqueID, RadTreeViewControl;
var ContentID = null;
function GridCreated(){
    dataGrid = this;
}
// rebind the grid from Client Side
function ReloadContent( action, params ){
    var eventParams = Param('action', (( action ) ? action : 'rebind') );
    if( params )
        for( var x in params )
            eventParams += '&' + Param( x, params[x]);
    // Ajax Callback
    if( dataGrid )
        dataGrid.AjaxRequest(ControlUniqueID, eventParams);        
    // reload the navigation tree
    if( RefreshWebsiteNavPanel )
        RefreshWebsiteNavPanel();
    // donot postback
    return false;
}    
    
function EditItem(type, id){
    if( type != 'Page' && type != 'Annoucement' )
        ShowWindow(type, id );
    else
        EditContent(type,  id );
    // find the type of the first selected item
    // and prompt for the form, passing the Url
    return false;
}
function EditContent( mod, id ){
    var url = ManagerUrls[ mod ];
    url += ( id ) ? '&ContentID='+id: '';
    location.replace( url );    
    return false;
}
function WebpageModule(){ LoadModule( 'website' ); }
function Content_Saving(){
    ShowLoader('ContentSavingStatus', 'Saving this to the database');
}
function Content_Saved(){
    HideLoader('ContentSavingStatus');
     alt('Saved', 'This item has been successfully saved to the database.', null, null, WebpageModule);
}
function Webpage_Saving(){
    ShowLoader('WebpageSaveStatus', 'Saving this webpage');
}
function Webpage_Saved(){
    HideLoader('WebpageSaveStatus');
    alt('Website Information', 'Your webpage has been updated successfully.', null, null, WebpageModule);
}
function DeleteItems_Callback( yesorno ){
    if( yesorno ){
        // delete Items
        setTimeout( "ReloadContent('deleteitems');" , 1000);
    }
}
function DeleteItems(){
    var go = cfm('Delete?', 'Are you sure you want to delete the selected item(s)?', DeleteItems_Callback );
    return false;
}    
function MoveContentToNewFolder( e ){
    e = ( e ) ? e : event;
    var folderTree = toggleMoveFolderTree();        
    if( folderTree ){
        // unselect all rad tree nodes
        var trv = RadTreeViewControl;
        trv.UnSelectAllNodes();            
        // update X & Y
        folderTree.style.left = (e.clientX-230)+'px';
        folderTree.style.top  = e.clientY+'px';                
    }    
    return false;
}

function UpdateContentFolder( node ){
    // send to server to do update
    ReloadContent( 'moveitemstofolder', {'FolderID': node.Value} );
    // hide the tree
    toggleMoveFolderTree();
    // prevent postback from the DocumentFolder TreeView
    return false;
}

function toggleMoveFolderTree(){
    var folderTree = el('FolderTreeToMoveContent');        
    if( folderTree ){
        toggleEl( folderTree.id );            
    }
    return folderTree;
}    

var folderTrees = new Array();
var contextNode;
var contextMenuClickEvent;

function BeforeFolderRightClickContextMenu(node, e){
    contextMenuClickEvent = e;                
    return true;
}

function FolderRightClickContextMenu(node, itemText){
    switch( itemText.toLowerCase() )
	{
		case "rename" :
			node.StartEdit();
			break;				
		case "delete" :
			// confirm
			return DeleteFolder_Confirm();
		case "add content":
		    if( ShowAddContentMenu )
		        ShowAddContentMenu( contextMenuClickEvent );
		    return false;
		case "new folder" :
		    return AddNewFolder();		    
		default :
			break;
	}
	return true;
}

function LoadingFolderContents( node ){
    // node that is Clicked
    contextNode = node;
    //update the folder
    updateDiv('FolderPathBar', '<span class="FolderPathBarText">' + node.Attributes.FolderPath + '</span>');	
    // update Folder Selection
    node.TreeView.UnSelectAllNodes();
    // update selection
    node.Selected = true;
    // reload the content on the Left, this function is on the content
    ReloadContent( 'viewcontentinfolder', {'FolderID': node.Value} );        
    // no postback
    return false;
}

function ModifyFolder( action ){
    if( IsRootFolder() )
        return;	    
    if( contextNode ){
        FolderRightClickContextMenu( contextNode, action);
    } else
        alt('Editing a Folder', 'A folder must be selected in order to delete, rename, or add sub folders.  Simply left click on a folder, and then the toolbar options "Edit Folder" and "Delete Folder" can be used.');
    return false;
}

function IsRootFolder(){
    if ( contextNode ){
        var ret = (contextNode.Category.toLowerCase() == 'rootfolder');
        if( ret )
            alt( 'Root Folder' , 'You cannot modify the root folder in your ePortfolio.' );
        return ret;
    }
    return false;
}
function CloseFolders( id ){
    return hideEl( id );
}
function AddNewFolder(){
    var hif = el( '_NewFolderName' );
    if( hif ){
        var newFolderName = prompt("What would you like to name your new folder?", "New Folder");			        
        if( newFolderName == null )
            return false;
        // set it and postback the page to add the folder    
        hif.value = newFolderName;
    }
    return true;
}
function AddFolder(){
    if( AddNewFolder() ){
        AjaxFolderPanel.AjaxRequest("action=addnewfolder");  
    }
    return false;
}
function DeleteFolder(){
    if( DeleteFolder_Confirm() )
        AjaxFolderPanel.AjaxRequest("action=deletefolder&FolderID="+ contextNode.Value);    
    return false;
}
function DeleteFolder_Confirm(){
    return  confirm("Are you sure you want to delete the folder '"+ contextNode.Text +"' and all its contents?");
}
function FolderStartAjax(){
    ShowLoader('FolderStatus', 'Updating...');
}
function FolderEndAjax(){
    HideLoader('FolderStatus');    
}
var ContentContextMenu;
function InitContextMenu(sender){
    ContentContextMenu = sender;
}  
// menu item is clicked
function ContextMenuContent(menu, e){
    ShowWindow( e.Item.Value );        
}
// popup the content menu
function ShowAddContentMenu( e ){
  e = ( e ) ? e : event;
  ContentContextMenu.Show( e );
  e.cancelBubble = true; //prevents IE from closing the menu
  if (e.stopPropagation)
     e.stopPropagation(); //prevents Firefox/Modzilla/Opera from closing the menu          
    return false;
}   
function Confirm_Init(){
    ShowLoader("ConfirmationStatus", 'Activating your account, please wait....');   
    return true;
}
function go(){
    location.replace('../');
}
function Confirm_Callback( obj ){
    HideLoader('ConfirmationStatus');
    if( obj.success )
        if( obj.success == 'true' ){
            alt('Activation Succes',obj.ConfirmComplete);
            setTimeout(go, 2500);                    
        }
        else
            alt('Activation Failed', obj.ConfirmError);
}
function GetRadWindow() {
   var oWindow = null;
   if (window.radWindow) oWindow = window.radWindow;
   else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
   return oWindow;
}
function CloseRadWin(){
    var w = GetRadWindow();
    if( w )
        w.Close('Close');
    return false;
}  
function GoLogin(){
    location.replace( '../login.aspx' );
}
function Register_Init(){
    ShowLoader('RegistrationStatus', 'Validating Registration....');   
    return true;
}        
function Register_Callback( obj ){
    HideLoader('RegistrationStatus');
    if( obj.RegistrationSuccess != 'False' ) {
        alt('Registration Success', obj.RegistrationMessage );      
        setTimeout(GoLogin, 10000);           
    }   
    else
        alt('Registration Error', obj.RegistrationMessage );
}
function AARequest_Start( val ){
    if( val ){
        var fn = eval('AARequest');
        if( fn )
            fn();
    }        
}
function AARequest_Init(){
    return true;
}
function AARequest_Callback( obj ){
    if( obj.Message )
        alt('Account Activation', obj.Message);
}
function AARequest_Notify(msg){
    cfm('Account Activation', msg, AARequest_Start);
}
var rabcbFolders, hiddenSelectedFolderID;
function SelectFolderOnRadCombo( node ){
    var hiddenInput = el( hiddenSelectedFolderID );
    if( rabcbFolders && hiddenInput ){
        hiddenInput.value = node.Value;
        rabcbFolders.SetText( node.Text );
    }
}
function InsertHTMLToEditor( html ){ CloseDlg( html ); }
function GetSelectedIems_Init(){
    ShowLoader('AssetManagerStatus', 'Inserting your selected items....');
    return true;
}
function GetSelectedIems_Callback( obj ){
    HideLoader('AssetManagerStatus');
    if( obj.EditorHtml )
        InsertHTMLToEditor( obj.EditorHtml );
}        
function ViewEdResource( url, title ){
    //ShowWindow('ResourceViewer', null, '?src='+ url + '&title='+title );
    var containerUrl = ManagerUrls[ 'ResourceViewer' ];
    openWin( containerUrl + '?src='+ url + '&title='+title , 'ResourceViewer', 'width=810,height=600,left=50,top=50,screenX=75,screenY=50,location=no,status=no,menubar=no,toolbar=yes,resizable=yes,scrollbars=yes');
}
function UploadFile(){
    ShowWindow('Upload');
    return false;
}
function AddBookmark(){
    ShowWindow('Bookmark');
    return false;
}
function toggleHelp( e, divid ){
    e = ( e ) ? e : event;
    if( e ){
        var divHelper = el( divid );
        divHelper.style.left = (e.clientX - 250) + 'px';
        divHelper.style.top  = (e.clientY+25) + 'px';    
        // show or hide;
        toggleEl( divid );
        // stop it
        if (e.stopPropagation)
         e.stopPropagation();
    }
    return false;
}
function WebsiteNavPanelCommand( params ){
    if( AjaxWebsiteNavPanel ){
        var eventParams = '';
        if( params )
            for( var x in params )
                eventParams += Param( x, params[x])+'&';
        // send the request
        AjaxWebsiteNavPanel.AjaxRequest( eventParams );
    }
}
function RefreshWebsiteNavPanel(){
   // setTimeout( "WebsiteNavPanelCommand( {'action':'reload'} );",1500);
   WebsiteNavPanelCommand( {'action':'reload'} );
}
function ViewCurrentWebsite(){
    //ShowWindow('WebsitePreviewWindow');
    var url    = ManagerUrls[ 'WebsitePreviewWindow' ]
    window.open(url, 'WebsitePreview', 'width=750,height=450,left=100,top=100,screenX=75,screenY=50,location=no,status=no,menubar=no,toolbar=yes,resizable=yes,scrollbars=yes');
    return false; 
}
function GetPlugin(code){
    //ShowWindow('GetPlugin', null, '?code='+code);
    var url = ManagerUrls[ 'GetPlugin' ] +'?code='+code;
    window.open(url, 'GetPlugin', 'width=750,height=450,left=100,top=100,screenX=75,screenY=50,location=no,status=no,menubar=no,toolbar=yes,resizable=yes,scrollbars=yes');
    return false; 
}
function ViewMyProfile(){
    ShowWindow('ViewMyProfile');
    return false; 
}