﻿/* JAVASCRIPT
   Karl Golka
   LG Executive Dashboard
   April 7, 2008
*******************************/
var bDebugging = false;


// call in progress
function callInProgress (xmlhttp) {
    switch (xmlhttp.readyState) {
        case 1: case 2: case 3:
            return true;
            break;
        // Case 4 and 0
        default:
            return false;
            break;
    }
}


// Register global responders that will occur on all AJAX requests
Ajax.Responders.register({
    onCreate: function(request) {
        request['timeoutId'] = window.setTimeout(
        function() {
            // If we have hit the timeout and the AJAX request is active, abort it and let the user know
            if (callInProgress(request.transport)) {
                request.transport.abort();
                // showFailureMessage();
                // Run the onFailure method if we set one up when creating the AJAX object
                if (request.options['onFailure']) {
                    request.options['onFailure'](request.transport, request.json);
                }
                }
            },
            5000 // milli seconds
        );
    },
    onComplete: function(request) {
        // Clear the timeout, the request completed ok
        window.clearTimeout(request['timeoutId']);
    }
});


 
// Ajax loading indicator
function loading() {
     ($('divLoading')) ? $('divLoading').toggle() : void(0); 
}

// TABLE TOGGLES
function BoxToggle(row)
{
    // for dash
    if (arguments[1])
        if (arguments[1] == '3')
        {
            // toggle
            Element.extend(row).toggleClassName('largepinkbox');        
            Element.extend(row).toggleClassName('pinkbox');        
        }
        else
            // toggle
            Element.extend(row).toggleClassName('pinkbox');        
    else
    {
        // toggle
        Element.extend(row).toggleClassName('boxon');
        Element.extend(row).up(2).toggleClassName('boxon');
    }
}

/* SetTimer
---------------------------------------------------------------------------------
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
---------------------------------------------------------------------------------

SetTimer starts a loop of ...
    ============================> 
        RefreshData() 
            => 
                Fetch() 
                    =>
                        (C#) GetChart() ... 

---------------------------------------------------------------------------------
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
--------------------------------------------------------------------------------- */
function SetTimer()
{      
    // refresh current tab
    RefreshData('current');
    
    // set time for this
    setTimeout('SetTimer()', 300000);    
    
}


/* VerifyLogin
--------------------------------------------------------------------------------- */
function VerifyLogin()
{   
   // get login, password
   var email = $('tbxEmail').value;
   var password = $('tbxPassword').value;
   
   // TODO: later add code for grabbing ReturnURL...
   
   // validate
   var valForm = new Validation('formLogin', {useTitles:true});
   if	(valForm.validate())
   {
        // loading
	    loading();
	
		// OLD AJAX: LGED.VerifyLogin(email, password, VerifyLogin_callback);
		new Ajax.Request('ajax/ajax-processor.aspx', {
            parameters: { method: 'VerifyLogin', email: email, password: password },
            onSuccess: function(transport) {
            
                 // redirect
                 location.href = transport.responseText;
               
            },
            onFailure: function(transport) {             
                // loading
	            loading();
                alert(transport.responseText);
            }
        });
   }
}
 


/* Fetch
--------------------------------------------------------------------------------- */
function Fetch(ele)
{      
    // variables
    var extra = '0';
    
    // get extra
    if (arguments[1])
        extra = arguments[1];
    
    // spin it
    $(ele).next('img').hide();
    $(ele).up().toggleClassName('ajax-nobkgnd');
    $(ele).show();
           
    // get imgsrc
    var imgtitle = $(ele).readAttribute('title');
    
    // get filters
    var filters = GrabForm('divFilters');
    
    // make ajax call to grab chart
    // OLD AJAX: LGED.GetChart(ele, imgtitle, filters, extra, GetChart_callback);    
    // NEW AJAX:
    // make the ajax call
    new Ajax.Request('../../ajax/ajax-processor.aspx', {
        parameters: { method: 'GetChart', ele: ele, imgtitle : imgtitle, filters : filters, extra: extra },
        onSuccess: function(transport) {
             
             try { 
               
               /* RETURNS:
               -----------------------
               0: error or not
               1: ele   
               2: imgsrc (chart URL)
               ----------------------- */                
                // variables
                var imgsrc = transport.responseText;
                
                // preload
                var imgPreloader = new Image();
                
                // once image is preloaded, show it
                imgPreloader.onload = function(){
            		
                    // on load
                    $(ele).next('img').src = imgsrc;
                    $(ele).hide();		
                    new Effect.Appear($(ele).next('img'));            		 
                }
            	
                // trigger it
                imgPreloader.src = imgsrc;
               
               }
               catch(err)
               {
                   alert('Error pre-loading image');
               }

        },
        onFailure: function(transport) {   
            //alert('calling '+ ele + ' again');          
            setTimeout('Fetch("'+ele+'")',1000);
        } 
    });
}




/* RefreshData
--------------------------------------------------------------------------------- */
function RefreshData(tab)
{  
    // if tab == 'current', get the current tab
    if (tab == 'current')
    {
        // get current tab
        tab = $$('.active-tab-body')[0].id;
        // alert(tab);
        
        // skip tab2 for now!
//        if (tab == 'tab2')
//            return;
    }
    
    // staff ?
    if (tab == 'tab4') // STAFF DESCRIPTIONS
        setTimeout('GetStaffDescriptions()', 500);
        
    // images ?
//    if (tab == 'tab6') // IMAGE GALLERY
//        setTimeout('GetPhotoGalleries()', 500);
//        
//     
    // get all ajax-loaders and hit their onload
    $$('#'+tab+ ' img.ajax-loader').each(function(s){        
         
        // only fetch if visible (tabs)
        if (s.visible) 
        {        
            // and see if there's an underscore in the id, if so, strip out what's after
            // and pass that as arg #2 (because it's seg question 2)
            if (s.id.indexOf('_') != -1)
            {
                // grab segment (after _)
                var nSeg = s.id.indexOf('_');
                var segment = s.id.substring(nSeg);
                
                // get it
                setTimeout('Fetch("'+s.id+'", "'+segment+'")',1500);
            }
            else       
                // get it
                setTimeout('Fetch("'+s.id+'")',1000);
        }                
    });
}

/* ExportReport
--------------------------------------------------------------------------------- */
function ExportReport(format)
{        
    // get filters
    var filters = GrabForm('divFilters');
    
    // get current tab
    var tab = $$('.active-tab-body')[0].id.replace(/tab/gi, '');
    
    // only sample data report available for tab 1
    if (tab != '2')
    {
        alert('Sample report is only available for the SEGMENTATION SURVEYS tab.');
        return;
    }
    
    // no report for tab 6
    if (tab != '1' && tab != '3' && tab != '2' && tab != '4' && tab != 7)
    {
        alert('No Report is currently available for this Tab.');
        return;
    }
    
    // get charts
    var charts = '';
    $$('#tab'+tab+ ' img.ajax-loader').each(function(s){
        
        if (s.visible) 
        {
            // get it
            charts += $(s.id).readAttribute('title')+',';
        }     
        
    });
    
     
    // popup window => SWITCH TO OPEN HIDDEN IFRAME
//	windowOpener('exporter.aspx?tab='+tab+'&format='+format+'&charts='+urlencode(charts)+'&filters='+urlencode(filters),
//	 'ExportReport', 'WIDTH=10,HEIGHT=10, LEFT=100, TOP=100'); 
//	 
	frames['iExport'].location = 'exporter.aspx?tab='+tab+'&format='+format+'&charts='+urlencode(charts)+'&filters='+urlencode(filters);
}


 
/* ForgotPassword
--------------------------------------------------------------------------------- */
function ForgotPassword()
{   
   // validate
   var valForm = new Validation('form01', {useTitles:true});
   if	(valForm.validate())
   {
        // loading
		loading();
        
        // grab email
        var email = $('tbxForgotEmail').value;         
        
        // make the ajax call
        new Ajax.Request('ajax/ajax-processor.aspx', {
            parameters: { method: 'ForgotPassword', email : email},
                onSuccess: function(transport) {
                    // loading
	                loading();
                    
                    // confirm
		            $('divConfirmation').show();
		            $('form01').hide();
                   
                },
                onFailure: function(transport) {             
                    // loading
	                loading();
                    alert(transport.responseText);
                }
            });
   }
}
 


/* Signout
--------------------------------------------------------------------------------- */
function Signout()
{   
    // loading
	loading();
	
    // make the ajax call
    new Ajax.Request('../../ajax/ajax-processor.aspx', {
        parameters: { method: 'Signout'},
            onSuccess: function(transport) {
                // loading
                loading();
                
                // redirct
                location.href="../../login.aspx";
               
            },
            onFailure: function(transport) {             
                // loading
                loading();
                //alert(transport.responseText);
            }
        });
}

 

/* Custom Validation Rules
--------------------------------------------------------------------------------- */
Validation.add('validate-zero2ten', 'Answer Response (0-10)', {
     min : 0, // value is not less than this number
     max : 10
});

Validation.add('validate-one', 'Answer Response (1 or blank)', {
     oneOf : ['1','']
});

Validation.add('validate-zero2hundred', 'Answer Response (0-100)', {
     min : 0, // value is not less than this number
     max : 100
});



/* GetStaffDescriptions
--------------------------------------------------------------------------------- */
function GetStaffDescriptions()
{   
   // loading
   loading();
   
   // get filters
   var filters = GrabForm('divFilters');    
        
   // call
   //LGED.GetStaffDescriptions(filters, GetStaffDescriptions_callback);
   // make the ajax call
    new Ajax.Request('../../ajax/ajax-processor.aspx', {
        parameters: { method: 'GetStaffDescriptions', filters: filters},
            onSuccess: function(transport) {
                // loading
                loading();
                
                // update
                $('divStaffDescription').update(transport.responseText);
               
            },
            onFailure: function(transport) {             
                // loading
                loading();
                //alert(transport.responseText);
            }
        });
   
}


/* GetPhotoGalleries
--------------------------------------------------------------------------------- */
function GetPhotoGalleries()
{   
   // loading
   loading();
   
   // url
   var url = location.href;
   
   // call
   //LGED.GetPhotoGalleries(url, GetPhotoGalleries_callback);
   // make the ajax call
        new Ajax.Request('../../ajax/ajax-processor.aspx', {
            parameters: { method: 'GetPhotoGalleries', url: url},
                onSuccess: function(transport) {
                   // loading
                   loading();
                   
                   // update
                   $('divPhotoGallery').update(transport.responseText);  
                   
                },
                onFailure: function(transport) {             
                   // loading
                   loading();  
                   //alert(transport.responseText);
                }
            });
   
}



/* RemoveWelcomeMsg
--------------------------------------------------------------------------------- */
function RemoveWelcomeMsg()
{   
   // loading
   loading();
   
   // call
   //LGED.RemoveWelcomeMsg(RemoveWelcomeMsg_callback);
   // make the ajax call
        new Ajax.Request('../../ajax/ajax-processor.aspx', {
            parameters: { method: 'RemoveWelcomeMsg'},
                onSuccess: function(transport) {
                   // loading
                   loading();
                   
                   // update         
                    new Effect.Fade($('hypClose01').up(1), { duration: 2}); 
                   
                },
                onFailure: function(transport) {             
                   // loading
                   loading();  
                   //alert(transport.responseText);
                }
            });
   
}


