$(document).ready(function() {
    // are we running in native app or in a browser?
    var isphone = false;
    if(document.URL.indexOf("http://") !== -1 
        && document.URL.indexOf("https://") !== -1
        && document.URL.indexOf("localhost") != 7
        && /eclipse/.test(document.URL) !== true) {
        isphone = true;
    }

    if(isphone) {
        document.addEventListener("deviceready", onDeviceReady, false);
    } else {
        onDeviceReady();
    }
    console.log('/eclipse/.test(document.URL): ' + /eclipse/.test(document.URL));
    console.log('document.URL: ' + document.URL);
    console.log(window.isphone);
});

function onDeviceReady() {
  var plus = [],
      minus = [],
      multiply = [],
      divide = [],
      page = 1,
      MAX_EXERCISES = 10;
      
  //debug object
  globals = {};
  globals.plus = plus;
  globals.minus = minus;
  globals.divide = divide;
  
  var lastClickTime = new Date;
  
  $('#page-plus a[href="#prev"]').off('vclick').on('vclick', function() {
    previous('#page-plus', plus);
  });
  
  $('#page-minus a[href="#prev"]').off('vclick').on('vclick', function() {
    previous('#page-minus', minus);
  });
  
  $('#page-multiply a[href="#prev"]').off('vclick').on('vclick', function() {
    previous('#page-multiply', multiply);
  });
  
  $('#page-divide a[href="#prev"]').off('vclick').on('vclick', function() {
    previous('#page-divide', divide);
  });
  
  
  $('#page-plus a[href="#next"], #page-plus a[href="#results"]').off('vclick').on('vclick', function() {
    processResult('#page-plus', plus);
  });
  
  $('#page-minus a[href="#next"], #page-minus a[href="#results"]').off('vclick').on('vclick', function() {
    processResult('#page-minus', minus);
  });
  
  $('#page-multiply a[href="#next"], #page-multiply a[href="#results"]').off('vclick').on('vclick', function() {
    processResult('#page-multiply', multiply);
  });
  
  $('#page-divide a[href="#next"], #page-divide a[href="#results"]').off('vclick').on('vclick', function() {
    processResult('#page-divide', divide);
  });
  
  $('#page-plus input[name="result"]').keypress(function(e) {
    if(e.which == 13) {
      if(page == MAX_EXERCISES) {
        $('#page-plus a[href="#results"]').trigger('click');
      } else {
        $('#page-plus a[href="#next"]').trigger('click');
      }
    }
  });
  
  $('#page-minus input[name="result"]').keypress(function(e) {
    if(e.which == 13) {
      if(page == MAX_EXERCISES) {
        $('#page-minus a[href="#results"]').trigger('click');
      } else {
        $('#page-minus a[href="#next"]').trigger('click');
      }
    }
  });
  
  $('#page-multiply input[name="result"]').keypress(function(e) {
    if(e.which == 13) {
      if(page == MAX_EXERCISES) {
        $('#page-multiply a[href="#results"]').trigger('click');
      } else {
        $('#page-multiply a[href="#next"]').trigger('click');
      }
    }
  });
  
  $('#page-divide input[name="result"]').keypress(function(e) {
    if(e.which == 13) {
      if(page == MAX_EXERCISES) {
        $('#page-divide a[href="#results"]').trigger('click');
      } else {
        $('#page-divide a[href="#next"]').trigger('click');
      }
    }
  });
  
  /**
   * ========= events ==========
   */
  //$(document).on("pageinit", "#plus-results", function(e) {
  //  plus.forEach(function(item) {
  //    
  //  });
  //});
  $(document).on("pageshow", '#page-plus', function(e, data) {
    generatePlus();
    renderRandomNums(plus);
  });
  
  $(document).on("pageshow", '#page-minus', function(e, data) {
    generateMinus();
    renderRandomNums(minus);
  });
  
  $(document).on("pageshow", '#page-multiply', function(e, data) {
    generateMultiply();
    renderRandomNums(multiply);
  });
  
  $(document).on("pageshow", '#page-divide', function(e, data) {
    generateDivide();
    renderRandomNums(divide);
  });
  
  $(document).on("pagehide", '#results', function(e, data) {
    $cloneItem = $('.results-wrapper .item:first').clone();
    //results wrapper cleanup
    $('.results-wrapper').html('');
    $('.results-wrapper').append($cloneItem);
    $('.spinner-wrapper').removeClass('hidden');
    $('.grade-wrapper').addClass('hidden');
  });
  
  $(document).on("pageshow", '#results', function(e, data) {
    var $cloneItem;
    var exercise = [];
    var prevPageId = data.prevPage.attr('id');
    var sign = '';
    if(prevPageId == 'page-plus') {
      exercise = plus;
      sign = '+';
    } else if(prevPageId == 'page-minus') {
      exercise = minus;
      sign = '-';
    } else if(prevPageId == 'page-multiply') {
      exercise = multiply;
      sign = '*';
    } else if(prevPageId == 'page-divide') {
      exercise = divide;
      sign = '/';
    }
    
    console.log('prevPageId: ' + prevPageId);
    console.log('exercise: ', exercise);
    var totalCorrect = 0;
    var resultsHtml = '';
    exercise.forEach(function(item) {
      $cloneItem = $('.results-wrapper .item').filter(':first').clone();
      $cloneItem.find('.number-a').text(item.numberA);
      $cloneItem.find('.number-b').text(item.numberB);
      $cloneItem.find('.result').text(typeof item.result !== 'undefined' && item.result !== '' ? item.result : 'x');
      var isCorrect = eval(item.numberA + sign + item.numberB) === item.result;
      if(isCorrect) {
        totalCorrect += 1;
        $cloneItem.find('.ico-incorrect').addClass('hidden');
      } else {
        $cloneItem.find('.correct').text('(' + eval(item.numberA + sign + item.numberB) + ')');
        $cloneItem.find('.ico-correct').addClass('hidden');
      }
      resultsHtml += '<div class="item">' + $cloneItem.html() + '</div>';
    });
    
    $('.results-wrapper').html(resultsHtml);
    
    if(totalCorrect >= MAX_EXERCISES - 1) {
      $('.result-grade').text('A'); 
    } else if(totalCorrect >= MAX_EXERCISES - 3) {
      $('.result-grade').text('B'); 
    } else if(totalCorrect >= MAX_EXERCISES - 5) {
      $('.result-grade').text('C'); 
    } else if(totalCorrect >= MAX_EXERCISES - 7) {
      $('.result-grade').text('D'); 
    } else if(totalCorrect >= MAX_EXERCISES - 8) {
      $('.result-grade').text('E'); 
    } else {
      $('.result-grade').text('F'); 
    }
    
    $('.sign').text(sign);
    $('.spinner-wrapper').addClass('hidden');
    $('.grade-wrapper').removeClass('hidden');
    $('.want-more-btn').attr('href', '#'+prevPageId);
    reset();
  });
  
  /**
   * ========= Functions ==========
   */
  function generatePlus() {
    for(var i = 1; i <= MAX_EXERCISES; i++) {
      plus.push({
        number: i,
        numberA: Math.round(Math.random() * 10),
        numberB: Math.round(Math.random() * 10)
      });
    }
  }
  
  //maybe in the future we can add some logic here. Eg. only plus results
  function generateMinus() {
    for(var i = 1; i <= MAX_EXERCISES; i++) {
      minus.push({
        number: i,
        numberA: Math.round(Math.random() * 10),
        numberB: Math.round(Math.random() * 10)
      });
    }
  }
  
  function generateMultiply() {
    for(var i = 1; i <= MAX_EXERCISES; i++) {
      multiply.push({
        number: i,
        numberA: Math.round(Math.random() * 10),
        numberB: Math.round(Math.random() * 10)
      });
    }
  }
  
  function generateDivide() {
    var counter = 1;
    while(counter <= MAX_EXERCISES) {
      var numA = Math.round(Math.random() * 10);
      var numB = Math.round(Math.random() * 10);
      if(isInt(numA / numB) && numB !== 0) {
        divide.push({
          number: counter,
          numberA: numA,
          numberB: numB
        });
        counter++;
      }
    }
  }
  
  function isInt(n) {
    return n % 1 === 0;
  }
  
  function previous(pageId, exercise) {
    //on mobile it is sometimes triggered twice so prevent it
    if(page > 1 && (new Date() - lastClickTime > 300)) {
      lastClickTime = new Date;
      page--;
      
      $(pageId + ' input[name="result"]').val(exercise[page - 1].result);
      renderRandomNums(exercise);
      renderPagination();
      if(page < MAX_EXERCISES) {
        $(pageId + ' a[href="#next"]').removeClass('hidden');
        $(pageId + ' .finish-btn').addClass('hidden');
      }
    }
  }
  
  /**
   * Process result from input
   * @param String pageId (#pageId)
   * @param Array exercise: type of exercise (plus|minus|multiply|divide)
   */
  function processResult(pageId, exercise) {
    //on mobile it is sometimes triggered twice so prevent it
    console.log('new Date() - lastClickTime' + (new Date() - lastClickTime));
    if(page <= MAX_EXERCISES && (new Date() - lastClickTime > 300) ) {
      lastClickTime = new Date;
      var result = $(pageId + ' input[name="result"]').val();
      result = parseInt(result);
      result = isNaN(result) ? '' : result;
      exercise[page - 1].result = result;
      
      page++;
      if(exercise[page - 1] && typeof exercise[page - 1].result !== 'undefined') {
        //set next page result
        $(pageId + ' input[name="result"]').val(exercise[page - 1].result);
      } else {
        $(pageId + ' input[name="result"]').val('');
      }
      renderRandomNums(exercise);
      
      if(page <= MAX_EXERCISES)
        renderPagination();
      
      if(page == MAX_EXERCISES) {
        $(pageId + ' a[href="#next"]').addClass('hidden');
        $(pageId + ' .finish-btn').removeClass('hidden');
      }
      console.log('page: ' + page);
    }
  }
  
  function reset() {
    plus = [],
    minus = [],
    multiply = [],
    divide = [],
    page = 1;
    
    renderPagination();
    
    $('a[href="#next"]').removeClass('hidden');
    $('.finish-btn').addClass('hidden');
    $('input[name="result"]').val('');
  }
  
  function renderPagination() {
    $('.exercise-count').text('(' + page + ' from ' + MAX_EXERCISES + ')');
  }
  
  function renderRandomNums(exercise) {
    if(exercise[page - 1]) {
      $('.random-num-a').text(exercise[page - 1].numberA);
      $('.random-num-b').text(exercise[page - 1].numberB);
    }
  }
}