jQuery.noConflict();

jQuery(function($) {
//login menu
if($('#loginError')[0]){
  $('li.login').addClass('openLogin');
}

  $('li.login a').hover(
    function () {
    if ($('li.login').is('.openLogin')) {
      return false;
    } else {
      $(this).parent('li.login').addClass('openLogin');
    }
    },
    function () {
    //
    }
  );


  $('#loginClose').click(function(){
    $('li.login.openLogin').removeClass('openLogin');
  });

$('.user-table tr:odd').addClass('odd');

});

jQuery(function($) {
//calculate amount
      $('#amount').bind("keyup", function(){
            var currentValue = $(this).val();
            var itemPrice = $('.item-price-value').text();
            itemPrice = itemPrice.replace(",","."); 
            var newTotal = (currentValue) * (itemPrice);
            newTotal = newTotal.toString().replace(".",",")
            $('.total-price-value').text(newTotal);
        });
});
/*
 * General DOM ready statemenets
 */
jQuery(function($) {
  
  //Question Selected Highlight
  $('.qar').find('article').each(function(){
    $(this).bind('click', function(){
      $(this).siblings('.selected').removeClass('selected');
      $(this).addClass('selected');
    });
  });
  
  //Boxes Equal heights
  $('.box').equalHeight();
  
  //Zebra Table
  $('#schedule-menu').find('table').each(function(){
    $(this).find('tr:even').addClass('even');
    
  });
  
  $('#answers-table').find('table').each(function(){
    $(this).find('tr:even').addClass('even');
    
  });
  
  $('#bigsection table:first tbody tr:even').addClass('even');
  
  $('.test-exams-report-item:even').addClass('even1');
  
  
  
  
  //Home Schedule Table
  $('#schedule-menu').find('li:first-child').addClass('active').end().find('div:first').show();
  $li = $('#schedule-menu li');
  $li.eq(0).click(function(){
    $li.parent().find('.active').removeClass('active');
    $(this).addClass('active');
    $('#schedule-menu').find('div').hide().end().find('div:eq(0)').show();
    return false;
  });   
  $li.eq(1).click(function(){
    $li.parent().find('.active').removeClass('active');
    $(this).addClass('active');
    $('#schedule-menu').find('div').hide().end().find('div:eq(1)').show();
    return false;
  });   
  
  $('.por-menu-item > a').attr('href','javascript:void(0);')
  
  //Show Correct Answers
  $showAnswer = $('#showAnswer');
  $hiddenAnswer = $('#hidden-answer');
  $answerPoints = $('.answer-points');
  //$answerPoints.hide();
  $showAnswer.bind('click', function(){
    $(this).parent().hide();
    $hiddenAnswer.find('td').each(function(){
      if($(this).find('.is-correct').length > 0){
        $(this).empty().append('X')
      } else {
        $(this).filter(':not(:first-child)').empty()
      }
      
    })
    $hiddenAnswer.show().find('.is-correct').show();
    $hiddenAnswer.find('.answer-points').show();
  });
  
});

/*
 * Register Scripts
 */

jQuery(function($){ 

  $form = $('#tx-srfeuserregister-pi1-fe_users_form');
  $examStream = $('#tx-srfeuserregister-pi1-tx_extfeusersdb_stream');
  $examSubjects = $('#tx-srfeuserregister-pi1-tx_extfeusersdb_subjects');
  $subjects = $('.form-column').parent();
  $selectFields = $(':checkbox', $form);
  
  $optRefresh = $examStream.find('option:selected').val();
  $('#subjects').find('div[id="s'+$optRefresh+'"]').show();
  
  //Onload Run Function
  updateSubjectsIds();
  
  $examStream.bind('change', function(){
    var $optVal = $(this).val();
    $('#subjects').find('>div:visible').hide();
    $('#subjects').find('div[id="s'+$optVal+'"]').show();
    updateSubjectsIds();
  });

  $selectFields.bind('change click', function(){
    updateSubjectsIds();
  });

  //Teacher Checkbox Functionality

  $teacherCheckbox = $('#tx-srfeuserregister-pi1-tx_extfeusersdb_teacher');
  if($teacherCheckbox.is(':checked')) $('#subjects-row').hide();
  
  $teacherCheckbox.bind('change', function(){
    if($(this).is(':checked')){
      $('#subjects-row').hide();
      $('#subjects-row').prev().hide();
      $('#subjects-row').prev().prev().hide();
    } else { 
      $('#subjects-row').show();
      $('#subjects-row').prev().show();
      $('#subjects-row').prev().prev().show(); 
    }
    
  });

  function updateSubjectsIds(){
    var selVal = '';
    $selectFields.filter(':checked:visible').each(function(index){
      var separator = (index == 0)?'':','; 
      selVal += separator + $(this).val(); 
    });    
    $examSubjects.val(selVal);
  }

  //Logged in menu change
  var $login = $('.login > a').click(function(e){ e.preventDefault(); });
  if ($('#register[href*=16]').length > 0) {
    $login.text('MIJN PROFIEL')
  } else {
    $login.text('INLOGGEN')
  }

});

jQuery.fn.equalHeight = function () {
    var height        = 0;
    var maxHeight    = 0;

    // Store the tallest element's height
    this.each(function () {
        height        = jQuery(this).outerHeight();
        maxHeight    = (height > maxHeight) ? height : maxHeight;
    });

    // Set element's min-height to tallest element's height
    return this.each(function () {
        var t            = jQuery(this);
        var minHeight    = maxHeight - (t.outerHeight() - t.height());
        var property    = jQuery.browser.msie && jQuery.browser.version < 7 ? 'height' : 'min-height';

        t.css(property, minHeight + 'px');
    });
};

/*
 * Twitter
 */

jQuery(function($){
  /*
   * JavaScript Pretty Date
   * Copyright (c) 2008 John Resig (jquery.com)
   * Licensed under the MIT license.
   */
  
  // Takes an ISO time and returns a string representing how
  // long ago the date represents.
  function prettyDate(time){
    var date = new Date(time || ""),
      diff = (((new Date()).getTime() - date.getTime()) / 1000),
      day_diff = Math.floor(diff / 86400);
    
    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
      return;

    return day_diff == 0 && (
        diff < 60 && "just now" ||
        diff < 120 && "1 minute ago" ||
        diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
        diff < 7200 && "1 hour ago" ||
        diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
      day_diff == 1 && "Yesterday" ||
      day_diff < 7 && day_diff + " days ago" ||
      day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
  }

  /*
   * Get Tweets
   */
  jQuery(function($){
    
    var $twitter = $('.twitter-content');
    var tweets = '';
    var $user = $('#twitter-user').val();
    query = 'http://search.twitter.com/search.json?callback=?&rpp=2&from='+$user;
    
    $.getJSON(
      query,
      function(data){
        $.each(data.results, function(i,item){    
          text = item.text;
          text = text.replace(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g,'<a href="$1://$2$3$4$5">$1:\//$2$3$4$5</a>');  
          tweets += '<article><section><div class="img"><img src="'+item.profile_image_url+'" alt=""></div><div class="txt"><h3>'+item.from_user+'</h3><span>'+item.from_user+'</span></div></section>'+text+'<aside class="time">'+prettyDate(item.created_at)+'</aside></article>';
        });
        $twitter.html(tweets);
      }
    );
  });

});

/*
 *  Download Answers Box
 */
jQuery(document).ready(function($) {
  $("#downloadDiv").bind('click change', function(event){
    
    //Button
    if ($(event.target).is(':button')) {    
      var button = $(event.target).attr('id');
      $.ajax({ 
        url: document.location.href+"?panda=1&action=download&go="+button+"&"+$("#downloadFRM").serialize(),
        success: function(data){
          $('#downloadDiv').empty();
          $('#downloadDiv').html(data);
          $('.box').equalHeight();
          if($('#streamDownload').val() > 0){
            get_json();
          }
        }
      });    
    }
    
    //Select
    if (($(event.target).is('#streamDownload')) && (event.type == 'change')){
      get_json();

    }  
    
  });
  
  function get_json() {
    
    var $firstSelect = $('#streamDownload'),
      $target = $('#subjectDownload');
      //$url = document.location.href;
    
    $.ajax({ 
      url : document.location.href+'?t='+Math.random()*10000,
      data: {
        panda: 1,
        action: "download",
        options: "get",
        streamBox: $firstSelect.val(),
        subject: $('#subjectDownload').val()
      },
      success: function(data){
        $('#subjecSelect').html(data);
      }
    });

  }
  get_json();
  
  /*
   * Calculate grade box
   */
  
  $("#calculategrade").bind('click change', function(event){
      
      //Button
      if ($(event.target).is('#calculate') || $(event.target).is('#backcalculate')) {        
        $.ajax({ 
          data: {
            panda: 1,
              action: "calculategrade",
              step : $(event.target).attr('id')
          },
          url: document.location.href+'?'+$('#gradeForm').serialize(),
          success: function(data){
            $('#calculategrade').empty().html(data);
            $('.box').equalHeight();
            if($('#gradestream').val() > 0){
              calcJson();
            }
          }
        });        
      };
      
      //console.log(event);
      
      //Select
      if (($(event.target).is('#gradestream')) && (event.type == 'change')){
        calcJson();
      }
  });
  function calcJson() {
    var $url = document.location.href,
      $stream = $('#gradestream');  
            
    /*$.getJSON($url,{gradestream: $stream.val(), type: 1, action: 'calculategrade'}, function(data){
         var select = $('#gradesubject');
          var options = select.attr('options');
          $('option', select).remove();
  
          $.each(data, function(array, array) {
              options[options.length] = new Option(array['label'], array['id'], array['selected']);
          });

      })*/
    
    $.ajax({ 
      url : document.location.href+'?t='+Math.random()*10000,
      data: {
        panda: 1,
        action: "calculategrade",
        options: "get",
        gradestream: $stream.val(),
        subject: $('#gradesubject').val()
      },
      success: function(data){
        $('#gradeSubject').html(data);
      }
    });
  }
  calcJson();
  
  /*
   * Top 5 box
   */
  $("#topfive").bind('click change', function(event){
      
      //Button
      if ($(event.target).is('#top5') || $(event.target).is('#backtop5')) {        
        $.ajax({ 
          data: {
            panda: 1,
              action: "topfive",
              stream : $('#top5stream').attr('value'),
              subject : $('#top5subject').attr('value'),
              step : $(event.target).attr('id')
          },
          url: document.location.href,
          success: function(data){
            $('#topfive').empty().html(data);
            $('.box').equalHeight();
            if($('#top5stream').val() > 0){
              json_get();
            }
          }
          
        });        
      };
      
      
      
      //console.log(event);
      
      //Select
      if (($(event.target).is('#top5stream')) && (event.type == 'change')){
          json_get();
      }  
      /*function json_get(){
        var $url = document.location.href,
          $stream = $('#top5stream');
                $.getJSON($url,{top5stream: $stream.val(), type: 1, action: 'topfive'}, function(data){
                   var select = $('#top5subject');
                    var options = select.attr('options');
                    $('option', select).remove();
            
                    $.each(data, function(array, array) {
                        options[options.length] = new Option(array['label'], array['id']);
                    });

                })
        }*/
      
  });
  function json_get(){
    var $url = document.location.href,
    $stream = $('#top5stream');
          /*$.getJSON($url,{top5stream: $stream.val(), panda: 1, action: 'topfive'}, function(data){
             /*var select = $('#top5subject');
              var options = select.attr('options');
              $('option', select).remove();
      
              $.each(data, function(array, array) {
                  options[options.length] = new Option(array['label'], array['id']);
              });
          $('#top5subjectWrap').html(data);
          });*/
          $.ajax({ 
          url : document.location.href+'?t='+Math.random()*10000,
          data: {
            panda: 1,
            action: "topfive",
            top5stream: $stream.val()
          },
          success: function(data){
            $('#top5subjectWrap').html(data);
          }
        });
  }
  json_get();
});

/*
 * Answers toggle
 */
jQuery(function($){
  
  var speed = 200,
    $lvl1 = $('div > .answers-list > li'),
    $lvl2 = $('.answer-list', $lvl1).hide(),
    $els = $('>:checkbox, >:radio', $lvl1);
  
  $els.each(function(){
  
    var $el = $(this);
    
    $el.bind('change', function(){
      toggleElements($els);
    });        
    
  
  /*
    var $el = $(this),
      $child = $('>ul', $el),
      $otherChildren = $el.siblings('li').find('>ul'),
      $item = $(':radio', $el),
      $otherItems = $el.siblings('li').find(':checkbox, :radio');
      
    $item.change(function(){
      if ($(this).is(':checked')) {
        $child.show(speed);
        $otherChildren.hide(speed);
        $otherItems.attr('checked', false);
      }
      
  
    });*/
    
  });
  
  toggleElements($els);
  
  function toggleElements($els){
    $.each($els, function(){
      var $el = $(this);    
      if ($el.is(':checked')) { $el.siblings('.answers-list').show(); }
      else { 
        $el.siblings('.answers-list').hide().find(':checkbox, :radio').attr('checked',false);        
      }
    });
  }
  
});

/*
 * more practice
 */
jQuery(function($){
  
  $('.practice-box').hide();
  $('.practice-box:first').show();
  $('.morePractice').live('click', function(){
    $('.practice-box:hidden:first').show();
    return false;
  });
  
});

/*
 * correct answer
 */
jQuery(function($){
  
  $('#showAnswer').live('click', function(){
    $('#main .multiple-element.is-correct').css({"background-color":"#6daf14"});

  });
  
});

/*
 * dialog confirming when we want to delete a test
 */
jQuery(function($){
  
  $("#dialog-confirm").dialog({
      width: 400,
    autoOpen: false,
    modal: true
    });
  
  
  $("a.delete-test").click(function(e) {
    e.preventDefault();
    var theHREF = $(this).attr("href");
  
  
    $("#dialog-confirm").dialog('option', 'buttons', {
        "Confirm" : function() {
          window.location.href = theHREF;
          },
        "Cancel" : function() {
          $(this).dialog("close");
          }
        });
  
    $("#dialog-confirm").dialog("open");
  
  });
  
});


/*
 * AJAX POST - on text exam
 */
jQuery(function($){
 var $form = $('.test-exam-form');
 if ($form.length > 0) {
  $('.next a', $form).click(function(e){
    var a = e.target;
    $('input[name=actionFrm]').val('answer');
    $.post( $form.attr('action'), $form.serialize(), function(){ document.location.href = a.href; });
    e.preventDefault();
  });
 }
});
