
// while in progress of download/contact, keep track of basic info:
var _jvisitor = {
    
    'form_subject'      : '',        // in case of downloads - this is the product_group
    'form_params_serialized' : '',
    
    'user_id'           : '0',
    'jungost_id'        : '0',
    'jungost_msg'       : '',
    'jungost_lead_link' : '',
    'jungost_lead_link_title' : '',
    'jungost_take_lead' : '',
    'jungost_take_name' : ''
    
}



function bleads_authentication(){
    
    return "gid=176&gidkey=wh5Ho0mgUr4pR0Fy";
    
}


function fixed_jungost_params( product_group ){
    
    var params  = '&' + bleads_authentication()
                  + "&download_action_type_field=download"
                  + "&download_product_group_field=";
                  
    var jungost_product = product_group;
    
    switch( product_group ){ // in some cases we have a custmo override in names used in jungost:
        
        case 'WinDriver'        : jungost_product = 'DriverTools'; break;
        case 'HotSwap'          : jungost_product = 'DriverTools'; break;
        case 'WiFi-DLNA'        : jungost_product = 'USBware'; break;
        case 'Wireless'         : jungost_product = 'USBware'; break;
        case 'USBware-Mobile'   : jungost_product = 'USBware'; break;
        case 'Analog'           : jungost_product = 'USBware'; break;
        case 'USBAnalyzer'      : jungost_product = 'Analyzers'; break;
        
        
        // Anything else remains the same...
    }
    
    params += jungost_product;
    
    return params;
}
    
    
    

function update_vars_from_jungost_response( data ){
// [!] apply any changes to:
//      1. catch these vars in php: jungost_response_vars_to_array()
//      2. local vars tracking, in js: update_vars_from_jungost_response()
   
   _jvisitor.jungost_id                 = data.id;
   _jvisitor.jungost_msg                = data.msg; 
   _jvisitor.jungost_lead_link          = data.viewlink;   // link to edit lead in Bleads
   _jvisitor.jungost_lead_link_title    = data.viewname;
   _jvisitor.jungost_take_lead          = data.takelink;   // link to take ownership of lead, in Bleads
   _jvisitor.jungost_take_name          = data.takename;
   
   
   //console.log('checkpoint1:', _jvisitor );
   
}

function jungost_params_as_string(){
   
   var param_string = 
            'ujid='       + _jvisitor.jungost_id +
            '&ujlink='    + encodeURI( _jvisitor.jungost_lead_link ) +
            '&ujlinkt='   + encodeURI( _jvisitor.jungost_lead_link_title ) +
            '&ujtake='    + encodeURI( _jvisitor.jungost_take_lead ) +
            '&ujtaket='   + encodeURI( _jvisitor.jungost_take_name );
            
   //console.log('checkpoint2:', param_string );             
   
   return param_string;
}

             

/*************************************************************************************
*  Sends lead data to jungost, and gets a JSON repsonse with fetched parameters
*  - Downloads....: sends to jungost AFTER saved in Express (no need for callback), while
*  - Contacts.....: first picks up additional info from jungost, and uses the callback to complete the save to Express
*/
function process_lead_on_jungost( params, optional_callback ){

    var processor_url = 'http://leads.jungo.com/_process_lead.php';
    
        $.getJSON( processor_url+'?callback=?', params, function(data){
            
            //console.log( data );
            
            update_vars_from_jungost_response( data );
            
            if( optional_callback )
                optional_callback(); 
                
        } );
}

/************************************************************************************
*  Updates an EXISITNG lead in Jungost with a new action (.i.e. file download)
*/
function send_lead_action_to_jungost( params ){

    var processor_url = 'http://leads.jungo.com/_update_lead.php';
    
    //var processor_url = '_update_lead.php';
    
        $.getJSON( processor_url+'?callback=?'+'&'+bleads_authentication(), 
                   params, 
                   function(data){
            
                    //console.log( data );
        } );

}



function update_express_user_with_jungost_id( user_id, jungost_id ){
    
    $.getJSON('_update_user_with_jungost_id.php', { 'user_id' : user_id, 'jungost_id' : jungost_id }, function(){
        
        //console.log('finished sending update11...');
    } );
    
    
} 






function fetch_download( id,product_name, codename, force_new_win ){

    // flash download start:    
    $('#fetch-file-capsule').html( "<div class='feedbacks yellow1'>Your Download should start in a few seconds...</div>");
    $('#instructions-box').hide();
    $('#fetch-file-capsule').show().effect("pulsate", { times: 3 }, 1000 );
    
    // using the fetch download to trnasport jungost data on the lead:
    var destination_link = 'initiate_download.php?id=' + id + '&' + jungost_params_as_string();
    
    JTracker('DL:' + id);   // Download file:...
    
    // dynamically add an iframe as a go-getter for download file:
    $(document.body).append("<iframe id='download_iframe' src='" + destination_link + "' style='display:none;'></iframe>");
    
    send_lead_action_to_jungost( { 'lead_id': _jvisitor.jungost_id, 'action_type': 'download', 'action_value': encodeURI(codename) } );
    
    
        
}



function submit_download_form( product_group, lang ){
 // TODO: make same way as contact....
 
 var error = '';
 
 _jvisitor.form_subject = product_group;
 
 error += verify_download_form_for( product_group );
 
 //if( product_group!='WinDriver' )
 error += verify_personal_fields( 'pre_download', '0' );
    
    
 
  if( error!='' )    // actual errors found:
  {
       $('#instructions-box').hide();
       
       form_error_msg( '#form-feedback', false, lang );
       $.scrollTo( '#form-feedback', 0 );       
       
       JTracker('DFE:' + product_group ); 
       return false;
  }  
  else     // process form complete:
  {
        $.scrollTo( '#form-feedback', 0 );
                
        $('#instructions-box').hide();
        form_ok_msg( '#form-feedback', 'Please wait while processing information...');
        
        params = $('#pre_download').serialize() + 
                 fixed_jungost_params( product_group );    // among others, convert to jungost names for groups (like 'DriverTools'')
        
        _jvisitor.form_params_serialized = params;
        
        // CRITICAL!!!   >> we send a callback func. to ACTUALLY save the data, only after the jungost processing is complete:
        //---------------------------------------------------------------------------------------------------------------------
        process_lead_on_jungost( params, callback_complete_download_form );  
        
        return false; // prevent the redirect....
  }

}

function callback_complete_download_form(){
    
    product_group = _jvisitor.form_subject;
    
    // SAVE user info + GENERATE downloadable files list:
        $('#downloads-list').load('download_new.php?dlist=yes&product=' + product_group,  params,  function(){
            
            // and when done:
            
                    _jvisitor.user_id = $('#_express_uid').html();
            
                    JTracker(           'DFC:' + product_group ); 
                    google_track_as(    'DFC:' + product_group ); 
                    
                    run_conversion_code();
                
                    //$('#global-feedback').html('<span class="title2">The following files are now available for download:</span>').show();
                    $('#global-feedback').html('<span class="title2">'+phrase('MSG_SELECT_DOWNLOAD')+'</span>').show();
                    
                    
                    $.scrollTo( '#global-feedback', 500);
                    $('#pre-download-box').hide(); // hide form
                    
                    
                    update_express_user_with_jungost_id( _jvisitor.user_id, _jvisitor.jungost_id ); // saves jungost id to Express as well!
                
        }).show();    
    
} 


function submit_contact_form( form_subject, lang ){

   // we need to perform validations of all input:
   // - the general fields shared with all fields (ONLY IF 'is_new' is TRUE (unregistered user)
   // - the per-form contact questions
   // process is send to Express db only AFTER the MSSQL returns some additional data back (id, and url to lead view in MSSQL), using a callback
    
   var error = '';
   
   _jvisitor.form_subject = form_subject;
   
   var params = $('#contact_form').serialize() + fixed_jungost_params( form_subject );
   
   _jvisitor.form_params_serialized = params;
   
   // validate general (personal) info:
   //-------------------------------------------------   
    error += verify_personal_fields( 'contact_form', '0' );
    error += verify_specific_contact_form_for( form_subject );
   
  if( error ) 
  {
        $('#instructions-box').hide();
        
        form_error_msg('#form-feedback',false, lang );
        $.scrollTo( '#form-feedback', 0 );

        JTracker('CFE:' + form_subject ); 
        return false;
  }
  // else....  process SUBMIT COMPLETE: 
   
  // will clear the 'button', and show an 'ajax-waiting' until done
  // after process is done - will show registration result:
  
  $('#ajax-indicator').show();
  form_ok_msg('#form-feedback', 'Sending contact form...', lang );

   // CRITICAL!!!   >> we send a callback func. to ACTUALLY save the data, only after the jungost processing is complete:
   //---------------------------------------------------------------------------------------------------------------------
    process_lead_on_jungost( params, callback_complete_send_contact );
                                  
  return false;
}

 

// part *2* of the submit contact form (and event signup form): once we get extra data from jungost (id, and link to lead view)
function callback_complete_send_contact(){
    
   //console.log('inside callback!');
    
   var processing_file = get_scripts_path()+'_send_contact_form.php';
   
     $('#form-feedback').load( processing_file+'?'+ _jvisitor.form_params_serialized +'&'+jungost_params_as_string(), 
                            function( new_user_id ){
                                
                                  _jvisitor.user_id = new_user_id;
                                  
                                  
                                
                                  JTracker(           'CFC:' + _jvisitor.form_subject ); 
                                  google_track_as(    'CFC:' + _jvisitor.form_subject );
                                    
                                  run_conversion_code();  
      
                                  $('#form-feedback').hide();
                                  $('#contact-form-container').hide();
                                  $('#instructions-box').html( phrase('MSG_CONTACT_DONE') ).show('slow');
                                  
                                  
                                  
                                  update_express_user_with_jungost_id( _jvisitor.user_id, _jvisitor.jungost_id ); // saves jungost id to Express as well!

    } ); 
    
    return false;
    
}






function submit_event_form( event_id ){

   // we need to perform validations of all input:
   // - the general fields shared with all fields (ONLY IF 'is_new' is TRUE (unregistered user)
   // - the per-form contact questions
    
   var error = '';
   
   var params = $('#contact_form').serialize() + fixed_jungost_params( 'Events-Signup' );
   
   _jvisitor.form_params_serialized = params;
   
   // validate general (personal) info:
   //-------------------------------------------------   
    error += verify_personal_fields( 'contact_form', '0' );
    
    error += verify_specific_contact_form_for( 'Events-Signup' );
   
  // break on errors:
  if( error ) 
  {
    form_error_msg('#form-feedback');
    $('#instructions-box').hide();
    $.scrollTo( '#form-feedback', 0 );
    JTracker('EFE:' + event_id ); 
    return false;
  }
   
  //-----------------------------------------------------------------------------
   
   // will clear the 'button', and show an 'ajax-waiting' until done
  // after process is done - will show registration result:
  
  $('#ajax-indicator').show();
  form_ok_msg('#form-feedback', 'Sending your registration request...');

  //console.log("params....", params);
  
  // CRITICAL!!!   >> we send a callback func. to ACTUALLY save the data, only after the jungost processing is complete:
  //---------------------------------------------------------------------------------------------------------------------
  process_lead_on_jungost( params, callback_complete_send_contact );

  JTracker('EFC:'+event_id );  
  google_track_as( 'groups/Events/' + event_id + '/EVENT_FORM_COMPLETE' );
 

}





/* !!NOT USED!! */
function submit_user_details( requires_pass )
{
     
   var ok = verify_my_account_fields( requires_pass );
   
   if( !ok ) return; // failed the form validations... HALT! 
   
   // else
   // passed > continue... 
   
   var params = $('#user_details').serialize();
   
   params += "&req_pass="   + requires_pass;
   
   var processing_file = get_scripts_path()+'_save_user_details.php';

   $('#ajax-indicator').show();
   
                 
  // will clear the 'button', and show an 'ajax-waiting' until done
  // after process is done - will show registration result:
  
   $('#form-edit-comments').load( processing_file+'?'+params, function(){
   
          $('#ajax-indicator').hide();
          
          var php_reply = $('#form-edit-comments').html();
          
          // if saving failed:
          if( php_reply!='saving...') 
          {
            form_error_msg('#form-edit-comments', php_reply );
            return false;
          }
          else // saved successfuly 
          {  
              $('#user-details-box').hide();
              $('#form-edit-comments').hide();
              $('#instructions-box').html('Your details have been updated!');
          }
                                            
   });

}


function login_exisiting_user(){

   $('#login-errors').html('');
   $('#ajax-indicator').show();
   document.login_user.submit(); 
   

}


 


function check_login(){
  
    var params =    'em=' + document.login_user.user_login_email_field.value + "&" +
                    'pa=' + document.login_user.user_login_password_field.value;
    
  
  var processing_file = get_scripts_path()+'_check_login.php';
  
  
  $('#login-errors').load( processing_file+'?'+params, function(){

           $('#ajax-indicator').hide();
           
           var php_result = $('#login-errors').html();
           
           if(  php_result == 'Logging in...' )
           {
              form_ok_msg( '#login-errors', 'Logging in...'); 
              document.login_user.submit();
           }
           else 
           {
              form_error_msg( '#login-errors', php_result );
           }

      });
  
 

}





function ajax_gif(){
    
    return '<div class="ajax-box"><img src="http://www.jungo.com/images/ajax_load.gif" border="0" /></div>';

}
  


function is_new_email_output( email_msg_field ){
// reads a dom content element that contains a php's response to the ajax call for:  check_email_is_new()

      var email_taken_stat = $( '#'+email_msg_field ).html();
      
      if( email_taken_stat.include('Already registered') )
        return false; 
      else
        return true;


}
  


function verify_personal_fields( parent_form, is_new ){

     var error = ""; 
     
     error += notEmpty(       document.forms[parent_form].user_name_field, false);
     error += mustSelect(     document.forms[parent_form].user_title_field );
     error += notEmpty(       document.forms[parent_form].user_company_field, false);
     error += checkWebsite(   document.forms[parent_form].user_company_website_field, false);
     error += mustSelect(     document.forms[parent_form].user_country_field);
     error += checkPhone(     document.forms[parent_form].user_phone_field, true);
     error += checkEmail( document.forms[parent_form].user_email_field );
       
     return error; 

}

function verify_my_account_fields( requires_pass, is_new ){
// when user 'submit' the form - make sure validations are met/passed:
// NOTE: verify is for form 'user_details'

  var error = "";
  var email_stat="nothing yet";
                                                  
  
  // run ALL validations >> will also trigger all 'red comments' of failed ones:
  
  // -- includes the basic fields:
  error += verify_personal_fields( 'user_details', '0' );  
                       
    
  // -- ..and some extra fields:

  if( requires_pass )
    error += notEmpty(        document.user_details.user_password_field, false,4,12);
  
  
  if( error!="" ) // if list actually was appended after inital msg - we REALLY have errors  
  {
    form_error_msg('#form-edit-comments');  // show default inputs error
    $.scrollTo( '#form-edit-comments', 0 );
    return false;
  }  
  
  else
  {
    // OK >> show wait notice:
    form_ok_msg( '#form-edit-comments', 'Please wait while processing information...' );
    $.scrollTo( '#form-edit-comments', 0 );
    return true;
  
  }
  
  
}


function toggle_forgot_password(){

    $('#forgot-password').hide(); 
    $('#reset-pass-login-feedback').html(''); 
    $('#forgot-password-link').toggle();
    return false;
    
}
              



function reset_login_msgs(){

    $('#login-errors').html('');
    $('#result-restore-email').html('');
    $('#forgot-password').hide();
    $('#forgot-password-link').show();
    $('#ajax-indicator').hide();

}




function request_pass_reminder( email_field, feedback_div ){

    
    email_field     = '#' + email_field;
    feedback_div    = '#' + feedback_div;
    
    var user_email = $( email_field ).val();
    
    $( feedback_div ).html( ajax_gif() + " Please wait...").show();
    $('#login-errors').html('');
    
    var processing_file = get_scripts_path()+'_restore_user_pass.php';
    
    $('#reset-pass-login-feedback').load( processing_file, {'email': user_email }, function(){

            $( feedback_div ).show().effect("highlight", {}, 1000);  
            
            // Extra actions - if success & FROM LOGIN BOX only:
            if( email_field=='#reset_pass_from_login' && $( feedback_div ).html().match("password sent") )
            {
              $('#forgot-password').hide();    // just sent remider. hide..
              $('#login-errors').html(''); // reset last error
            } 
            
    });
  


}
           

function switch_dialog( active_dialog ){

  
  // hiding all dialogs:
  $('#download-dialog-box').hide();
  $('#login-box').hide();
  
  //reset feedback msgs:
  $('#feedback-output').html('');
  
  // show only active one:
  switch( active_dialog ){
  
    case 'download'         :     $('#download-dialog-box').show();
                                  $('#fetch-file-capsule').hide();
                                  break;
  
    case 'edit'             :     $('#register-box').show();
                                  $('#fetch-file-capsule').hide();  
                                  break;
  
  }
  

}

function check_login_event( theKey ){
// used to catch 'enter' key to submit form without buttons/clicks: 
  
  if (theKey == 13)
        {
            check_login( 'user' );
        }

}



function handle_job_title(){

    
    if( $('#user_title_field').val()=='*other*' )
    {
        $('#user_title2').show("slow");
        $('#user_title2_field').val('');
        
    }
    else
    {
        $('#user_title2').hide();
        $('#user_title2_field').val('');
    }
    

}
 

 
function handle_other_field_for( orginal_field )
{

    var other_fieldname = '#' + orginal_field + '2_field';
    var span_other_field = '#' + orginal_field + '2';
    var full_original_name = '#' + orginal_field + '_field';
    

    if( $( full_original_name ).val() == '*other*' )
    {
        $( span_other_field ).show("slow");
        $( other_fieldname ).val('');
        
        
    }
    else
    {
        $( span_other_field ).hide();
        $( other_fieldname ).val('');
        
    }
    


}



function hasId( objId ){
// some effects break if performed on non-exisitng div. this will prevent errors.

    result = document.getElementById( objId );
    
    return result;

}



function form_error_msg( out_div, msg, lang ){

    if( !msg || msg===undefined )
        var msg = phrase('MSG_FIELD_ERRORS');
        
    if( !lang || lang===undefined ) lang='en';  // default language is 'en'
      
    $( out_div ).addClass('feedbacks red1').removeClass('green1').removeClass('yellow1').show();

    $( out_div ).html( msg );

}



function form_ok_msg( out_div, msg, lang ){

    $( out_div ).addClass('feedbacks green1').removeClass('red1').removeClass('yellow1').show();
    
    if( !lang || lang===undefined ) lang='en';  // default language is 'en'
    
    $( out_div ).html( msg );
    
}

  

function ajax_bypass(){

    return false;

}



function phrase( str ){   
// before using it, must initiate per php page using transport_lang_msgs_for_js()
    
    if( str && jungoapp.phrases!=="undefined" && typeof(jungoapp.phrases[str]) !=="undefined" )
        return jungoapp.phrases[str];
    else
        return "(error: missing phrase for: "+str+")";
    
}
