/* JAVASCRIPT / AJAX METHODS
   Karol Golka
   Aug 02, 2007
   Camp Timberlane
*******************************/

/* AJAX globals (and other globals)
--------------------------------------------------------------------------------- */
AjaxPro.timeoutPeriod = 30000; // 16 seconds
AjaxPro.onTimeout = handleTimeout;
AjaxPro.onError = handleError;

var myLocation = "/";
if (window.location.href.indexOf('localhost') != -1)
	myLocation = "http://localhost/CampTimberlane/";

// timeouts
function handleTimeout()
{
    if (confirm("A timeout has occurred. \r\n\r\nClick OK to reload the page or CANCEL to continue waiting."))	
	    // reload
	    location.reload();
	//else
        // test 01
	    //this.event.returnValue = true;
	
}
// AjaxPro.onLoading = function(b){ alert('your mom'); };

// errors
function handleError(res)
{
    // debugger;
    //alert("Error encountered. 102: " + res.Message);
	
}

/* OTHER GLOBALS
--------------------------------------------------------------------------------- */
var numBackgrounds = 15;

/* SwitchBackground
--------------------------------------------------------------------------------- */
function SwitchBackground(change)
{   
    // background colors;
    var bgcolors = ['#080F15', '#101010', '#0F140E', '#0E1003', '#303D34',
                    '#191B27', '#101010', '#8DAF63', '#403F47', '#746D67',
                    '#B4B4B4', '#9C5424', '#020202', '#0F140E', '#804606'];
   
    // grab current index
    var background = $('body').getStyle('background-image');
    var nStart = background.indexOf('ct-bg-') + 6;
    var nFinish = background.indexOf('.jpg');
    var nCurrent = background.substring(nStart, nFinish);
    
    // change it
    nCurrent = parseInt(nCurrent) + parseInt(change);
    
    // test if <= 0 ... OR ... >= numBackgrounds
    if (nCurrent <= 0)
        // cycle this way
        nCurrent = numBackgrounds;
    else if (nCurrent > numBackgrounds)
        // cycle that way
        nCurrent = 1;
    
    // make new background url
    background = 
        background.substring(0, nStart)
        + String(nCurrent) +
        background.substring(nFinish);
    
    // show overlay
    $('overlayBackground').style.display = 'block';
   
    // load background accordingly
//    $('body').morph('background-image:' + background, {duration: 0.5});
    $('body').setStyle({
        backgroundImage : background,
        backgroundColor : bgcolors[nCurrent-1]
    });
    
    // delay a bit
    setTimeout('HideOverlay()', 300);
}

function HideOverlay() { 
    // show overlay
//    $('overlay').style.display = 'none';
    new Effect.Fade('overlayBackground', {duration: .2});
}




function InsertReEnrollSelect(xhtmlSelect) {
    
    Element.extend('lightbox');
    $('lightbox').update('<div id="lbContent">'        
	    + '<div id="blueboxtop"><h2>Choose a Camper to Re-Enroll:</h2></div>'
	    + '<div id="blueboxcontent" style="height: 150px;"><div id="bbc1">'
    	+ '    <div class="qa"><label>This application is for:</label>'
		+ xhtmlSelect
		+ '    </div>	 '    		
	    + '</div></div>'
	    + '<div id="blueboxbottom"></div>'    
    + '</div>');
    
    // show everything
    $('overlay').style.display = 'block';
    $('lightbox').style.display = 'block';
    $('lbContent').style.display = 'block';
     
}

function ProcessSelectedReEnrollmentCamper(sel)
{     
    // hide lightbox
    $('overlay').style.display = 'none';
    $('lightbox').style.display = 'none';
    
    // get value
    option = sel.value.split('|');
    
    // get camper info (split) 
    // id_camper, firstname, lastname               
                
     // show welcome back message
    $('divReEnroll').addClassName('welcome-back');
    
    // hide normal
    $('spanReturning').hide();
    $('spanWelcomeBack').show();

    // res.value[3] needs to have full name, scratch that, just displaying email instead
    //$('spanFullName').update(res.value[4] + ' ' + res.value[5]);
               
    // hide keylog?
    ToggleKeylog();

    // add hidden textbox (making sure it's not already there?)
    // put id_user into it, to pass that across to make things easier later
    new Insertion.After('divReEnroll', 
        '<input type="text" id="tbxReEnroll" name="tbxReEnroll" value="' + option[0] + '" style="display:none;" />');

    // fill out firstname/lastname and add LOCKED classname
    $('tbxFirstName').value = option[1];
    $('tbxLastName').value = option[2];
    $('tbxFirstName').addClassName('prepopulated');
    $('tbxLastName').addClassName('prepopulated');
    $('tbxFirstName').disable();
    $('tbxLastName').disable();   
     
}


/* VerifyLogin
--------------------------------------------------------------------------------- */
function VerifyLogin()
{   
    
   // get login, password
   var email = $('tbxKeylogUsername').value;
   var password = $('tbxKeylogPassword').value;
   // TODO: later add code for grabbing ReturnURL...
   
   // validate
   var valForm = new Validation('myKeylogForm', {useTitles:true});
   if	(valForm.validate() && $('spinnerKeylog').style.display.toLowerCase() != 'block')
   {
        // hide keylog button, show spinner
        $('hypKeylog').toggle();
        $('spinnerKeylog').toggle();        
        
        // call
        CT.VerifyLogin(email, password, VerifyLogin_callback);
   }
}

// CALLBACK
function VerifyLogin_callback(res)
{ 	
    // hide keylog button, show spinner
    $('hypKeylog').toggle();
    $('spinnerKeylog').toggle();       


	if (res.value[0] == "-1")
   {
       // show error
       // $('pFlash').show().update(res.value[1]);       
      // alert(res.value[1]);
   }
   else if (res.value[0] == "-2")
   {
       // show error
       // $('pFlash').show().update(res.value[1]);       
       alert(res.value[1]);
       
       // --------------------------------------------------------
        // 0 kids
        // --------------------------------------------------------
        // hide application
        $('c1').update('<p class="postitnote huggish">' +
            'We are having trouble locating your camper\'s records, please contact the support team at <a href="mailto:mailto:mike@camptimberlane.com">mike@camptimberlane.com</a>, thanks.');
        // alert error
        // show message with support email
        // .............
        
   }
   else { 
        
        // IF ON CAMPER APPLICATION PAGE, DON'T REDIRECT
        // return id_camper, firstname, lastname IF ONLY ONE CAMPER FOR THIS PARENT
        // return 0, <select ....><option value="id_camper|firstname|lastname">Full Name..." for multiples
        
        if (location.href.toLowerCase().indexOf('application.aspx') != -1 && res.value[1] == 'parent')
        {
            // alert('got parent login during application page!');
            // --------------------------------------------------------
            // 1 kid ### DONE
            // --------------------------------------------------------
            // 
            if (res.value[2] == '1')
            {
                // returns
                // id_camper, firstname, lastname 
                // alert('got one kid' + res.value[3] + ', ' + res.value[4] + ', ' + res.value[5] + '...');
                
                 // show welcome back message
                $('divReEnroll').addClassName('welcome-back');
                
                // hide normal
                $('spanReturning').hide();
                $('spanWelcomeBack').show();

                // res.value[3] needs to have full name, scratch that, just displaying email instead
                //$('spanFullName').update(res.value[4] + ' ' + res.value[5]);
                           
                // hide keylog?
                ToggleKeylog();

                // add hidden textbox (making sure it's not already there?)
                // put id_user into it, to pass that across to make things easier later
                new Insertion.After('divReEnroll', 
                    '<input type="text" id="tbxReEnroll" name="tbxReEnroll" value="' + res.value[3] + '" style="display:none;" />');

                // fill out firstname/lastname and add LOCKED classname
                $('tbxFirstName').value = res.value[4];
                $('tbxLastName').value = res.value[5];
                $('tbxFirstName').addClassName('prepopulated');
                $('tbxLastName').addClassName('prepopulated');
                $('tbxFirstName').disable();
                $('tbxLastName').disable();
                
                
                
            }
            
            // --------------------------------------------------------
            // 2+ kids
            // --------------------------------------------------------
            else if (res.value[2] == '2+')
            {
                // alert('got 2+ kids: ' + res.value[3]);
                InsertReEnrollSelect(res.value[3]);                           
            }
            
            
            
            
            
            
            // show welcome back message
//            $('divReEnroll').addClassName('welcome-back');
//            // hide normal
//            $('spanReturning').hide();
//            $('spanWelcomeBack').show();
//            
//            // res.value[3] needs to have full name, scratch that, just displaying email instead
//            $('spanFullName').update(res.value[2]);
//                       
//            // hide keylog?
//            ToggleKeylog();
//            
//            // add hidden textbox (making sure it's not already there?)
//            // put id_user into it, to pass that across to make things easier later
//            new Insertion.After('divReEnroll', 
//                '<input type="text" id="tbxReEnroll" name="tbxReEnroll" value="' + res.value[3] + '" style="display:none;" />');
//            
        }
        else
            // redirect
            location.href = myLocation + 'internal/' + res.value[1];
   }
}

/* SubmitCamperApplication
--------------------------------------------------------------------------------- */
function SubmitCamperApplication(paymentmode, button)
{   
   // validate
   var valForm = new Validation('content', {useTitles:true});
   if	(valForm.validate())
   {
        // get pay amount
        var payamount = $('tbxAmount2Pay').value;
        
        // check if amount is correct
        if (paymentmode == 'payonline' && isNaN(parseInt(payamount)))
        {
            // error
            alert("Please enter a valid amount to pay.");
            return;                
        }
        
        // show 3 dots
        $('3dot').show();
        
        // disable button
        button.disabled = true;
        
        // grab form
        var xmlForm = GrabForm('content');
        
        // call
        CT.SubmitCamperApplication(xmlForm, paymentmode, payamount, SubmitCamperApplication_callback);
   }
}

// CALLBACK
function SubmitCamperApplication_callback(res)
{
   // switch return value
   if (res.value[0] != "0")
   {
       // hide 3 dots
       $('3dot').hide();
   
       // show error
       alert(res.value[1]);
   }
   else { 
         // send to // OLD : google checkout... or confirmation page
         // NEW: send to app-receieved
         location.href = res.value[1];
   }
}

/* SubmitStaffApplication
--------------------------------------------------------------------------------- */
function SubmitStaffApplication()
{   
   // validate
   var valForm = new Validation('content', {useTitles:true});
   if	(valForm.validate())
   {
        // show 3 dots
        $('3dot').show();
        
        // grab form
        var xmlForm = GrabForm('content');
         
        // call
        CT.SubmitStaffApplication(xmlForm, SubmitStaffApplication_callback);
   }
}

// CALLBACK
function SubmitStaffApplication_callback(res)
{
   // switch return value
   if (res.value[0] != "0")
   {
       // hide 3 dots
       $('3dot').hide();
   
       // show error
       alert(res.value[1]);
   }
   else { 
         // send to confirmation page
         location.href = res.value[1];
   }
}


/* AjaxTest
--------------------------------------------------------------------------------- 
function AjaxTest()
{   
    // call
    CT.AjaxTest(AjaxTest_callback);
}

// CALLBACK
function AjaxTest_callback(res)
{
    try
    {
        // confirm success
        $('divAjax').innerHTML = res.value;
        new Effect.Highlight('divAjax');
    }
    catch(err)
    {
        alert(err.description);
    }
}
*/


/* ToggleKeylog
--------------------------------------------------------------------------------- */
function ToggleKeylog()
{
    // get state
    if ($('keylog').getStyle('top') == '-84px')
    {
        $('keylog').morph('top: 0%;', {duration: .3});
        $('tbxKeylogUsername').focus();
    }
    else
    {
        // hide
        $('keylog').morph('top: -84px;', {duration: .3});
    }
}

/* DragIt
--------------------------------------------------------------------------------- */
function DragIt()
{
	//new Draggable('lightwindow_contents', {handle: 'blueboxtop', starteffect: false, endeffect: false, zindex: 100000, constraint:'horizontal'});
}

/* ReloadBlueBox
--------------------------------------------------------------------------------- */
function ReloadBlueBox(next, previous)
{ 
	// call
    CT.ReloadBlueBox(next, previous, ReloadBlueBox_callback);
}

// CALLBACK
function ReloadBlueBox_callback(res)
{
   // switch return value
   if (res.value[0] == "0")
   {
     
       // reload bluebox content
       $('lbContent').innerHTML = res.value[1];
       }
   else { 
         // error
         alert(res.value[1]);
   }
}

/* SendProspectiveCamperNotice
--------------------------------------------------------------------------------- */
function SendProspectiveCamperNotice(button)
{ 
     // validate
   var valForm = new Validation('myForm', {useTitles:true});
   if	(valForm.validate())
   {
        // disable button
        button.disabled = true;
        
        // spinner
        $('imgSpinner').toggle();
        
        // grab form
        var xmlForm = GrabForm('myForm');
         
	    // call
        CT.SendProspectiveCamperNotice(xmlForm, SendProspectiveCamperNotice_callback);
   }
}

// CALLBACK
function SendProspectiveCamperNotice_callback(res)
{
    // spinner
    $('imgSpinner').toggle();

   // switch return value
   if (res.value[0] == "0")
   {
        // switch out content/confirmation
        $('myForm').toggle();
        $('divConfirmation').toggle();        
       }
   else { 
         // error
         alert(res.value[1]);
   }
}


/* SavePreRegistrationForm
--------------------------------------------------------------------------------- */
function SavePreRegistrationForm(button)
{  
	
   // validate
   var valForm = new Validation('blueboxcontent', {useTitles:true});
   if	(valForm.validate())
   {
        // disable button
        button.disabled = true;
        
		// show 3 dots
        $('3dot').show();
        
        // grab form
        var xmlForm = GrabForm('blueboxcontent');
         
        // call
        CT.SavePreRegistrationForm(xmlForm, 'advancedregistration', SavePreRegistrationForm_callback);
   }
}

// CALLBACK
function SavePreRegistrationForm_callback(res)
{
	// hide 3 dots
    $('3dot').hide();
    
   // switch return value
   if (res.value[0] != "0")
   {   
       // show error
       alert(res.value[1]);
   }
   else { 
         // show confirm
         $('pFormSent').show();
         $('formstuff').hide();
		 
   }
}

/* SaveAlumniReconnectForm
--------------------------------------------------------------------------------- */
function SaveAlumniReconnectForm(button)
{  
	
   // validate
   var valForm = new Validation('blueboxcontent', {useTitles:true});
   if	(valForm.validate())
   {
        // disable button
        button.disabled = true;
        
		// show 3 dots
        $('3dot').show();
        
        // grab form
        var xmlForm = GrabForm('blueboxcontent');
         
        // call
        CT.SaveAlumniReconnectForm(xmlForm, 'alumnireconnect', SaveAlumniReconnectForm_callback);
   }
}

// CALLBACK
function SaveAlumniReconnectForm_callback(res)
{
	// hide 3 dots
    $('3dot').hide();
    
   // switch return value
   if (res.value[0] != "0")
   {   
       // show error
       alert(res.value[1]);
   }
   else { 
         // show confirm
         $('pFormSent').show();
         $('formstuff').hide();
		 
   }
}

/* ForgotPassword
--------------------------------------------------------------------------------- */
function ForgotPassword(button)
{  
	
   // validate
   var valForm = new Validation('blueboxcontent', {useTitles:true});
   if	(valForm.validate())
   {
        // disable button
        $(button).update('Sending You Your Password...');	 
        button.disabled = true;
        
        // grab inputs
        var role = $('selRole').value;
        var email = $('tbxEmail').value;
         
        // call
        CT.ForgotPassword(role, email, ForgotPassword_callback);
   }
}

// CALLBACK
function ForgotPassword_callback(res)
{
    // switch return value
   if (res.value[0] != "0")
   {   
       // show error
       alert(res.value[1]);
       
       // toss button back (ghetto) :)
       $('btnSubmit').disabled = false;
       $('btnSubmit').update('Send Me My Password!');
   }
   else { 
         // show confirm
         $('pFormSent').show();
         $('formstuff').hide();
         
         // pre-populate real email box
         $('tbxKeylogUsername').value = $('tbxEmail').value;
         
		 
   }
}

/* SubmitCamperApplicationRegister
--------------------------------------------------------------------------------- */
function SubmitCamperApplicationRegister(paymentmode, button)
{   
   // validate
   var valForm = new Validation('content', {useTitles:true});
   if	(valForm.validate())
   {
        // get pay amount
        var payamount = $('tbxAmount2Pay').value;
        
        // check if amount is correct
        if (paymentmode == 'payonline' && isNaN(parseInt(payamount)))
        {
            // error
            alert("Please enter a valid amount to pay.");
            return;                
        }
        
        // show 3 dots
        $('3dot').show();
        
        // disable button
        button.disabled = true;
        
        // grab form
        var xmlForm = GrabForm('content');
        
        // call
        CT.SubmitCamperApplicationRegister(xmlForm, paymentmode, payamount, SubmitCamperApplicationRegister_callback);
   }
}

// CALLBACK
function SubmitCamperApplicationRegister_callback(res)
{
   // switch return value
   if (res.value[0] != "0")
   {
       // hide 3 dots
       $('3dot').hide();
   
       // show error
       alert(res.value[1]);
   }
   else { 
         // send to // OLD : google checkout... or confirmation page
         // NEW: send to app-receieved
         location.href = res.value[1];
   }
}