//Usage

//load your JSON (you could jQuery if you prefer)
function loadJSON(callback) {

  
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', '/wp-content/plugins/gravity-spin-the-wheel/libs/prizewheeljs/wheel_data.php', true); 
  xobj.onreadystatechange = function() {
    if (xobj.readyState == 4 && xobj.status == "200") {
      //Call the anonymous function (callback) passing in the response
      callback(xobj.responseText);
    }
  };
  xobj.send(null);
}




//your own function to capture the spin results
function myResult(e) {
  //e is the result object
    console.log('Spin Count: ' + e.spinCount + ' - ' + 'Win: ' + e.win + ' - ' + 'Message: ' +  e.msg);

    // if you have defined a userData object...
    if(e.userData){
      
      console.log('User defined score: ' + e.userData.score)
      console.log('result value: ' + e.userData.selectedvalue)
      jQuery(".prizewheelclass select").val(e.userData.selectedvalue).change();
      var selectedvalis = jQuery(".prizewheelclass select").val();
      console.log('updated field value to ' + selectedvalis);
    }

    


  //if(e.spinCount == 3){
    //show the game progress when the spinCount is 3
    //console.log(e.target.getGameProgress());
    //restart it if you like
    //e.target.restart();
  //}  

}

//your own function to capture any errors
function myError(e) {
  //e is error object
  console.log('Spin Count: ' + e.spinCount + ' - ' + 'Message: ' +  e.msg);

}

function myGameEnd(e) {
  //e is gameResultsArray
  console.log("the game has ended " + e);
  TweenMax.delayedCall(5, function(){
    /*location.reload();*/
  })

  console.log("I'm going to close the form and submit it now");
  doneplaying = 1;
  jQuery(".prizewheelcontainer .gform_wrapper form").submit();

  jQuery(document).bind('gform_confirmation_loaded', function(){
    jQuery( ".hideaftersubmit" ).hide();
  });

}




function prizewheelinit() {

  loadJSON(function(response) {
  // getPhpvars(function(response) {  

    // Parse JSON string to an object
    // var jsonData = JSON.parse(response);

    var newData = phpvars['my_values_inner'];



    //if you want to spin it using your own button, then create a reference and pass it in as spinTrigger
    // var mySpinBtn = document.querySelector('.spinBtn');
    var mySpinBtn = document.querySelector('.wheeltriggerelement');

    jQuery( ".spinBtn2" ).click(function() {
      setTimeout(function() { // 50ms delay to let the DOM update LV_invalid_field for empty fields
        if( !jQuery( ".LV_invalid_field" ).length ){
          // console.log("No errors. wheel will now spin.");
          // fire the wheel
          jQuery('.wheeltriggerelement').click();
        }
        else{
          // console.log("validation errors, wheel will not spin");
        }
      }, 50);
    });



    //create a new instance of Spin2Win Wheel and pass in the vars object
    var myWheel = new Spin2WinWheel();
    
    //WITH your own button
    myWheel.init({data:newData, onResult:myResult, onGameEnd:myGameEnd, onError:myError, spinTrigger:mySpinBtn});
    
    //WITHOUT your own button
    //myWheel.init({data:jsonData, onResult:myResult, onGameEnd:myGameEnd, onError:myError);

    // setTimeout(function() {
    //   myWheel.restart()
    // }, 2200);



    // console.log("working json");
    // console.log(jsonData);
    // console.log(JSON.stringify(jsonData));
    // console.log("nonworking stuff");
    // console.log(phpvars);
    // console.log(JSON.stringify(phpvars));

  });
}



//And finally call it
// open the prizewheel after the remodal modal opens
jQuery(document).on('opened', '.remodal', function () {

    // jsonData = phpvars;
    // setTimeout(function() {
      prizewheelinit(); 
    // }, 800);

// console.log("choices are...");
// console.log(phpvars);

});


 jQuery(document).ready(function () {
  
  doneplaying = 0;

  // open the modal
  console.log( "ready!" );
  var modalinst = jQuery('[data-remodal-id=modal]').remodal();
  modalinst.open();


  // disable enter key on form fields.
  jQuery(document).on( 'keypress', '.gform_wrapper', function (e) {
      var code = e.keyCode || e.which;
      if ( code == 13 && ! jQuery( e.target ).is( 'textarea,input[type="submit"],input[type="button"]' ) ) {
          e.preventDefault();
          return false;
      }
  } );

  // spin the wheel instead of submitting the form
   jQuery(".prizewheelcontainer .gform_wrapper form").submit(function(event) {
       //do what ever you need to here
       if(doneplaying == 1){
        return true;
       } else{
        return false;
       }
    });
});
