/******************************************************************************
     File Name :   homepage.js
    Created By:    Muthu Vijayan
       Created on:    11-18-2008
    Modified on:    NA
    Description:    Has all the common functions of home page..
/******************************************************************************/
 
 var DIR = "user";   
 var SMALLIMAGE = '../images/loadingSmall.gif';
 var LOADSMALLIMAGE = "<img src='"+SMALLIMAGE+"'>";   
 var domain_address = 'http://'+top.location.host;  // To Get the Domain Address                                                        
                                                            
/************************************************************************************************
     @Name : processLogin
     @params:  None
     @return: None. 
     purpose: To login the user.
     Created by: Muthu Vijayan
************************************************************************************************/                           

function processLogin()
{               
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    
    //client side vallidation
    if(username == 'Username' || username == '')
    {
        alert('Please enter your username');
        username = '';
        document.getElementById('username').focus();
       
        return false; 
    }else if(password == '')
    {
        alert('Please enter your password');
        password = '';
        document.getElementById('password').focus();
       
        return false; 
    }
    
    
    
    var md5pass = hex_md5(password); //md5 hash of password
    
//    alert(md5pass);
    //var queryStr = $('loginForm').serialize();   
    var queryStr = "vb_login_username="+encode64(username)+"&vb_login_password="+encode64(password)+"&do=wmlogin"+"&vb_login_md5password="+md5pass+"&vb_login_md5password_utf="+md5pass+"&securitytoken=guest";
    
    if($('remember').checked == true) //set cookie
    {
         queryStr += '&setcookie=1';   
    }
    
    var url = domain_address+"/forum/WM_login.php";
//    var url = "http://www.thecathenation.com/tempblock1/forum/WM_login.php";
//   console.log(queryStr); 
    //show loading
    nowLoading('block'); 
    
    new Ajax.Request(url,
                {   
                    method: 'post',
                    parameters: queryStr, 
                    onComplete:function(response)
                    {   
                        //hide loading
                         nowLoading('none'); 
                        
                        var result = response.responseText;
                        //alert(result);
                              
                        
                        if(result == 'failed') //got error code, so failed
                        {
                            alert('Invalid Username/Password');
                            updateLogin();
                            
                        }
                        else
                        {
                           updateLogin('inline'); //show inline
                           showInHome('tab1');
                           
                           //user logged into WM, no show fb connect button
                           $('facebook_button').style.display = 'block';
                        }                
                                             
                         //updateLogin();
                         //showInHome('tab1');
                    }
                }
                );
                
                return false;
 }

 
                
/************************************************************************************************
     @Name : processLogin
     @params:  None
     @return: None. 
     purpose: To login the user.
     Created by: Muthu Vijayan
************************************************************************************************/                           

    function reportError(request)
    {
    alert('Sorry. There was an error.');
    }
                              
               
/************************************************************************************************
     @Name : processLogin
     @params:  None
     @return: None. 
     purpose: To login the user.
     Created by: Muthu Vijayan
************************************************************************************************/                           
   
   function updateLogin(status)
   {
        new Ajax.Updater('logInOut','user/processLogin.php');
        
         //show/hide cathe fun page
        if(status)
            $('showFun').style.display = status;
   }

   /************************************************************************************************
     @Name : checkSession
     @params:  None
     @return: None. 
     purpose: To update login on session timedout.
     Created by: Muthu Vijayan
************************************************************************************************/                           
   
   function checkSession()
   {
        new Ajax.Updater('logInOut','user/check_login.php');
        
   }          
   
   
                  
/************************************************************************************************
     @Name : processLogout
     @params:  None
     @return: None. 
     purpose: To logout the user.
     Created by: Muthu Vijayan
************************************************************************************************/                           

function processLogout(hashkey)
{
    var url;
    
    /*if(confirm('Are you sure to log out?'))
    {*/
        //show loading
        nowLoading('block'); 
        url = domain_address+"/forum/login.php";
        var params = "do=logout&logouthash="+hashkey;
      
        new Ajax.Request(url,
                    {   
                        method: 'get',
                        parameters: params,
                        onComplete:function(req)
                        {   
                             //hide loading
                             nowLoading('none'); 
                             updateLogin('none');//param =>dont display cathe fun     
                             //user logged out of WM, donot show fb connect button
                             $('facebook_button').style.display = 'none';
                             
                             showInHome(); //logout page
                             
                        }
                    }
                    );   
    //}
}


/************************************************************************************************
     @Name : nowLoading
     @params:  None
     @return: None. 
     purpose: To show/hide the loading image
     Created by: Muthu Vijayan
************************************************************************************************/      

function nowLoading(status)
{
    $('nowLoading').style.display = status;
}


/************************************************************************************************
     @Name : toggleGraph
     @params:  None
     @return: None. 
     purpose: To show/hide the graph.
     Created by: Muthu Vijayan
************************************************************************************************/      

function toggleGraph(gname)
{
     // hide all   
     $('weight').style.display = 'none';
     $('bmi').style.display = 'none';
     
     //set visibilty for the graph selected
     $(gname).style.display = 'block';

}

   function showWeight()
   {
    //alert('called');                            
        $a.blockUI({ message: $a('#weighInTB') }); 
            
   }
   
   
                 
/************************************************************************************************
     @Name : loadWorkouts
     @params:  None
     @return: None. 
     purpose: To load all the workouts scheduled for that date
     Created by: Muthu Vijayan
************************************************************************************************/                           

function loadWorkouts(todate)
{   
    var url;
    
    url = DIR+"/calendar_home.php";
    params = "loadDate="+todate;
            
    //show loading
    nowLoading('block');             
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
                                 result = result.split('~');
                                 
                             if(result.length > 1)
                             {    
                                 
                                 $('loadDate').innerHTML = result[0]; 
                                 $('loadData').innerHTML = result[1]; 
    //                             $('schedule_date').setAttribute('value',todate)
                                 $('schedule_date').value = todate;
                                 
                                 $('dailyNote').innerHTML = result[2];
                             }else
                             {
                                //may be session logged out
                                $('container').innerHTML = result;
                             }   
                                                                  
                        }
                    }
                    );   
    
}

/************************************************************************************************
     @Name : saveCalendarNotes 
     @params:  None
     @return: None. 
     purpose: To save the notes correponds to a calendar date
     Created by: Muthu Vijayan
************************************************************************************************/                           

function saveCalendarNotes()
{   
    var url;
    
    if($('today_notes').value == '')
    {
        alert('Please enter the notes');
        $('today_notes').focus();
        return false;
    }
    
    url = DIR+"/calendar_home.php";
    var params = $('notesForm').serialize();
            
    //show loading
//    nowLoading('block');  
    $('updateNotes').disabled = true;
    $('updateNotes').value = 'Updating..';
    $('notesImage').innerHTML = '<img src="images/ajax-loader.gif" />';
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,
                        onComplete:function(response)
                        {   
                             //hide loading
//                             nowLoading('none');
                              $('updateNotes').disabled = false;
                              $('updateNotes').value = 'Update Note';
                             
                               $('notesImage').innerHTML = '';                                                      
                             /*var result = response.responseText;
                                 result = result.split('~');
                             
                             $('loadDate').innerHTML = result[0]; 
                             $('loadData').innerHTML = result[1]; 
//                             $('schedule_date').setAttribute('value',todate)
                             $('schedule_date').value = todate;*/
                                                                  
                        }
                    }
                    );   
    
}

/************************************************************************************************
     @Name : validateHistoryDate 
     @params:  None
     @return: None. 
     purpose: To validate the date range
     Created by: Shanthi Michael
************************************************************************************************/                           

function validateHistoryDate()
{   
    var url;
    
    if($('from_date').value.length == 0) {
        alert('Please select the From Date');
        $('from_date').focus();
        return false;
    }

	if($('to_date').value.length == 0) {
        alert('Please select the To Date');
        $('to_date').focus();
        return false;
    }

	if ($('from_date').value > $('to_date').value) {
		alert("From date exceeds To date");		
		$('from_date').focus();
		$('from_date').select();
		return false;
	}
	document.form1.submit();

}

/************************************************************************************************
     @Name : showDetails
     @params:  None
     @return: None. 
     purpose: To show the details div
     Created by: Muthu Vijayan
************************************************************************************************/                           

function showDetails(index)
{
    var what = 'details_'+index;
    var link = 'link_'+index;
    
    $(what).style.display = 'block';
//    Effect.BlindDown(what, { duration: 3.0 });
    $(link).href = 'javascript:hideDetails('+index+')';
    $(link).innerHTML = 'Hide Details';
   
}

/************************************************************************************************
     @Name : hideDetails
     @params:  None
     @return: None. 
     purpose: To hide the details div
     Created by: Muthu Vijayan
************************************************************************************************/                           

function hideDetails(index)
{                            
    var what = 'details_'+index;
    var link = 'link_'+index;
    
    $(what).style.display = 'none';
    //Effect.BlindUp(what);
    $(link).href = 'javascript:showDetails('+index+')';
    $(link).innerHTML = 'Show Details';
   
}


function fnLoadCalendar(id,val)
{

        var url=DIR+"/getCalender.php?val="+Val+"&id="+id;

        //document.getElementById('calender').innerHTML = "<img src='../images/loading2.gif'>";       

        nowLoading('block'); 
        
        new Ajax.Request(url,
                        {   
                            method: 'get',
                            
                            onComplete:function(response)
                            {   
                                 //hide loading
                                 nowLoading('none');
                                 
                                  var result = response.responseText;   
                                  //load calendar
                                $('calender').innerHTML = result; 
                            }
                        }
                        ); 

        /*xmlHttp=GetXmlHttpObject(fnGetMonth);

        xmlHttp.open("GET", url , true);

        xmlHttp.send(null)  */
            
}

function focusbutton()
{
    $('login').focus();
}


/************************************************************************************************
     @Name : saveWorkouts
     @params:  None
     @return: None. 
     purpose: To hide the details div
     Created by: Muthu Vijayan
************************************************************************************************/                           

function saveWorkouts(formId,filename)
{   
    if(!validateWorkoutName())
       return false;

    url = DIR+"/"+filename+".php";
    params = $(formId).serialize();
//    console.log(params); //should be removed
//                  return;
    //show loading
    nowLoading('block');             
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
                                 result = result.split('~');
                             
                             loadCalendarTab(result[0],result[1]);
                             
                             //if($('message'))
                               // $('message').innerHTML = result[0]; 
                               
                            /* var date1 = result[0];
                             
                             var dates1 = date1.split("-");
                             
                             var date_id1 = dates1[2] - 1; 
                             
                                                                         
                             //load calendar
                             fnChangeMonth(result[1]);
                           
                             //fnLoadCalendar(date_id1,result[1]) 
                             
                             //load sidebar      
                             loadWorkouts(result[0]);
                             /*$('loadData').innerHTML = result[1];
                             $('schedule_date').setAttribute('value',todate)*/
                                                                  
                        }
                    }
                    );                                                      


}

function createPdf(wid,wsid,filename,type,status) 
{
    //hide loading
    nowLoading('none');
    
    url= DIR+"/"+filename+'.php?type='+type+'&status='+status+'&wid='+wid+'&dt='+wsid;
    
    loadNutrition(url,'Print Workout Card');
}


function loadCalendar(date,cal_date_format,wid,wsid,pdf_filename,type,status)
{   
    url = DIR+"/loadCalendarTab.php";
    params = "date="+date+"&date_format="+cal_date_format;
    //show loading
    nowLoading('block');             
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
                             
                             $('container').innerHTML = result; 
                             
                             createPdf(wid,wsid,pdf_filename,type,status)  
                             
                                                                  
                        }
                    }
                    );   


}
                            

function saveWtWorkouts(formId,filename,wid,wsid,pdf_filename,type,status)
{     
     
    if(validateWt('txttime','METVal','calVal'))
    {
         if(!validateWorkoutName())
            return false;
    
        url = DIR+"/"+filename+".php";
        params = $(formId).serialize();
    //    console.log(params); //should be removed
    //                  return;
        //show loading
        nowLoading('block');             
        
        new Ajax.Request(url,
                        {   
                            method: 'post',
                            parameters: params,
                            //requestHeaders:{Content-type:application/pdf,Content-Disposition:attachment;filename='downloaded.pdf'"}
                            onComplete:function(response)
                            {   
/*                                var result = response.responseText;
                                     result = result.split('~');
                                                         
                                 //load sidebar      
                                 //loadWorkouts(result[0]);
                                                
                                 if(wid == '0')
                                 {
                                    //This happens only when adding a new weight workout.,so there must be a result[3]
                                    
                                    wid = result[2];
                                 } 
                                 
                                   if(wsid == '0')
                                 {
                                    //This happens only when adding a new weight workout.,so there must be a result[3]
                                    
                                    wsid = result[3];
                                 } 
                                    
                                                                                  
                                 //load calendar
                                 loadCalendar(result[0],result[1],wid,wsid,pdf_filename,type,status);*/
                                 
                                 var result = response.responseText.evalJSON();
//                                     result = result.split('~');
//                                                   console.log(result);                          
                                 //load sidebar      
                                 //loadWorkouts(result[0]);
                                                
                                 if(wid == '0')
                                 {
                                    //This happens only when adding a new weight workout.,so there must be a result[3]
                                    
                                    wid = result.workout;
                                 } 
                                                                             
                                 if(wsid == '0')
                                 {
                                    //This happens only when adding a new weight workout.,so there must be a result[3]
                                    
                                    wsid = result.ws_id;
                                 } 
                                    
                                                                                  
                                 //load calendar
                                 loadCalendar(result.sdate,result.reloadCal,wid,wsid,pdf_filename,type,status);
                                                                  
                                 
                                                                      
                            }  
                        }
                        );   

    }
}


/*******************/
function updateWeightWorkouts(formId,filename,wid,wsid,pdf_filename,type,status)
{     
     
    /*if(validateWt('txttime','METVal','calVal'))
    {*/
        url = DIR+"/"+filename+".php";
        params = $(formId).serialize();
    //    console.log(params); //should be removed
    //                  return;
        //show loading
        nowLoading('block');             
        
        new Ajax.Request(url,
                        {   
                            method: 'post',
                            parameters: params,
                            //requestHeaders:{Content-type:application/pdf,Content-Disposition:attachment;filename='downloaded.pdf'"}
                            onComplete:function(response)
                            {   
                                var result = response.responseText;
                                     result = result.split('~');
                                                         
                                 //load sidebar      
                                 //loadWorkouts(result[0]);
                                                
                                 if(wid == '0')
                                 {
                                    //This happens only when adding a new weight workout.,so there must be a result[3]
                                    
                                    wid = result[2];
                                 } 
                                 
                                   if(wsid == '0')
                                 {
                                    //This happens only when adding a new weight workout.,so there must be a result[3]
                                    
                                    wsid = result[3];
                                 } 
                                    
                                                                                  
                                 //load calendar
                                 //updateCalendar(result[0],result[1],wid,wsid,pdf_filename,type,status);
                                 
                                 loadCalendar(result[0],result[1],wid,wsid,pdf_filename,type,status);
                                 //fnChangeMonth(result[1]);
                               
                                 //fnLoadCalendar(date_id1,result[1]) 
                                               
                                               
    //                            setTimeout("createPdf("+wid+","+wsid+")",10000);                                   
                                 
                                                                      
                            }  
                        }
                        );   

   // }
}

/*********************/


function updateSTSWorkouts(formId,filename,wid,wsid,pdf_filename,type,status)
{          
     url = DIR+"/"+filename+".php";
    params = $(formId).serialize();
//    console.log(params); //should be removed
//                  return;
    //show loading
    nowLoading('block');             
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,
                        //requestHeaders:{Content-type:application/pdf,Content-Disposition:attachment;filename='downloaded.pdf'"}
                        onComplete:function(response)
                        {   
                            var result = response.responseText;
                                 res = result.split('~');
                                 
                              if(wid == '0')
                                 {                                 
                                    wid = res[2];
                                 }    
                                                
                                 if(wsid == '0')
                                 {
                                    //This happens only when adding a new weight workout.,so there must be a result[3]
                                    
                                    wsid = res[3];
                                 }
                            
                            //updateCalendar(res[0],res[1],res[2],res[3],pdf_filename,type,status);
                            
                            loadCalendar(res[0],res[1],wid,wsid,pdf_filename,type,status);   
                             
                                                                  
                        }  
                    }
                    ); 
}

function updateloadWorkouts(todate,wid,wsid,pdf_filename,type,status)
{   

    var url;    
    url = DIR+"/calendar_home.php";
    params = "loadDate="+todate;
    //show loading

    nowLoading('block');             

    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,
                        onComplete:function(response)
                        {   
                             //hide loading
                             //nowLoading('none');

                             var result = response.responseText;
                                 result = result.split('~');

                             $('loadDate').innerHTML = result[0]; 
                             $('loadData').innerHTML = result[1]; 
                             $('schedule_date').setAttribute('value',todate)
                             
                             createPdf(wid,wsid,pdf_filename,type,status)
                             
                        }
                    }
                    );   
}  

function updateCalendar(todate,value,wid,wsid,pdf_filename,type,status)
{

    var url=DIR+"/getCalender.php?val="+value;

    new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             var res = response.responseText;    
                             
                             $('calender').innerHTML = res;
                             
                             updateloadWorkouts(todate,wid,wsid,pdf_filename,type,status);
                        }
                    }
                    );    
        //    new Ajax.Updater('calender',url, {
          //  onComplete : alert('completed'); updateloadWorkouts(todate,wid,wsid) }) 
}

/************************************************************************************************
     @Name : changeFlag
     @params:  id of the checkbox
     @return: None. 
     purpose: To set the flag for mark as completed
     Created by: Muthu Vijayan
************************************************************************************************/                           

function changeFlag(index,schId,rotation,workoutType,date)
{   
    
//     store the schId in an intermediate variable so as to use for ticker
    var rstsId = schId;

    // set the rotation date id for DVD and STS
    //because we have only dvd_uid not the rotation date id, we need to frame it.
    
    //check its is rotation & type
    if(rotation && (workoutType == 4 || workoutType == 5))
    {
        var schId = $(schId+'_rdateId').value;  // This was set already in a hidden field
    }

    var set = (rotation)?'C':'R';

    var chkbox = 'chk'+index;
    var flag;
    
   if($(chkbox).checked == true)
        flag = set;
   else
        flag = 'S';     
        
   //alert(fbWMConnect.fnGetSession());
//   Invoke the facebook connection function to ensure the session still exists
   fnInvokeConnection();
        
    var url = DIR+"/updateFlag.php?scheduleId="+schId+"&flag="+flag+"&isRotation="+rotation+"&date="+date+"&workoutType="+workoutType+"&rstsUid="+rstsId;  
    //show loading
    nowLoading('block');             
        
    new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                             
//                              var result = response.responseText;   
                              var result = response.responseText.evalJSON();   
                                 
                              if(result.status == 0) // facebook permission failed, load the permission dialog
                              {
                                 //loadNutrition(result.url,'Facebook Permission Window');
//                                 fbWMConnect.fnShowPopup('Require permission to proceed','reauthDiv',false);
    //                create a div and then load the popup,so that the poup window function can be reused 
                                // fbWMConnect.fnCreateAuthDiv('Require permission to proceed','reauthDiv',false);
                                fbWMConnect.fnPermissionDialog(0);
                              }else if(result.session_expired)
                              {
                                //session expired
                                //fbWMConnect.fnShowTimedOut(result.message,'expiredDiv',false);  
                                fbWMConnect.fnFbSessionRefresh(); // refresh FB session so that JS also terminates it
                                //session is not there, perhaps terminated, display login
                                fbWMConnect.fnShowLogin();
                               
                                //fbWMConnect.fnFbSessionReset(2); // chnage the FB connect status message in the window.  
                                // 2 indicates that only php session is terminated not JS session
                                
                                
                              }else if(result.session_infinite)
                              {
                                //fbWMConnect.fnInfiniteSessionDialog(result.message,'infiniteDiv',false);  
                                fbWMConnect.permissionFor ='offline_access';
                                fbWMConnect.fnPermissionDialog(0);
                              }
                              
                              //load calendar
                             //fnChangeMonth(fntrim(result));
                             loadCalendarTab(date,fntrim(result.date));
                        }
                    }
                    );     
}



/************************************************************************************************
     @Name : clearLoginBox
     @params:  id of the checkbox
     @return: None. 
     purpose: To clear the login box.
     Created by: Muthu Vijayan
************************************************************************************************/                           

function clearLoginBox(id)
{ 

    if($(id).value == 'Username')
    {
        $(id).value='';
    }else if($(id).value == '******')
    {
        $(id).value='';
    }    

}


/************************************************************************************************
     @Name : numbersOnly
     @params:  id of the textbox
     @return: None. 
     purpose: To have only numbers
     Created by: Muthu Vijayan
************************************************************************************************/                           

function numbersOnly1(id)
{ 
    if(isNaN($(id).value))
    {
        alert('Please enter only numbers');
        $(id).value='';
        $(id).focus();
        return false;
    }    
    
}



/************************************************************************************************
     @Name : validateDVD
     @params:  id of the textbox
     @return: None. 
     purpose: To have only numbers
     Created by: Muthu Vijayan
************************************************************************************************/                           

function validateDVD(time,met,calories,formId,filename,index)
{        

    if($('dvd'+index))
    {
         if($F('dvd'+index) == 'null')
         {
            alert("Please Select the DVD");
            $("dvd"+index).focus(); 
            return false;
         }
    }else if($(time).value == '' || isNaN($(time).value))
    {
        alert('Please Enter only numbers in time field');
        $(time).value='';
        $(time).focus();
        return false;
        
    }else if($(met).value == '' || isNaN($(met).value))
    {
        alert('Please Enter only numbers in met field');
        $(met).value='';
        $(met).focus();
        return false;
    }else if($(calories).value == '' || isNaN($(calories).value))
    {
        alert('Please Enter only numbers in calories field');
        $(calories).value='';
        $(calories).focus();
        return false;
    }       
    
//    return true;
    saveWorkouts(formId,filename);
}
/************************************************************************************************
     @Name : validate
     @params:  id of the textbox
     @return: None. 
     purpose: To have only numbers
     Created by: Muthu Vijayan
************************************************************************************************/                           

function validate(time,met,calories,formId,filename,index)
{ 

//only for DVD
    if($('dvd'+index))
    {             
        if($F("dvd"+index) == "null")
        {
           alert("Please Select the DVD") 
           $("dvd"+index).focus(); 
           return false;
        }   
    }

    if($(time).value == '' || isNaN($(time).value))
    {
        alert('Please Enter only numbers in time field');
        $(time).value='';
        $(time).focus();
        return false;
        
    }else if($(met).value == '' || isNaN($(met).value))
    {
        alert('Please Enter only numbers in met field');
        $(met).value='';
        $(met).focus();
        return false;
    }else if($(calories).value == '' || isNaN($(calories).value))
    {
        alert('Please Enter only numbers in calories field');
        $(calories).value='';
        $(calories).focus();
        return false;
    }       
    
//    return true;
    saveWorkouts(formId,filename);
}

/************************************************************************************************
     @Name : validateWt
     @params:  id of the textbox
     @return: None. 
     purpose: To validate
     Created by: Muthu Vijayan
************************************************************************************************/                           

function validateWt(time,met,calories)
{        
    
    if($(time).value == '' || isNaN($(time).value))
    {
        alert('Please Enter only numbers in time field');
        $(time).value='';
        $(time).focus();
        return false;
        
    }else if($(met).value == '' || isNaN($(met).value))
    {
        alert('Please Enter only numbers in met field');
        $(met).value='';
        $(met).focus();
        return false;
    }else if($(calories).value == '' || isNaN($(calories).value))
    {
        alert('Please Enter only numbers in calories field');
        $(calories).value='';
        $(calories).focus();
        return false;
    }       
    
    return true;
    
}


/************************************************************************************************
     @Name : deleteWorkouts
     @params:  id of the checkbox
     @return: None. 
     purpose: To set the flag for mark as completed
     Created by: Muthu Vijayan
************************************************************************************************/        

function editWorkouts(formId,wsId,index,wType,isRotation)
{
    var url = DIR+"/edit_workout.php";  
    //show loading
    nowLoading('block');    
              
    var params = $(formId).serialize();
    var refreshId = "calender"; 

    fnUpdateWorkout(url, refreshId, params);
    
    //if the workout is weight or sts, load the main bar and close this.
    if(wType == 3 || wType == 5)
    {
        $('details_'+index).style.display = 'none';
        $('link_'+index).href = '#';
    }
    
    //on load
    //fnCallOnBodyLoad(wsId,isRotation);
    
    //for all exercises
    fnloadExercises('name','sort');
    
    

}                   

/************************************************************************************************
     @Name : deleteWorkouts
     @params:  id of the checkbox
     @return: None. 
     purpose: To set the flag for mark as completed
     Created by: Muthu Vijayan
************************************************************************************************/                           

function deleteWorkouts(schId,rotation,workoutType,sdate,isMulCardio)
{   
    
    if (confirm("Are you sure you want to delete?"))
    {
        
        var url = DIR+"/deleteWorkouts.php?sdate="+sdate+"&scheduleId="+schId+"&workoutType="+workoutType+"&isRotation="+rotation;  
        
        if(workoutType == 2)
            url += "&isMulCardio="+isMulCardio;
        //show loading
        nowLoading('block');             
            
        new Ajax.Request(url,
                        {   
                            method: 'get',
                            onComplete:function(response)
                            {   
                                 //hide loading
                                 nowLoading('none');
                                 
                                  var result = response.responseText;   
                                  //load calendar
                                 fnChangeMonth(fntrim(result));
                                 
                                 loadWorkouts(sdate);
                            }
                        }
                        );  
    }   
}

/************************************************************************************************
     @Name : checkDeleteWt
     @params:  id of the checkbox
     @return: None. 
     purpose: To set the flag for mark as completed
     Created by: Muthu Vijayan
************************************************************************************************/ 
checkDeleteWt = function(schId,isRotation)
{
   
    var status = 0; 
                   
    for (j=0; j<document.workout_details.elements.length; j++)
    {  

        if((document.workout_details.elements[j].type == 'checkbox') && 
            (document.workout_details.elements[j].checked==true))
        {       
//            status = 1;
            status++;
        }
    }
    
    
    if(status == 0)
    {
        alert('Choose atleast one exercise to delete');
        return false;
        
    }
    else
    {
        deleteWorkoutsDetails(schId,isRotation,status);
    }
    

}
    
/************************************************************************************************
     @Name : deleteWorkoutsDetails
     @params:  id of the checkbox
     @return: None. 
     purpose: To set the flag for mark as completed
     Created by: Muthu Vijayan
************************************************************************************************/                           

function deleteWorkoutsDetails(schId,isRotation,status)
{   
    var frameParams='';
//    var loop = status - 1 ; 
    var j = 0;
                                             
    if(document.workout_details.elements.length > 0)
    {   
        for(var i=0;i<document.workout_details.elements.length;i++)
        {  
            //if(document.detailsForm.elements[i].type == 'checkbox' && (document.detailsForm.elements[i].checked==true))
            if((document.workout_details.elements[i].type == 'checkbox') && 
            (document.workout_details.elements[i].checked==true)) //if(document.workout_details.detailsId[i].checked==true)
            {
                if(isNaN(document.workout_details.elements[i].value))
                {             
                  
                    var childNode = document.workout_details.elements[i].value;
                    $('actTable').removeChild($(childNode));
                    $('records').value = $('records').value - 1;
                                         
                    /*if(j == status) // iterate the selected items
                        return false;*/
                   // continue;
                }
                else
                {
                    frameParams += document.workout_details.elements[i].value;
                    frameParams += ',';
                }   
            }    
        }
                
                
        if(frameParams)
        {        
            var lastPos =frameParams.lastIndexOf(',');
            var params = frameParams.substr(0,lastPos);   
             
            var url = DIR+"/deleteWeightDetails.php?detailsId="+params+"&isRotation="+isRotation;  
        //show loading
        nowLoading('block');             
            
        new Ajax.Request(url,
                        {   
                            method: 'get',
                            onComplete:function(response)
                            {   
                                 //hide loading
                                 nowLoading('none');
                                 
                                  var result = response.responseText;   
                                  //load excersises
                                fnCallOnBodyLoad(schId);
                            }
                        }
                        );     
        }
        
        }

}



function checkAll()
{

    /*if(document.workout_details.elements.length > 0)
    {   
        for(var i=0;i<document.workout_details.elements.length;i++)
        {       
              if(document.workout_details.elements[i].type == 'checkbox')
              {
                document.workout_details.elements[i].checked = true;    
              }
        
        }
    }*/
        
    if(document.workout_details.detailsId.length > 0)
    {   
        for(var i=0;i<document.workout_details.detailsId.length;i++)
        {
            document.workout_details.detailsId[i].checked = true;    
        }
        
    }else
    {
        //Note : if there is only one checkbox, it won't be an array and length property can't be identified.
        if(document.workout_details.detailsId)
            document.workout_details.detailsId.checked = true;        
    }  

}


/*********************Weight Tab********************************/

/************************************************************************************************
     @Name : fnSaveWt
     @params:  None
     @return: None. 
     purpose: To save the weight details
     Created by: Muthu Vijayan
************************************************************************************************/                           

function fnSaveWt(formId,filename)
{
      if($F("wt_value") == '')
      {
           alert("Weight Field cannot be blank"); 
           $("wt_value").focus();
           return false;
      }
       
    /*  if($F("ht_value") == '')
      {
           alert("Height Field cannot be blank"); 
           $("ht_value").focus();
           return false;
      }  */
      
      saveWeight(formId,filename)          
}

/************************************************************************************************
     @Name : saveWeight
     @params:  None
     @return: None. 
     purpose: To save the weight details
     Created by: Muthu Vijayan
************************************************************************************************/                           

function saveWeight(formId,filename)
{   
    url = DIR+"/"+filename+".php";
    params = $(formId).serialize();

    if($('import'))
    { 
        if($('import').value == 1) /** import option is set, so send weight details for weight ticker update */
        {                                                                                                      
            var startWt =$('startWt').value;
            var goalWt =$('goalWt').value;
            var wt = $('wt_value').value;
            
            //validate whether the entered weight value is correct.
             /* Commented by Shanthi Micahel to remove the validation for the weight
			 if((parseInt(wt) < parseInt(startWt)) && 
               (parseInt(wt) < parseInt(goalWt)) ||
               (parseInt(wt) > parseInt(startWt)) && 
               (parseInt(wt) > parseInt(goalWt))
               )
               {
                    msg = 'Your Start weight is '+startWt +'\n';
                    msg +=  'Your Goal weight is '+goalWt +'\n';
                    msg += 'You need to enter a Valid weight to update the ticker!';
                     alert(msg);
                     return false;
               }*/
            
            
            if(wt)
            {
                params += '&currentWt='+wt;
            }
        } 
    }   
    //console.log(params);
    //show loading
    nowLoading('block');             
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
                                 result = result.split('~');
                                 
                                 if(result[0] == 1)
                                 {
                                    $('currentWeight').innerHTML = result[1];
                                    $('currentBMI').innerHTML = result[2];
                                    $('loadWeightGraph').innerHTML = result[3];
                                    $('loadBMIGraph').innerHTML = result[4];
                                    $('weightTableView').innerHTML = result[8];
                                    $('bmiTableView').innerHTML = result[9];
                                    $('lastWeighDate').innerHTML = result[7];
                                    $('lastWeighTotal').innerHTML = result[5]+' '+result[6];
                                    
                                    // reset the hightlighted tab
                                       for(var i=1; i<=6; i++)
                                         {                       
                                            document.getElementById('weight'+i).className = '';
                                            document.getElementById('bmi'+i).className = '';
                                         }
                                             
                                         //highlight the selected tab
                                         document.getElementById('weight1').className = 'current';
                                         document.getElementById('bmi1').className = 'current';
                                 }
                                 else
                                    {
                                        $('Bodyfat_value').innerHTML = result[1]+" "+result[4];
                                        $('lastBodyLogValue').innerHTML = result[1]+" "+result[4];
                                        $('lastBodyLogDate').innerHTML = result[2]; 
                                        $('graph').innerHTML = result[3];
                                        $("bodyLogTableView").innerHTML = result[5];  
                                        
                                        // reset the hightlighted tab
                                       for(var i=1; i<=6; i++)
                                         {                       
                                            document.getElementById('bodylog'+i).className = '';
                                         }
                                             
                                         //highlight the selected tab
                                         document.getElementById('bodylog1').className = 'current';
                                    }                             
                        }
                    }
                    );   


}

 /************************************************************************************************
     @Name : invokeGraph
     @params:  days,duration
     @return: None. 
     purpose: To load the corresponding graph
     Created by: Muthu Vijayan
************************************************************************************************/           

function invokeGraph(section,load,refreshId,me)
{
    var url = DIR+"/frameGraph.php";
    
    var params = '&which='+section+'&load='+load;
    
    var table = (load == 1)?'weightTableView':'bmiTableView';
    
    var currentClass = (load == 1)?'weight':'bmi';
    
   for(var i=1; i<=6; i++)
     {
        
        document.getElementById(currentClass+i).className = '';
     }
         
    if(me)
    {
     //highlight the selected tab
     document.getElementById(me).className = 'current';
    } 
    
    //show loading
    nowLoading('block');  
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,             
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
                                 result = result.split('~');
                                 
                             $(refreshId).innerHTML = result[0];
                             $(table).innerHTML = result[1];
                                                                  
                        }
                    }
                    );   
                    
}
 

 /************************************************************************************************
     @Name : numbersOnly
     @params:  
     @return: None. 
     purpose: To load the corresponding graph
     Created by: Muthu Vijayan
************************************************************************************************/           
   
function numbersOnly(e)
{                        
        var unicode=e.charCode? e.charCode : e.keyCode
        if (unicode!=8 && unicode!=9 && unicode!=46)
        { //if the key isn't the backspace,tab,dot key (which we should allow)
            if (unicode<48||unicode>57) //if not a number
            return false;
        }
    
}
/***************************************************************/

/*****************SETTINGS TAB**********************************/

saveUserSettings = function()
{
    /* Added by Shanthi Micahel - Start */
	var height = document.getElementById('height_value');
    var age    = document.getElementById('age_value');    
	if(height.value == '' || height.value <= 0)
    {
        alert('Please enter your height');
        height.focus();       
        return false; 
    }
	if(age.value == '' || age.value <= 0)
    {
        alert('Please enter your age');
        age.focus();       
        return false; 
    }
	/* Added by Shanthi Micahel - End */
	
	var url = DIR+'/settings_home.php';
    var params = $('settingsForm').serialize();
    
     //show loading
    nowLoading('block');  
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,             
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
							 alert("Settings successfully updated");
//                                 result = result.split('~');
                                 
                       //      $(refreshId).innerHTML = result;
                                                                  
                        }
                    }
                    );   

}


/***************************************************************/
/************************************************************************************************
     @Name : saveGoals
     @params:  
     @return: None. 
     purpose: To save the goals section.
     Created by: Muthu Vijayan
************************************************************************************************/           
 saveGoals = function()
 {
 
    var url = DIR+'/setGoal.php';
    var params = ('goalsForm').serialize();
    
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,             
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
//                                 result = result.split('~');
                                 
                             $('showMsg').innerHTML = result;
                                                                  
                        }
                    }
                    );  
 
 }
 
 /************************************************************************************************
     @Name : updateGoals
     @params:  
     @return: None. 
     purpose: To update the goals section.
     Created by: Muthu Vijayan
************************************************************************************************/           
 updateGoals = function(goalId,updateNode,graphId,unit)
 {
 
    var url = DIR+'/updateGoal.php';
    var params = $('goal_'+goalId).value;
              
    //validate
    if(params == '')
    {
        alert('Please enter only numeric value');
        $('goal_'+goalId).value = '';
        $('goal_'+goalId).focus();
        
        return false;
    }
    
    //show loading
     nowLoading('block');
     
    url += '?gval='+encode64(params)+'&goalId='+goalId;
    
    new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             
                             //$(updateNode).innerHTML = LOADSMALLIMAGE;  
                             //hide loading
                                nowLoading('none');                        
                                                                                  
                             var result = response.responseText;
                                 result = result.split('~');
                                 
                             $(updateNode).innerHTML = result[0]+' '+unit;
                             $(graphId).innerHTML = result[1];
                              //show change goal                
                               $("changeGoal_"+goalId).style.display = 'block';
                               
                               $("modifyGoal_"+goalId).style.display = 'none';
                               $(updateNode).style.display = 'block';
                             
                                //if goal wt is found, then update its value for ticker operation
                                if($('goalWt'))
                                    $('goalWt').value = params;
                        }
                    }
                    );  
 
 }
 
 /************************************************************************************************
     @Name : thickboxDone
     @params: tab to load 
     @return: None. 
     purpose: To close the thckbox and load the tab
     Created by: Muthu Vijayan
************************************************************************************************/   
 thickboxDone = function(load)
 {
    tb_remove();
    //$a("#TB_window").remove(); //close thickbox
    if(load == "tab4")
    showInHome(load);  //load tab
    else if(load != "2")
    getBodyGraph(load)
    else
   getBodyGraph(4) 
 }
 
 
 
 /************************************************************************************************
     @Name : closeThickbox
     @params: close thickbox
     @return: None. 
     purpose: To close the thckbox and load the tab
     Created by: Muthu Vijayan
************************************************************************************************/   
 closeRotationsThickbox = function()
 {
    tb_remove();
    //$a("#TB_window").remove(); //close thickbox
    
    //check wether the browser is safari
    /*if(isBrowserSafari())      
        showInHome('tab2',1);  //load tab // 1 is added to skip the DIR
    else      */
        showInHome('tab2');  //load calendar tab
        
    
 }
 /************************************************************************************************
     @Name : saveGoals
     @params:  
     @return: None. 
     purpose: To save the goals section.
     Created by: Muthu Vijayan
**************************************************************************************************/

loadGoalInput = function(goalId,node,graphId,unit)
{
        
     var input = '<input type="text" name="goal_'+goalId+'" id="goal_'+goalId+'" onkeypress="return numbersOnly(event);">';
         input += '<input type="button" name="btn" value="Save Goal" onclick="updateGoals('+goalId+',\''+node+'\',\''+graphId+'\',\''+unit+'\')">';
         input += '<input type=button value="Cancel" onclick="cancelGoalInput('+goalId+',\''+node+'\')">';
         
      $("modifyGoal_"+goalId).innerHTML = input;
      
      //hide change goal
      $("changeGoal_"+goalId).style.display = 'none';      
      $("modifyGoal_"+goalId).style.display = 'block';      
      
      // actual data
      $(node).style.display = 'none';      

}                               

 /************************************************************************************************
     @Name : cancelGoalInput
     @params:  
     @return: None. 
     purpose: To cancel the change goal option
     Created by: Muthu Vijayan
************************************************************************************************/   

function cancelGoalInput(goalId,node)
{            
    //show change goal
     $("changeGoal_"+goalId).style.display = 'block';      
     $(node).style.display = 'block';    
    
     $("modifyGoal_"+goalId).style.display = 'none';      

}



 /************************************************************************************************
     @Name : saveGoals
     @params:  
     @return: None. 
     purpose: To save the goals section.
     Created by: Muthu Vijayan
************************************************************************************************/   

fnLoadSubCategories = function(whose,tab)
{
    var url = DIR+'/loadSubCategories.php?for='+whose+'&tab='+tab;
    //var params = ('goalsForm').serialize();
    
    $('loadSubCategories').innerHTML = LOADSMALLIMAGE;
    $('loadSelectedExercises').innerHTML = LOADSMALLIMAGE;
    
    new Ajax.Updater('loadSubCategories',url);
    

}
 
 /************************************************************************************************
     @Name : fnLoadSubCatDetails
     @params:  
     @return: None. 
     purpose: To save the goals section.
     Created by: Muthu Vijayan
************************************************************************************************/   

fnLoadSubCatDetails = function(whose,value)
{
    var url = DIR+'/loadSubCatDetails.php?for='+whose+'&value='+value;
    //var params = ('goalsForm').serialize();
    
    $('loadSelectedExercises').innerHTML = LOADSMALLIMAGE;
    new Ajax.Updater('loadSelectedExercises',url);
    

}


/************************************************************************************************
     @Name : fnSaveOneRm
     @params:  
     @return: None. 
     purpose: To save the goals section.
     Created by: Muthu Vijayan
************************************************************************************************/   

fnSaveOneRm = function()
{
    var url = DIR+'/oneRM_home.php';
    var params = $('oneRMForm').serialize();
    sort = $('sort_type').value
    cat = $('subCat').value
    
    //$('ORM').innerHTML = LOADSMALLIMAGE;
        //show loading
     nowLoading('block');
                         
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,             
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
                                 res = result.split('~');
                                 
                             $('ORM').innerHTML = res[0];
                             $('resultList').innerHTML = res[1];
                          
                             if(cat == 'No Subcategories for the selected Category')
                             {
                                  fnloadExercises('name','sort');     
                             }
                             
                             else if(cat == 0)
                             {
                                fnloadExercises(sort,'sort'); 
                             }
                             else
                             {
                                fnLoadSubCatDetails(sort,cat); 
                             }
                                                                  
                        }
                    }
                    ); 
    

}

/************************************************************************************************
     @Name : fnUpdateOneRm
     @params:  
     @return: None. 
     purpose: To update the oneRM section.
     Created by: Muthu Vijayan
************************************************************************************************/   

fnUpdateOneRm = function()
{
    var url = DIR+'/edit_oneRM.php';
    var params = $('oneRMForm').serialize();
    
    //$('ORM').innerHTML = LOADSMALLIMAGE;
        //show loading
     nowLoading('block');
                         
    new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters: params,             
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
//                                 result = result.split('~');
                             editRMDetails(result);    
                             //$('ORM').innerHTML = result;
                                                                  
                        }
                    }
                    ); 
    

}

/************************************************************************************************
     @Name : fnGetDetails
     @params:  
     @return: None. 
     purpose: To get the exercise details
     Created by: Muthu Vijayan
************************************************************************************************/   

fnGetDetails = function(exerId)
{   
    var url = DIR+'/getAllDetails.php?exerId='+exerId;
    
 /*   if(!$('oneRMImage'))
        return false; */
        //show loading
     nowLoading('block');             
     
     $('ORMExerImage').innerHTML = LOADSMALLIMAGE;
                         
    new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                             nowLoading('none');
                                                                                  
                             var result = response.responseText;
                                 result = result.split('~');
                                 
                             $('ORMExerImage').innerHTML = result[1];
                             $('ORMExerDetails').innerHTML = result[0];
                             
                                                                  
                        }
                    }
                    );  
    

}

/************************************************************************************************
     @Name : toggleViews
     @params:  None
     @return: None. 
     purpose: To show/hide the graph/table.
     Created by: Muthu Vijayan
************************************************************************************************/      

function toggleViews(view,hide)
{
     // hide all   
     $(hide).style.display = 'none';
    // console.log("hai")     
     //set visibilty for the graph selected
     $(view).style.display = 'block';

}

/************************************************************************************************
     @Name : deleteRMDetails
     @params:  id of the checkbox
     @return: None. 
     purpose: To delete the one RM exercies
     Created by: Muthu Vijayan
************************************************************************************************/

checkDeleteRM = function()
{
   
    var status = 0; 
                   
    for (j=0; j<document.detailsForm.elements.length; j++)
    {  

        if((document.detailsForm.elements[j].type == 'checkbox') && 
            (document.detailsForm.elements[j].checked==true))
        {       
            status = 1;
        }
    }
    
    
    if(status == 0)
    {
        alert('Choose atleast one exercise to delete');
        return false;
        
    }else
    {
        deleteRMDetails();
    }
    

}

/************************************************************************************************
     @Name : deleteRMDetails
     @params:  id of the checkbox
     @return: None. 
     purpose: To delete the one RM exercies
     Created by: Muthu Vijayan
************************************************************************************************/                           

deleteRMDetails = function()
{   
    var frameParams='';
        
        if(confirm('This action cannot be undone.\nAre you sure you want to delete the selected items?'))
        {
        
            for(var i=0;i<document.detailsForm.elements.length;i++)
            {
                //if(document.detailsForm.detailsId[i].checked==true)
                if(document.detailsForm.elements[i].type == 'checkbox' && (document.detailsForm.elements[i].checked==true))
                {  
                    frameParams += document.detailsForm.elements[i].value;
                    frameParams += ',';
                }    
            }
            
            var lastPos =frameParams.lastIndexOf(',');
            var params = frameParams.substr(0,lastPos);   
             
            var url = DIR+"/deleteRMDetails.php?repId="+params;  
            //show loading
            nowLoading('block');             
                
            new Ajax.Request(url,
                            {   
                                method: 'get',
                                onComplete:function(response)
                                {   
                                     //hide loading
                                     nowLoading('none');
                                     
                                      var result = response.responseText;   
                                      //load excersises
                                    showInHome('tab8');
                                }
                            }
                            );     
        }else
            return false;          
   }



/************************************************************************************************
     @Name : deleteRMDetails
     @params:  id of the checkbox
     @return: None. 
     purpose: To delete the one RM exercies
     Created by: Muthu Vijayan
************************************************************************************************/                           

editRMDetails = function(params)
{   

     var url = DIR+"/edit_oneRM.php?repId="+params;  
            //show loading
            nowLoading('block');             
                
            new Ajax.Request(url,
                            {   
                                method: 'get',
                                onComplete:function(response)
                                {   
                                     //hide loading
                                     nowLoading('none');
                                     
                                      var result = response.responseText;   
                                      //load excersises
                                      $('container').innerHTML = result;  
                                }
                            }
                            );   


}
  
  
  /************************************************************************************************
     @Name : validateOneRM
     @params:  id of the textbox
     @return: None. 
     purpose: To have only numbers
     Created by: Muthu Vijayan
************************************************************************************************/                           

function validateOneRM(mode)
{ 
   
    if($F('selExer') == -1)
    {
        alert('Please Select an Exercise');
        $('selExer').focus();
        return false;
        
    }else if($F('wt_lifted') == '' || isNaN($F('wt_lifted')))
    {
        alert('Please Enter only numbers to calculate');
        $('wt_lifted').value='';
        $('wt_lifted').focus();
        return false;
    }
    
//    return true;
    if(!mode)
        fnSaveOneRm();
    else
        fnUpdateOneRm();    
}


 /************************************************************************************************
     @Name : loadNutrition
     @params:  url of the page,title
     @return: None. 
     purpose: To open thickbox
     Created by: Muthu Vijayan
************************************************************************************************/                   

loadNutrition = function(url,title)
{                                                            //450
     var url = url+'&keepthis=false&TB_iframe=true&height=485&width=950';
//     var url = url+'&modal=true&height=450&width=950';
                    
     tb_show(title,url);
} 

/************************************************************************************************
     @Name : loadSTSlink
     @params:  url of the page,title
     @return: None. 
     purpose: To open thickbox
     Created by: Muthu Vijayan
************************************************************************************************/                   

loadStslink = function(disc_id)
{    
     if(navigator.appName == 'Netscape')                   
        $('printBtn').setAttribute('onclick','javascript:loadSTSBox('+disc_id+')');
     else   
        $('printBtn').onclick = function() { loadSTSBox(disc_id); }; //function() { 'javascript:loadSTSBox('+disc_id+')'};
                    
}

/************************************************************************************************
     @Name : loadSTSlink
     @params:  url of the page,title
     @return: None. 
     purpose: To open thickbox
     Created by: Muthu Vijayan
************************************************************************************************/                   

loadSTSBox = function(disc_id)
{
     var url = DIR+'/stsWorkoutCard.php?disc='+disc_id+'&keepthis=false&TB_iframe=true&height=485&width=950';
                    
     tb_show('Print STS Workout Card',url);
                    
}

/************************************************************************************************
     @Name : loadOneRMBox
     @params:  None
     @return: None. 
     purpose: To open thickbox
     Created by: Shanthi Michael
************************************************************************************************/                   

loadOneRMBox = function()
{
     var url = DIR+'/loadOneRMResults.php?keepthis=false&TB_iframe=true&height=485&width=950';
                    
     tb_show('Print One Rep Max Result',url);
                    
}

/************************************************************************************************
     @Name : loadRepHistory
     @params:  rep_id, exer_id
     @return: None. 
     purpose: To open thickbox
     Created by: Shanthi Michael
************************************************************************************************/                   

loadRepHistory = function(rep_id, exer_id)
{
     var url = DIR+'/oneRMHistory.php?repId='+rep_id+'&exerId='+exer_id+'&keepthis=false&TB_iframe=true&height=485&width=950';
                    
     tb_show('View One Rep Max History',url);
                    
}

/*************START CODE FOR NEW CALENDAR DESIGN**************************************/

/*************************************************************************************
     @Name : fetchWorkouts
     @params:  form id 
     @return: None. 
     purpose: To fecth the weight workouts
     Created by: Muthu Vijayan
**************************************************************************************/                           

fetchWorkouts = function(formId,file)
{   
    if(!file)
        file = 'editWeightWorkouts';
    
    var url = DIR+"/"+file+".php";
     
   // var params = 'uid='+uid+'&isRotation='+isRotation+'&date='+date+'&wtype='+wtype+'&flag='+flag+'&index='+index;
    var params = $(formId).serialize();  
   
                   
    //show loading
    nowLoading('block');          
    
    var refreshId = 'container';           
    
    new Ajax.Updater(refreshId,url,{method:'post',
                    parameters:params,
                    onComplete:function(req)
                            {                        
                                var res = req.responseText 
                                nowLoading('none');                   
                                $(refreshId).innerHTML=res;
                                
                            },
                    evalScripts: true 
            });
                        
}



/*************END CODE FOR NEW CALENDAR DESIGN**************************************/

/*************START CODE FOR NEW STS DESIGN**************************************/

showTemplate = function(sts_uid,index,task)
{
     var url = DIR+"/oneRM_Sts.php";
     
     //url += 's_id='+sts_uid+'&index='+index+'&task='+task;
     var params = $('stsForm'+index).serialize();
                       
    //show loading
    nowLoading('block');         
    
    var refreshId = 'row'+index; 
    
    new Ajax.Updater(refreshId,url,{method:'post',
                    parameters:params, 
                    onComplete:function(req)
                            {                        
                                var res = req.responseText; 
                                nowLoading('none');                   
                                $(refreshId).innerHTML=res;
                                
                            },
                    evalScripts: true 
            });

}


calculateRm = function(sts_uid,index,task,isSaved,isRotation,action)
{
     var url = DIR+"/oneRM_Sts.php";
     
     var wt = $('wt_lifted'+index).value;
     var rep = $('reps'+index).value;
     var stsExId = $('sts_exer_uid'+index).value;
     
     
     if(!wt)
     {
        alert('Please enter the weight');
        $('wt_lifted'+index).focus();
        return false;        
     }
     
     // for older records that might lack the sts_exercise ids
     if(!stsExId && isSaved == 0)
     {
        stsExId = sts_uid;
     }
     
     var params = 's_id='+sts_uid+'&index='+index+'&task='+task+'&wt_lifted='+wt+'&reps='+rep+'&isSaved='+isSaved+'&isRotation='+isRotation+'&stsExId='+stsExId;
     
     if(action == 1)
     {
        var selEx = $('selExer'+index).value;
        params += '&selExer='+selEx;
     }   
        
        //alert(params)
     //var params = $('stsForm'+index).serialize();
                       
    //show loading
    nowLoading('block');         
    
    var refreshId = 'row'+index; 
    
    new Ajax.Updater(refreshId,url,{method:'post',
                    parameters:params, 
                    onComplete:function(req)
                            {                        
                                var res = req.responseText; 
                                nowLoading('none');                   
                                $(refreshId).innerHTML=res;
                                
                            },
                    evalScripts: true 
            });

}


checkRM = function(sts_uid,index,task,isSaved,isRotation)
{
     var url = DIR+"/oneRM_Sts.php?";
     
     url += 's_id='+sts_uid+'&index='+index+'&task='+task+'&isSaved='+isSaved+'&isRotation='+isRotation;
                       
    //show loading
    nowLoading('block');         
    
    var refreshId = 'row'+index; 
    
    new Ajax.Updater(refreshId,url,{method:'get',
                    onComplete:function(req)
                            {                        
                                var res = req.responseText; 
                                nowLoading('none');                   
                                $(refreshId).innerHTML=res;
                                
                            },
                    evalScripts: true 
            });

}       
/*************END CODE FOR NEW STS DESIGN**************************************/


loadVideoWindow = function (youtubeId)
{
     //var url = DIR+'/getVideoData.php?videoId='+youtubeId+'&keepthis=false&TB_iframe=true&height=380&width=425';
     var url = DIR+'/getVideoData.php?videoId='+youtubeId+'&height=380&width=425&modal=true';
                    
     tb_show('STS Videos',url);
                    

}
/*loadVideoWindow = function (youtubeId)
{
    //Effect.Appear('showVideo',{ duration: 1.0 });
  //  return false;
  
   var youtubeUrl = 'http://www.youtube.com/v/'+youtubeId;
   
   var data = '<object type="application/x-shockwave-flash" style="width:425px; height:350px;" id="video" data="'+youtubeUrl+'"><param wmode="opaque" id="video1"  name="movie" value="'+youtubeUrl+'" /></object>';
   
//   $('video').data = $('video1').value = youtubeUrl;
   $('video').innerHTML = data;
   // youtubeUrl;
}  */

closeVideoWindow = function ()
{
    Effect.SwitchOff('showVideo');
    
     $('video').innerHTML = '';
}

/******************************oneRM modification*******************************************/


sortExerciseList = function (sortBy,orderBy)
{
    
     var val = $('sort_name').value;
     var subcat = $('sort_subcat').value;
     
     var setOrder;
     
     // set the hidden sortby
     $('h_sortby').value = sortBy;
     
    if(!orderBy) orderBy = 'asc'; //set default
    /*if(orderBy == 'asc')
        setOrder = 'desc';
    else            
        setOrder = 'asc';*/
        
     if(orderBy == 'asc')
     {
        $('orderImage').innerHTML = "<img title='Click to sort Descending' src='http://cathe.com/workout/images/1rm_sortUp.gif' alt='Ascending' onclick='sortExerciseList($(\"h_sortby\").value,\"desc\")' />";
     }else
     {
           $('orderImage').innerHTML = "<img title='Click to sort Ascending' src='http://cathe.com/workout/images/1rm_sortDown.gif' alt='Descending' onclick='sortExerciseList($(\"h_sortby\").value,\"asc\")' />";
     }
     
    
     if(subcat)
       var url= DIR+"/loadSubCatDetails.php?for="+val+"&value="+subcat+"&sortBy="+sortBy+"&orderBy="+orderBy;
     else  
       var url= DIR+"/getExerciseDetails.php?eleName=sort&val="+val+"&sortBy="+sortBy+"&orderBy="+orderBy;
    
       //show loading
       nowLoading('block');

       new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText;
                            $('loadSelectedExercises').innerHTML = result;
                        }
                    }
                    );


}


setHiddenValues = function (sortSubcat)
{

    if($('sort_subcat'))
    {   
        $('sortby_name').checked=true;
        //$('sort_name').value = sortName;
        $('sort_subcat').value = sortSubcat;
        $('h_sortby').value='exercise_name'; 
        
        //reset image
        $('orderImage').innerHTML = "<img title='Click to sort Descending' src='http://cathe.com/workout/images/1rm_sortUp.gif' alt='Ascending' onclick='sortExerciseList($(\"h_sortby\").value,\"desc\")' />";  
        
    }
}


resetValues = function (value)
{
    $('sort_name').value=value;
    $('sortby_name').checked=true;
    $('h_sortby').value='exercise_name';
    
    //reset to null
    $('sort_subcat').value = '';
    
    //reset image
    $('orderImage').innerHTML = "<img title='Click to sort Descending' src='http://cathe.com/workout/images/1rm_sortUp.gif' alt='Ascending' onclick='sortExerciseList($(\"h_sortby\").value,\"desc\")' />";  
}


var direction;
var field;

sortResults = function(fieldName)
{
      this.field = fieldName;
      //get values
      getValues();
      
      setValues();        
      // set it
      //$('sort_direction').value = this.setVal;
    
      var url= DIR+"/oneRM_sort.php?sortField="+fieldName+"&sortDirection="+this.direction;
    
       //show loading
       nowLoading('block');

       new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText;
                            $('resultList').innerHTML = result;
                            showSortImage();
                        }
                    }
                    );
}


getValues = function()
{
    this.direction = $('sort_direction').value; //get the value    
}


//set the values
setValues = function()
{
    
    if(this.direction == 'desc')
        $('sort_direction').value = 'asc';
    else
        $('sort_direction').value = 'desc';
}

//set Image

showSortImage = function ()
{
   //  $(this.field+'_Image').style.display = 'block';
     
     if(this.direction == 'desc')
       $(this.field+'_Image').src = 'http://cathe.com/workout/images/1rmResults_sortDown.gif';      
     else  
       $(this.field+'_Image').src = 'http://cathe.com/workout/images/1rmResults_sortUp.gif';
    
}

/********************************************************************************************/

/************************************WORKOUTS TAB FUNCTIONALITY********************************/


// load the workouts

loadCategories = function (value)
{
    if (value == "cardio")
       toggleExDetails('none');
    else 
       toggleExDetails('block');                                                           
       
       var url= DIR+"/getWorkoutsTabDetails.php?val="+value

       //show loading
       nowLoading('block');

       new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText;
                                result = result.split('~');
                                
                            $('loadSelectedExercises').innerHTML = result[1];
                            $('loadSubCategories').innerHTML = result[0];
                        }
                    }
                    );

}


loadSubValues = function (value)
{
    if(value == 'all')
        fnloadExercises('name','sort');
    else    
        fnLoadSubCatDetails('mg',value);
        
}

loadCardioList = function (value)
{
    var url;
    
    if(value == 18) //plyo exercise, load from MG
    {
         url = DIR+'/loadSubCatDetails.php?for=mg&value='+value;
         toggleExDetails('block');
    }    
    else
    {
         url = DIR+'/getWorkoutsTabDetails.php?cat_id='+value;
         toggleExDetails('none');
    }    
    
    $('loadSelectedExercises').innerHTML = LOADSMALLIMAGE;

    new Ajax.Updater('loadSelectedExercises',url);

}




frameRow = function (load)
{   
       var curVal = parseInt($('records').value);
       
      
       var SelStr = $('selExer').selectedIndex
       var val =  $('selExer').value
       var seltxt = $('selExer').options[SelStr].text;
       var exname = seltxt.split(',')
       
       //add validation
       if(val == -1)
       {
            alert('Please select the exercise');
            return false;
       }
       
       var strengthFields=null;
       var cardioFields=null;
                                  
       if(load == 'ct')      //only for cross train
       {                           
           //show/hide the req things
           if($('exer_type').value == 'cardio')
           {
                strengthFields = 1;
                cardioFields = 0;
           }else
           {
                strengthFields = 0;
                cardioFields = 1;
           }
       }   
       
       var setPlyo = 0;
        //if category is plyo, set the variable to 1;
       if($('categories').value == 18)
       {
            setPlyo = 1;
       }
        
       /*if(isNaN(val) || val<0)
       {
            alert("Select an Exercise")
            return
       }             */
       var reps = "";
        
        // frame reps select box
        for (i=1;i<31;i++)
        {   
            reps += '<option value="'+i+'">'+i+'</option>';
        }
        
        var reps_per = "";
        for (i=100;i>=40;i--)
        {
            reps_per += '<option value="'+i+'">'+i+'%</option>';
        }
       
        var tBody = $('actTable');
        //var tBody = myTable.getElementsByTagName('tbody')[0];
        //var newTR = document.createElement('tr');
        
        //var setClass = (curVal%2 == 0)?'weightColorRow':'';
       // newTR.setAttribute('class',setClass);
        //newTR.setAttribute('id','row'+curVal);        
        //newTR.className = setClass;           
        
        var setClass = (curVal%2 == 0)?'lightGray':'';

        var bgcolor = (setClass == 'lightGray')?'#efefef':'';  

        var newTR = Builder.node('tr', {className:setClass,id:'row'+curVal,bgcolor:bgcolor});  
        
        tBody.appendChild(newTR);         
                

        $('row'+curVal).className = setClass; 

        

        //Create Sort TD

        /*newTD = document.createElement('td');

        

        newTD.setAttribute('id','exSort'+curVal);

      

newTD.innerHTML = '<span id="moveup'+curVal+'"><img src="images/moveUp.png" onclick="moveup('+curVal+');return false;" alt="Move Up"/></span><span id="movedown'+curVal+'" style="display:none"><img src="images/moveDown.png" onclick="movedown('+curVal+');return false;" alt="Move Down"/></span>';       

        

        newTR.appendChild (newTD);       
                                                    
        

        $('exSort'+curVal).className = 'exSort';    */ 
        
        //check box 
        // newTD = document.createElement('td');
       /* var newTD = Builder.node('td', {className:'addWeightCheckbox'},[
                    Builder.node('input', {type:'checkbox',
                                            name:'detailsId',
                                            value:'row'+curVal
                                           } )
        ]);
        //newTD.setAttribute('class','addWeightCheckbox');
        //newTD.className = 'addWeightCheckbox';
        //newTD.innerHTML = '<input type="checkbox" name="detailsId" value="row'+curVal+'" />';
        newTR.appendChild (newTD);       */
        
        //for ID
        /*newTD = Builder.node('td', {className:'exNo'},[
                    Builder.node('input', {type:'hidden',
                                            name:'exerId'+curVal,
                                            id:'exerId'+curVal,
                                            value:val
                                           } ),
                    Builder.node('label', {
                                            id:'label_id'+curVal                                            
                                           },val )
        ]);
        
         
          newTR.appendChild (newTD);*/
         
         //Exercise name
        //newTD = document.createElement('td');
        newTD = Builder.node('td', {className:'exName'},[
                    Builder.node('input', {type:'hidden',
                                            name:'exerId'+curVal,
                                            id:'exerId'+curVal,
                                            value:val
                                           } ),
                    Builder.node('input', {type:'hidden',
                                            name:'exer_name'+curVal,
                                            id:'exer_name'+curVal,
                                            value:exname[0]
                                           } ),
                    Builder.node('label', {
                                            id:'label_name'+curVal                                            
                                           },exname[0]  )
        ]);
       
       
        newTR.appendChild (newTD);
         
       
       if(load == 'wt' || load == 'ct')
       {
         //1RM
		  
          newTD = Builder.node('td', {className:'ex1RM'},[
            Builder.node('input', {type:'text',
                                    name:'RM'+curVal,
                                    id:'RM'+curVal,              
									style:"text-align:right",
                                    onkeypress:"return numbersOnly(event);",
                                    onChange:"fnCalWeight(this.value,this.name)",
                                    size:6
                                   } )
        ]);
//         newTD.className = 'addWeightORM';   
         //newTD.innerHTML = '<input type="text" name="RM'+curVal+'" id="RM'+curVal+'" value="'+RMval+'" size="5" onChange="fnCalWeight(this.value,this.name)">';
         newTR.appendChild (newTD);

         //1RM Percent   
         newTD = document.createElement('td');       
         newTD.className = 'ex1RMPercent';   
         newTD.innerHTML = '<div id="repsperdiv'+curVal+'"><select name="reps_per'+curVal+'" id="reps_per'+curVal+'" onChange="fnCalWeight(this.value,this.name)" >'+reps_per+'</select></div>';
         newTR.appendChild (newTD);
             
        //newTD = document.createElement('td'); 
        //newTD.setAttribute("class","addWeightWeight");
        newTD = Builder.node('td', {className:'exWeight'},[
                    Builder.node('input', {type:'text',
                                            name:'weight'+curVal,
                                            id:'weight'+curVal,
											style:"text-align:right",
                                            onkeypress:"return numbersOnly(event);",
                                            size:6
                                           })
        ]);
        
        //newTD.className = 'addWeightWeight';    
        //newTD.innerHTML = '<input type="text" size="7"  name="weight'+curVal+'" id="weight'+curVal+'" value="'+Wtval+'"  />';
        newTR.appendChild (newTD);

        //addWeightReps
         newTD = document.createElement('td');
         newTD.setAttribute("class","exReps"); 
         
            newTD.innerHTML = '<div id="repsdiv'+curVal+'"> <select name="reps'+curVal+'" id="reps'+curVal+'" >'+reps+'</select></div>';
         newTR.appendChild (newTD);
		          fnloadOneRM(val, 'RM'+curVal, 'weight'+curVal);

       }
       
       if(strengthFields)
       {
            $('RM'+curVal).setAttribute('disabled','disabled');
            $('reps_per'+curVal).setAttribute('disabled','disabled');
            $('weight'+curVal).setAttribute('disabled','disabled');
            $('reps'+curVal).setAttribute('disabled','disabled');
       }
       
       
       if(load == 'cd' || load == 'ct')
       {    
        //Duration
        
                 newTD = Builder.node('td', [
                            Builder.node('input', {type:'text',
                                                    name:'duration'+curVal,
                                                    id:'duration'+curVal,
                                                    onkeypress:"return numbersOnly(event);",
                                                    size:5
                                                   })
                ]);
                

                 
                 newTR.appendChild (newTD);     
                 
                   //Level
                
                 newTD = Builder.node('td', [
                            Builder.node('input', {type:'text',
                                                    name:'level'+curVal,
                                                    id:'level'+curVal,
                                                    onkeypress:"return numbersOnly(event);",
                                                    size:2
                                                   })
                ]);                                                              

                newTR.appendChild (newTD);   
                
                  //Distance
                
                 newTD = Builder.node('td', [
                            Builder.node('input', {type:'text',
                                                    name:'distance'+curVal,
                                                    id:'distance'+curVal,
                                                    onkeypress:"return numbersOnly(event);",
                                                    size:6
                                                   })
                ]);                                                              

                newTR.appendChild (newTD);  
                
                
                  //RPM
                
                 newTD = Builder.node('td', [
                            Builder.node('input', {type:'text',
                                                    name:'rpm'+curVal,
                                                    id:'rpm'+curVal,
                                                    onkeypress:"return numbersOnly(event);",
                                                    size:3
                                                   })
                ]);                                                              

                newTR.appendChild (newTD);  
                
                  //Speed
                
                 newTD = Builder.node('td', [
                            Builder.node('input', {type:'text',
                                                    name:'speed'+curVal,
                                                    id:'speed'+curVal,
                                                    onkeypress:"return numbersOnly(event);",
                                                    size:6
                                                   })
                ]);                                                              

                newTR.appendChild (newTD);  
                
                
                  //Laps
                
                 newTD = Builder.node('td', [
                            Builder.node('input', {type:'text',
                                                    name:'laps'+curVal,
                                                    id:'laps'+curVal,
                                                    onkeypress:"return numbersOnly(event);",
                                                    size:3
                                                   })
                ]);                                                              

                newTR.appendChild (newTD);  
                
                  //Pace
                
                 newTD = Builder.node('td', [
                            Builder.node('input', {type:'text',
                                                    name:'pace'+curVal,
                                                    id:'pace'+curVal,
                                                    onkeypress:"return numbersOnly(event);",
                                                    size:3
                                                   })
                ]);                                                              

                newTR.appendChild (newTD);  
                 
       }
       
       //show for all
        //Rest
                
                 newTD = Builder.node('td', {className:'exReps'}, [
                            Builder.node('input', {type:'text',
                                                    name:'rest'+curVal,
                                                    id:'rest'+curVal,
                                                    size:5                                                    
                                                   })
                ]); 
                
                newTR.appendChild (newTD);  
       
       if(cardioFields)
       {
            $('duration'+curVal).setAttribute('disabled','disabled');
            $('level'+curVal).setAttribute('disabled','disabled');
            $('distance'+curVal).setAttribute('disabled','disabled');
            $('rpm'+curVal).setAttribute('disabled','disabled');
            $('speed'+curVal).setAttribute('disabled','disabled');
            $('laps'+curVal).setAttribute('disabled','disabled');
            $('pace'+curVal).setAttribute('disabled','disabled');
          //  $('rest'+curVal).setAttribute('disabled','disabled');
       }
       
          
          //Remove image
        
         newTD = Builder.node('td', { className:"exRemove",id:"exRemove"+curVal},[
                    Builder.node('img', {alt:'Remove Exercise',
                                            src:'images/removeEx.png',
                                            onclick:"deleteWorkoutRows('row"+curVal+"',"+curVal+");"
                                           }),
                   Builder.node('input', {
                                            name:'wt_identity'+curVal,
                                            id:'wt_identity'+curVal,
                                            value:$('exer_type').value,
                                            type:'hidden'
                                          }),
                   Builder.node('input', {
                                            name:'isPlyo'+curVal,
                                            id:'isPlyo'+curVal,
                                            value:setPlyo,
                                            type:'hidden'
                                          }),
                   Builder.node('input', {
                                            name:'order_row'+curVal,
                                            id:'order_row'+curVal,
                                            value:curVal+1,
                                            type:'hidden'
                                          })
        ]);                                                              

        newTR.appendChild (newTD);  
          
         tBody.appendChild(newTR); 
          
        /* $("moveup0").style.display = 'none';  // To hide the Current Moveup button
         //$("movedown0").style.display = 'none';  // To hide the Current Moveup button
         if(curVal == 0)
            $("movedown"+curVal).style.display = 'none'; // To hide the Current Movedown button
         
         if(curVal > 0) 
         {  
            previous = curVal-1; 
            $("movedown"+previous).style.display = 'block'; // To hide the Previous Row Movedown button
         }*/                                  
      
        document.getElementById('records').value=curVal + 1; 
        
        //for validation purpose
        document.getElementById('records_total').value=curVal + 1; 
        
//         next_row = curVal + 1;
         
//         console.log(next_row);
        
         
         
    }

function fnloadOneRM(eid, RM, weight)
 {    
	  var url= DIR+"/getRepDetails.php?id="+eid

       //show loading
       nowLoading('block');

       new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText;
                            $(RM).value=result;
							$(weight).value=result;
                        }
                    }
                    );

 }
    
    
displayWorkouts = function (value)
{       
       
       var url= DIR+"/displayWorkoutsTabDetails.php?type="+value
       var btn;
       //show loading
       nowLoading('block');
       
       //reset the values
       $('records').value = 0;
       
       //set the save value
       $('toSave').value = value;
       
       if(value == 'cd')
            toggleExDetails('none');
       else 
            toggleExDetails('block');
            
        setMessage('none');
       //pre-load values according to the value selected
       /*switch(value)
       {
            case 'wt':
               btn =  Builder.node('input',{type:'button',value:'Add Exercise',onclick:'frameRow("'+value+'")'});
            break;
            
            case 'ct':
               btn =  Builder.node('input',{type:'button',value:'Add Exercise',onclick:'frameRow("'+value+'")'});
            break;
       }                                                                                                      */
       
       if(value)
       {   
            btn =  Builder.node('input',{type:'button',id:"btnAddEx",value:'Add Exercise',onclick:'frameRow("'+value+'")'});
            $('btnExer').innerHTML = ''; //clear the already exisitng button
            $('btnExer').appendChild(btn);
       }    

       new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText; 
                                
                                result = result.split('~');
                                                      
                            
                                $('loadSelectedExercises').innerHTML = result[1];
                                $('loadSubCategories').innerHTML = result[0];
//                                $('createExTable').innerHTML = result[3];     //template
                                $('table_id').innerHTML = result[3];     //template
                                //$('exer_type').innerHTML = result[2]; // main category*/
                                $('choose_exType').innerHTML = result[2]; // main category*/
                                
                            //show all
                            $('createStepOne').style.display = 'block';
                            $('createStepTwo').style.display = 'block';
                            $('Step3').style.display = 'block';
                            
                        }
                    }
                    );

}


saveWorkoutsTabDetails = function()
{
    //get the save value
    //var save = $('toSave').value;
       if(!validateWorkoutName())
            return false;

       var url= DIR+"/saveWorkoutsTabDetails.php";
       var params = $('workout_details').serialize();
       //show loading
       nowLoading('block');
       
       new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters:params,
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText;
                            var res = result.split("~");
                               
                             if(res[0] == 1) // Load Error Message
                             {
                                alert(res[1]);
                                if($('WOName'))
                                {
                                    $('WOName').value='';
                                    $('WOName').focus();
                                    return false;
                                }
                             } 
                              
                            showInHome('tab7');
                            
                        }
                    }
                    );
    
}

showWorkoutTypes = function(value)
{
       
       var url= DIR+"/grabWorkouts.php?type="+value
       //var params = $('workout_details').serialize();       
       // selected type
       $('selType').value = value;
       
       if($('Step1'))
       {
           $('Step1').style.display = 'none';
           
           $('Step2').style.display = 'none';
           
           $('createStepTwo').style.display = 'none';
           
           $('Step3').style.display = 'none';
       }    
       
       
       //show loading
       nowLoading('block');
       
       new Ajax.Request(url,
                    {   
                        method: 'get',
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            $('savedWorktouts').style.display = 'block';
                            $('selectEditWorkout').innerHTML = response.responseText;
                            
                        }
                    }
                    );
    
}

frameWorkoutDetails = function (val)
     {
        if(val > 0)
        {
             var url = DIR+'/show_Workouts_tab.php?workout_id='+val;
             
             url += '&load='+$('selType').value;
             
             nowLoading('block');    
             
             var value = $('selType').value;
             
             if(value == 'cd')
                toggleExDetails('none');
             else   
                toggleExDetails('block');
             
            //reset the values
            setMessage('none');
//            $('records').value = 0;
           
            //set the save value
            $('toSave').value = value;
             
             
             if(value)
               {   
                    btn =  Builder.node('input',{type:'button',id:"btnAddEx",value:'Add Exercise',onclick:'frameRow("'+value+'")'});
                    $('btnExer').innerHTML = ''; //clear the already exisitng button
                    $('btnExer').appendChild(btn);
               }
             
             new Ajax.Request(url,
                    {   
                        method: 'get',         
                        
                        onComplete:function(response)
                        {   
                               nowLoading('none');    
                               
                               var result = response.responseText;
                               
                               var res = result.split('~');
                               
                               $('Step1').style.display = 'block';
                               
                               $('Step2').style.display = 'block';
                               
                               $('createStepTwo').style.display = 'block';
                               
                               $('Step3').style.display = 'block';
                               
                               $('itemDescription').value = fntrim(res[0]);
                               
                               $('txttime').value = res[1];
                               
                               $('METVal').value = res[2];
                               
                         //      $('level').value = res[3];
                               
                               $('calVal').value = res[3];
                               
                               $('notes').value = res[4];
                               
                               $('BMIVal').value = res[9];
                               
                               $('total_distance').value = res[6];
                               
                               $('exerciseList').innerHTML = res[5];
                               $('loadSubCategories').innerHTML = res[7];
                               $('loadSelectedExercises').innerHTML = res[8];
                               
                               //$('exer_type').innerHTML = res[10]; // main category  
                               if($('choose_exType'))
                                    $('choose_exType').innerHTML = res[10]; // main category  
                               
//                               fnloadExercises('name','sort');  
                        }
                    
                    }
                    );  
        }
        else
        {
            //block all
            
            $('Step1').style.display = 'none';
            $('Step2').style.display = 'none';
            $('Step3').style.display = 'none';
            $('createStepTwo').style.display = 'none';
            
            alert("Please Select the Workout");
        }       
     }
    

    toggleExDetails = function(mode)
    {
        $('ORMExerImage').style.display = mode;
        $('ORMExerDetails').style.display = mode;
    }
    
    
     setMessage = function (action)
     {
        $('exMsg').style.display = action;    
     }
    /* To enable and disable the sortable functionality in the workouts tab */
    
    //assign globals
    var table;
    var tableDnD;
    
    setSort = function ()
    {
        table = $('createExTable');
        tableDnD = new TableDnD();
        tableDnD.init(table);
        
        //disble add exercises
        $('btnAddEx').disabled = true;
        //$('exMsg').style.display = 'block';
        setMessage('block');
        
//        set highlight property
        new Effect.Highlight($('exMsg'), { startcolor: '#ffff99',endcolor: '#ffffff' });
        
        
    }
    
    unsetSort = function ()
    {
        table = $('createExTable');
        tableDnD = new TableDnD();
        tableDnD.stop(table);
        
        //enable add exercises
        $('btnAddEx').disabled = false;
//        $('exMsg').style.display = 'none';
        setMessage('none');
    }
    
    /**********************************/
    
    workoutPrintCard = function ()
    {
    
        if(!validateWorkoutName())
            return false;
            
        var type = $('toSave').value;
    
        if(type)
        {
            if(type == 'wt')
            {
                download_workouts(1); //save wt woekout // 1 ->indicates from print card fn n
                
            }else
            {
                // save workouts
                //saveWorkoutsTabDetails();
                
                var url= DIR+"/saveWorkoutsTabDetails.php";
                var params = $('workout_details').serialize();
               //show loading
               nowLoading('block');
       
               new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters:params,
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                            
                            var result = response.responseText;
                            var res = result.split("~");
                               
                            if(res[0] == 2) // Load PDF
                             {
                                  var url= DIR+'/workoutsTabCard.php?type='+type+'&wid='+res[1];
                
                                  loadNutrition(url,'Print Workout Card'); 
                             }
                             else if(res[0] == 1) // Load Error Message
                             {
                                alert(res[1]);
                                if($('WOName'))
                                {
                                    $('WOName').value='';
                                    $('WOName').focus();
                                    return false;
                                }
                             }
                            
                            showInHome('tab7');
                            
                        }
                    }
                    );
                       
            }
        }       
    }
    
    
    //delete workout card rows
    
    deleteWorkoutRows = function (node,value)
    {
        $('actTable').removeChild($(node));
        
        // create a hidden text array that holds all the deleted rows identity        
        var input = Builder.node('input',{type:'hidden',name:'removeRow[]',value:value});
        
        $('actTable').appendChild(input); 
        
        //reduce the total _records value
        $('records_total').value = $('records_total').value - 1;
    }
    
    
    // validate the workoutname
    validateWorkoutName = function ()
    {
        if($("WOName"))
        { 
            if(fntrim($F("WOName")) == "")
            {
                alert("Workout Name is Mandatory")
                $("WOName").focus();
                $("WOName").select();
                return false;    
            
            }
            
            if($F("WOName").match(/[^0-9a-zA-Z:_().'"\- ]/))          
            {
                alert("Workout Name Should contain only Alphanumeric Values")
                $("WOName").focus();
                $("WOName").select();
                return false;    
            } 
        }   
                    
        if($("records"))
        {                 
        
            //check for the hidden exercises, happens because the user has only general /basic information
            if($('loadOnNeed')) //check whether it has an id
            {
                if($('loadOnNeed').style.display == 'none') //hidden,so break it;
                    return true;
            }
            
            if(parseInt($F("records")) == 0)
            {
               alert("Please Select Atleast One Exercise")
               $("selExer").focus();
                return false;       

            }
               
            if($("records_total"))
            { 
                if(parseInt($F("records_total")) == 0)
                {
                   alert("Please Select Atleast One Exercise")
                   $("selExer").focus();
                    return false;       

                }
            } 
        }
        return true;
    }
    
/********************************************************************************************/

loadSavedCardioWorkouts = function(val)
{
        if(val == 0)
        {
            fnWorkoutDetails(2); //load cardio general workouts
            return false;
        }
            
       var url= DIR+"/loadCardioWorkoutDetails.php";
       var params = $('workout_details').serialize();
       //show loading
       nowLoading('block');
       
       new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters:params,
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText;
                            //var res = result.split("~");
                            
                            $('Workoutform').innerHTML = result;
                             
                            
                        }
                    }
                    );
    
}

displaySavedCardio = function(formId,index)
{                                   
        var set=0;
        
        if($('loadSavedCardio').checked)
            set = 1;

       var url= DIR+"/showSavedCardio.php";
       var params = $(formId).serialize();
       
       params += '&set='+set;
       //console.log(params);
       //show loading
       nowLoading('block');
       
       new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters:params,
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                             
                            var result = response.responseText;
                            //var res = result.split("~");
                              $('details_'+index).innerHTML = result;
                            //loadCalendarTab();
                             
                            
                        }
                    }
                    );
    
}

/********************************************************************/

loadCopyWindow = function (formId)
{

    var params = $(formId).serialize(true);
     
    var parameters = 'workoutType='+params.workoutType+'&wsid='+params.wsid+'&sdate='+params.sdate+'&isRotation='+params.isRotation;
    
    if(params.workoutSubTypeId)
        parameters += '&workoutSubTypeId='+params.workoutSubTypeId;
        
     var url = DIR+'/copyWorkoutTemplate.php?';
        url += parameters;
        url += '&height=300&width=500&keepthis=false&TB_iframe=true';
//     var url = '#TB_inline?height=155&width=300&inlineId=inline';
//     new Epoch('epoch_popup','popup',$('popup_container'));      
     
     tb_show('Copy Workout',url);
}




closeBox = function(result)
{
   tb_remove();
   
   if(result.status == 1)
        alert(result.message);
   else
        loadCalendarTab(result.date,result.monthYear);              
}

/********************************************************************/

/************Execise STS notes*********************************/

showNotes = function(id,img)
{                
    $(id).show();
    
    //chnage the onclick event;
    //$(img).onClick = 'hideNotes('+id+','+img+')';
    if($(img))
    {
        if(navigator.appName == 'Netscape')
            $(img).setAttribute('onClick','hideNotes("'+id+'","'+img+'")');
        else
            $(img).onclick = function() { hideNotes(id,img) };

            //$(img).onclick = 'javascript:hideNotes("'+id+'","'+img+'")';
                
        //set the collapseimage
        $(img).src = 'images/collapseButton.png';
    }    
}

hideNotes = function(id,img)
{ 
    $(id).hide();
  
    //chnage the onclick event;
//    $(img).onClick = 'showNotes("'+id+'","'+img+'")';
    if($(img))
    {
        if(navigator.appName == 'Netscape') 
            $(img).setAttribute('onClick','showNotes("'+id+'","'+img+'")');
        else
            $(img).onclick = function() { showNotes(id,img) };    
        //set the collapseimage
        $(img).src = 'images/expandButton.png';
    }   
}

saveExNotes = function(index,save)
{
    var notes = $('exNotes'+index).value;
    if(!notes)
    {
        alert('Please enter the notes!');
        return false;
    }
    
     var url= DIR+"/saveNotes.php";
     
//     frame params
     var params = 'exNotes='+escape(notes); // escape($('exNotes'+index).value);
         params += '&exerId='+$('exer_id'+index).value;
     
       //show loading
     nowLoading('block');
       
     new Ajax.Request(url,
                    {   
                        method: 'post',
                        parameters:params,
                        onComplete:function(response)
                        {   
                             //hide loading
                            nowLoading('none');
                                            
                            //update the notes section
                            var exnotes = ' Note :'+ notes; //$('exNotes'+index).value;
                            var span = Builder.node('span',{onclick:'editNotes('+index+')'},
                                        [
                                        Builder.node('font',{color:'#666'},exnotes),
                                        Builder.node('input',{type:'hidden',id:'exNotes'+index,value:notes})
                                        ]
                            );                         
                             $('td_notes'+index).innerHTML = '';   //clear the existing stuff
                             $('td_notes'+index).appendChild(span); // append the span
                                            
                             //should be shown only for save and not for update, becoz already it has the expand button
                             if(save)
                             {
                                 //set the collapseimage
                                 var img = Builder.node('img',{src:'images/collapseButton.png',
                                                                id:'exCol'+index,
                                                               onClick:'hideNotes("notes'+index+'","exCol'+index+'")'});
                        
                                 // need to insert the collapse btn before everything in the row.
                               /*  $('row'+index).firstChild
                                                  .nextSibling
                                                  .insertBefore(img,$('exer_id'+index));//.firstChild.nextSibling.firstChild.nextSibling);         */
                                $('row'+index).getElementsByTagName('td')[0]
                                                  .insertBefore(img,$('exer_id'+index));                   
                                                  
//                                 Add an argument to the function call, becoz now the notes has been added
                                $('addNotes'+index).setAttribute('href','javascript:showNotes("notes'+index+'","exCol'+index+'")');
                             }
                        }
                    }
                    );
}


editNotes = function (index)
{
    var addnode;
    var textVal = $('exNotes'+index).value;
    
    addnode  = Builder.node('td', { colspan:"11"},[
                Builder.node('label','Edit Note :'),
                Builder.node('input',{type:'text',name:'notes',size:'50',id:'exNotes'+index,value:textVal,onkeypress:'return rejectEnterKey(event);',maxlength:"80"}),
                Builder.node('input',{type:'hidden',name:'notesHidden',size:'50',id:'hiddenNotes'+index,value:textVal}),
                Builder.node('input',{type:'button',name:'update',value:'Update',onclick:'javascript:saveExNotes('+index+')'}),
                Builder.node('input',{type:'button',name:'cancel',value:'Cancel',onclick:'cancelNotes('+index+')'})
                ]);
    
    
    $('td_notes'+index).innerHTML = '';   //clear existing code
    $('td_notes'+index).appendChild(addnode);
    
}


cancelNotes = function (index)
{
        var node;
        var textVal = $('exNotes'+index).value;
        var hiddenTextVal = $('hiddenNotes'+index).value;
//        var hiddenTextVal = ($('hiddenNotes'+index))?$('hiddenNotes'+index).value:$('exNotes'+index).value; //for new, there wont be any hdden field
        
        if(!textVal || !hiddenTextVal) // no input value, show add note
        {
                node  = Builder.node('td', { colspan:"11"},[
                    Builder.node('label','Add a Note :'),
                    Builder.node('input',{type:'text',name:'notes',size:'50',id:'exNotes'+index,onkeypress:'return rejectEnterKey(event);',maxlength:"80"}),
                    Builder.node('input',{type:'hidden',name:'hiddenNotes',size:'50',id:'hiddenNotes'+index}),
                    Builder.node('input',{type:'button',name:'save',value:'Save',onclick:'javascript:saveExNotes('+index+')'}),
                    Builder.node('input',{type:'button',name:'cancel',value:'Cancel',onclick:'cancelNotes('+index+')'})
                    ]);
        }else
        {
              var exnotes = ' Note :'+ hiddenTextVal;
              node  = Builder.node('td', { colspan:"11"},[
                                    Builder.node('span',{onclick:'editNotes('+index+')'},     
                                        [
                                        Builder.node('font',{color:'#666'},exnotes),
                                        Builder.node('input',{type:'hidden',id:'exNotes'+index,value:hiddenTextVal})
                                        ]
                            )]);
        }           
        
        $('td_notes'+index).innerHTML = '';   //clear existing code
        $('td_notes'+index).appendChild(node);
        
        hideNotes('notes'+index,'exCol'+index);
}

 /************************************************************************************************
     @Name : rejectEnterKey
     @params:  
     @return: None. 
     purpose: To negelect the enter key 
     Created by: Muthu Vijayan
************************************************************************************************/           
   
function rejectEnterKey(e)
{                        
        var unicode=e.charCode? e.charCode : e.keyCode
        if(unicode == 13) //enter key
            return false;
}

genPdf = function (type,status,stsId,wsId,filename)
{
    var url= filename+".php";
       var params = '?type='+type+'&status='+status+'&wid='+stsId+'&dt='+wsId;
       //show loading
      // nowLoading('block');
       
       /*new Ajax.Request(url,
                    {   
                        method: 'get',
                        parameters:params,
                        onComplete:function(response)
                        {   
                             //hide loading
        //                    nowLoading('none');
                            
                        }
                    }
                    );*/
                    
                    document.location = url+params;
}

 /************************************************************************************************
     @Name : esckeyPressed
     @params:  
     @return: None. 
     purpose: called when the esc button is clicked on rotations window
     Created by: Muthu Vijayan
************************************************************************************************/           
   
function escKeyPressed()
{                        
        tb_remove();
            return false;
}

/************************************************************************************************
     @Name	: calendarPrint
     @params: none
     @return: none 
     purpose: Open a new window with calendar preview and print option
     Created by:Shanthi Michael
************************************************************************************************/ 

function calendarPrint() 
{
	var display_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
	display_setting+="scrollbars=yes,width=750, height=600, left=100, top=25";

	var content_innerhtml = document.getElementById("calender").innerHTML;
	var document_print=window.open("","",display_setting);
	document_print.document.open();
	document_print.document.write('<html><head><title>Print Workout Manager Calendar</title>');
	document_print.document.write('<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /><link rel="stylesheet" type="text/css" media="all" href="css/960.css" /><link rel="stylesheet" type="text/css" media="all" href="css/text.css" /><link rel="stylesheet" type="text/css" media="all" href="css/wmStyles.css" /><link rel="stylesheet" type="text/css" media="all" href="css/calendarImgSprite.css" /></head>');
	document_print.document.write('<body style="font-family:verdana; font-size:12px;"><div class="calendar" style="border: 1px solid thin;">');
	document_print.document.write(content_innerhtml);
	document_print.document.write('</div></body></html>');
	document_print.print();
	document_print.document.close();
	return false;
}