Difference between revisions of "MediaWiki:Common.js"

From SQLZOO
Jump to: navigation, search
Line 1: Line 1:
 
//Common.js original
 
//Common.js original
 
 
/* Any JavaScript here will be loaded for all users on every page load. */
 
/* Any JavaScript here will be loaded for all users on every page load. */
 
var numberOfQuestions = 0;
 
var numberOfQuestions = 0;
Line 7: Line 6:
  
 
//Function to find results in Object ==> getObjects(objName, 'id', 'dataWhatYouLookingFor'); // Returns an array of matching objects
 
//Function to find results in Object ==> getObjects(objName, 'id', 'dataWhatYouLookingFor'); // Returns an array of matching objects
function getObjects(obj, key, val) {
+
function getObjects(obj, key, val) {
var objects = [];
+
  var objects = [];
for (var i in obj) {
+
  for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
+
    if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
+
    if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
+
      objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
+
    } else if (i == key && obj[key] == val) {
objects.push(obj);
+
      objects.push(obj);
}
+
    }
}
+
  }
return objects;
+
  return objects;
}
+
}
  
$(function(){
+
$(function () {
//Display Path in sidebar (Istvan)
+
  //Display Path in sidebar (Istvan)
//GET COHORT
+
  //GET COHORT
if($.inArray('user', wgUserGroups) >= 0){
+
  if ($.inArray('user', wgUserGroups) >= 0) {
$.getJSON('/userData.php',{action:'userCohort',wgUserName:wgUserName},function(d){
+
    $.getJSON('/userData.php', {
//IF the user is member of a cohort create a different menu.
+
      action: 'userCohort',
if(d.cohort.length > 0){
+
      wgUserName: wgUserName
var divPathMenu =$($('<div/>',{id:'divSlideCont'})).append($('<div/>',{id:'divPathMenuCont'}));
+
    }, function (d) {
var pathMenu = $('<div class="portal"/>').append(divPathMenu);
+
      //IF the user is member of a cohort create a different menu.
$('#p-Reference').before(pathMenu);
+
      if (d.cohort.length > 0) {
function createPath(cohort){
+
        var divPathMenu = $($('<div/>', {
$.getJSON('/userData.php',{action:'userPath',cohort:cohort},function(e){
+
          id: 'divSlideCont'
$('#divPathMenuCont').css({'background':'none'});
+
        })).append($('<div/>', {
var path = e.path[0].pathName;
+
          id: 'divPathMenuCont'
$('#divPathMenuCont').empty();
+
        }));
$.getJSON('/userData.php',{action:'menuDb',path:path,member:wgUserName},function(f){
+
        var pathMenu = $('<div class="portal"/>').append(divPathMenu);
  var ul = $('<ul/>',{id:'cohortMenu','class':'dropdown mm_sub'});
+
        $('#p-Reference').before(pathMenu);
for (var i=0;i<f.tut.length;i++){
+
 
                  var NoCObj = [];
+
        function createPath(cohort) {
                  var NoQObj = [];
+
          $.getJSON('/userData.php', {
                  var NoCs = 0; //NumberOfCorrect answers
+
            action: 'userPath',
                  var NoQs = 0; //NumberOfQuestions in a tutorial
+
            cohort: cohort
                  NoQObj = getObjects(f.maxCor, 'wikipage', f.tut[i].wikipage);
+
          }, function (e) {
                  NoCObj = getObjects(f.statMe, 'sname', f.tut[i].sname);
+
            $('#divPathMenuCont').css({
if(NoCObj.length==0){
+
              'background': 'none'
NoCs = 0;
+
            });
} else {
+
            var path = e.path[0].pathName;
NoCs = parseInt(NoCObj[0].correct);
+
            $('#divPathMenuCont').empty();
}
+
            $.getJSON('/userData.php', {
                  NoQs = parseInt(NoQObj[0].maxCor);
+
              action: 'menuDb',
                  var maxWidth = 29.2; // adjust the value so that it fits menu well
+
              path: path,
                  var pbWidth = parseFloat(maxWidth) * NoCs / NoQs;
+
              member: wgUserName
                  var mprogbar = $('<div/>',{'class':'progressbarbg1'}).append($('<div/>',{'class':'progressbar1', 'id':f.tut[i].wikipage, css:{'width':pbWidth}}));
+
            }, function (f) {
                  ul.append($('<li/>').append($('<a/>',{'class':'pathTxta', href:'/wiki/'+f.tut[i].wikipage,text:f.tut[i].sname})).append(mprogbar));
+
              var ul = $('<ul/>', {
}
+
                id: 'cohortMenu',
                $('#divPathMenuCont')
+
                'class': 'dropdown mm_sub'
                  .append($('<div class=body/>')
+
              });
.append(ul)
+
              for (var i = 0; i < f.tut.length; i++) {
)
+
                var NoCObj = [];
.append($("<table id='pathMenuTable'><tr><td>Cohort: </td><td>"+cohort+"</td></tr><tr><td>Path: </td><td>"+path+"</td></tr><tr><td>Teacher: </td><td>"+e.path[0].teacher+"</td></tr></table>"))
+
                var NoQObj = [];
.append($('<div/>',{'class':'divClear'}));
+
                var NoCs = 0; //NumberOfCorrect answers
                if(d.cohort.length>1){
+
                var NoQs = 0; //NumberOfQuestions in a tutorial
$('#divPathMenuCont').append($('<div/>',{id:'divBtns'})).append($('<div/>',{'class':'divClear'}));
+
                NoQObj = getObjects(f.maxCor, 'wikipage', f.tut[i].wikipage);
$('#divBtns')
+
                NoCObj = getObjects(f.statMe, 'sname', f.tut[i].sname);
.append('<div class="dwnBtnClass"></div>') //<img id="dwnBtn" src="/design/dwnArrow_black.png" />
+
                if (NoCObj.length == 0) {
.append('<div class="upBtnClass"></div>'); //<img id="upBtn" src="/design/upArrow_black.png" />
+
                  NoCs = 0;
 +
                } else {
 +
                  NoCs = parseInt(NoCObj[0].correct);
 
                 }
 
                 }
});
+
                NoQs = parseInt(NoQObj[0].maxCor);
});
+
                var maxWidth = 29.2; // adjust the value so that it fits menu well
}
+
                var pbWidth = parseFloat(maxWidth) * NoCs / NoQs;
+
                var mprogbar = $('<div/>', {
function getCohort(index){
+
                  'class': 'progressbarbg1'
var cohort = d.cohort[index].id;
+
                }).append($('<div/>', {
createPath(cohort);
+
                  'class': 'progressbar1',
}
+
                  'id': f.tut[i].wikipage,
+
                  css: {
var index = 0;
+
                    'width': pbWidth
getCohort(index);
+
                  }
+
                }));
$('div.upBtnClass').live("click", function(){
+
                ul.append($('<li/>').append($('<a/>', {
var maxIndex = d.cohort.length-1;
+
                  'class': 'pathTxta',
if (index >= maxIndex){
+
                  href: '/wiki/' + f.tut[i].wikipage,
index = maxIndex;
+
                  text: f.tut[i].sname
} else {
+
                })).append(mprogbar));
index = index + 1;
+
              }
getCohort(index);
+
              $('#divPathMenuCont')
}
+
                .append($('<div class=body/>')
});
+
                  .append(ul)
+
              )
$('div.dwnBtnClass').live("click", function(){
+
                .append($("<table id='pathMenuTable'><tr><td>Cohort: </td><td>" + cohort + "</td></tr><tr><td>Path: </td><td>" + path + "</td></tr><tr><td>Teacher: </td><td>" + e.path[0].teacher + "</td></tr></table>"))
var minIndex = 0;
+
                .append($('<div/>', {
if (index <= minIndex){
+
                  'class': 'divClear'
index = 0;
+
                }));
} else {
+
              if (d.cohort.length > 1) {
index = index - 1;
+
                $('#divPathMenuCont').append($('<div/>', {
getCohort(index);
+
                  id: 'divBtns'
}
+
                })).append($('<div/>', {
});
+
                  'class': 'divClear'
}
+
                }));
});
+
                $('#divBtns')
}
+
                  .append('<div class="dwnBtnClass"></div>') //<img id="dwnBtn" src="/design/dwnArrow_black.png" />
 +
                .append('<div class="upBtnClass"></div>'); //<img id="upBtn" src="/design/upArrow_black.png" />
 +
              }
 +
            });
 +
          });
 +
        }
 +
 
 +
        function getCohort(index) {
 +
          var cohort = d.cohort[index].id;
 +
          createPath(cohort);
 +
        }
 +
 
 +
        var index = 0;
 +
        getCohort(index);
 +
 
 +
        $('div.upBtnClass').live("click", function () {
 +
          var maxIndex = d.cohort.length - 1;
 +
          if (index >= maxIndex) {
 +
            index = maxIndex;
 +
          } else {
 +
            index = index + 1;
 +
            getCohort(index);
 +
          }
 +
        });
 +
 
 +
        $('div.dwnBtnClass').live("click", function () {
 +
          var minIndex = 0;
 +
          if (index <= minIndex) {
 +
            index = 0;
 +
          } else {
 +
            index = index - 1;
 +
            getCohort(index);
 +
          }
 +
        });
 +
      }
 +
    });
 +
  }
  
 
   var engine = $('<div class="portal"/>')
 
   var engine = $('<div class="portal"/>')
Line 117: Line 154:
 
         )
 
         )
 
       )
 
       )
    )
+
  )
  
   $('#right-navigation').after($('<ul/>',{'id':'zoolinks'})
+
   $('#right-navigation').after($('<ul/>', {
    .append($('<li/>').append($('<a/>',{href:'http://csszoo.net',text:'CSS',id:'css_link', title:'Learn CSS! visit CSSzoo'})))
+
      'id': 'zoolinks'
    .append($('<li/>').append($('<a/>',{href:'http://progzoo.net',text:'Java',id:'java_link', title:'Hungry for Java tutorials? ProgZoo is for you'})))
+
    })
    .append($('<li/>').append($('<a/>',{href:'http://linuxzoo.net',text:'Linux',id:'linux_link', title:'Linux Zoo tutoials!'})))
+
    .append($('<li/>').append($('<a/>', {
    .append($('<li/>',{'id':'book'}).append($('<a/>',{href:'http://www.oreilly.com/catalog/sqlhks/',id:'sql_hacks',title:'Try/buy SQL Hacks book'})))
+
      href: 'http://csszoo.net',
 +
      text: 'CSS',
 +
      id: 'css_link',
 +
      title: 'Learn CSS! visit CSSzoo'
 +
    })))
 +
    .append($('<li/>').append($('<a/>', {
 +
      href: 'http://progzoo.net',
 +
      text: 'Java',
 +
      id: 'java_link',
 +
      title: 'Hungry for Java tutorials? ProgZoo is for you'
 +
    })))
 +
    .append($('<li/>').append($('<a/>', {
 +
      href: 'http://linuxzoo.net',
 +
      text: 'Linux',
 +
      id: 'linux_link',
 +
      title: 'Linux Zoo tutoials!'
 +
    })))
 +
    .append($('<li/>', {
 +
      'id': 'book'
 +
    }).append($('<a/>', {
 +
      href: 'http://www.oreilly.com/catalog/sqlhks/',
 +
      id: 'sql_hacks',
 +
      title: 'Try/buy SQL Hacks book'
 +
    })))
 
   );
 
   );
  
 
   $('#p-Reference').before(engine);
 
   $('#p-Reference').before(engine);
 
+
 
 
   //Adverts
 
   //Adverts
   $('<img/>',{src:'/design/sqlhacks.png',alt:'SQL Hacks book ad'})
+
   $('<img/>', {
 +
    src: '/design/sqlhacks.png',
 +
    alt: 'SQL Hacks book ad'
 +
  })
 
     .appendTo($('#sql_hacks'));
 
     .appendTo($('#sql_hacks'));
 
   $('#p-googleadsense').prependTo('#footer');
 
   $('#p-googleadsense').prependTo('#footer');
  
   if (wgCanonicalNamespace=='MediaWiki' || wgCanonicalNamespace=='Special')
+
   if (wgCanonicalNamespace == 'MediaWiki' || wgCanonicalNamespace == 'Special')
 
     $('#p-googleadsense').hide();
 
     $('#p-googleadsense').hide();
  
var startAt = Math.max(1,$('#startAt').text()*1);
+
  var startAt = Math.max(1, $('#startAt').text() * 1);
var qu = $('.qu,.ht,.err');
+
  var qu = $('.qu,.ht,.err');
+
 
 
   //Hints
 
   //Hints
 
   var hint = $('.hint', q);
 
   var hint = $('.hint', q);
 
   hint.hide();
 
   hint.hide();
   hint.each(function(){
+
   hint.each(function () {
 
     var htitle = $(this).attr("title");
 
     var htitle = $(this).attr("title");
     var hnt = $('<div/>', {'class':'hnt', 'text':htitle});
+
     var hnt = $('<div/>', {
 +
      'class': 'hnt',
 +
      'text': htitle
 +
    });
 
     var hidden = $(this);
 
     var hidden = $(this);
     hnt.click(function(e){
+
     hnt.click(function (e) {
      e.preventDefault();
+
      e.preventDefault();
      hidden.toggle("slow");});
+
      hidden.toggle("slow");
 +
    });
 
     $(this).before(hnt);
 
     $(this).before(hnt);
 
   });
 
   });
  
for(var i=0;i<qu.length;i++){
+
  for (var i = 0; i < qu.length; i++) {
var id = i+1;
+
    var id = i + 1;
var q = qu[i];
+
    var q = qu[i];
var lsName = wgPageName + '_' + 'frm__' + id;
+
    var lsName = wgPageName + '_' + 'frm__' + id;
var def = $('.def',q);
+
    var def = $('.def', q);
if (def.length>1){
+
    if (def.length > 1) {
var pick = def.filter(function(){
+
      var pick = def.filter(function () {
var clss = $(this).attr('class').split(' ');
+
        var clss = $(this).attr('class').split(' ');
for(var k=0;k<clss.length;k++)
+
        for (var k = 0; k < clss.length; k++)
if (clss[k].match("^e-")) return false;
+
          if (clss[k].match("^e-")) return false;
return true
+
        return true
});
+
      });
for(var j=0;j<def.length;j++)
+
      for (var j = 0; j < def.length; j++)
  if ($(def[j]).hasClass('e-'+curEng))
+
        if ($(def[j]).hasClass('e-' + curEng))
  pick = $(def[j]);
+
          pick = $(def[j]);
def = pick;
+
      def = pick;
}
+
    }
var txt = def.text();
+
    var txt = def.text();
// replace the default text with user's last query if available in LS
+
    // replace the default text with user's last query if available in LS
if (localStorage.getItem(lsName+"_arr_"+curEng))
+
    if (localStorage.getItem(lsName + "_arr_" + curEng)) {
{
+
      var lsArray = JSON.parse(localStorage.getItem(lsName + "_arr_" + curEng));
var lsArray = JSON.parse(localStorage.getItem(lsName+"_arr_"+curEng));
+
      txt = lsArray[lsArray.length - 1];
txt = lsArray[lsArray.length-1];
+
    }
}
+
 
+
    var ans = $('.ans', q).text();
var ans = $('.ans',q).text();
+
    var tdy = $('.tidy', q).text();
var tdy = $('.tidy',q).text();
+
    var frm = $('<form/>', {
var frm = $('<form/>',{name:'frm__'+id,id:'frm__'+id})
+
      name: 'frm__' + id,
.append($('<div/>',{'class':'quf'})
+
      id: 'frm__' + id
  .append($('<textarea></textarea>',
+
    })
{value:$.trim(txt),
+
      .append($('<div/>', {
  rows:2+Math.max(Math.max(4 ,txt.split(/[\n\r]+/).length),ans.split(/[\n\r]+/).length),
+
          'class': 'quf'
  cols:2+Math.max(Math.max(45,maxlen(txt.split(/[\n\r]+/))),maxlen(ans.split(/[\n\r]+/))),
+
        })
  'class':'sql',
+
        .append($('<textarea></textarea>', {
  id:'txtar_'+id}))
+
          value: $.trim(txt),
  .append($('<br/>'))
+
          rows: 2 + Math.max(Math.max(4, txt.split(/[\n\r]+/).length), ans.split(/[\n\r]+/).length),
  .append($('<button/>',{text:'Submit SQL','class':'submitSQL',click:goBaby}))
+
          cols: 2 + Math.max(Math.max(45, maxlen(txt.split(/[\n\r]+/))), maxlen(ans.split(/[\n\r]+/))),
  .append($('<div/>',{text:'Restore default','class':'reset',click:function(){
+
          'class': 'sql',
      var qu = $(this).parents('.qu, .ht, .err');
+
          id: 'txtar_' + id
                              var def = $('.def',qu);
+
        }))
                      var txt = findBestDefText(qu,$('#engine').val());
+
        .append($('<br/>'))
                      qu.find('textarea.sql').val(txt);
+
        .append($('<button/>', {
  }}))
+
          text: 'Submit SQL',
);
+
          'class': 'submitSQL',
+
          click: goBaby
def.after(frm);
+
        }))
var lhs = $('<div/>',{css:{width:'60ex',marginRight:'2ex','float':'left'}});
+
        .append($('<div/>', {
lhs.append($('<span/>',{text:(startAt+i)+'.','class':'id'}));
+
          text: 'Restore default',
lhs.append($(q).children());
+
          'class': 'reset',
$(q).append(lhs);
+
          click: function () {
     $(q).append($('<div/>',{text:'result','class':'res'}));
+
            var qu = $(this).parents('.qu, .ht, .err');
+
            var def = $('.def', qu);
//Show additional info if available for active angine
+
            var txt = findBestDefText(qu, $('#engine').val());
var ecomm = $('.ecomm,.link',q);
+
            qu.find('textarea.sql').val(txt);
var ecomm1 = ecomm.filter(false);
+
          }
if (ecomm.length>0){
+
        }))
var curEng = $('#engine').val();
+
    );
for(var j=0;j<ecomm.length;j++)
+
 
  if ($(ecomm[j]).hasClass('e-'+curEng))
+
    def.after(frm);
ecomm1 = $(ecomm[j]);
+
    var lhs = $('<div/>', {
}
+
      css: {
for (var j = 0; j < ecomm.length; j++)
+
        width: '60ex',
{
+
        marginRight: '2ex',
if ($(ecomm[j]).get(0) == ecomm1.get(0))
+
        'float': 'left'
{
+
      }
$(ecomm[j]).show();
+
    });
}
+
    lhs.append($('<span/>', {
else
+
      text: (startAt + i) + '.',
{
+
      'class': 'id'
$(ecomm[j]).hide();
+
    }));
}
+
    lhs.append($(q).children());
}
+
    $(q).append(lhs);
 +
     $(q).append($('<div/>', {
 +
      text: 'result',
 +
      'class': 'res'
 +
    }));
 +
 
 +
    //Show additional info if available for active angine
 +
    var ecomm = $('.ecomm,.link', q);
 +
    var ecomm1 = ecomm.filter(false);
 +
    if (ecomm.length > 0) {
 +
      var curEng = $('#engine').val();
 +
      for (var j = 0; j < ecomm.length; j++)
 +
        if ($(ecomm[j]).hasClass('e-' + curEng))
 +
          ecomm1 = $(ecomm[j]);
 +
    }
 +
    for (var j = 0; j < ecomm.length; j++) {
 +
      if ($(ecomm[j]).get(0) == ecomm1.get(0)) {
 +
        $(ecomm[j]).show();
 +
      } else {
 +
        $(ecomm[j]).hide();
 +
      }
 +
    }
  
var ecomm = $('.link',q);
+
    var ecomm = $('.link', q);
var ecomm1 = def.filter(function(){
+
    var ecomm1 = def.filter(function () {
var clss = $(this).attr('class').split(' ');
+
      var clss = $(this).attr('class').split(' ');
for(var k=0;k<clss.length;k++)
+
      for (var k = 0; k < clss.length; k++)
if (clss[k].match("^e-")) return false;
+
        if (clss[k].match("^e-")) return false;
return true
+
      return true
});
+
    });
if (ecomm.length>0){
+
    if (ecomm.length > 0) {
var curEng = $('#engine').val();
+
      var curEng = $('#engine').val();
for(var j=0;j<ecomm.length;j++)
+
      for (var j = 0; j < ecomm.length; j++)
  if ($(ecomm[j]).hasClass('e-'+curEng))
+
        if ($(ecomm[j]).hasClass('e-' + curEng))
ecomm1 = $(ecomm[j]);
+
          ecomm1 = $(ecomm[j]);
}
+
    }
for (var j = 0; j < ecomm.length; j++)
+
    for (var j = 0; j < ecomm.length; j++) {
{
+
      if ($(ecomm[j]).get(0) == ecomm1.get(0)) {
if ($(ecomm[j]).get(0) == ecomm1.get(0))
+
        $(ecomm[j]).show();
{
+
      } else {
$(ecomm[j]).show();
+
        $(ecomm[j]).hide();
}
+
      }
else
+
    }
{
+
    numberOfQuestions = id;
$(ecomm[j]).hide();
+
  }
}
 
}
 
numberOfQuestions = id;
 
}
 
  
if (numberOfQuestions == 0)
+
  if (numberOfQuestions == 0)
numberOfQuestions = 1;
+
    numberOfQuestions = 1;
 
   //Put in the answers if url includes answer=1
 
   //Put in the answers if url includes answer=1
   if (window.location.search && /answer/.test(window.location.search)){
+
   if (window.location.search && /answer/.test(window.location.search)) {
     $('<def/>',{text:"Cheat mode",css:{position:'fixed',right:'2ex',
+
     $('<def/>', {
                  bottom:'2ex',width:'14ex',backgroundColor:'yellow',padding:'2ex',
+
      text: "Cheat mode",
                  textAlign:'center'}})
+
      css: {
 +
        position: 'fixed',
 +
        right: '2ex',
 +
        bottom: '2ex',
 +
        width: '14ex',
 +
        backgroundColor: 'yellow',
 +
        padding: '2ex',
 +
        textAlign: 'center'
 +
      }
 +
    })
 
       .appendTo($('body'));
 
       .appendTo($('body'));
     $('.quf textarea').each(function(){
+
     $('.quf textarea').each(function () {
      $(this).val($(this).closest('form').next('.ans').text());
+
      $(this).val($(this).closest('form').next('.ans').text());
 
     })
 
     })
 
   }
 
   }
  
 
   //Fill in default answers
 
   //Fill in default answers
   if (wgUserName && wgPageName){
+
   if (wgUserName && wgPageName) {
     $.getJSON('/userData.php',{action:'getMostRecent',wgUserName:wgUserName,wgPageName:wgPageName},function(d){
+
     $.getJSON('/userData.php', {
       for(var i=0;i<d.ret.length;i++){
+
      action: 'getMostRecent',
 +
      wgUserName: wgUserName,
 +
      wgPageName: wgPageName
 +
    }, function (d) {
 +
       for (var i = 0; i < d.ret.length; i++) {
 
         var q = d.ret[i].question.split('#');
 
         var q = d.ret[i].question.split('#');
         q = q[1].replace('.','');
+
         q = q[1].replace('.', '');
         var ta = $('#frm__'+q+' div.quf textarea');
+
         var ta = $('#frm__' + q + ' div.quf textarea');
 
         ta.val(d.ret[i].txt);
 
         ta.val(d.ret[i].txt);
         if (d.ret[i].score==100)
+
         if (d.ret[i].score == 100)
           showCorrect($('#frm__'+q).parents('.qu,.ht,.err'));
+
           showCorrect($('#frm__' + q).parents('.qu,.ht,.err'));
 
       }
 
       }
 
     });
 
     });
Line 282: Line 379:
 
//The div.qu (or div.ht) node contains a number of div.def
 
//The div.qu (or div.ht) node contains a number of div.def
 
//These may be specific to an engine in which case they have one or more e-sqlserver e-mysql classes
 
//These may be specific to an engine in which case they have one or more e-sqlserver e-mysql classes
function findBestDefText(quNode,engine){
+
function findBestDefText(quNode, engine) {
   var def = $('.def',q);
+
   var def = $('.def', q);
   if (def.length==0) return "";
+
   if (def.length == 0) return "";
   if (def.length==1) return def.text();
+
   if (def.length == 1) return def.text();
   var perfect=$('.def.e-'+engine)
+
   var perfect = $('.def.e-' + engine)
   if (perfect.length==1) return perfect.text();
+
   if (perfect.length == 1) return perfect.text();
   for(var k=0;k<def.length;k++){
+
   for (var k = 0; k < def.length; k++) {
 
     if (!$(def[i]).attr('class').match('e-'))
 
     if (!$(def[i]).attr('class').match('e-'))
 
       return $(def[i]).text();
 
       return $(def[i]).text();
Line 297: Line 394:
  
 
function updateProgressbar() {
 
function updateProgressbar() {
var numberOfQuestions = parseInt(localStorage.getItem(wgPageName+'_numberOfQuestions'));
+
  var numberOfQuestions = parseInt(localStorage.getItem(wgPageName + '_numberOfQuestions'));
// A little workaround - max progressbar width is 96% of its background's width
+
  // A little workaround - max progressbar width is 96% of its background's width
var maxWidth = parseFloat($('.progressbarbg').css('width')) * 0.96;
+
  var maxWidth = parseFloat($('.progressbarbg').css('width')) * 0.96;
//var barModification = parseFloat($('.progressbar').css('width')) + maxWidth * 1 / numberOfQuestions;
+
  //var barModification = parseFloat($('.progressbar').css('width')) + maxWidth * 1 / numberOfQuestions;
//$('.progressbar').css('width', barModification);
+
  //$('.progressbar').css('width', barModification);
numberOfCorrect = $('div.qcorrect').length;
+
  numberOfCorrect = $('div.qcorrect').length;
numberOfAnswered=$('div.qincorrect').length;
+
  numberOfAnswered = $('div.qincorrect').length;
numberOfQuestions = $('div.qu').length;
+
  numberOfQuestions = $('div.qu').length;
 +
 
 +
  // Display completion info
 +
  $(".summary").html("There are " + numberOfQuestions + " questions on this page.<br/>" + numberOfCorrect + " of your answers were correct.");
 +
  // Save completion info
 +
  if (localStorage) {
 +
    localStorage.setItem(wgPageName + '_numberOfQuestions', numberOfQuestions);
 +
    localStorage.setItem(wgPageName + '_numberOfCorrect', numberOfCorrect);
 +
  }
  
// Display completion info
+
  //Progress bar
$(".summary").html("There are "+numberOfQuestions+" questions on this page.<br/>"+numberOfCorrect+" of your answers were correct.");
+
 
// Save completion info
+
  var barModification = parseFloat(maxWidth) * numberOfCorrect / numberOfQuestions;
if (localStorage)
+
  $('.progressbar').css('width', barModification);
{
+
 
localStorage.setItem(wgPageName+'_numberOfQuestions', numberOfQuestions);
+
  //Progress bar in main menu
localStorage.setItem(wgPageName+'_numberOfCorrect', numberOfCorrect);
+
  var maxWidth = 50;
}
+
  pbWidth = parseFloat(maxWidth) * numberOfCorrect / numberOfQuestions;
+
 
//Progress bar
+
  var barId = $('#firstHeading').text().replace(/\ /g, '_');
+
  $("#" + barId).css('width', pbWidth);
var barModification = parseFloat(maxWidth) * numberOfCorrect / numberOfQuestions;
+
 
$('.progressbar').css('width', barModification);
+
  //Progress bars in Path Menu
+
  var wikipage = window.location.pathname;
//Progress bar in main menu
+
  wikipage = wikipage.split('/');
var maxWidth = 50;
+
 
pbWidth = parseFloat(maxWidth)*numberOfCorrect/numberOfQuestions;
+
  var path = $('#pathNameTxt').text();
+
  var NoCs = 0;
var barId = $('#firstHeading').text().replace(/\ /g, '_');
+
  var NoQs = 0;
$("#"+barId).css('width',pbWidth);
+
 
+
  $.getJSON('/userData.php', {
//Progress bars in Path Menu
+
    action: 'updProgressBar',
var wikipage = window.location.pathname;  
+
    wgUserName: wgUserName,
    wikipage = wikipage.split('/');  
+
    path: path,
+
    wikipage: wikipage[2]
var path = $('#pathNameTxt').text();
+
  }, function (d) {
var NoCs =0;
+
    if (d.corr.length > 0) {
var NoQs =0;
+
      NoCs = parseInt(d.corr[0].correct);
+
      NoQs = parseInt(d.maxCor[0].maxCor);
$.getJSON('/userData.php',{action:'updProgressBar',wgUserName:wgUserName,path:path,wikipage:wikipage[2]},function(d){
+
      var maxWidthp = 29.2;
if(d.corr.length > 0){
+
      var pbWidthp = parseFloat(maxWidthp) * NoCs / NoQs;
NoCs = parseInt(d.corr[0].correct);
+
      $('#' + wikipage[2]).css('width', pbWidthp);
NoQs = parseInt(d.maxCor[0].maxCor);
+
    }
var maxWidthp = 29.2;
+
  });
var pbWidthp = parseFloat(maxWidthp) * NoCs / NoQs;
 
$('#'+wikipage[2]).css('width', pbWidthp);
 
 
}
 
 
});
 
 
}
 
}
  
function goBaby(){
+
function goBaby() {
 
   var qu = $(this).parents('.qu, .ht, .err');
 
   var qu = $(this).parents('.qu, .ht, .err');
 
   var lsUse = ((qu[0].getAttribute('class') != 'ht') && ($(qu[0]).find('.ans').length > 0));
 
   var lsUse = ((qu[0].getAttribute('class') != 'ht') && ($(qu[0]).find('.ans').length > 0));
Line 355: Line 454:
 
   var parlst = $('.params').text().split(';');
 
   var parlst = $('.params').text().split(';');
 
   var params = {};
 
   var params = {};
   for(var i=0;i<parlst.length;i++){
+
   for (var i = 0; i < parlst.length; i++) {
 
     var pair = parlst[i].split(':');
 
     var pair = parlst[i].split(':');
     params[pair[0]]=pair[1];
+
     params[pair[0]] = pair[1];
 
   }
 
   }
 
   qu.find('.res').addClass('waiting');
 
   qu.find('.res').addClass('waiting');
   $.ajax({url:'/sqlgo.pl',cache:false,'type':'post',dataType:'json',
+
   $.ajax({
          data:{sql:sql.replace(/\xA0/g,' '), //Mediawiki inserts &nbsp; before a %. We need to change it back to a space.CM 13/6/12
+
    url: '/sqlgo.pl',
                format:'json',
+
    cache: false,
                question:$('.id',qu).text(),
+
    'type': 'post',
                wgUserName:wgUserName,
+
    dataType: 'json',
                cookie:$.cookie('oliver'),
+
    data: {
                page:wgPageName,
+
      sql: sql.replace(/\xA0/g, ' '), //Mediawiki inserts &nbsp; before a %. We need to change it back to a space.CM 13/6/12
                server:$('#engine').val(),
+
      format: 'json',
                setup:$('.setup',qu).text().replace(/\xA0/g,' '),
+
      question: $('.id', qu).text(),
                tidy:$('.tidy',qu).text().replace(/\xA0/g,' '),
+
      wgUserName: wgUserName,
                answer:$('.ans',qu).text().replace(/\xA0/g,' '),
+
      cookie: $.cookie('oliver'),
                schema:params['schema']
+
      page: wgPageName,
              },
+
      server: $('#engine').val(),
          success:function(d){
+
      setup: $('.setup', qu).text().replace(/\xA0/g, ' '),
            var res = qu.find('.res');
+
      tidy: $('.tidy', qu).text().replace(/\xA0/g, ' '),
            res.empty().removeClass('waiting')
+
      answer: $('.ans', qu).text().replace(/\xA0/g, ' '),
            if (d.error){
+
      schema: params['schema']
              res.append($('<h1/>',{text:'SQLZoo System Error:'}))
+
    },
              res.append($('<div/>',{text:d.error}))
+
    success: function (d) {
              return;
+
      var res = qu.find('.res');
            }
+
      res.empty().removeClass('waiting')
      var headerPresent = false;
+
      if (d.error) {
            for (var i = 0; i < d.sql.length; i++)
+
        res.append($('<h1/>', {
            {
+
          text: 'SQLZoo System Error:'
    if (!d || !d.sql || !d.sql[i]){
+
        }))
      res.append($('<h1/>',{text:'SQLZoo System Error:'}))
+
        res.append($('<div/>', {
      res.append($('<div/>',{text:"Problem with d or d.sql or d.sql[0]"}))
+
          text: d.error
      return;
+
        }))
    }
+
        return;
      if (d.sql[i].error){
+
      }
      res.append($('<h1/>',{text:'Error:'}))
+
      var headerPresent = false;
      res.append($('<div/>',{text:d.sql[i].error}))
+
      for (var i = 0; i < d.sql.length; i++) {
      return;
+
        if (!d || !d.sql || !d.sql[i]) {
    }
+
          res.append($('<h1/>', {
    var legend = "Result:";
+
            text: 'SQLZoo System Error:'
    if (d.score && d.answer && d.answer.length==1 && d.answer[0].fields){
+
          }))
      if (d.score == 100)
+
          res.append($('<div/>', {
        legend = showCorrect(qu);
+
            text: "Problem with d or d.sql or d.sql[0]"
      else if (d.answer[0].fields.length>d.sql[0].fields.length)
+
          }))
      legend = 'Too few columns';
+
          return;
      else if (d.answer[0].fields.length<d.sql[0].fields.length)
+
        }
      legend = 'Too many columns';
+
        if (d.sql[i].error) {
      else if (d.answer[0].rows.length>d.sql[0].rows.length)
+
          res.append($('<h1/>', {
      legend = 'Too few rows';
+
            text: 'Error:'
      else if (d.answer[0].rows.length<d.sql[0].rows.length)
+
          }))
      legend = 'Too many rows';
+
          res.append($('<div/>', {
    }
+
            text: d.sql[i].error
    if (!headerPresent)
+
          }))
    {
+
          return;
    res.append($('<h1/>',{text:legend}));
+
        }
    headerPresent = true;
+
        var legend = "Result:";
    }
+
        if (d.score && d.answer && d.answer.length == 1 && d.answer[0].fields) {
    var t = mkTable(d.sql[i]);
+
          if (d.score == 100)
      t.addClass('sqlmine')
+
            legend = showCorrect(qu);
      .appendTo(res);
+
          else if (d.answer[0].fields.length > d.sql[0].fields.length)
    if (d.answer && d.answer.length>0 && d.score<100){
+
            legend = 'Too few columns';
      res.append($('<div/>',{text:'Show correct result','class':'showtxt'})
+
          else if (d.answer[0].fields.length < d.sql[0].fields.length)
      .click(function(){
+
            legend = 'Too many columns';
        $(this).next().show('slow');
+
          else if (d.answer[0].rows.length > d.sql[0].rows.length)
      })
+
            legend = 'Too few rows';
      );
+
          else if (d.answer[0].rows.length < d.sql[0].rows.length)
      var a = mkTable(d.answer[0]);
+
            legend = 'Too many rows';
      a.addClass('sqlans');
+
        }
      a.appendTo(res);
+
        if (!headerPresent) {
    }
+
          res.append($('<h1/>', {
    }//End of success of goBaby
+
            text: legend
          },
+
          }));
          error:function(jqXHR,textStatus,errorThrown){
+
          headerPresent = true;
            qu.find('.res').empty().removeClass('waiting')
+
        }
              .append($('<h1/>',{'class':'syserr',text:'SQLZOO system error:'}))
+
        var t = mkTable(d.sql[i]);
              .append($('<div/>',{text:textStatus}))
+
        t.addClass('sqlmine')
              .append($('<div/>',{text:errorThrown}))
+
          .appendTo(res);
              .append($('<div/>').html(jqXHR.responseText))
+
        if (d.answer && d.answer.length > 0 && d.score < 100) {
          }
+
          res.append($('<div/>', {
        });
+
              text: 'Show correct result',
 +
              'class': 'showtxt'
 +
            })
 +
            .click(function () {
 +
              $(this).next().show('slow');
 +
            })
 +
          );
 +
          var a = mkTable(d.answer[0]);
 +
          a.addClass('sqlans');
 +
          a.appendTo(res);
 +
        }
 +
      } //End of success of goBaby
 +
    },
 +
    error: function (jqXHR, textStatus, errorThrown) {
 +
      qu.find('.res').empty().removeClass('waiting')
 +
        .append($('<h1/>', {
 +
          'class': 'syserr',
 +
          text: 'SQLZOO system error:'
 +
        }))
 +
        .append($('<div/>', {
 +
          text: textStatus
 +
        }))
 +
        .append($('<div/>', {
 +
          text: errorThrown
 +
        }))
 +
        .append($('<div/>').html(jqXHR.responseText))
 +
    }
 +
  });
 
   return false;
 
   return false;
}//GoBaby
+
} //GoBaby
function showCorrect(qu){
+
function showCorrect(qu) {
 
   var legend = 'Correct answer';
 
   var legend = 'Correct answer';
   var def = $('.def',qu);
+
   var def = $('.def', qu);
   if ($(".qcorrect", qu).length == 0){
+
   if ($(".qcorrect", qu).length == 0) {
     var qcorr = $('<div/>', {'class':'qcorrect', 'title':'You have answered this question correctly.'});
+
     var qcorr = $('<div/>', {
 +
      'class': 'qcorrect',
 +
      'title': 'You have answered this question correctly.'
 +
    });
 
     def.before(qcorr);
 
     def.before(qcorr);
 
   }
 
   }
Line 447: Line 576:
 
}
 
}
  
function maxlen(l){
+
function maxlen(l) {
 
   var r = 0;
 
   var r = 0;
   for(var i=0;i<l.length;i++)
+
   for (var i = 0; i < l.length; i++)
     r = Math.max(r,l[i].length);
+
     r = Math.max(r, l[i].length);
 
   return r;
 
   return r;
 
}
 
}
function truncate(s){
+
 
   if (s.length<15) return s;
+
function truncate(s) {
   return s.substring(0,13)+"..";
+
   if (s.length < 15) return s;
 +
   return s.substring(0, 13) + "..";
 
}
 
}
function mkTable(a){
+
 
 +
function mkTable(a) {
 
   var t = $('<table/>');
 
   var t = $('<table/>');
 
   t.append($('<tr/>'));
 
   t.append($('<tr/>'));
 
   var isnum = [];
 
   var isnum = [];
 
   if (!a.fields || !a.rows) return t;
 
   if (!a.fields || !a.rows) return t;
   for(var i=0;i<a.fields.length;i++){
+
   for (var i = 0; i < a.fields.length; i++) {
     $('tr',t).append($('<th/>',{text:truncate(a.fields[i])}));
+
     $('tr', t).append($('<th/>', {
 +
      text: truncate(a.fields[i])
 +
    }));
 
     var allNum = 1;
 
     var allNum = 1;
     for(var j=0;j<a.rows.length;j++){
+
     for (var j = 0; j < a.rows.length; j++) {
 
       if (a.rows[j] && a.rows[j][i] && (typeof a.rows[j][i] == "string") && !a.rows[j][i].match(/^[0-9.]*$/))
 
       if (a.rows[j] && a.rows[j][i] && (typeof a.rows[j][i] == "string") && !a.rows[j][i].match(/^[0-9.]*$/))
 
         allNum = 0;
 
         allNum = 0;
Line 471: Line 604:
 
     isnum.push(allNum);
 
     isnum.push(allNum);
 
   }
 
   }
   for(var j=0;j<a.rows.length;j++){
+
   for (var j = 0; j < a.rows.length; j++) {
 
     var tr = $('<tr/>').appendTo(t);
 
     var tr = $('<tr/>').appendTo(t);
     for(var k=0;k<a.rows[j].length;k++){
+
     for (var k = 0; k < a.rows[j].length; k++) {
       var td = $('<td/>',{text:a.rows[j][k]});
+
       var td = $('<td/>', {
 +
        text: a.rows[j][k]
 +
      });
 
       if (isnum[k]) td.addClass('r');
 
       if (isnum[k]) td.addClass('r');
 
       td.appendTo(tr);
 
       td.appendTo(tr);
Line 487: Line 622:
  
 
// this script helps to manage browser inconsistency across different os
 
// this script helps to manage browser inconsistency across different os
function css_browser_selector(u){var ua=u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1},g='gecko',w='webkit',s='safari',o='opera',m='mobile',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3.6')?g+' ff3 ff3_6':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('blackberry')?m+' blackberry':is('android')?m+' android':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?m+' j2me':is('iphone')?m+' iphone':is('ipod')?m+' ipod':is('ipad')?m+' ipad':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win'+(is('windows nt 6.0')?' vista':''):is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);
+
function css_browser_selector(u) {
 
+
  var ua = u.toLowerCase(),
 +
    is = function (t) {
 +
      return ua.indexOf(t) > -1
 +
    }, g = 'gecko',
 +
    w = 'webkit',
 +
    s = 'safari',
 +
    o = 'opera',
 +
    m = 'mobile',
 +
    h = document.documentElement,
 +
    b = [(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? g + ' ff2' : is('firefox/3.5') ? g + ' ff3 ff3_5' : is('firefox/3.6') ? g + ' ff3 ff3_6' : is('firefox/3') ? g + ' ff3' : is('gecko/') ? g : is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 : (/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) : is('konqueror') ? 'konqueror' : is('blackberry') ? m + ' blackberry' : is('android') ? m + ' android' : is('chrome') ? w + ' chrome' : is('iron') ? w + ' iron' : is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') : is('mozilla/') ? g : '', is('j2me') ? m + ' j2me' : is('iphone') ? m + ' iphone' : is('ipod') ? m + ' ipod' : is('ipad') ? m + ' ipad' : is('mac') ? 'mac' : is('darwin') ? 'mac' : is('webtv') ? 'webtv' : is('win') ? 'win' + (is('windows nt 6.0') ? ' vista' : '') : is('freebsd') ? 'freebsd' : (is('x11') || is('linux')) ? 'linux' : '', 'js'];
 +
  c = b.join(' ');
 +
  h.className += ' ' + c;
 +
  return c;
 +
};
 +
css_browser_selector(navigator.userAgent);
  
 +
// display site description
 
// display site logo
 
// display site logo
$(function(){
+
$(function () {
   $('<a/>',{href:'http://sqlzoo.net/w/index.php',id:'mp-logo',title:'Zoo You!'})
+
   $('<a/>', {
     .append($('<img/>',{id:'logoImg', src:'/design/sql_zoo_logo05.png',alt:'SQLzoo logo'}))
+
    href: 'http://sqlzoo.net/w/index.php',
 +
    id: 'mp-logo',
 +
    title: 'Zoo You!'
 +
  })
 +
     .append($('<img/>', {
 +
      id: 'logoImg',
 +
      src: '/design/sql_zoo_logo05.png',
 +
      alt: 'SQLzoo logo'
 +
    }))
 
     .appendTo($('#mw-head-base'))
 
     .appendTo($('#mw-head-base'))
});
+
   $("#mp-logo").append(" <h2 id='logo-desc'>Interactive <span>SQL <span>Tutorial</span></span></h2>");
+
  // assemble and display main nav menu
// display site description
+
  //Original dropdown menu starts from here or backup common.js_29.7.13.js
$(document).ready(function(){
+
  var ml1 = [
   $(function(){
+
    ['1 SELECT basics', 'SELECT_basics', 'Some simple queries to get you started'],
    $("#mp-logo").append(" <h2 id='logo-desc'>Interactive <span>SQL <span>Tutorial</span></span></h2>");
+
    ['2 SELECT from WORLD', 'SELECT_from_WORLD_Tutorial', 'Finding facts about countries'],
 +
    ['3 SELECT from Nobel', 'SELECT_from_Nobel_Tutorial', 'More practice with SELECT statements'],
 +
    ['4 SELECT within SELECT', 'SELECT_within_SELECT_Tutorial', 'Using the results of one query inside another'],
 +
    ['5 SUM and COUNT', 'SUM_and_COUNT', 'Apply aggregate functions'],
 +
    ['6 JOIN', 'The_JOIN_operation', 'Gathering data from more than one table'],
 +
    ['7 More JOIN', 'More_JOIN_operations', 'Getting data from the movie database'],
 +
    ['8 Using NULL', 'Using_Null', 'Dealing with missing data'],
 +
    ['9 Self JOIN', 'Self_join', 'Dealing with missing data'],
 +
    ['10 SQL Quizzes', 'Tutorial_Quizzes', 'Test your knowledge with multiple choice quizzes']
 +
  ];
 +
  var mm1 = $('<ul/>', {
 +
    id: 'mm1',
 +
    'class': 'dropdown mm_sub'
 +
  });
 +
  //Adding progress bar to the menu
 +
  for (var i = 0; i < ml1.length; i++) {
 +
    var maxWidth = 50; // adjust the value so that it fits menu well
 +
    var NoQ = localStorage.getItem(ml1[i][1] + '_numberOfQuestions');
 +
    if (!NoQ) NoQ = 1;
 +
    var NoC = localStorage.getItem(ml1[i][1] + '_numberOfCorrect');
 +
    if (!NoC) NoC = 0;
 +
    var pbWidth = parseFloat(maxWidth) * NoC / NoQ;
 +
    var mprogbar = $('<div/>', {
 +
      'class': 'progressbarbg1'
 +
    }).append($('<div/>', {
 +
      'class': 'progressbar1',
 +
      'id': ml1[i][1],
 +
      css: {
 +
        'width': pbWidth
 +
      }
 +
    }));
 +
    mm1.append($('<li/>').append($('<a/>', {
 +
      href: '/wiki/' + ml1[i][1],
 +
      text: ml1[i][0]
 +
    })).append(ml1[i][2]).append(mprogbar));
 +
  }
 +
  var mm2 = $('<ul/>', {
 +
    id: 'mm2',
 +
    'class': 'dropdown mm_sub'
 
   });
 
   });
});
+
  mm2.append('<li><a href="/wiki/AdventureWorks">1 AdventureWorks</a> Flogging sports gear. Assessment for CO22008 2007/8</li>');
 +
  mm2.append('<li><a href="/wiki/Neeps">2 Neeps</a> A timetable database</li>');
 +
  mm2.append('<li><a href="/wiki/Musicians">3 Musicians</a> Concerts and compositions</li>');
 +
  mm2.append('<li><a href="/wiki/Southwind">4 Southwind</a> Buying and selling</li>');
 +
  mm2.append('<li><a href="/wiki/Dressmaker">5 Dressmaker</a> Constructing clothing</li>');
 +
  mm2.append('<li><a href="/wiki/Congestion Charging">6 Congestion Charging</a> Monitoring traffic (old questions)</li>');
  
// display language selector
+
  var mm3 = $('<ul/>', {
$(function(){
+
    id: 'mm3',
    $('<div/>',{id:'language'}).appendTo($('#mw-head-base'))
+
    'class': 'dropdown mm_sub'
+
  });
    var lang = $('<ul/>',{id:'lang','class':'side_nav_sub'});
+
  mm3.append('<li><a href="/wiki/SELECT_Reference">SELECT</a>How to read the data from a database.</li>');
        lang.append('<li><a id="en" href="/wiki/Main_Page"></li>');
+
  mm3.append('<li><a href="/wiki/CREATE_and_DROP_Reference">CREATE and DROP</a>How to create tables, indexes, views and other things. How to get rid of them.</li>');
        lang.append('<li><a id="de" href="/wiki/Main_Page/de"></a></li>');
+
  mm3.append('<li><a href="/wiki/INSERT_and_DELETE_Reference">INSERT and DELETE</a>How to put records into a table, change them and how to take them out again.</li>');
        lang.append('<li><a id="fr" href="/wiki/Main_Page/fr"></a></li>');
+
  mm3.append('<li><a href="/wiki/DATE_and_TIME_Reference">DATE and TIME</a>How to work with dates; adding, subtracting and formatting.</li>');
+
  mm3.append('<li><a href="/wiki/Functions_Reference">Functions</a>How to use string functions, logical functions and mathematical functions.</li>');
    $('#language').append(lang);
+
  mm3.append('<li><a href="/wiki/Users_Reference">Users</a>How to create users, GRANT and DENY access, get at other peoples tables. How to find processes and kill them.</li>');
 
+
  mm3.append('<li><a href="/wiki/Meta_Data_Reference">Meta Data</a>How to find out what tables and columns exist. How to count and limit the rows return.</li>');
    $('<img/>',{src:'/design/en2.png',alt:'SQL zoo in English'})
+
  mm3.append('<li><a href="/wiki/Hacks_Reference">SQL Hacks</a>Useful SQL hacks .</li>');
      .appendTo($('#en'));
 
    $('<img/>',{src:'/design/de2.png',alt:'SQL zoo in German'})
 
      .appendTo($('#de'));
 
    $('<img/>',{src:'/design/fr2.png',alt:'SQL zoo in French'})
 
      .appendTo($('#fr'));
 
});
 
  
 +
  var mm = $('<ul/>', {
 +
    id: 'main_menu'
 +
  }).appendTo('#mw-head-base');
 +
  mm.append('<li id="mm1"><a href="/" class="navlink">Tutorials</a></li>');
 +
  mm.append('<li id="mm2"><a href="/" class="navlink">Assessments</a></li>');
 +
  mm.append('<li id="mm3"><a href="/" class="navlink">Reference</a></li>');
  
 +
  $('#mm1').append(mm1);
 +
  $('#mm2').append(mm2);
 +
  $('#mm3').append(mm3);
  
 +
  $('#main_menu').wrap('<div id="navigation_horiz" />');
 +
  $('#navigation_horiz').naviDropDown({
 +
    dropDownWidth: '35em'
 +
  });
  
 +
  // stick on top elements that need to be visible
 +
  $("#main_menu").addClass("stickableMenu");
 +
  $("#p-Reference").addClass("stickableRef");
 +
  $(".ref_section").addClass("stickableDbRef");
 +
});
  
 +
$(document).scroll(function () {
 +
  var useFixedMenu = $(document).scrollTop() > 175;
 +
  $('.stickableMenu').toggleClass('fixedMenu', useFixedMenu);
  
// assemble and display main nav menu
+
  //   var useFixedRef = $(document).scrollTop() > 275;
 +
  //    $('.stickableRef').toggleClass('fixedRef', useFixedRef);
  
$(function(){
+
   $('.stickableDbRef').toggleClass('fixedDbRef', $(document).scrollTop() > 275);
 
//Original dropdown menu starts from here or backup common.js_29.7.13.js
 
var ml1 =
 
[['1 SELECT basics',  'SELECT_basics','Some simple queries to get you started']
 
,['2 SELECT from WORLD','SELECT_from_WORLD_Tutorial','Finding facts about countries']
 
,['3 SELECT from Nobel','SELECT_from_Nobel_Tutorial','More practice with SELECT statements']
 
,['4 SELECT within SELECT','SELECT_within_SELECT_Tutorial','Using the results of one query inside another']
 
,['5 SUM and COUNT','SUM_and_COUNT','Apply aggregate functions']
 
,['6 JOIN','The_JOIN_operation','Gathering data from more than one table']
 
,['7 More JOIN','More_JOIN_operations','Getting data from the movie database']
 
,['8 Using NULL','Using_Null','Dealing with missing data']
 
,['9 Self JOIN','Self_join','Dealing with missing data']
 
,['10 SQL Quizzes','Tutorial_Quizzes','Test your knowledge with multiple choice quizzes']
 
];
 
var mm1 = $('<ul/>',{id:'mm1','class':'dropdown mm_sub'});
 
//Adding progress bar to the menu
 
for(var i=0;i<ml1.length;i++){
 
  var maxWidth = 50; // adjust the value so that it fits menu well
 
  var NoQ = localStorage.getItem(ml1[i][1] + '_numberOfQuestions');
 
  if (!NoQ) NoQ = 1;
 
  var NoC = localStorage.getItem(ml1[i][1] + '_numberOfCorrect');
 
  if (!NoC) NoC = 0;    
 
  var pbWidth = parseFloat(maxWidth) * NoC / NoQ;
 
  var mprogbar = $('<div/>',{'class':'progressbarbg1'}).append($('<div/>',{'class':'progressbar1', 'id':ml1[i][1], css:{'width':pbWidth}}));
 
  mm1.append($('<li/>').append($('<a/>',{href:'/wiki/'+ml1[i][1],text:ml1[i][0]})).append(ml1[i][2]).append(mprogbar));
 
}
 
var mm2 = $('<ul/>',{id:'mm2','class':'dropdown mm_sub'});
 
mm2.append('<li><a href="/wiki/AdventureWorks">1 AdventureWorks</a> Flogging sports gear. Assessment for CO22008 2007/8</li>');
 
mm2.append('<li><a href="/wiki/Neeps">2 Neeps</a> A timetable database</li>');
 
mm2.append('<li><a href="/wiki/Musicians">3 Musicians</a> Concerts and compositions</li>');
 
mm2.append('<li><a href="/wiki/Southwind">4 Southwind</a> Buying and selling</li>');
 
mm2.append('<li><a href="/wiki/Dressmaker">5 Dressmaker</a> Constructing clothing</li>');
 
mm2.append('<li><a href="/wiki/Congestion Charging">6 Congestion Charging</a> Monitoring traffic (old questions)</li>');
 
 
var mm3 = $('<ul/>',{id:'mm3','class':'dropdown mm_sub'});
 
mm3.append('<li><a href="/wiki/SELECT_Reference">SELECT</a>How to read the data from a database.</li>');
 
mm3.append('<li><a href="/wiki/CREATE_and_DROP_Reference">CREATE and DROP</a>How to create tables, indexes, views and other things. How to get rid of them.</li>');
 
mm3.append('<li><a href="/wiki/INSERT_and_DELETE_Reference">INSERT and DELETE</a>How to put records into a table, change them and how to take them out again.</li>');
 
mm3.append('<li><a href="/wiki/DATE_and_TIME_Reference">DATE and TIME</a>How to work with dates; adding, subtracting and formatting.</li>');
 
mm3.append('<li><a href="/wiki/Functions_Reference">Functions</a>How to use string functions, logical functions and mathematical functions.</li>');
 
mm3.append('<li><a href="/wiki/Users_Reference">Users</a>How to create users, GRANT and DENY access, get at other peoples tables. How to find processes and kill them.</li>');
 
mm3.append('<li><a href="/wiki/Meta_Data_Reference">Meta Data</a>How to find out what tables and columns exist. How to count and limit the rows return.</li>');
 
mm3.append('<li><a href="/wiki/Hacks_Reference">SQL Hacks</a>Useful SQL hacks .</li>');
 
 
var mm = $('<ul/>',{id:'main_menu'}).appendTo('#mw-head-base');
 
mm.append('<li id="mm1"><a href="/" class="navlink">Tutorials</a></li>');
 
mm.append('<li id="mm2"><a href="/" class="navlink">Assessments</a></li>');
 
mm.append('<li id="mm3"><a href="/" class="navlink">Reference</a></li>');
 
 
$('#mm1').append(mm1);
 
$('#mm2').append(mm2);
 
$('#mm3').append(mm3);
 
 
 
$('#main_menu').wrap('<div id="navigation_horiz" />');
 
$('#navigation_horiz').naviDropDown({
 
  dropDownWidth: '35em'
 
});
 
 
 
 
});
 
});
  
// stick on top elements that need to be visible
+
// swap classes on external links to change their side icons
$(function(){
+
$(function () {
    $("#main_menu").addClass("stickableMenu");
+
  $(".external").addClass("zoo_external");
    $("#p-Reference").addClass("stickableRef");
+
  $(".external").removeClass("external");
    $(".ref_section").addClass("stickableDbRef");
 
});
 
 
 
$(document).scroll(function() {
 
    var useFixedMenu = $(document).scrollTop() > 175;
 
    $('.stickableMenu').toggleClass('fixedMenu', useFixedMenu);
 
   
 
//    var useFixedRef = $(document).scrollTop() > 275;
 
//    $('.stickableRef').toggleClass('fixedRef', useFixedRef);
 
 
 
    $('.stickableDbRef').toggleClass('fixedDbRef', $(document).scrollTop() > 275);
 
 
});
 
});
  
// swap classes on external links to change their side icons
+
//Deal with variations in the "how to" scripts
 
$(function(){
 
$(function(){
$(".external").addClass("zoo_external");
+
  $('div.ht').each(function(){
$(".external").removeClass("external");
+
    var lnglst = $('.def',this);
});
+
    var varlst = [];
 +
    if (lnglst.length>1){
 +
      $('.def',this).each(function(){
 +
        var clist = $(this).attr('class').split(' ');
 +
        for(var i=0;i<clist.length;i++)
 +
          if (clist[i].length>2 && clist[i].substr(0,2)=='e-')
 +
            varlst.push({engine:clist[i].substr(2),val:$(this)})
 +
      });
 +
    }
 +
    if (varlst.length>0){
 +
      var msg = $('<div/>',{'class':'variations'});
 +
      msg.append($('<div/>',{text:'There are variations'}));
 +
      for(var i=0;i<varlst.length;i++){
 +
        $('<div/>',{'class':'a-'+varlst[i].engine})
 +
          .append($('<div/>',{text:varlst[i].engine}))
 +
          .append(varlst[i].val.clone().removeClass('def'))
 +
          .appendTo(msg);
 +
      }
 +
    }
 +
    $(this).append(msg);
 +
  })
 +
})
  
/* === Designer js ends here === */
+
$(function () {
 +
  // Insert tables into Quiz distractors
 +
  var qq = $('.question');
 +
  for (var i = 0; i < qq.length; i++) {
 +
    var q = $(qq[i]);
 +
    var distractors = "ABCDE";
 +
    for (var j = 0; j < distractors.length; j++) {
 +
      var tans = $('table caption:contains("Table-' + distractors[j] + '")', q).parents('table').addClass('innerTable');
 +
      if (tans.length > 0) {
 +
        var ttd = $('table tr td:contains("Table-' + distractors[j] + '")', q).addClass('innerTable');
 +
        if (ttd.length > 0) {
 +
          ttd.empty();
 +
          ttd.append(tans);
 +
        }
 +
      }
 +
    }
 +
  }
 +
  $('input.check').each(function (i, e) {
 +
    $(this).attr('id', 'quiz_d_' + i);
 +
  });
 +
  $('tr.proposal').each(function (i, e) {
 +
    var tds = $('td', $(this));
 +
    var html1 = $(tds[1]).html();
 +
    $(tds[1]).html($('<label/>', {
 +
      html: html1,
 +
      'for': $('input', $(this)).attr('id')
 +
    }));
 +
  })
  
 +
  // Find labels which contains "query-" to add class for css
 +
  $("label:contains('Query-')").addClass('labelAns'); //contains Query-
 +
  $(".quizQuestions table.object tr.proposal label").not($('.quizQuestions table.object tr.proposal label div.mw-geshi').parent()).not($('.quizQuestions table.object tr.proposal label table.innerTable').parent()).addClass('labelAns');
  
// Insert tables into Quiz distractors
+
  // Find radioButtons with title="Right" to highlight the Right results in Quizzes
var qq = $('.question');
+
  $("input:radio[title=Right]").each(function () {
for (var i = 0; i < qq.length; i++)
+
    $(this).parents(':eq(1)').children().addClass("right");
{
+
  });
var q = $(qq[i]);
 
var distractors = "ABCDE";
 
for (var j=0;j<distractors.length;j++){
 
var tans = $('table caption:contains("Table-'+distractors[j]+'")', q).parents('table').addClass('innerTable');
 
if (tans.length>0)
 
{
 
var ttd = $('table tr td:contains("Table-'+distractors[j]+'")', q).addClass('innerTable');
 
if (ttd.length>0){
 
  ttd.empty();
 
  ttd.append(tans);
 
}
 
}
 
}
 
}
 
  
$(function(){
+
  // Find radioButtons with title="Wrong" to highlight the Right results in Quizzes
   $('input.check').each(function(i,e){
+
   $("input:radio[title=Wrong][checked=checked]").each(function () {
     $(this).attr('id','quiz_d_'+i);
+
     $(this).parents(':eq(1)').children().addClass("wrong");
 
   });
 
   });
   $('tr.proposal').each(function(i,e){
+
 
     var tds = $('td',$(this));
+
   $("input:radio[title=Wrong]").not(':checked').each(function () {
    var html1= $(tds[1]).html();
+
     $(this).parents(':eq(1)').children().addClass("right");
    $(tds[1]).html($('<label/>',{html:html1,'for':$('input',$(this)).attr('id') }));
 
 
   })
 
   })
 
// Find labels which contains "query-" to add class for css
 
$("label:contains('Query-')").addClass('labelAns'); //contains Query-
 
$(".quizQuestions table.object tr.proposal label").not($('.quizQuestions table.object tr.proposal label div.mw-geshi').parent()).not($('.quizQuestions table.object tr.proposal label table.innerTable').parent()).addClass('labelAns');
 
 
// Find radioButtons with title="Right" to highlight the Right results in Quizzes
 
$("input:radio[title=Right]").each(function(){
 
$(this).parents(':eq(1)').children().addClass("right");
 
});
 
 
// Find radioButtons with title="Wrong" to highlight the Right results in Quizzes
 
$("input:radio[title=Wrong][checked=checked]").each(function(){
 
$(this).parents(':eq(1)').children().addClass("wrong");
 
});
 
 
$("input:radio[title=Wrong]").not(':checked').each(function(){
 
$(this).parents(':eq(1)').children().addClass("right");
 
 
})
 
 
 
 
 
 
})
 
})
  
$(document).ready($(function(){
+
$(function () {
// Toggle Class when the answer is selected - Istvan
+
  // Toggle Class when the answer is selected - Istvan
$('.quizQuestions table.object tr.proposal').click(function(){
+
  $('.quizQuestions table.object tr.proposal').click(function () {
var rbtnId = $(this).find('label').attr('for');
+
    var rbtnId = $(this).find('label').attr('for');
if($("#"+rbtnId).attr("checked")=="checked") {  
+
    if ($("#" + rbtnId).attr("checked") == "checked") {
$(this).children().addClass('picked');
+
      $(this).children().addClass('picked');
 
       //Store data in QUIZLOG table
 
       //Store data in QUIZLOG table
 
       var cookie = wgUserName;
 
       var cookie = wgUserName;
 
       var question = $(this).parents('.question').children('.header').text().split('.'); //question[0]
 
       var question = $(this).parents('.question').children('.header').text().split('.'); //question[0]
question = question[0].replace(/[^a-z0-9,]/gi, '');
+
      question = question[0].replace(/[^a-z0-9,]/gi, '');
question = wgPageName+"#"+question+".";
+
      question = wgPageName + "#" + question + ".";
       var txt = $(this).children('.sign.picked').children().val().split(""); //p0-A; p1-B; p2-C; p3-D; p4-E;
+
       var txt = $(this).children('.sign.picked').children().val().split(""); //p0-A; p1-B; p2-C; p3-D; p4-E;
 
       var results = ["A", "B", "C", "D", "E"];
 
       var results = ["A", "B", "C", "D", "E"];
 
       txt = results[txt[1]];
 
       txt = results[txt[1]];
 
       var score = null;
 
       var score = null;
$.getJSON('/userData.php',{action:'recordChoice',wikipage:wgPageName,cookie:wgUserName,question:question,txt:txt,score:score,user:wgUserName},function(e){
+
      $.getJSON('/userData.php', {
})
+
        action: 'recordChoice',
}
+
        wikipage: wgPageName,
$(".check").not(':checked').parent().parent().children().removeClass("picked");
+
        cookie: wgUserName,
});
+
        question: question,
+
        txt: txt,
var quiz = window.location.href.split("#");
+
        score: score,
+
        user: wgUserName
var indx = $.inArray("quiz0", quiz);
+
      }, function (e) {})
if(indx>-1){
+
    }
//Selecting input checked and answered right  
+
    $(".check").not(':checked').parent().parent().children().removeClass("picked");
wikipage = wgPageName;
+
  });
cookie = wgUserName;
+
 
//whn = now();
+
  var quiz = window.location.href.split("#");
var results = ["A", "B", "C", "D", "E"];
+
 
score = "100";
+
  var indx = $.inArray("quiz0", quiz);
user = wgUserName;
+
  if (indx > -1) {
var questionArr=[];
+
    //Selecting input checked and answered right  
var txtArr = [];
+
    wikipage = wgPageName;
+
    cookie = wgUserName;
$('.quizQuestions table.object tr.proposal').children('.sign.right').children('input[type=radio]:checked').each(function(){
+
    //whn = now();
+
    var results = ["A", "B", "C", "D", "E"];
question = $(this).attr('name').split(""); //question[1] this is the question number on the wikipage
+
    score = "100";
question = parseInt(question[1])+1;
+
    user = wgUserName;
question = wgPageName+"#"+question+".";
+
    var questionArr = [];
txt = $(this).val().split("");//This is the answer
+
    var txtArr = [];
txt = results[txt[1]];
+
 
+
    $('.quizQuestions table.object tr.proposal').children('.sign.right').children('input[type=radio]:checked').each(function () {
txtArr.push(txt);
+
 
questionArr.push(question);
+
      question = $(this).attr('name').split(""); //question[1] this is the question number on the wikipage
+
      question = parseInt(question[1]) + 1;
});
+
      question = wgPageName + "#" + question + ".";
var txtStr = JSON.stringify(txtArr);
+
      txt = $(this).val().split(""); //This is the answer
var questStr = JSON.stringify(questionArr);
+
      txt = results[txt[1]];
txtStr = txtStr.replace(/[^a-z0-9,_#.]/gi, '');
+
 
questStr = questStr.replace(/[^a-z0-9,_#.]/gi, '');
+
      txtArr.push(txt);
$.getJSON('/userData.php',{action:'updateAnswers',wikipage:wgPageName,cookie:wgUserName,question:questStr,txt:txtStr,score:score,user:wgUserName},function(e){
+
      questionArr.push(question);
        console.log("cool");
+
 
})
+
    });
console.log("end");
+
    var txtStr = JSON.stringify(txtArr);
}
+
    var questStr = JSON.stringify(questionArr);
}))
+
    txtStr = txtStr.replace(/[^a-z0-9,_#.]/gi, '');
 +
    questStr = questStr.replace(/[^a-z0-9,_#.]/gi, '');
 +
    $.getJSON('/userData.php', {
 +
      action: 'updateAnswers',
 +
      wikipage: wgPageName,
 +
      cookie: wgUserName,
 +
      question: questStr,
 +
      txt: txtStr,
 +
      score: score,
 +
      user: wgUserName
 +
    }, function (e) {
 +
      console.log("cool");
 +
    })
 +
    console.log("end");
 +
  }
 +
})
  
 
//Connor 23/7/12 creates the labels for the multiple choice questions allowing them to be highlighted.
 
//Connor 23/7/12 creates the labels for the multiple choice questions allowing them to be highlighted.
 
  
 
//Analytics code
 
//Analytics code
  var _gaq = _gaq || [];
+
var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-33860668-1']);
+
_gaq.push(['_setAccount', 'UA-33860668-1']);
  _gaq.push(['_trackPageview']);
+
_gaq.push(['_trackPageview']);
 
 
  (function() {
 
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
 
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 
  })();
 
  
 +
(function () {
 +
  var ga = document.createElement('script');
 +
  ga.type = 'text/javascript';
 +
  ga.async = true;
 +
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 +
  var s = document.getElementsByTagName('script')[0];
 +
  s.parentNode.insertBefore(ga, s);
 +
})();
  
//JSON
 
(function($){var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.toJSON=typeof JSON==='object'&&JSON.stringify?JSON.stringify:function(o){if(o===null){return'null';}
 
var type=typeof o;if(type==='undefined'){return undefined;}
 
if(type==='number'||type==='boolean'){return''+o;}
 
if(type==='string'){return $.quoteString(o);}
 
if(type==='object'){if(typeof o.toJSON==='function'){return $.toJSON(o.toJSON());}
 
if(o.constructor===Date){var month=o.getUTCMonth()+1,day=o.getUTCDate(),year=o.getUTCFullYear(),hours=o.getUTCHours(),minutes=o.getUTCMinutes(),seconds=o.getUTCSeconds(),milli=o.getUTCMilliseconds();if(month<10){month='0'+month;}
 
if(day<10){day='0'+day;}
 
if(hours<10){hours='0'+hours;}
 
if(minutes<10){minutes='0'+minutes;}
 
if(seconds<10){seconds='0'+seconds;}
 
if(milli<100){milli='0'+milli;}
 
if(milli<10){milli='0'+milli;}
 
return'"'+year+'-'+month+'-'+day+'T'+
 
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
 
if(o.constructor===Array){var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i])||'null');}
 
return'['+ret.join(',')+']';}
 
var name,val,pairs=[];for(var k in o){type=typeof k;if(type==='number'){name='"'+k+'"';}else if(type==='string'){name=$.quoteString(k);}else{continue;}
 
type=typeof o[k];if(type==='function'||type==='undefined'){continue;}
 
val=$.toJSON(o[k]);pairs.push(name+':'+val);}
 
return'{'+pairs.join(',')+'}';}};$.evalJSON=typeof JSON==='object'&&JSON.parse?JSON.parse:function(src){return eval('('+src+')');};$.secureEvalJSON=typeof JSON==='object'&&JSON.parse?JSON.parse:function(src){var filtered=src.replace(/\\["\\\/bfnrtu]/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered)){return eval('('+src+')');}else{throw new SyntaxError('Error parsing JSON, source is not valid.');}};$.quoteString=function(string){if(string.match(escapeable)){return'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
 
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
 
return'"'+string+'"';};})(jQuery);
 
  
/*
 
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 
*
 
* Uses the built in easing capabilities added In jQuery 1.1
 
* to offer multiple easing options
 
*
 
* TERMS OF USE - jQuery Easing
 
*
 
* Open source under the BSD License.
 
*
 
* Copyright © 2008 George McGinley Smith
 
* All rights reserved.
 
*
 
* Redistribution and use in source and binary forms, with or without modification,
 
* are permitted provided that the following conditions are met:
 
*
 
* Redistributions of source code must retain the above copyright notice, this list of
 
* conditions and the following disclaimer.
 
* Redistributions in binary form must reproduce the above copyright notice, this list
 
* of conditions and the following disclaimer in the documentation and/or other materials
 
* provided with the distribution.
 
*
 
* Neither the name of the author nor the names of contributors may be used to endorse
 
* or promote products derived from this software without specific prior written permission.
 
*
 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 
*  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 
*  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 
*  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 
* OF THE POSSIBILITY OF SUCH DAMAGE.
 
*
 
*/
 
  
 
// t: current time, b: begInnIng value, c: change In value, d: duration
 
// t: current time, b: begInnIng value, c: change In value, d: duration
 
jQuery.easing['jswing'] = jQuery.easing['swing'];
 
jQuery.easing['jswing'] = jQuery.easing['swing'];
  
jQuery.extend( jQuery.easing,
+
jQuery.extend(jQuery.easing, {
{
+
  def: 'easeOutQuad',
def: 'easeOutQuad',
+
  swing: function (x, t, b, c, d) {
swing: function (x, t, b, c, d) {
+
    //alert(jQuery.easing.default);
//alert(jQuery.easing.default);
+
    return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
+
  },
},
+
  easeInQuad: function (x, t, b, c, d) {
easeInQuad: function (x, t, b, c, d) {
+
    return c * (t /= d) * t + b;
return c*(t/=d)*t + b;
+
  },
},
+
  easeOutQuad: function (x, t, b, c, d) {
easeOutQuad: function (x, t, b, c, d) {
+
    return -c * (t /= d) * (t - 2) + b;
return -c *(t/=d)*(t-2) + b;
+
  },
},
+
  easeInOutQuad: function (x, t, b, c, d) {
easeInOutQuad: function (x, t, b, c, d) {
+
    if ((t /= d / 2) < 1) return c / 2 * t * t + b;
if ((t/=d/2) < 1) return c/2*t*t + b;
+
    return -c / 2 * ((--t) * (t - 2) - 1) + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
+
  },
},
+
  easeInCubic: function (x, t, b, c, d) {
easeInCubic: function (x, t, b, c, d) {
+
    return c * (t /= d) * t * t + b;
return c*(t/=d)*t*t + b;
+
  },
},
+
  easeOutCubic: function (x, t, b, c, d) {
easeOutCubic: function (x, t, b, c, d) {
+
    return c * ((t = t / d - 1) * t * t + 1) + b;
return c*((t=t/d-1)*t*t + 1) + b;
+
  },
},
+
  easeInOutCubic: function (x, t, b, c, d) {
easeInOutCubic: function (x, t, b, c, d) {
+
    if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
if ((t/=d/2) < 1) return c/2*t*t*t + b;
+
    return c / 2 * ((t -= 2) * t * t + 2) + b;
return c/2*((t-=2)*t*t + 2) + b;
+
  },
},
+
  easeInQuart: function (x, t, b, c, d) {
easeInQuart: function (x, t, b, c, d) {
+
    return c * (t /= d) * t * t * t + b;
return c*(t/=d)*t*t*t + b;
+
  },
},
+
  easeOutQuart: function (x, t, b, c, d) {
easeOutQuart: function (x, t, b, c, d) {
+
    return -c * ((t = t / d - 1) * t * t * t - 1) + b;
return -c * ((t=t/d-1)*t*t*t - 1) + b;
+
  },
},
+
  easeInOutQuart: function (x, t, b, c, d) {
easeInOutQuart: function (x, t, b, c, d) {
+
    if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
+
    return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
+
  },
},
+
  easeInQuint: function (x, t, b, c, d) {
easeInQuint: function (x, t, b, c, d) {
+
    return c * (t /= d) * t * t * t * t + b;
return c*(t/=d)*t*t*t*t + b;
+
  },
},
+
  easeOutQuint: function (x, t, b, c, d) {
easeOutQuint: function (x, t, b, c, d) {
+
    return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
return c*((t=t/d-1)*t*t*t*t + 1) + b;
+
  },
},
+
  easeInOutQuint: function (x, t, b, c, d) {
easeInOutQuint: function (x, t, b, c, d) {
+
    if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
+
    return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
+
  },
},
+
  easeInSine: function (x, t, b, c, d) {
easeInSine: function (x, t, b, c, d) {
+
    return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
+
  },
},
+
  easeOutSine: function (x, t, b, c, d) {
easeOutSine: function (x, t, b, c, d) {
+
    return c * Math.sin(t / d * (Math.PI / 2)) + b;
return c * Math.sin(t/d * (Math.PI/2)) + b;
+
  },
},
+
  easeInOutSine: function (x, t, b, c, d) {
easeInOutSine: function (x, t, b, c, d) {
+
    return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
+
  },
},
+
  easeInExpo: function (x, t, b, c, d) {
easeInExpo: function (x, t, b, c, d) {
+
    return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
+
  },
},
+
  easeOutExpo: function (x, t, b, c, d) {
easeOutExpo: function (x, t, b, c, d) {
+
    return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
+
  },
},
+
  easeInOutExpo: function (x, t, b, c, d) {
easeInOutExpo: function (x, t, b, c, d) {
+
    if (t == 0) return b;
if (t==0) return b;
+
    if (t == d) return b + c;
if (t==d) return b+c;
+
    if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
+
    return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
+
  },
},
+
  easeInCirc: function (x, t, b, c, d) {
easeInCirc: function (x, t, b, c, d) {
+
    return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
+
  },
},
+
  easeOutCirc: function (x, t, b, c, d) {
easeOutCirc: function (x, t, b, c, d) {
+
    return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
+
  },
},
+
  easeInOutCirc: function (x, t, b, c, d) {
easeInOutCirc: function (x, t, b, c, d) {
+
    if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
+
    return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
+
  },
},
+
  easeInElastic: function (x, t, b, c, d) {
easeInElastic: function (x, t, b, c, d) {
+
    var s = 1.70158;
var s=1.70158;var p=0;var a=c;
+
    var p = 0;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
+
    var a = c;
if (a < Math.abs(c)) { a=c; var s=p/4; }
+
    if (t == 0) return b;
else var s = p/(2*Math.PI) * Math.asin (c/a);
+
    if ((t /= d) == 1) return b + c;
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
+
    if (!p) p = d * .3;
},
+
    if (a < Math.abs(c)) {
easeOutElastic: function (x, t, b, c, d) {
+
      a = c;
var s=1.70158;var p=0;var a=c;
+
      var s = p / 4;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
+
    } else var s = p / (2 * Math.PI) * Math.asin(c / a);
if (a < Math.abs(c)) { a=c; var s=p/4; }
+
    return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
else var s = p/(2*Math.PI) * Math.asin (c/a);
+
  },
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
+
  easeOutElastic: function (x, t, b, c, d) {
},
+
    var s = 1.70158;
easeInOutElastic: function (x, t, b, c, d) {
+
    var p = 0;
var s=1.70158;var p=0;var a=c;
+
    var a = c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
+
    if (t == 0) return b;
if (a < Math.abs(c)) { a=c; var s=p/4; }
+
    if ((t /= d) == 1) return b + c;
else var s = p/(2*Math.PI) * Math.asin (c/a);
+
    if (!p) p = d * .3;
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
+
    if (a < Math.abs(c)) {
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
+
      a = c;
},
+
      var s = p / 4;
easeInBack: function (x, t, b, c, d, s) {
+
    } else var s = p / (2 * Math.PI) * Math.asin(c / a);
if (s == undefined) s = 1.70158;
+
    return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
return c*(t/=d)*t*((s+1)*t - s) + b;
+
  },
},
+
  easeInOutElastic: function (x, t, b, c, d) {
easeOutBack: function (x, t, b, c, d, s) {
+
    var s = 1.70158;
if (s == undefined) s = 1.70158;
+
    var p = 0;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
+
    var a = c;
},
+
    if (t == 0) return b;
easeInOutBack: function (x, t, b, c, d, s) {
+
    if ((t /= d / 2) == 2) return b + c;
if (s == undefined) s = 1.70158;  
+
    if (!p) p = d * (.3 * 1.5);
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
+
    if (a < Math.abs(c)) {
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
+
      a = c;
},
+
      var s = p / 4;
easeInBounce: function (x, t, b, c, d) {
+
    } else var s = p / (2 * Math.PI) * Math.asin(c / a);
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
+
    if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
},
+
    return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
easeOutBounce: function (x, t, b, c, d) {
+
  },
if ((t/=d) < (1/2.75)) {
+
  easeInBack: function (x, t, b, c, d, s) {
return c*(7.5625*t*t) + b;
+
    if (s == undefined) s = 1.70158;
} else if (t < (2/2.75)) {
+
    return c * (t /= d) * t * ((s + 1) * t - s) + b;
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
+
  },
} else if (t < (2.5/2.75)) {
+
  easeOutBack: function (x, t, b, c, d, s) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
+
    if (s == undefined) s = 1.70158;
} else {
+
    return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
+
  },
}
+
  easeInOutBack: function (x, t, b, c, d, s) {
},
+
    if (s == undefined) s = 1.70158;
easeInOutBounce: function (x, t, b, c, d) {
+
    if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
+
    return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
+
  },
}
+
  easeInBounce: function (x, t, b, c, d) {
 +
    return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b;
 +
  },
 +
  easeOutBounce: function (x, t, b, c, d) {
 +
    if ((t /= d) < (1 / 2.75)) {
 +
      return c * (7.5625 * t * t) + b;
 +
    } else if (t < (2 / 2.75)) {
 +
      return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
 +
    } else if (t < (2.5 / 2.75)) {
 +
      return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
 +
    } else {
 +
      return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
 +
    }
 +
  },
 +
  easeInOutBounce: function (x, t, b, c, d) {
 +
    if (t < d / 2) return jQuery.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b;
 +
    return jQuery.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b;
 +
  }
 
});
 
});
  
/*
+
/**
*
+
  * hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
  * TERMS OF USE - EASING EQUATIONS
+
  * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*
 
* Open source under the BSD License.  
 
*
 
* Copyright © 2001 Robert Penner
 
* All rights reserved.
 
  *  
 
* Redistribution and use in source and binary forms, with or without modification,
 
* are permitted provided that the following conditions are met:
 
*
 
* Redistributions of source code must retain the above copyright notice, this list of
 
* conditions and the following disclaimer.
 
* Redistributions in binary form must reproduce the above copyright notice, this list
 
* of conditions and the following disclaimer in the documentation and/or other materials
 
* provided with the distribution.
 
*
 
* Neither the name of the author nor the names of contributors may be used to endorse
 
* or promote products derived from this software without specific prior written permission.
 
*
 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 
*  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 
*  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 
*  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 
* OF THE POSSIBILITY OF SUCH DAMAGE.  
 
 
  *
 
  *
 +
* @param  f  onMouseOver function || An object with configuration options
 +
* @param  g  onMouseOut function  || Nothing (use configuration options object)
 +
* @author    Brian Cherne <brian@cherne.net>
 
  */
 
  */
/**
+
(function ($) {
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
+
  $.fn.hoverIntent = function (f, g) {
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
+
    var cfg = {
*
+
      sensitivity: 7,
* @param  f  onMouseOver function || An object with configuration options
+
      interval: 100,
* @param  g  onMouseOut function  || Nothing (use configuration options object)
+
      timeout: 0
* @author    Brian Cherne <brian@cherne.net>
+
    };
*/
+
    cfg = $.extend(cfg, g ? {
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
+
      over: f,
/**
+
      out: g
* plugin: jquery.naviDropDown.js
+
    } : f);
* author: kt.cheung @ Brandammo
+
    var cX, cY, pX, pY;
* website: www.brandammo.co.uk
+
    var track = function (ev) {
* version: 1.0
+
      cX = ev.pageX;
* date: 19th feb 2011
+
      cY = ev.pageY;
* description: simple jquery navigation drop down menu with easing and hoverIntent
+
    };
 +
    var compare = function (ev, ob) {
 +
      ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
 +
      if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
 +
        $(ob).unbind("mousemove", track);
 +
        ob.hoverIntent_s = 1;
 +
        return cfg.over.apply(ob, [ev]);
 +
      } else {
 +
        pX = cX;
 +
        pY = cY;
 +
        ob.hoverIntent_t = setTimeout(function () {
 +
          compare(ev, ob);
 +
        }, cfg.interval);
 +
      }
 +
    };
 +
    var delay = function (ev, ob) {
 +
      ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
 +
      ob.hoverIntent_s = 0;
 +
      return cfg.out.apply(ob, [ev]);
 +
    };
 +
    var handleHover = function (e) {
 +
      var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
 +
      while (p && p != this) {
 +
        try {
 +
          p = p.parentNode;
 +
        } catch (e) {
 +
          p = this;
 +
        }
 +
      }
 +
      if (p == this) {
 +
        return false;
 +
      }
 +
      var ev = jQuery.extend({}, e);
 +
      var ob = this;
 +
      if (ob.hoverIntent_t) {
 +
        ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
 +
      }
 +
      if (e.type == "mouseover") {
 +
        pX = ev.pageX;
 +
        pY = ev.pageY;
 +
        $(ob).bind("mousemove", track);
 +
        if (ob.hoverIntent_s != 1) {
 +
          ob.hoverIntent_t = setTimeout(function () {
 +
            compare(ev, ob);
 +
          }, cfg.interval);
 +
        }
 +
      } else {
 +
        $(ob).unbind("mousemove", track);
 +
        if (ob.hoverIntent_s == 1) {
 +
          ob.hoverIntent_t = setTimeout(function () {
 +
            delay(ev, ob);
 +
          }, cfg.timeout);
 +
        }
 +
      }
 +
    };
 +
    return this.mouseover(handleHover).mouseout(handleHover);
 +
  };
 +
})(jQuery);
  
Copyright (c) 2011 KT Cheung
+
(function ($) {
  
Permission is hereby granted, free of charge, to any person obtaining a copy
+
  $.fn.naviDropDown = function (options) {
of this software and associated documentation files (the "Software"), to deal
 
in the Software without restriction, including without limitation the rights
 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 
copies of the Software, and to permit persons to whom the Software is
 
furnished to do so, subject to the following conditions:
 
  
The above copyright notice and this permission notice shall be included in
+
    //set up default options
all copies or substantial portions of the Software.
+
    var defaults = {
 +
      dropDownClass: 'dropdown', //the class name for your drop down
 +
      dropDownWidth: 'auto', //the default width of drop down elements
 +
      slideDownEasing: 'easeInOutCirc', //easing method for slideDown
 +
      slideUpEasing: 'easeInOutCirc', //easing method for slideUp
 +
      slideDownDuration: 500, //easing duration for slideDown
 +
      slideUpDuration: 500, //easing duration for slideUp
 +
      orientation: 'horizontal' //orientation - either 'horizontal' or 'vertical'
 +
    };
  
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+
    var opts = $.extend({}, defaults, options);
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 
THE SOFTWARE.
 
  
**/
+
    return this.each(function () {
 +
      var $this = $(this);
 +
      $this.find('.' + opts.dropDownClass).css('width', opts.dropDownWidth).css('display', 'none');
  
(function($){
+
      var buttonWidth = $this.find('.' + opts.dropDownClass).parent().width() + 'px';
 +
      var buttonHeight = $this.find('.' + opts.dropDownClass).parent().height() + 'px';
 +
      if (opts.orientation == 'horizontal') {
 +
        //$this.find('.'+opts.dropDownClass).css('left', '0px').css('top', buttonHeight);
 +
      }
 +
      if (opts.orientation == 'vertical') {
 +
        $this.find('.' + opts.dropDownClass).css('left', buttonWidth).css('top', '0px');
 +
      }
  
  $.fn.naviDropDown = function(options) {
+
      $this.find('li').hoverIntent(getDropDown, hideDropDown);
 
+
    });
//set up default options
+
 
var defaults = {
+
    function getDropDown() {
dropDownClass: 'dropdown', //the class name for your drop down
+
      activeNav = $(this);
dropDownWidth: 'auto', //the default width of drop down elements
+
      showDropDown();
slideDownEasing: 'easeInOutCirc', //easing method for slideDown
+
    }
slideUpEasing: 'easeInOutCirc', //easing method for slideUp
+
 
slideDownDuration: 500, //easing duration for slideDown
+
    function showDropDown() {
slideUpDuration: 500, //easing duration for slideUp
+
      activeNav.find('.' + opts.dropDownClass).slideDown({
orientation: 'horizontal' //orientation - either 'horizontal' or 'vertical'
+
        duration: opts.slideDownDuration,
};  
+
        easing: opts.slideDownEasing
 
+
      });
var opts = $.extend({}, defaults, options);
+
    }
 +
 
 +
    function hideDropDown() {
 +
      activeNav.find('.' + opts.dropDownClass).slideUp({
 +
        duration: opts.slideUpDuration,
 +
        easing: opts.slideUpEasing
 +
      }); //hides the current dropdown
 +
    }
  
    return this.each(function() { 
 
  var $this = $(this);
 
  $this.find('.'+opts.dropDownClass).css('width', opts.dropDownWidth).css('display', 'none');
 
 
 
  var buttonWidth = $this.find('.'+opts.dropDownClass).parent().width() + 'px';
 
  var buttonHeight = $this.find('.'+opts.dropDownClass).parent().height() + 'px';
 
  if(opts.orientation == 'horizontal') {
 
//$this.find('.'+opts.dropDownClass).css('left', '0px').css('top', buttonHeight);
 
  }
 
  if(opts.orientation == 'vertical') {
 
$this.find('.'+opts.dropDownClass).css('left', buttonWidth).css('top', '0px');
 
  }
 
 
 
  $this.find('li').hoverIntent(getDropDown, hideDropDown);
 
    });
 
 
function getDropDown(){
 
activeNav = $(this);
 
showDropDown();
 
}
 
 
function showDropDown(){
 
activeNav.find('.'+opts.dropDownClass).slideDown({duration:opts.slideDownDuration, easing:opts.slideDownEasing});
 
}
 
 
function hideDropDown(){
 
activeNav.find('.'+opts.dropDownClass).slideUp({duration:opts.slideUpDuration, easing:opts.slideUpEasing});//hides the current dropdown
 
}
 
 
 
   };
 
   };
 
})(jQuery);
 
})(jQuery);
  
 
//**************** USERACCOUNT.JS STARTS HERE ****************//
 
//**************** USERACCOUNT.JS STARTS HERE ****************//
 +
var docTitle = "User:" + wgUserName + " - SQLZOO";
 +
if (document.title === docTitle) {
 +
  function ownStat() {
 +
    $.getJSON('/userData.php', {
 +
      action: 'userStuff',
 +
      wgUserName: wgUserName
 +
    }, function (d) {
 +
 +
      if (d.cohort.length > 0) { //Check if user is member of any cohort
 +
 +
        var createUserStat = $('<div/>', {
 +
          id: 'divUserStat'
 +
        });
 +
        $('#content_2').append(createUserStat);
 +
 +
        $('#divUserStat')
 +
          .append($('<div/>', {
 +
            id: 'userContHeader'
 +
          }))
 +
          .append($('<div/>', {
 +
            id: 'userCont'
 +
          }));
 +
        $('#userContHeader')
 +
          .append($('<div/>', {
 +
            id: 'divStatHeader'
 +
          }))
 +
 +
        function emptyUserCont() {
 +
          $('#userCont')
 +
            .empty()
 +
            .append($('<div/>', {
 +
              id: 'divMeTable'
 +
            }))
 +
            .append($('<div/>', {
 +
              id: 'questCont'
 +
            }))
 +
            .append($('<div/>', {
 +
              id: 'answCont'
 +
            }))
 +
            .append($('<div/>', {
 +
              id: 'divClear2'
 +
            }));
 +
        }
 +
 +
        var id = "0";
 +
        //Adding myself to an existing cohort
 +
        $('#divStatHeader').append($('<div/>', {
 +
          id: 'addMeCont'
 +
        }));
 +
        var textAddMe = "<span id='addMeTxt'>Add me to an existing Cohort</span>";
 +
        var inputAddMe = $('<input/>', {
 +
          id: 'inputAddMe'
 +
        });
 +
        var btnAddMe = $('<div/>', {
 +
          id: 'btnAddme',
 +
          text: 'AddMe'
 +
        });
 +
        var warnTxt = $('<div/>', {
 +
          id: 'warnText',
 +
          text: "Cohort doesn't exists!"
 +
        });
 +
        $('#addMeCont').append(textAddMe);
 +
        $('#addMeCont').append($('<div/>', {
 +
          id: 'ibAddMe'
 +
        })).append($('<div/>', {
 +
          'class': 'divClear'
 +
        }));
 +
        $('#ibAddMe').append(inputAddMe).append(btnAddMe).append(warnTxt).hide();
 +
        $('#addMeTxt').click(function () {
 +
          $('#ibAddMe').slideToggle("100");
 +
          $('#btnAddme').live('click', function () {
 +
            var mem = wgUserName;
 +
            var cohortName = $('#inputAddMe').val();
 +
 +
            $.getJSON('/userData.php', {
 +
              action: 'addStudent',
 +
              cohortName: cohortName,
 +
              mem: mem
 +
            }, function (b) {
 +
              //b.noCohort="1" - no cohort in db
 +
 +
              if (b.noCohort == "0") {
 +
                $('#warnText').hide();
 +
                $('#inputAddMe').val("");
 +
                window.location.reload(true);
 +
              } else {
 +
                $('#warnText').show();
 +
              }
 +
            });
 +
            $('#inputAddMe').val("");
 +
          });
 +
        });
 +
 +
        //Adding cohort selector buttons to the header
 +
        function cohortSelectors() {
 +
          $('#divCoSelCont').empty();
 +
          for (var i = 0; i < d.cohort.length; i++) {
 +
            var cohort = d.cohort[i].id;
 +
            var path = d.path[i][0].pathName;
 +
            var divCoSelect = $('<div/>', {
 +
              'class': 'btnCoSelect',
 +
              id: i,
 +
              text: cohort + ' ' + ' ' + path
 +
            });
 +
            var divSep = $('<div/>', {
 +
              'class': 'divSeparator'
 +
            });
 +
            $('#divStatHeader').append($('<div/>', {
 +
              id: 'divCoSelCont'
 +
            }));
 +
            $('#divCoSelCont').append(divCoSelect).append(divSep);
 +
 +
          }
 +
          $('#0').addClass('btnCoSelectPicked');
 +
          var divClear = $('<div/>', {
 +
            'class': 'divClear'
 +
          });
 +
          $('#divStatHeader').append(divClear);
 +
        }
 +
 +
        cohortSelectors();
 +
 +
        //Click function on cohort selector buttons
 +
        $('div.btnCoSelect').click(function () {
 +
          $('div.btnCoSelect').removeClass('btnCoSelectPicked');
 +
          $(this).addClass('btnCoSelectPicked');
 +
          id = $(this).attr('id');
 +
          tutquizArrays(id);
 +
          pageLoad(id);
 +
        });
 +
 +
        //Pushing the questions in an array
 +
        var allquestArr = [];
 +
        var allansArr = [];
 +
 +
        function tutquizArrays(id) {
 +
          allquestArr = [];
 +
          $.each(d.questions[id], function (i, quest) {
 +
            allquestArr.push({
 +
              quest: d.questions[id][i].quest,
 +
              flag: d.questions[id][i].flag
 +
            });
 +
          });
 +
          allansArr = [];
 +
          $.each(d.answ[id], function (i, answ) {
 +
            allansArr.push({
 +
              answ: d.answ[id][i].txt,
 +
              whn: d.answ[id][i].whn,
 +
              score: d.answ[id][i].score
 +
            });
 +
          });
 +
        }
 +
 +
        //Create attempt divs
 +
        function answCreateFunc(allansArr) {
 +
          if (allansArr.length == 0) {
 +
            $('#answCont').hide();
 +
          } else {
 +
            if (!$('#answContHeader').hasClass('answContHead')) {
 +
              $('#answCont').append($('<div/>', {
 +
                id: 'answContHeader',
 +
                'class': 'answContHead'
 +
              }));
 +
              $('#answCont').append($('<div/>', {
 +
                id: 'answContAnsw'
 +
              }));
 +
              $('#answContHeader').append('<span id="spanAnTxt">ATTEMPTS</span>');
 +
            }
 +
            //Quizzes
 +
            if ($('.pickedTut').hasClass('quizRowUsr')) {
 +
              $('.questClass').removeClass('pickedQuest');
 +
 +
              $('#answContAnsw').slideUp(500, function () {
 +
                $('#answContAnsw').empty();
 +
                for (var j = 0; j < allansArr.length; j++) {
 +
                  var datime = allansArr[j].whn;
 +
                  datime = datime.split(" ");
 +
                  var divDatime = $('<div/>', {
 +
                    'class': 'classDatime'
 +
                  }).append(allansArr[j].whn);
 +
                  var divAnsAns = $('<div/>', {
 +
                    'class': 'classAnsAns'
 +
                  }).append(allansArr[j].answ);
 +
                  var answ = $('<div/>', {
 +
                    id: 'answ' + j,
 +
                    'class': 'answQuizClass'
 +
                  }).append(divDatime).append(divAnsAns);
 +
                  var score = parseInt(allansArr[j].score);
 +
                  $('#answContAnsw').append(answ);
 +
                  if (score === 100) {
 +
                    $('#answ' + j).addClass('goodAnsw');
 +
                  }
 +
                }
 +
              });
 +
              $('#answCont').animate({
 +
                width: "185px",
 +
                opacity: "show"
 +
              }, 500, "linear", function () {
 +
                $('#answContAnsw').slideDown(500);
 +
              });
 +
            } else {
 +
              //Tutorials
 +
              //runs when clicking from Quiz to Tutorial
 +
              if ($('#answContAnsw').children().hasClass('answQuizClass')) {
 +
                $('#answCont').css({
 +
                  'width': 'auto'
 +
                });
 +
 +
                $('#answContAnsw').slideUp(500, function () {
 +
                  $('#answContAnsw').empty();
 +
                  for (var j = 0; j < allansArr.length; j++) {
 +
                    var datime = allansArr[j].whn;
 +
                    datime = datime.split(" ");
 +
                    var answ = $('<div>', {
 +
                      id: 'answ' + j,
 +
                      'class': 'answClass'
 +
                    }).append(allansArr[j].whn).append("<pre class='brush:[sql]'>" + allansArr[j].answ + "</pre>");
 +
                    var score = parseInt(allansArr[j].score);
 +
                    $('#answContAnsw').append(answ);
 +
                    if (score === 100) {
 +
                      $('#answ' + j).addClass('goodAnsw');
 +
                    }
 +
                  }
 +
                  $('#answCont').show();
 +
                  var x = $('#answContAnsw').css('width'); //get the new width
 +
                  $('#answCont').css({
 +
                    'width': '185px'
 +
                  }); //set the previous width
 +
                  $('#answCont').animate({
 +
                    width: x
 +
                  }, 500, function () {
 +
                    $('#answContAnsw').slideDown(500);
 +
                  });
 +
                });
 +
              } else if ($('#answContAnsw').children().hasClass('answClass')) {
 +
                //@reload runs this
 +
                $('#answCont').show();
 +
                $('#answCont').css({
 +
                  'width': 'auto'
 +
                });
 +
                var origX = $('#answContAnsw').css('width');
 +
                $('#answContAnsw').slideUp(500, function () {
 +
                  $('#answContAnsw').empty().hide();
 +
                  for (var j = 0; j < allansArr.length; j++) {
 +
                    var datime = allansArr[j].whn;
 +
                    datime = datime.split(" ");
 +
                    var answ = $('<div>', {
 +
                      id: 'answ' + j,
 +
                      'class': 'answClass'
 +
                    }).append(allansArr[j].whn).append("<pre class='brush:[sql]'>" + allansArr[j].answ + "</pre>");
 +
                    var score = parseInt(allansArr[j].score);
 +
                    $('#answContAnsw').append(answ);
 +
                    if (score === 100) {
 +
                      $('#answ' + j).addClass('goodAnsw');
 +
                    }
 +
                  }
 +
                  var x = $('#answContAnsw').css('width');
 +
                  $('#answCont').css({
 +
                    'width': origX
 +
                  });
 +
                  $('#answCont').animate({
 +
                    width: x
 +
                  }, 500, function () {
 +
                    $('#answContAnsw').slideDown(500);
 +
                  });
 +
 +
                });
 +
              } else {
 +
                //runs at first load
 +
                $('#answCont').css({
 +
                  'width': 'auto'
 +
                });
 +
                $('#answContAnsw').hide();
 +
                for (var j = 0; j < allansArr.length; j++) {
 +
                  var datime = allansArr[j].whn;
 +
                  datime = datime.split(" ");
 +
                  var answ = $('<div>', {
 +
                    id: 'answ' + j,
 +
                    'class': 'answClass'
 +
                  }).append(allansArr[j].whn).append("<pre class='brush:[sql]'>" + allansArr[j].answ + "</pre>");
 +
                  var score = parseInt(allansArr[j].score);
 +
                  $('#answContAnsw').append(answ);
 +
                  if (score === 100) {
 +
                    $('#answ' + j).addClass('goodAnsw');
 +
                  }
 +
                }
 +
                var x = $('#answContAnsw').css('width');
 +
                $('#answCont').css({
 +
                  'width': '0'
 +
                });
 +
                $('#answCont').animate({
 +
                  width: x
 +
                }, 500, function () {
 +
                  $('#answContAnsw').slideDown(500);
 +
                });
 +
              }
 +
            }
 +
          }
 +
        }
 +
 +
        //Create questions divs
 +
        function questCreateFunc(allquestArr) {
 +
          $('#questCont').append($('<div/>', {
 +
            id: 'questClassCont'
 +
          }));
 +
          $('#questClassCont').slideUp(500, function () {
 +
            $('#questClassCont').empty();
 +
            for (var j = 0; j < allquestArr.length; j++) {
 +
              var quest = $('<div>', {
 +
                id: 'quest' + j,
 +
                'class': 'questClass',
 +
                text: allquestArr[j].quest
 +
              });
 +
 +
              if (allquestArr[j].flag == "q") {
 +
                $('#questClassCont').append(quest);
 +
                $('#quest' + j).addClass('questQuizClass');
 +
              } else {
 +
                $('#questClassCont').append(quest);
 +
                $('#quest' + j).addClass('questTutClass');
 +
 +
              }
 +
            }
 +
            $('#quest0.questTutClass').addClass('pickedQuest');
 +
            $('#questClassCont').delay(0).slideDown(500);
 +
          })
 +
        }
  
var docTitle = "User:"+wgUserName+" - SQLZOO";
+
        function pageLoad(id) {
if (document.title === docTitle){
+
          emptyUserCont();
  function ownStat(){
+
          //Tutorials and quizzes table
$.getJSON('/userData.php',{action:'userStuff',wgUserName:wgUserName},function(d){
+
          var table = $('<table/>', {
+
            id: 'statMeTable'
if(d.cohort.length>0){ //Check if user is member of any cohort
+
          });
+
          var trh = $('<tr/>', {
+
            id: 'tHeaderMeUsr'
var createUserStat = $('<div/>',{id:'divUserStat'});
+
          }).append('<th><span>TUTORIALS & QUIZZES</span></th><th><span>SCORES</span></th><th><span>RESULTS</span></th>');
$('#content_2').append(createUserStat);
+
          table.append(trh);
+
          for (var i = 0; i < d.tut[id].length; i++) {
$('#divUserStat')
+
            var tr = $('<tr/>');
.append($('<div/>',{id:'userContHeader'}))
 
.append($('<div/>',{id:'userCont'}));
 
$('#userContHeader')
 
.append($('<div/>',{id:'divStatHeader'}))
 
 
function emptyUserCont(){
 
$('#userCont')
 
.empty()
 
.append($('<div/>',{id:'divMeTable'}))
 
.append($('<div/>',{id:'questCont'}))
 
.append($('<div/>',{id:'answCont'}))
 
.append($('<div/>',{id:'divClear2'}));
 
}
 
 
var id = "0";
 
 
//Adding myself to an existing cohort
 
 
$('#divStatHeader').append($('<div/>',{id:'addMeCont'}));
 
var textAddMe = "<span id='addMeTxt'>Add me to an existing Cohort</span>";
 
var inputAddMe = $('<input/>',{id:'inputAddMe'});
 
var btnAddMe = $('<div/>',{id:'btnAddme', text:'AddMe'});
 
var warnTxt = $('<div/>',{id:'warnText', text:"Cohort doesn't exists!"});
 
$('#addMeCont').append(textAddMe);
 
$('#addMeCont').append($('<div/>',{id:'ibAddMe'})).append($('<div/>',{'class':'divClear'}));
 
$('#ibAddMe').append(inputAddMe).append(btnAddMe).append(warnTxt).hide();
 
 
 
$('#addMeTxt').click(function(){
 
$('#ibAddMe').slideToggle("100");
 
 
$('#btnAddme').live('click', function(){
 
var mem = wgUserName;
 
var cohortName = $('#inputAddMe').val();
 
 
$.getJSON('/userData.php',{action:'addStudent',cohortName:cohortName,mem:mem},function(b){
 
//b.noCohort="1" - no cohort in db
 
 
if(b.noCohort=="0"){
 
$('#warnText').hide();
 
$('#inputAddMe').val("");
 
window.location.reload(true);
 
} else{
 
$('#warnText').show();
 
}
 
});
 
$('#inputAddMe').val("");
 
});
 
});
 
 
//Adding cohort selector buttons to the header
 
function cohortSelectors(){
 
$('#divCoSelCont').empty();
 
for (var i=0; i<d.cohort.length; i++){
 
var cohort = d.cohort[i].id;
 
var path = d.path[i][0].pathName;
 
var divCoSelect = $('<div/>',{'class':'btnCoSelect',id:i,text:cohort+' '+' '+path});
 
var divSep = $('<div/>',{'class':'divSeparator'});
 
$('#divStatHeader').append($('<div/>',{id:'divCoSelCont'}));
 
$('#divCoSelCont').append(divCoSelect).append(divSep);
 
 
}
 
$('#0').addClass('btnCoSelectPicked');
 
var divClear = $('<div/>',{'class':'divClear'});
 
$('#divStatHeader').append(divClear);
 
}
 
  
cohortSelectors();
+
            if (d.tut[id][i].flag == 't') {
+
              var tr = $('<tr/>', {
//Click function on cohort selector buttons
+
                'class': 'tutsRowUsr',
$('div.btnCoSelect').click(function(){
+
                id: d.tut[id][i].wikipage
$('div.btnCoSelect').removeClass('btnCoSelectPicked');
+
              }); //.addClass('tutsClass');
$(this).addClass('btnCoSelectPicked');
+
            } else {
id=$(this).attr('id');
+
              var tr = $('<tr/>', {
tutquizArrays(id);
+
                'class': 'quizRowUsr',
pageLoad(id);
+
                id: d.tut[id][i].wikipage
+
              }); //.addClass('quizClass');
+
            }
});
+
            var td = $('<td/>');
+
            var te = $('<td/>');
//Pushing the questions in an array
+
            var tf = $('<td/>');
var allquestArr = [];
+
            td.append(d.tut[id][i].sname);
var allansArr = [];
+
            var resultObj = [];
+
            resultObj = getObjects(d.statMe[id], 'Tutorials', d.tut[id][i].sname);
function tutquizArrays(id){
+
            if (resultObj.length == 0) {
allquestArr = [];
+
              var res = '';
$.each(d.questions[id], function(i, quest){
+
              te.append(res);
allquestArr.push({quest:d.questions[id][i].quest, flag:d.questions[id][i].flag});
+
              tf.append(res);
});
+
              tr.append(td).append(te).append(tf).addClass('statMeRows');
allansArr = [];
+
              table.append(tr);
$.each(d.answ[id], function(i, answ){
 
allansArr.push({answ:d.answ[id][i].txt, whn:d.answ[id][i].whn, score:d.answ[id][i].score});
 
});
 
}
 
 
//Create attempt divs
 
function answCreateFunc(allansArr){
 
if(allansArr.length==0){
 
$('#answCont').hide();
 
 
}else{
 
 
if(!$('#answContHeader').hasClass('answContHead')){
 
$('#answCont').append($('<div/>',{id:'answContHeader','class':'answContHead'}));
 
$('#answCont').append($('<div/>',{id:'answContAnsw'}));
 
$('#answContHeader').append('<span id="spanAnTxt">ATTEMPTS</span>');
 
}
 
//Quizzes
 
if ($('.pickedTut').hasClass('quizRowUsr')){
 
$('.questClass').removeClass('pickedQuest');
 
 
$('#answContAnsw').slideUp(500, function(){
 
$('#answContAnsw').empty();
 
for (var j=0;j<allansArr.length;j++){
 
var datime = allansArr[j].whn;
 
datime = datime.split(" ");
 
var divDatime = $('<div/>',{'class':'classDatime'}).append(allansArr[j].whn);
 
var divAnsAns = $('<div/>',{'class':'classAnsAns'}).append(allansArr[j].answ);
 
var answ = $('<div/>',{id:'answ'+j, 'class':'answQuizClass'}).append(divDatime).append(divAnsAns);
 
var score = parseInt(allansArr[j].score);
 
$('#answContAnsw').append(answ);
 
if(score===100){
 
$('#answ'+j).addClass('goodAnsw');
 
}
 
}
 
});
 
 
$('#answCont').animate({
 
width:"185px",
 
opacity:"show"},500, "linear", function(){
 
$('#answContAnsw').slideDown(500);
 
});
 
 
}else{
 
//Tutorials
 
//runs when clicking from Quiz to Tutorial
 
if ($('#answContAnsw').children().hasClass('answQuizClass')){
 
$('#answCont').css({'width':'auto'});
 
 
$('#answContAnsw').slideUp(500, function(){
 
$('#answContAnsw').empty();
 
for (var j=0;j<allansArr.length;j++){
 
var datime = allansArr[j].whn;
 
datime = datime.split(" ");
 
var answ = $('<div>',{id:'answ'+j, 'class':'answClass'}).append(allansArr[j].whn).append("<pre class='brush:[sql]'>"+allansArr[j].answ+"</pre>");
 
var score = parseInt(allansArr[j].score);
 
$('#answContAnsw').append(answ);
 
if(score===100){
 
$('#answ'+j).addClass('goodAnsw');
 
}
 
}
 
$('#answCont').show();
 
var x = $('#answContAnsw').css('width'); //get the new width
 
$('#answCont').css({'width':'185px'}); //set the previous width
 
$('#answCont').animate({width:x},500, function(){
 
$('#answContAnsw').slideDown(500);
 
 
});
 
});
 
 
}else if ($('#answContAnsw').children().hasClass('answClass')){
 
//@reload runs this
 
$('#answCont').show();
 
$('#answCont').css({'width':'auto'});
 
var origX = $('#answContAnsw').css('width');
 
 
 
$('#answContAnsw').slideUp(500, function(){
 
$('#answContAnsw').empty().hide();
 
for (var j=0;j<allansArr.length;j++){
 
var datime = allansArr[j].whn;
 
datime = datime.split(" ");
 
var answ = $('<div>',{id:'answ'+j, 'class':'answClass'}).append(allansArr[j].whn).append("<pre class='brush:[sql]'>"+allansArr[j].answ+"</pre>");
 
var score = parseInt(allansArr[j].score);
 
$('#answContAnsw').append(answ);
 
if(score===100){
 
$('#answ'+j).addClass('goodAnsw');
 
}
 
}
 
var x = $('#answContAnsw').css('width');
 
$('#answCont').css({'width':origX});
 
$('#answCont').animate({width:x},500, function(){
 
$('#answContAnsw').slideDown(500);
 
});
 
 
});
 
}else {
 
//runs at first load
 
$('#answCont').css({'width':'auto'});
 
$('#answContAnsw').hide();
 
for (var j=0;j<allansArr.length;j++){
 
var datime = allansArr[j].whn;
 
datime = datime.split(" ");
 
var answ = $('<div>',{id:'answ'+j, 'class':'answClass'}).append(allansArr[j].whn).append("<pre class='brush:[sql]'>"+allansArr[j].answ+"</pre>");
 
var score = parseInt(allansArr[j].score);
 
$('#answContAnsw').append(answ);
 
if(score===100){
 
$('#answ'+j).addClass('goodAnsw');
 
}
 
}
 
 
var x = $('#answContAnsw').css('width');
 
$('#answCont').css({'width':'0'});
 
$('#answCont').animate({width:x},500, function(){
 
$('#answContAnsw').slideDown(500);
 
 
});
 
 
}
 
}
 
}
 
}
 
 
//Create questions divs
 
function questCreateFunc(allquestArr){
 
$('#questCont').append($('<div/>',{id:'questClassCont'}));
 
$('#questClassCont').slideUp(500, function(){
 
$('#questClassCont').empty();
 
for (var j=0;j<allquestArr.length;j++){
 
var quest = $('<div>',{id:'quest'+j,'class':'questClass', text:allquestArr[j].quest});
 
 
if(allquestArr[j].flag =="q"){
 
$('#questClassCont').append(quest);
 
$('#quest'+j).addClass('questQuizClass');
 
}else{
 
$('#questClassCont').append(quest);
 
$('#quest'+j).addClass('questTutClass');
 
 
}
 
}
 
$('#quest0.questTutClass').addClass('pickedQuest');
 
$('#questClassCont').delay(0).slideDown(500);
 
})
 
}
 
 
function pageLoad(id){
 
 
emptyUserCont();
 
 
//Tutorials and quizzes table
 
var table = $('<table/>',{id:'statMeTable'});
 
var trh = $('<tr/>',{id:'tHeaderMeUsr'}).append('<th><span>TUTORIALS & QUIZZES</span></th><th><span>SCORES</span></th><th><span>RESULTS</span></th>');
 
table.append(trh);
 
for (var i=0; i<d.tut[id].length; i++){
 
var tr = $('<tr/>');
 
 
if(d.tut[id][i].flag == 't'){
 
var tr = $('<tr/>',{'class':'tutsRowUsr',id:d.tut[id][i].wikipage}); //.addClass('tutsClass');
 
} else {
 
var tr = $('<tr/>',{'class':'quizRowUsr',id:d.tut[id][i].wikipage});   //.addClass('quizClass');
 
}
 
var td = $('<td/>'); var te = $('<td/>'); var tf = $('<td/>');
 
td.append(d.tut[id][i].sname);
 
var resultObj = [];
 
resultObj = getObjects(d.statMe[id], 'Tutorials', d.tut[id][i].sname);
 
if(resultObj.length==0){
 
var res = '';
 
te.append(res);
 
tf.append(res);
 
tr.append(td).append(te).append(tf).addClass('statMeRows');
 
table.append(tr);
 
 
} else {
 
te.append(resultObj[0].Score);
 
tf.append(resultObj[0].Results);
 
tr.append(td).append(te).append(tf).addClass('statMeRows');
 
table.append(tr);
 
}
 
 
}
 
 
$('#divMeTable').append(table);
 
$('#statMeTable tr:nth-child(2)').addClass('pickedTut');
 
 
//questions
 
$('#questCont').append($('<div/>',{id:'questContHeader'}));
 
$('#questContHeader').append('<span id="spanQuTxt">QUESTIONS</span>');
 
 
questCreateFunc(allquestArr);
 
 
//Answers
 
 
answCreateFunc(allansArr);
 
 
}
 
 
tutquizArrays(id);
 
pageLoad(id);
 
 
 
//Refresh answers
 
function refansFunc(quest){
 
 
 
var wikipage = $('.pickedTut').attr('id'); //for quizzes
 
if ($('.pickedTut').hasClass('quizRowUsr')){
 
 
//WIKIPAGE
 
$.getJSON('/userData.php',{action:'answersQuiz',wikipage:wikipage,wgUserName:wgUserName},function(f){
 
allansArr = [];
 
$.each(f.answ, function(i, answ){
 
allansArr.push({answ:f.answ[i].txt, whn:f.answ[i].whn, score:f.answ[i].score});
 
});
 
 
answCreateFunc(allansArr);
 
});
 
 
 
}else{
 
 
$.getJSON('/userData.php',{action:'answersTut',quest:quest,wgUserName:wgUserName},function(f){
 
allansArr = [];
 
$.each(f.answ, function(i, answ){
 
allansArr.push({answ:f.answ[i].txt, whn:f.answ[i].whn, score:f.answ[i].score});
 
});
 
 
answCreateFunc(allansArr);
 
});
 
}
 
 
 
}
 
 
//Click on Tutorial or Quiz
 
 
$('#statMeTable tr.statMeRows').live('click', function(){
 
$('#statMeTable tr.statMeRows').removeClass('pickedTut');
 
$(this).addClass('pickedTut');
 
path = d.path[id][0].pathName;
 
 
var tutName = $(this).find(':first-child').text();
 
$.getJSON('/userData.php',{action:'quest',path:path,tutName:tutName},function(e){
 
allquestArr = [];
 
$.each(e.quest, function(i, quest){
 
allquestArr.push({quest:e.quest[i].quest, flag:e.quest[i].flag});
 
});
 
 
questCreateFunc(allquestArr);
 
var quest = allquestArr[0].quest;
 
 
refansFunc(quest);
 
});
 
});
 
  
//Click event for only Tutorial Questions
+
            } else {
$('div.questTutClass').live('click', function(){
+
              te.append(resultObj[0].Score);
$('div.questTutClass').removeClass('pickedQuest');
+
              tf.append(resultObj[0].Results);
$(this).addClass('pickedQuest');
+
              tr.append(td).append(te).append(tf).addClass('statMeRows');
var quest = $(this).text();
+
              table.append(tr);
refansFunc(quest);
+
            }
});
 
}
 
});
 
 
 
  }
 
 
 
 
 
////////////////////////////*****TEACHERS STUFF STARTS HERE*****///////////////////////////////// 
 
 
 
  if($.inArray('teacher', wgUserGroups) > -1){
 
 
$(function(){
 
  
 
+
          }
  var popupDiv = $('<div/>',{id:'divPopup'})
+
 
  $('#bodyContent').prepend(popupDiv);
+
          $('#divMeTable').append(table);
  $('#divPopup').hide();
+
          $('#statMeTable tr:nth-child(2)').addClass('pickedTut');
 
+
 
  //Create Tab structure
+
          //questions
  $('#bodyContent').prepend($('<div/>',{id:'tab_box_1', 'class':'tabbed_box'}));
+
          $('#questCont').append($('<div/>', {
  $('#tab_box_1').append($('<div/>',{id:'tab_area', 'class':'tabbed_area'}));
+
            id: 'questContHeader'
 
+
          }));
  $('#tab_area').append($('<ul/>',{id:'ulTabs', 'class':'tabs'}));
+
          $('#questContHeader').append('<span id="spanQuTxt">QUESTIONS</span>');
  $('#ulTabs').append("<li><a href='#' id='tab_1' title='content_1' class='tab active'>Cohort Stats</a></li>");
+
 
  $('#ulTabs').append("<li><a href='#' id='tab_2' title='content_2' class='tab' >Own Stat</a></li>");
+
          questCreateFunc(allquestArr);
 
+
 
 
+
          //Answers
  $('#tab_area').append($('<div/>',{id:'content_1', 'class':'content'}));
+
 
  $('#tab_area').append($('<div/>',{id:'content_2', 'class':'content'}));
+
          answCreateFunc(allansArr);
+
        }
 
+
 
  ownStat();
+
        tutquizArrays(id);
 
+
        pageLoad(id);
 
+
 
  // When a link is clicked   
+
        //Refresh answers
    $("a.tab").click(function () {
+
        function refansFunc(quest) {
       
+
          var wikipage = $('.pickedTut').attr('id'); //for quizzes
 +
          if ($('.pickedTut').hasClass('quizRowUsr')) {
 +
            //WIKIPAGE
 +
            $.getJSON('/userData.php', {
 +
              action: 'answersQuiz',
 +
              wikipage: wikipage,
 +
              wgUserName: wgUserName
 +
            }, function (f) {
 +
              allansArr = [];
 +
              $.each(f.answ, function (i, answ) {
 +
                allansArr.push({
 +
                  answ: f.answ[i].txt,
 +
                  whn: f.answ[i].whn,
 +
                  score: f.answ[i].score
 +
                });
 +
              });
 +
 
 +
              answCreateFunc(allansArr);
 +
            });
 +
          } else {
 +
            $.getJSON('/userData.php', {
 +
              action: 'answersTut',
 +
              quest: quest,
 +
              wgUserName: wgUserName
 +
            }, function (f) {
 +
              allansArr = [];
 +
              $.each(f.answ, function (i, answ) {
 +
                allansArr.push({
 +
                  answ: f.answ[i].txt,
 +
                  whn: f.answ[i].whn,
 +
                  score: f.answ[i].score
 +
                });
 +
              });
 +
              answCreateFunc(allansArr);
 +
            });
 +
          }
 +
        }
 +
 
 +
        //Click on Tutorial or Quiz
 +
 
 +
        $('#statMeTable tr.statMeRows').live('click', function () {
 +
          $('#statMeTable tr.statMeRows').removeClass('pickedTut');
 +
          $(this).addClass('pickedTut');
 +
          path = d.path[id][0].pathName;
 +
 
 +
          var tutName = $(this).find(':first-child').text();
 +
          $.getJSON('/userData.php', {
 +
            action: 'quest',
 +
            path: path,
 +
            tutName: tutName
 +
          }, function (e) {
 +
            allquestArr = [];
 +
            $.each(e.quest, function (i, quest) {
 +
              allquestArr.push({
 +
                quest: e.quest[i].quest,
 +
                flag: e.quest[i].flag
 +
              });
 +
            });
 +
            questCreateFunc(allquestArr);
 +
            var quest = allquestArr[0].quest;
 +
            refansFunc(quest);
 +
          });
 +
        });
 +
 
 +
        //Click event for only Tutorial Questions
 +
        $('div.questTutClass').live('click', function () {
 +
          $('div.questTutClass').removeClass('pickedQuest');
 +
          $(this).addClass('pickedQuest');
 +
          var quest = $(this).text();
 +
          refansFunc(quest);
 +
        });
 +
      }
 +
    });
 +
  }
 +
 
 +
  ////////////////////////////*****TEACHERS STUFF STARTS HERE*****///////////////////////////////// 
 +
 
 +
  if ($.inArray('teacher', wgUserGroups) > -1) {
 +
 
 +
    $(function () {
 +
      var popupDiv = $('<div/>', {
 +
        id: 'divPopup'
 +
      })
 +
      $('#bodyContent').prepend(popupDiv);
 +
      $('#divPopup').hide();
 +
 
 +
      //Create Tab structure
 +
      $('#bodyContent').prepend($('<div/>', {
 +
        id: 'tab_box_1',
 +
        'class': 'tabbed_box'
 +
      }));
 +
      $('#tab_box_1').append($('<div/>', {
 +
        id: 'tab_area',
 +
        'class': 'tabbed_area'
 +
      }));
 +
 
 +
      $('#tab_area').append($('<ul/>', {
 +
        id: 'ulTabs',
 +
        'class': 'tabs'
 +
      }));
 +
      $('#ulTabs').append("<li><a href='#' id='tab_1' title='content_1' class='tab active'>Cohort Stats</a></li>");
 +
      $('#ulTabs').append("<li><a href='#' id='tab_2' title='content_2' class='tab' >Own Stat</a></li>");
 +
 
 +
      $('#tab_area').append($('<div/>', {
 +
        id: 'content_1',
 +
        'class': 'content'
 +
      }));
 +
      $('#tab_area').append($('<div/>', {
 +
        id: 'content_2',
 +
        'class': 'content'
 +
      }));
 +
 
 +
      ownStat();
 +
 
 +
      // When a link is clicked   
 +
      $("a.tab").click(function () {
 
         // switch all tabs off   
 
         // switch all tabs off   
         $(".active").removeClass("active");
+
         $(".active").removeClass("active");
         
 
 
         // switch this tab on   
 
         // switch this tab on   
         $(this).addClass("active");
+
         $(this).addClass("active");
         
 
 
         // slide all elements with the class 'content' up   
 
         // slide all elements with the class 'content' up   
         $(".content").slideUp();
+
         $(".content").slideUp();
         $('#answCont').css({'width':'auto'});
+
         $('#answCont').css({
+
          'width': 'auto'
 +
        });
 +
 
 
         // Now figure out what the 'title' attribute value is and find the element with that id.  Then slide that down.   
 
         // Now figure out what the 'title' attribute value is and find the element with that id.  Then slide that down.   
         var content_show = $(this).attr("title");
+
         var content_show = $(this).attr("title");
         $("#"+content_show).slideDown();
+
         $("#" + content_show).slideDown();
       
+
      });
    });
+
 
 
+
      //**************createCohort append to TAB 1 (#content_1)
 
+
 
//**************createCohort append to TAB 1 (#content_1)
+
      var createCohort = $('<div/>', {
+
        id: 'divCohort'
  var createCohort = $('<div/>',{id:'divCohort'});
+
      });
  $('#content_1').append(createCohort);
+
      $('#content_1').append(createCohort);
 
+
 
  //Creating Cohort Selector
+
      //Creating Cohort Selector
  var pathDb = $('<select/>',{id:'selectPath', title:'Select path', 'class':'btnClass'}); //Getting the path id from Db and store in this array
+
      var pathDb = $('<select/>', {
  $.getJSON('/userData.php',{action:'getPathDb'},function(d){
+
        id: 'selectPath',
for (var i=0; i<d.pathDb.length; i++){
+
        title: 'Select path',
var optionList = $('<option/>',{val:i, text:d.pathDb[i].pathId});
+
        'class': 'btnClass'
pathDb.append(optionList);
+
      }); //Getting the path id from Db and store in this array
}
+
      $.getJSON('/userData.php', {
+
        action: 'getPathDb'
});
+
      }, function (d) {
 
+
        for (var i = 0; i < d.pathDb.length; i++) {
//Create buttons and input field
+
          var optionList = $('<option/>', {
$('#divCohort')
+
            val: i,
.append($('<div>',{id:'divCohortHeader'}))
+
            text: d.pathDb[i].pathId
.append($('<div/>',{id:'cohorCont'}))
+
          });
.append($('<div/>',{id:'cohortContStat'}))
+
          pathDb.append(optionList);
.append($('<div/>',{id:'memberCont'}))
+
        }
.append($('<div/>',{id:'divClear'}));
+
      });
 
$('#divCohortHeader')
 
.append($('<input/>',{'type':'text',id:'newCohortName','class':'btnClass', name:'newCohortName', title:'Type a cohort name',required:'required'}))
 
.append(pathDb)
 
.append($('<input/>',{'type':'button',value:'Add Cohort','class':'btnClass',click:addCohorts}))
 
.append($('<input/>',{'type':'button',value:'Rename Cohort',id:'btnEdCo','class':'btnClass',click:editCohorts}))
 
.append($('<input/>',{'type':'button',value:'% or Score',id:'btnStatCo','class':'btnClass',click:changeView}))
 
.append($('<input/>',{'type':'button',value:'Add Students',id:'btnAddStu','class':'btnClass',click:addStudents}))
 
.append($('<input/>',{'type':'button',value:'Delete Student',id:'btnDelStu','class':'btnClass',click:delStudents}));
 
$('#btnDelCo').hide();
 
$('#btnEdCo').hide();
 
$('#btnStatCo').hide();
 
$('#btnAddStu').hide();
 
$('#btnDelStu').hide();
 
$('#memberCont').hide();
 
updateCohorts();
 
  
+
      //Create buttons and input field
+
      $('#divCohort')
//Unselect cohort when clicked somewhere else
+
        .append($('<div>', {
$(document).click(function(e) {
+
          id: 'divCohortHeader'
if ($(e.target).is('#cohorCont, #cohorCont *, #cohortContStat, #cohortContStat *, #divPopup, #divPopup *,.btnClass, #newCohortName, #memberCont, #memberCont *')) {
+
        }))
return;
+
        .append($('<div/>', {
}else{
+
          id: 'cohorCont'
$('.cohortClass').removeClass('pickedCo');
+
        }))
$('#newCohortName').val('');
+
        .append($('<div/>', {
+
          id: 'cohortContStat'
$('#cohortContStat').slideUp(500, function(){$(this).empty();});
+
        }))
$('#memberCont').slideUp(500, function(){$(this).empty();});
+
        .append($('<div/>', {
+
          id: 'memberCont'
$('#btnDelCo').hide();
+
        }))
$('#btnStatCo').hide();
+
        .append($('<div/>', {
$('#btnAddStu').hide();
+
          id: 'divClear'
$('#btnDelStu').hide();
+
        }));
$('#btnEdCo').hide();
 
}
 
});
 
 
});
 
 
//Add cohorts to list and DB
 
function addCohorts(){
 
 
if($('#newCohortName').val()==""){
 
alert("Type cohort name!")
 
}else{
 
var selVal = $('#selectPath').val();
 
var selPath = $('#selectPath option[value='+selVal+']').text();
 
$.getJSON('/userData.php',{action:'addCohort',wgUserName:wgUserName,cohortName:$('#newCohortName').val(),selPath:selPath},function(d){
 
 
updateCohorts();
 
 
});
 
 
}
 
 
}
 
  
//Updating the list of cohorts from DB
+
      $('#divCohortHeader')
function updateCohorts(){
+
        .append($('<input/>', {
$('#cohorCont').slideUp(300);
+
          'type': 'text',
$('#cohorCont').slideDown(300, function(){
+
          id: 'newCohortName',
$('#cohorCont').empty();
+
          'class': 'btnClass',
$.getJSON('/userData.php',{action:'listTeachersCohorts',wgUserName:wgUserName},function(d){
+
          name: 'newCohortName',
for (var i=0; i<d.cohorts.length; i++){
+
          title: 'Type a cohort name',
var cohortList = $('<div/>',{'class':'cohortClass',id:'divCo'+i,click:clickListCo})
+
          required: 'required'
.append("<span class='cohortTxtClass'>"+d.cohorts[i].id+"</span>")
+
        }))
.append("<img src='/design/bin.png' name='divCo"+i+"' onClick=binClick(name) class='imgBin' title='Delete Cohort' alt='22'>")
+
        .append(pathDb)
.append("<span class='pathNameClass'>"+d.cohorts[i].pathName+"</span>");
+
        .append($('<input/>', {
$('#cohorCont').append(cohortList);
+
          'type': 'button',
}
+
          value: 'Add Cohort',
  if($('#cohorCont>div').length>0){
+
          'class': 'btnClass',
$('#cohorCont div:nth-child(1)').trigger('click');
+
          click: addCohorts
  }
+
        }))
 +
        .append($('<input/>', {
 +
          'type': 'button',
 +
          value: 'Rename Cohort',
 +
          id: 'btnEdCo',
 +
          'class': 'btnClass',
 +
          click: editCohorts
 +
        }))
 +
        .append($('<input/>', {
 +
          'type': 'button',
 +
          value: '% or Score',
 +
          id: 'btnStatCo',
 +
          'class': 'btnClass',
 +
          click: changeView
 +
        }))
 +
        .append($('<input/>', {
 +
          'type': 'button',
 +
          value: 'Add Students',
 +
          id: 'btnAddStu',
 +
          'class': 'btnClass',
 +
          click: addStudents
 +
        }))
 +
        .append($('<input/>', {
 +
          'type': 'button',
 +
          value: 'Delete Student',
 +
          id: 'btnDelStu',
 +
          'class': 'btnClass',
 +
          click: delStudents
 +
        }));
 +
      $('#btnDelCo').hide();
 +
      $('#btnEdCo').hide();
 +
      $('#btnStatCo').hide();
 +
      $('#btnAddStu').hide();
 +
      $('#btnDelStu').hide();
 +
      $('#memberCont').hide();
 +
      updateCohorts();
  
});
+
      //Unselect cohort when clicked somewhere else
$('#newCohortName').val("");
+
      $(document).click(function (e) {
$('#memberCont').empty().hide();
+
        if ($(e.target).is('#cohorCont, #cohorCont *, #cohortContStat, #cohortContStat *, #divPopup, #divPopup *,.btnClass, #newCohortName, #memberCont, #memberCont *')) {
});
+
          return;
}
+
        } else {
 +
          $('.cohortClass').removeClass('pickedCo');
 +
          $('#newCohortName').val('');
  
//Delete cohorts from list and DB
+
          $('#cohortContStat').slideUp(500, function () {
function deleteCohorts(){
+
            $(this).empty();
var id = $('.pickedCo .cohortTxtClass').text();
+
          });
+
          $('#memberCont').slideUp(500, function () {
  $.getJSON('/userData.php',{action:'delCohort',wgUserName:wgUserName,cohortName:id},function(d){
+
            $(this).empty();
+
          });
  });
+
          $('#btnDelCo').hide();
  updateCohorts();
+
          $('#btnStatCo').hide();
}
+
          $('#btnAddStu').hide();
+
          $('#btnDelStu').hide();
//Edit cohorts name  cohortClass
+
          $('#btnEdCo').hide();
function editCohorts(){
+
        }
  var prevCo = $('.pickedCo .cohortTxtClass').text();
+
      });
  var newCo = $('#newCohortName').val();
+
    });
 
 
  $.getJSON('/userData.php',{action:'editCohort',oldCohort:prevCo,cohortName:newCo},function(d){
 
 
  });
 
  updateCohorts();
 
}
 
//Click event on Cohort list
 
function clickListCo(){
 
 
  $('.cohortClass').removeClass('pickedCo');
 
  $(this).addClass('pickedCo');
 
  $('#btnDelCo').show();
 
  $('#btnStatCo').show();
 
  $('#btnAddStu').show();
 
  $('#btnDelStu').show();
 
  $('#btnEdCo').show();
 
  $('#memberCont').slideUp(500, function(){$(this).empty();});
 
  var cohortId = $('.pickedCo .cohortTxtClass').text();
 
  $('#newCohortName').val(cohortId);
 
   
 
  cohortStat();
 
}
 
 
//Update Member's list
 
function updateMembers(){
 
  $('#cohortContStat').empty();
 
  var cohortId = $('.pickedCo .cohortTxtClass').text();
 
$.getJSON('/userData.php',{action:'listMembers',cohortName:cohortId},function(d){
 
 
});
 
}
 
 
//Click event on Member(student)
 
function clickMem(){
 
  $('.memberClass').removeClass('pickedMe');
 
  $(this).addClass('pickedMe');
 
}
 
 
//Member(student) statistics
 
function studentStat(){
 
 
 
  $('#memberCont').slideUp(500);
 
  var member = $('.pickedMe').text();
 
  var path = $('.pickedCo .pathNameClass').text();
 
  $('#memberCont').empty();
 
//Getting stat from DB
 
$.getJSON('/userData.php',{action:'statMember',path:path,member:member},function(d){
 
var table = $('<table/>',{id:'statMeTable'});
 
var trh = $('<tr/>',{id:'tHeaderMe'}).append('<th><span>TUTORIALS<br>AND<br>QUIZZES</span></th><th><span>SCORE</span></th><th><span>RESULTS</span></th>');
 
table.append(trh);
 
for (var i=0; i<d.tut.length; i++){
 
 
if(d.tut[i].flag=="q"){
 
var tr = $('<tr/>',{'class':'quizRow'});
 
}else{
 
var tr = $('<tr/>',{'class':'tutRow'});
 
}
 
var td = $('<td/>'); var te = $('<td/>'); var tf = $('<td/>');
 
 
td.append(d.tut[i].sname)
 
var resultObj = [];
 
resultObj = getObjects(d.statMe, 'Tutorials', d.tut[i].sname);
 
if(resultObj.length==0){
 
var res = '';
 
te.append(res);
 
tf.append(res);
 
tr.append(td).append(te).append(tf);
 
table.append(tr);
 
 
} else {
 
te.append(resultObj[0].Score);
 
tf.append(resultObj[0].Results);
 
 
tr.append(td).append(te).append(tf);
 
table.append(tr);
 
}  
 
}
 
 
$('#memberCont').append($('<div/>',{id:'memContHeader'})).append($('<div/>',{id:'divMeTable'}));
 
$('#divMeTable').append(table);
 
 
$('#memberCont').slideDown(500);
 
 
});
 
 
}
 
 
//Add students to a cohort
 
function addStudents(){
 
if($('.cohortClass').hasClass('pickedCo')){
 
var id = $('.pickedCo .cohortTxtClass').text();
 
var members = [];
 
$('body').append($('<div/>',{'class':'overlay'}));
 
$('#divPopup').show();
 
$('#divPopup').append($('<input/>',{'type':'button',value:'x',id:'btnClosePopup','class':'btnClass',click:function(){
 
$('.overlay').remove();
 
$('#divPopup').hide().empty();}}))
 
.append($('<div/>',{id:'popupCont'}))
 
.append($('<input/>',{'type':'button',value:'OK',id:'btnOkPopup','class':'btnClass',click:function(){
 
//Popup OK button stuff
 
members = $('#txtPopup').val();
 
$.getJSON('/userData.php',{action:'addStudent',wgUserName:wgUserName,cohortName:id,mem:members},function(d){
 
 
//cohortStat();
 
 
});
 
$('.overlay').remove();
 
$('#divPopup').hide().empty();
 
cohortStat();
 
}}));
 
 
$('#popupCont').append($('<textarea/>',{id:'txtPopup',rows:'10', cols:'10'}));
 
}else{
 
alert('Select a cohort!');
 
}
 
}
 
 
function delStudents(){
 
var stu = $('.pickedMe').text();
 
var cohort = $('.pickedCo .cohortTxtClass').text();
 
$('body').append($('<div/>',{'class':'overlay'}));
 
$('#divPopup').show().addClass('dialog');
 
$('#divPopup').append($('<input/>',{'type':'button',value:'x',id:'btnClosePopup','class':'btnClass',click:function(){
 
$('.overlay').remove();
 
$('#divPopup').removeClass('dialog').hide().empty()}}))
 
.append($('<div/>',{id:'textCont'}))
 
.append($('<div/>',{id:'popupCont'}))
 
 
var btn = $('<input/>',{'type':'button',value:'Yes',id:'btnOkPopup','class':'btnClass',click:function(){
 
//Popup - YES button stuff
 
$.getJSON('/userData.php',{action:'delStudent',student:stu,cohort:cohort},function(d){
 
 
});
 
$('.overlay').remove();
 
$('#memberCont').hide().empty();
 
cohortStat();
 
$('#divPopup').removeClass('dialog').hide().empty()}})
 
btn.appendTo('#popupCont');
 
 
btn =$('<input/>',{'type':'button',value:'No',id:'btnNoPop','class':'btnClass',click:function(){
 
$('.overlay').remove();
 
$('#divPopup').removeClass('dialog').hide().empty()}}) ;
 
btn.appendTo('#popupCont');
 
 
 
var textCont = $('<span/>',{id:'spanNoti', text:'Do you really want to remove student from cohort?'})
 
textCont.appendTo('#textCont');
 
 
 
 
 
}
 
 
//Getting Cohort statistics from DB
 
function cohortStat(){
 
var cohort = $('.pickedCo .cohortTxtClass').text();
 
var path = $('.pickedCo .pathNameClass').text();
 
if($('#cohortContStat').children().length > 0){
 
$('#cohortContStat').slideUp(500, function(){
 
 
});
 
}
 
 
//Getting stat from DB
 
 
$.getJSON('/userData.php',{action:'statCohort',cohortName:cohort,pathId:path},function(d){
 
 
if(d.stu.length > 0){
 
$('#cohortContStat').empty();
 
var table = $('<table/>',{id:'statCoTable'});
 
//Create the header of the table
 
var trh = $('<tr/>',{id:'tHeader'}).append("<th><span>Members</span></th>");
 
for(var i=0;i<d.tut.length;i++){
 
var th = $('<th/>');
 
if (d.tut[i].flag=="q"){
 
var aa = $('<span/>',{'class':"thQuizzies"});
 
aa.append(d.tut[i].sname);
 
}else{
 
var aa = $('<span/>');
 
aa.append(d.tut[i].sname);
 
}
 
th.append(aa);
 
 
trh.append(th);
 
table.append(trh);
 
}
 
 
//Adding data to table
 
for(var n=0;n<d.stu.length;n++){
 
var tr = $('<tr/>');
 
var name = d.stu[n].mem;
 
var ta = $('<td/>');
 
ta.append(name);
 
tr.append(ta);
 
var nameObj = [];
 
nameObj = getObjects(d.statCo, 'member', name); //Contains all results for 1 person
 
for(var j=0;j<d.tut.length;j++){
 
var tb = $('<td/>');
 
resultObj = []; //Contains result for a specific tutorial for 1 person
 
resultObj = getObjects(nameObj, 'Tutorials', d.tut[j].sname);
 
var ab = $('<span/>');
 
var ac = $('<span/>');
 
var perc = "";
 
var score = "";
 
if(resultObj.length ==0){ //If there is no result:
 
perc = '';
 
score = '';
 
ab.append(perc).addClass('perc');
 
ac.append(score).addClass('score')
 
tb.append(ab).append(ac);
 
tr.append(tb);
 
 
}else{
 
perc = resultObj[0].Results;
 
score = resultObj[0].Score;
 
ab.append(perc).addClass('perc');
 
ac.append(score).addClass('score')
 
tb.append(ab).append(ac);
 
tb.append(ab).append(ac);
 
tr.append(tb);
 
 
}
 
table.append(tr);
 
}
 
 
}
 
  
$('#cohortContStat').append($('<div/>',{id:'divTableHeader'})).append($('<div/>',{id:'divTable'}));
+
    //Add cohorts to list and DB
+
    function addCohorts() {
$('#divTable').append(table);
+
      if ($('#newCohortName').val() == "") {
$('.score').addClass('displayNone');
+
        alert("Type cohort name!")
colorCode();
+
      } else {
+
        var selVal = $('#selectPath').val();
$('#cohortContStat').delay(100).slideDown(500);
+
        var selPath = $('#selectPath option[value=' + selVal + ']').text();
//Student stat when clicking on student
+
        $.getJSON('/userData.php', {
$('#statCoTable tr td:first-child').addClass('memberClass');
+
          action: 'addCohort',
$('#statCoTable tr td:first-child').click(function(){
+
          wgUserName: wgUserName,
$('.memberClass').removeClass('pickedMe');
+
          cohortName: $('#newCohortName').val(),
$(this).addClass('pickedMe');
+
          selPath: selPath
+
        }, function (d) {
studentStat();
+
          updateCohorts();
+
        });
})
+
      }
}
+
    }
});
+
 
+
    //Updating the list of cohorts from DB
+
    function updateCohorts() {
}
+
      $('#cohorCont').slideUp(300);
//Color table cells depending on results
+
      $('#cohorCont').slideDown(300, function () {
function colorCode(){
+
        $('#cohorCont').empty();
$('#statCoTable tr td').not(':first-child').each(function() {
+
        $.getJSON('/userData.php', {
var res = $(this).find('.perc').html();
+
          action: 'listTeachersCohorts',
res = parseInt(res);
+
          wgUserName: wgUserName
if (res == ""){
+
        }, function (d) {
$(this).addClass('none')
+
          for (var i = 0; i < d.cohorts.length; i++) {
}else{
+
            var cohortList = $('<div/>', {
if (res === 100){
+
              'class': 'cohortClass',
$(this).addClass('perfect')
+
              id: 'divCo' + i,
} else if((79<res)&&(res<100)){
+
              click: clickListCo
$(this).addClass('good')
+
            })
} else if((49<res)&&(res<80)){
+
              .append("<span class='cohortTxtClass'>" + d.cohorts[i].id + "</span>")
$(this).addClass('medium')
+
              .append("<img src='/design/bin.png' name='divCo" + i + "' onClick=binClick(name) class='imgBin' title='Delete Cohort' alt='22'>")
}else if (res << 50){
+
              .append("<span class='pathNameClass'>" + d.cohorts[i].pathName + "</span>");
$(this).addClass('lazy')
+
            $('#cohorCont').append(cohortList);
}
+
          }
}
+
          if ($('#cohorCont>div').length > 0) {
});
+
            $('#cohorCont div:nth-child(1)').trigger('click');
+
          }
}
+
 
+
        });
//Change data appearence
+
        $('#newCohortName').val("");
function changeView(){
+
        $('#memberCont').empty().hide();
$('.perc').toggleClass('displayNone');
+
      });
$('.score').toggleClass('displayNone');
+
    }
}
+
 
+
    //Delete cohorts from list and DB
//Function to find results in Object ==> getObjects(objName, 'id', 'dataWhatYouLookingFor'); // Returns an array of matching objects
+
    function deleteCohorts() {
function getObjects(obj, key, val) {
+
      var id = $('.pickedCo .cohortTxtClass').text();
var objects = [];
+
 
for (var i in obj) {
+
      $.getJSON('/userData.php', {
if (!obj.hasOwnProperty(i)) continue;
+
        action: 'delCohort',
if (typeof obj[i] == 'object') {
+
        wgUserName: wgUserName,
objects = objects.concat(getObjects(obj[i], key, val));
+
        cohortName: id
} else if (i == key && obj[key] == val) {
+
      }, function (d) {
objects.push(obj);
+
 
}
+
      });
}
+
      updateCohorts();
return objects;
+
    }
}
+
 
+
    //Edit cohorts name  cohortClass
//Delete cohorts from list when clicking on img bin.
+
    function editCohorts() {
function binClick(name){
+
      var prevCo = $('.pickedCo .cohortTxtClass').text();
 
+
      var newCo = $('#newCohortName').val();
$('#divPopup').show().addClass('dialog');
+
 
$('#divPopup').append($('<input/>',{'type':'button',value:'x',id:'btnClosePopup','class':'btnClass',click:function(){
+
      $.getJSON('/userData.php', {
$('#divPopup').removeClass('dialog').hide().empty()}}))
+
        action: 'editCohort',
.append($('<div/>',{id:'textCont'}))
+
        oldCohort: prevCo,
.append($('<div/>',{id:'popupCont'}))
+
        cohortName: newCo
+
      }, function (d) {
var btn = $('<input/>',{'type':'button',value:'Yes',id:'btnOkPopup','class':'btnClass',click:function(){
+
 
//Popup OK button stuff
+
      });
$('#'+name).addClass('pickedCo');
+
      updateCohorts();
deleteCohorts();
+
    }
$('#divPopup').removeClass('dialog').hide().empty()}})
+
 
btn.appendTo('#popupCont');
+
    //Click event on Cohort list
+
    function clickListCo() {
btn =$('<input/>',{'type':'button',value:'No',id:'btnNoPop','class':'btnClass',click:function(){
+
      $('.cohortClass').removeClass('pickedCo');
$('#divPopup').removeClass('dialog').hide().empty()}}) ;
+
      $(this).addClass('pickedCo');
btn.appendTo('#popupCont');
+
      $('#btnDelCo').show();
+
      $('#btnStatCo').show();
+
      $('#btnAddStu').show();
var textCont = $('<span/>',{id:'spanNoti', text:'Do you really want to delete this cohort?'})
+
      $('#btnDelStu').show();
textCont.appendTo('#textCont');
+
      $('#btnEdCo').show();
$('#cohortContStat').hide().empty();
+
      $('#memberCont').slideUp(500, function () {
}
+
        $(this).empty();
+
      });
+
      var cohortId = $('.pickedCo .cohortTxtClass').text();
+
      $('#newCohortName').val(cohortId);
//////////////////*******Stuffs for 'user' *******////////////////////////
+
      cohortStat();
+
    }
+
 
+
    //Update Member's list
   } else if($.inArray('user', wgUserGroups) == 1){
+
    function updateMembers() {
$(function(){
+
      $('#cohortContStat').empty();
$('#bodyContent').prepend($('<div/>',{id:'content_2'}));
+
      var cohortId = $('.pickedCo .cohortTxtClass').text();
ownStat();
+
      $.getJSON('/userData.php', {
$('#content_2').show();
+
        action: 'listMembers',
})
+
        cohortName: cohortId
   }  
+
      }, function (d) {
 +
 
 +
      });
 +
    }
 +
 
 +
    //Click event on Member(student)
 +
    function clickMem() {
 +
      $('.memberClass').removeClass('pickedMe');
 +
      $(this).addClass('pickedMe');
 +
    }
 +
 
 +
    //Member(student) statistics
 +
    function studentStat() {
 +
 
 +
      $('#memberCont').slideUp(500);
 +
      var member = $('.pickedMe').text();
 +
      var path = $('.pickedCo .pathNameClass').text();
 +
      $('#memberCont').empty();
 +
      //Getting stat from DB
 +
      $.getJSON('/userData.php', {
 +
        action: 'statMember',
 +
        path: path,
 +
        member: member
 +
      }, function (d) {
 +
        var table = $('<table/>', {
 +
          id: 'statMeTable'
 +
        });
 +
        var trh = $('<tr/>', {
 +
          id: 'tHeaderMe'
 +
        }).append('<th><span>TUTORIALS<br>AND<br>QUIZZES</span></th><th><span>SCORE</span></th><th><span>RESULTS</span></th>');
 +
        table.append(trh);
 +
        for (var i = 0; i < d.tut.length; i++) {
 +
 
 +
          if (d.tut[i].flag == "q") {
 +
            var tr = $('<tr/>', {
 +
              'class': 'quizRow'
 +
            });
 +
          } else {
 +
            var tr = $('<tr/>', {
 +
              'class': 'tutRow'
 +
            });
 +
          }
 +
          var td = $('<td/>');
 +
          var te = $('<td/>');
 +
          var tf = $('<td/>');
 +
          td.append(d.tut[i].sname)
 +
          var resultObj = [];
 +
          resultObj = getObjects(d.statMe, 'Tutorials', d.tut[i].sname);
 +
          if (resultObj.length == 0) {
 +
            var res = '';
 +
            te.append(res);
 +
            tf.append(res);
 +
            tr.append(td).append(te).append(tf);
 +
            table.append(tr);
 +
          } else {
 +
            te.append(resultObj[0].Score);
 +
            tf.append(resultObj[0].Results);
 +
 
 +
            tr.append(td).append(te).append(tf);
 +
            table.append(tr);
 +
          }
 +
        }
 +
 
 +
        $('#memberCont').append($('<div/>', {
 +
          id: 'memContHeader'
 +
        })).append($('<div/>', {
 +
          id: 'divMeTable'
 +
        }));
 +
        $('#divMeTable').append(table);
 +
        $('#memberCont').slideDown(500);
 +
      });
 +
    }
 +
 
 +
    //Add students to a cohort
 +
    function addStudents() {
 +
      if ($('.cohortClass').hasClass('pickedCo')) {
 +
        var id = $('.pickedCo .cohortTxtClass').text();
 +
        var members = [];
 +
        $('body').append($('<div/>', {
 +
          'class': 'overlay'
 +
        }));
 +
        $('#divPopup').show();
 +
        $('#divPopup').append($('<input/>', {
 +
          'type': 'button',
 +
          value: 'x',
 +
          id: 'btnClosePopup',
 +
          'class': 'btnClass',
 +
          click: function () {
 +
            $('.overlay').remove();
 +
            $('#divPopup').hide().empty();
 +
          }
 +
        }))
 +
          .append($('<div/>', {
 +
            id: 'popupCont'
 +
          }))
 +
          .append($('<input/>', {
 +
            'type': 'button',
 +
            value: 'OK',
 +
            id: 'btnOkPopup',
 +
            'class': 'btnClass',
 +
            click: function () {
 +
              //Popup OK button stuff
 +
              members = $('#txtPopup').val();
 +
              $.getJSON('/userData.php', {
 +
                action: 'addStudent',
 +
                wgUserName: wgUserName,
 +
                cohortName: id,
 +
                mem: members
 +
              }, function (d) {
 +
                //cohortStat();
 +
              });
 +
              $('.overlay').remove();
 +
              $('#divPopup').hide().empty();
 +
              cohortStat();
 +
            }
 +
          }));
 +
        $('#popupCont').append($('<textarea/>', {
 +
          id: 'txtPopup',
 +
          rows: '10',
 +
          cols: '10'
 +
        }));
 +
      } else {
 +
        alert('Select a cohort!');
 +
      }
 +
    }
 +
 
 +
    function delStudents() {
 +
      var stu = $('.pickedMe').text();
 +
      var cohort = $('.pickedCo .cohortTxtClass').text();
 +
      $('body').append($('<div/>', {
 +
        'class': 'overlay'
 +
      }));
 +
      $('#divPopup').show().addClass('dialog');
 +
      $('#divPopup').append($('<input/>', {
 +
        'type': 'button',
 +
        value: 'x',
 +
        id: 'btnClosePopup',
 +
        'class': 'btnClass',
 +
        click: function () {
 +
          $('.overlay').remove();
 +
          $('#divPopup').removeClass('dialog').hide().empty()
 +
        }
 +
      }))
 +
        .append($('<div/>', {
 +
          id: 'textCont'
 +
        }))
 +
        .append($('<div/>', {
 +
          id: 'popupCont'
 +
        }))
 +
 
 +
      var btn = $('<input/>', {
 +
        'type': 'button',
 +
        value: 'Yes',
 +
        id: 'btnOkPopup',
 +
        'class': 'btnClass',
 +
        click: function () {
 +
          //Popup - YES button stuff
 +
          $.getJSON('/userData.php', {
 +
            action: 'delStudent',
 +
            student: stu,
 +
            cohort: cohort
 +
          }, function (d) {});
 +
          $('.overlay').remove();
 +
          $('#memberCont').hide().empty();
 +
          cohortStat();
 +
          $('#divPopup').removeClass('dialog').hide().empty()
 +
        }
 +
      })
 +
      btn.appendTo('#popupCont');
 +
 
 +
      btn = $('<input/>', {
 +
        'type': 'button',
 +
        value: 'No',
 +
        id: 'btnNoPop',
 +
        'class': 'btnClass',
 +
        click: function () {
 +
          $('.overlay').remove();
 +
          $('#divPopup').removeClass('dialog').hide().empty()
 +
        }
 +
      });
 +
      btn.appendTo('#popupCont');
 +
 
 +
      var textCont = $('<span/>', {
 +
        id: 'spanNoti',
 +
        text: 'Do you really want to remove student from cohort?'
 +
      })
 +
      textCont.appendTo('#textCont');
 +
    }
 +
 
 +
    //Getting Cohort statistics from DB
 +
    function cohortStat() {
 +
      var cohort = $('.pickedCo .cohortTxtClass').text();
 +
      var path = $('.pickedCo .pathNameClass').text();
 +
      if ($('#cohortContStat').children().length > 0) {
 +
        $('#cohortContStat').slideUp(500, function () {
 +
        });
 +
      }
 +
 
 +
      //Getting stat from DB
 +
 
 +
      $.getJSON('/userData.php', {
 +
        action: 'statCohort',
 +
        cohortName: cohort,
 +
        pathId: path
 +
      }, function (d) {
 +
        if (d.stu.length > 0) {
 +
          $('#cohortContStat').empty();
 +
          var table = $('<table/>', {
 +
            id: 'statCoTable'
 +
          });
 +
          //Create the header of the table
 +
          var trh = $('<tr/>', {
 +
            id: 'tHeader'
 +
          }).append("<th><span>Members</span></th>");
 +
          for (var i = 0; i < d.tut.length; i++) {
 +
            var th = $('<th/>');
 +
            if (d.tut[i].flag == "q") {
 +
              var aa = $('<span/>', {
 +
                'class': "thQuizzies"
 +
              });
 +
              aa.append(d.tut[i].sname);
 +
            } else {
 +
              var aa = $('<span/>');
 +
              aa.append(d.tut[i].sname);
 +
            }
 +
            th.append(aa);
 +
            trh.append(th);
 +
            table.append(trh);
 +
          }
 +
 
 +
          //Adding data to table
 +
          for (var n = 0; n < d.stu.length; n++) {
 +
            var tr = $('<tr/>');
 +
            var name = d.stu[n].mem;
 +
            var ta = $('<td/>');
 +
            ta.append(name);
 +
            tr.append(ta);
 +
            var nameObj = [];
 +
            nameObj = getObjects(d.statCo, 'member', name); //Contains all results for 1 person
 +
            for (var j = 0; j < d.tut.length; j++) {
 +
              var tb = $('<td/>');
 +
              resultObj = []; //Contains result for a specific tutorial for 1 person
 +
              resultObj = getObjects(nameObj, 'Tutorials', d.tut[j].sname);
 +
              var ab = $('<span/>');
 +
              var ac = $('<span/>');
 +
              var perc = "";
 +
              var score = "";
 +
              if (resultObj.length == 0) { //If there is no result:
 +
                perc = '';
 +
                score = '';
 +
                ab.append(perc).addClass('perc');
 +
                ac.append(score).addClass('score')
 +
                tb.append(ab).append(ac);
 +
                tr.append(tb);
 +
              } else {
 +
                perc = resultObj[0].Results;
 +
                score = resultObj[0].Score;
 +
                ab.append(perc).addClass('perc');
 +
                ac.append(score).addClass('score')
 +
                tb.append(ab).append(ac);
 +
                tb.append(ab).append(ac);
 +
                tr.append(tb);
 +
              }
 +
              table.append(tr);
 +
            }
 +
          }
 +
 
 +
          $('#cohortContStat').append($('<div/>', {
 +
            id: 'divTableHeader'
 +
          })).append($('<div/>', {
 +
            id: 'divTable'
 +
          }));
 +
 
 +
          $('#divTable').append(table);
 +
          $('.score').addClass('displayNone');
 +
          colorCode();
 +
 
 +
          $('#cohortContStat').delay(100).slideDown(500);
 +
          //Student stat when clicking on student
 +
          $('#statCoTable tr td:first-child').addClass('memberClass');
 +
          $('#statCoTable tr td:first-child').click(function () {
 +
            $('.memberClass').removeClass('pickedMe');
 +
            $(this).addClass('pickedMe');
 +
            studentStat();
 +
          })
 +
        }
 +
      });
 +
    }
 +
    //Color table cells depending on results
 +
    function colorCode() {
 +
      $('#statCoTable tr td').not(':first-child').each(function () {
 +
        var res = $(this).find('.perc').html();
 +
        res = parseInt(res);
 +
        if (res == "") {
 +
          $(this).addClass('none')
 +
        } else {
 +
          if (res === 100) {
 +
            $(this).addClass('perfect')
 +
          } else if ((79 < res) && (res < 100)) {
 +
            $(this).addClass('good')
 +
          } else if ((49 < res) && (res < 80)) {
 +
            $(this).addClass('medium')
 +
          } else if (res << 50) {
 +
            $(this).addClass('lazy')
 +
          }
 +
        }
 +
      });
 +
    }
 +
 
 +
    //Change data appearence
 +
    function changeView() {
 +
      $('.perc').toggleClass('displayNone');
 +
      $('.score').toggleClass('displayNone');
 +
    }
 +
 
 +
    //Delete cohorts from list when clicking on img bin.
 +
    function binClick(name) {
 +
 
 +
      $('#divPopup').show().addClass('dialog');
 +
      $('#divPopup').append($('<input/>', {
 +
        'type': 'button',
 +
        value: 'x',
 +
        id: 'btnClosePopup',
 +
        'class': 'btnClass',
 +
        click: function () {
 +
          $('#divPopup').removeClass('dialog').hide().empty()
 +
        }
 +
      }))
 +
        .append($('<div/>', {
 +
          id: 'textCont'
 +
        }))
 +
        .append($('<div/>', {
 +
          id: 'popupCont'
 +
        }))
 +
 
 +
      var btn = $('<input/>', {
 +
        'type': 'button',
 +
        value: 'Yes',
 +
        id: 'btnOkPopup',
 +
        'class': 'btnClass',
 +
        click: function () {
 +
          //Popup OK button stuff
 +
          $('#' + name).addClass('pickedCo');
 +
          deleteCohorts();
 +
          $('#divPopup').removeClass('dialog').hide().empty()
 +
        }
 +
      })
 +
      btn.appendTo('#popupCont');
 +
 
 +
      btn = $('<input/>', {
 +
        'type': 'button',
 +
        value: 'No',
 +
        id: 'btnNoPop',
 +
        'class': 'btnClass',
 +
        click: function () {
 +
          $('#divPopup').removeClass('dialog').hide().empty()
 +
        }
 +
      });
 +
      btn.appendTo('#popupCont');
 +
 
 +
      var textCont = $('<span/>', {
 +
        id: 'spanNoti',
 +
        text: 'Do you really want to delete this cohort?'
 +
      })
 +
      textCont.appendTo('#textCont');
 +
      $('#cohortContStat').hide().empty();
 +
    }
 +
    //////////////////*******Stuffs for 'user' *******////////////////////////
 +
   } else if ($.inArray('user', wgUserGroups) == 1) {
 +
    $(function () {
 +
      $('#bodyContent').prepend($('<div/>', {
 +
        id: 'content_2'
 +
      }));
 +
      ownStat();
 +
      $('#content_2').show();
 +
    })
 +
   }
 
}
 
}

Revision as of 23:38, 6 March 2014

//Common.js original
/* Any JavaScript here will be loaded for all users on every page load. */
var numberOfQuestions = 0;
var numberOfAnswered = 0;
var numberOfCorrect = 0;

//Function to find results in Object ==> getObjects(objName, 'id', 'dataWhatYouLookingFor'); // Returns an array of matching objects
function getObjects(obj, key, val) {
  var objects = [];
  for (var i in obj) {
    if (!obj.hasOwnProperty(i)) continue;
    if (typeof obj[i] == 'object') {
      objects = objects.concat(getObjects(obj[i], key, val));
    } else if (i == key && obj[key] == val) {
      objects.push(obj);
    }
  }
  return objects;
}

$(function () {
  //Display Path in sidebar (Istvan)
  //GET COHORT
  if ($.inArray('user', wgUserGroups) >= 0) {
    $.getJSON('/userData.php', {
      action: 'userCohort',
      wgUserName: wgUserName
    }, function (d) {
      //IF the user is member of a cohort create a different menu.
      if (d.cohort.length > 0) {
        var divPathMenu = $($('<div/>', {
          id: 'divSlideCont'
        })).append($('<div/>', {
          id: 'divPathMenuCont'
        }));
        var pathMenu = $('<div class="portal"/>').append(divPathMenu);
        $('#p-Reference').before(pathMenu);

        function createPath(cohort) {
          $.getJSON('/userData.php', {
            action: 'userPath',
            cohort: cohort
          }, function (e) {
            $('#divPathMenuCont').css({
              'background': 'none'
            });
            var path = e.path[0].pathName;
            $('#divPathMenuCont').empty();
            $.getJSON('/userData.php', {
              action: 'menuDb',
              path: path,
              member: wgUserName
            }, function (f) {
              var ul = $('<ul/>', {
                id: 'cohortMenu',
                'class': 'dropdown mm_sub'
              });
              for (var i = 0; i < f.tut.length; i++) {
                var NoCObj = [];
                var NoQObj = [];
                var NoCs = 0; //NumberOfCorrect answers
                var NoQs = 0; //NumberOfQuestions in a tutorial
                NoQObj = getObjects(f.maxCor, 'wikipage', f.tut[i].wikipage);
                NoCObj = getObjects(f.statMe, 'sname', f.tut[i].sname);
                if (NoCObj.length == 0) {
                  NoCs = 0;
                } else {
                  NoCs = parseInt(NoCObj[0].correct);
                }
                NoQs = parseInt(NoQObj[0].maxCor);
                var maxWidth = 29.2; // adjust the value so that it fits menu well
                var pbWidth = parseFloat(maxWidth) * NoCs / NoQs;
                var mprogbar = $('<div/>', {
                  'class': 'progressbarbg1'
                }).append($('<div/>', {
                  'class': 'progressbar1',
                  'id': f.tut[i].wikipage,
                  css: {
                    'width': pbWidth
                  }
                }));
                ul.append($('<li/>').append($('<a/>', {
                  'class': 'pathTxta',
                  href: '/wiki/' + f.tut[i].wikipage,
                  text: f.tut[i].sname
                })).append(mprogbar));
              }
              $('#divPathMenuCont')
                .append($('<div class=body/>')
                  .append(ul)
              )
                .append($("<table id='pathMenuTable'><tr><td>Cohort: </td><td>" + cohort + "</td></tr><tr><td>Path: </td><td>" + path + "</td></tr><tr><td>Teacher: </td><td>" + e.path[0].teacher + "</td></tr></table>"))
                .append($('<div/>', {
                  'class': 'divClear'
                }));
              if (d.cohort.length > 1) {
                $('#divPathMenuCont').append($('<div/>', {
                  id: 'divBtns'
                })).append($('<div/>', {
                  'class': 'divClear'
                }));
                $('#divBtns')
                  .append('<div class="dwnBtnClass"></div>') //<img id="dwnBtn" src="/design/dwnArrow_black.png" />
                .append('<div class="upBtnClass"></div>'); //<img id="upBtn" src="/design/upArrow_black.png" />
              }
            });
          });
        }

        function getCohort(index) {
          var cohort = d.cohort[index].id;
          createPath(cohort);
        }

        var index = 0;
        getCohort(index);

        $('div.upBtnClass').live("click", function () {
          var maxIndex = d.cohort.length - 1;
          if (index >= maxIndex) {
            index = maxIndex;
          } else {
            index = index + 1;
            getCohort(index);
          }
        });

        $('div.dwnBtnClass').live("click", function () {
          var minIndex = 0;
          if (index <= minIndex) {
            index = 0;
          } else {
            index = index - 1;
            getCohort(index);
          }
        });
      }
    });
  }

  var engine = $('<div class="portal"/>')
    .append($('<div id="engineTxt"><h5>Engine</h5></div>'))
    .append($('<div id="engineSel" class="body"/>')
      .append($('<ul/>')
        .append($('<li/>')
          .append($('<select id=engine/>')
            .append('<option value=mysql>MySQL</option>')
            .append('<option value=oracle>Oracle</option>')
            .append('<option value=sqlserver>SQL Server</option>')
            .append('<option value=postgres>PostgreSQL</option>')
            .append('<option id=ingres>Ingres</option>')
            .append('<option id=db2>DB2</option>')
          )
        )
      )
  )

  $('#right-navigation').after($('<ul/>', {
      'id': 'zoolinks'
    })
    .append($('<li/>').append($('<a/>', {
      href: 'http://csszoo.net',
      text: 'CSS',
      id: 'css_link',
      title: 'Learn CSS! visit CSSzoo'
    })))
    .append($('<li/>').append($('<a/>', {
      href: 'http://progzoo.net',
      text: 'Java',
      id: 'java_link',
      title: 'Hungry for Java tutorials? ProgZoo is for you'
    })))
    .append($('<li/>').append($('<a/>', {
      href: 'http://linuxzoo.net',
      text: 'Linux',
      id: 'linux_link',
      title: 'Linux Zoo tutoials!'
    })))
    .append($('<li/>', {
      'id': 'book'
    }).append($('<a/>', {
      href: 'http://www.oreilly.com/catalog/sqlhks/',
      id: 'sql_hacks',
      title: 'Try/buy SQL Hacks book'
    })))
  );

  $('#p-Reference').before(engine);

  //Adverts
  $('<img/>', {
    src: '/design/sqlhacks.png',
    alt: 'SQL Hacks book ad'
  })
    .appendTo($('#sql_hacks'));
  $('#p-googleadsense').prependTo('#footer');

  if (wgCanonicalNamespace == 'MediaWiki' || wgCanonicalNamespace == 'Special')
    $('#p-googleadsense').hide();

  var startAt = Math.max(1, $('#startAt').text() * 1);
  var qu = $('.qu,.ht,.err');

  //Hints
  var hint = $('.hint', q);
  hint.hide();
  hint.each(function () {
    var htitle = $(this).attr("title");
    var hnt = $('<div/>', {
      'class': 'hnt',
      'text': htitle
    });
    var hidden = $(this);
    hnt.click(function (e) {
      e.preventDefault();
      hidden.toggle("slow");
    });
    $(this).before(hnt);
  });

  for (var i = 0; i < qu.length; i++) {
    var id = i + 1;
    var q = qu[i];
    var lsName = wgPageName + '_' + 'frm__' + id;
    var def = $('.def', q);
    if (def.length > 1) {
      var pick = def.filter(function () {
        var clss = $(this).attr('class').split(' ');
        for (var k = 0; k < clss.length; k++)
          if (clss[k].match("^e-")) return false;
        return true
      });
      for (var j = 0; j < def.length; j++)
        if ($(def[j]).hasClass('e-' + curEng))
          pick = $(def[j]);
      def = pick;
    }
    var txt = def.text();
    // replace the default text with user's last query if available in LS
    if (localStorage.getItem(lsName + "_arr_" + curEng)) {
      var lsArray = JSON.parse(localStorage.getItem(lsName + "_arr_" + curEng));
      txt = lsArray[lsArray.length - 1];
    }

    var ans = $('.ans', q).text();
    var tdy = $('.tidy', q).text();
    var frm = $('<form/>', {
      name: 'frm__' + id,
      id: 'frm__' + id
    })
      .append($('<div/>', {
          'class': 'quf'
        })
        .append($('<textarea></textarea>', {
          value: $.trim(txt),
          rows: 2 + Math.max(Math.max(4, txt.split(/[\n\r]+/).length), ans.split(/[\n\r]+/).length),
          cols: 2 + Math.max(Math.max(45, maxlen(txt.split(/[\n\r]+/))), maxlen(ans.split(/[\n\r]+/))),
          'class': 'sql',
          id: 'txtar_' + id
        }))
        .append($('<br/>'))
        .append($('<button/>', {
          text: 'Submit SQL',
          'class': 'submitSQL',
          click: goBaby
        }))
        .append($('<div/>', {
          text: 'Restore default',
          'class': 'reset',
          click: function () {
            var qu = $(this).parents('.qu, .ht, .err');
            var def = $('.def', qu);
            var txt = findBestDefText(qu, $('#engine').val());
            qu.find('textarea.sql').val(txt);
          }
        }))
    );

    def.after(frm);
    var lhs = $('<div/>', {
      css: {
        width: '60ex',
        marginRight: '2ex',
        'float': 'left'
      }
    });
    lhs.append($('<span/>', {
      text: (startAt + i) + '.',
      'class': 'id'
    }));
    lhs.append($(q).children());
    $(q).append(lhs);
    $(q).append($('<div/>', {
      text: 'result',
      'class': 'res'
    }));

    //Show additional info if available for active angine
    var ecomm = $('.ecomm,.link', q);
    var ecomm1 = ecomm.filter(false);
    if (ecomm.length > 0) {
      var curEng = $('#engine').val();
      for (var j = 0; j < ecomm.length; j++)
        if ($(ecomm[j]).hasClass('e-' + curEng))
          ecomm1 = $(ecomm[j]);
    }
    for (var j = 0; j < ecomm.length; j++) {
      if ($(ecomm[j]).get(0) == ecomm1.get(0)) {
        $(ecomm[j]).show();
      } else {
        $(ecomm[j]).hide();
      }
    }

    var ecomm = $('.link', q);
    var ecomm1 = def.filter(function () {
      var clss = $(this).attr('class').split(' ');
      for (var k = 0; k < clss.length; k++)
        if (clss[k].match("^e-")) return false;
      return true
    });
    if (ecomm.length > 0) {
      var curEng = $('#engine').val();
      for (var j = 0; j < ecomm.length; j++)
        if ($(ecomm[j]).hasClass('e-' + curEng))
          ecomm1 = $(ecomm[j]);
    }
    for (var j = 0; j < ecomm.length; j++) {
      if ($(ecomm[j]).get(0) == ecomm1.get(0)) {
        $(ecomm[j]).show();
      } else {
        $(ecomm[j]).hide();
      }
    }
    numberOfQuestions = id;
  }

  if (numberOfQuestions == 0)
    numberOfQuestions = 1;
  //Put in the answers if url includes answer=1
  if (window.location.search && /answer/.test(window.location.search)) {
    $('<def/>', {
      text: "Cheat mode",
      css: {
        position: 'fixed',
        right: '2ex',
        bottom: '2ex',
        width: '14ex',
        backgroundColor: 'yellow',
        padding: '2ex',
        textAlign: 'center'
      }
    })
      .appendTo($('body'));
    $('.quf textarea').each(function () {
      $(this).val($(this).closest('form').next('.ans').text());
    })
  }

  //Fill in default answers
  if (wgUserName && wgPageName) {
    $.getJSON('/userData.php', {
      action: 'getMostRecent',
      wgUserName: wgUserName,
      wgPageName: wgPageName
    }, function (d) {
      for (var i = 0; i < d.ret.length; i++) {
        var q = d.ret[i].question.split('#');
        q = q[1].replace('.', '');
        var ta = $('#frm__' + q + ' div.quf textarea');
        ta.val(d.ret[i].txt);
        if (d.ret[i].score == 100)
          showCorrect($('#frm__' + q).parents('.qu,.ht,.err'));
      }
    });
  }
})
//Find the text that best matches the specified engine
//The div.qu (or div.ht) node contains a number of div.def
//These may be specific to an engine in which case they have one or more e-sqlserver e-mysql classes
function findBestDefText(quNode, engine) {
  var def = $('.def', q);
  if (def.length == 0) return "";
  if (def.length == 1) return def.text();
  var perfect = $('.def.e-' + engine)
  if (perfect.length == 1) return perfect.text();
  for (var k = 0; k < def.length; k++) {
    if (!$(def[i]).attr('class').match('e-'))
      return $(def[i]).text();
  }
  //No match found, no default found - just give the first one
  return $(def[0]).text();
}

function updateProgressbar() {
  var numberOfQuestions = parseInt(localStorage.getItem(wgPageName + '_numberOfQuestions'));
  // A little workaround - max progressbar width is 96% of its background's width
  var maxWidth = parseFloat($('.progressbarbg').css('width')) * 0.96;
  //var barModification = parseFloat($('.progressbar').css('width')) + maxWidth * 1 / numberOfQuestions;
  //$('.progressbar').css('width', barModification);
  numberOfCorrect = $('div.qcorrect').length;
  numberOfAnswered = $('div.qincorrect').length;
  numberOfQuestions = $('div.qu').length;

  // Display completion info
  $(".summary").html("There are " + numberOfQuestions + " questions on this page.<br/>" + numberOfCorrect + " of your answers were correct.");
  // Save completion info
  if (localStorage) {
    localStorage.setItem(wgPageName + '_numberOfQuestions', numberOfQuestions);
    localStorage.setItem(wgPageName + '_numberOfCorrect', numberOfCorrect);
  }

  //Progress bar

  var barModification = parseFloat(maxWidth) * numberOfCorrect / numberOfQuestions;
  $('.progressbar').css('width', barModification);

  //Progress bar in main menu
  var maxWidth = 50;
  pbWidth = parseFloat(maxWidth) * numberOfCorrect / numberOfQuestions;

  var barId = $('#firstHeading').text().replace(/\ /g, '_');
  $("#" + barId).css('width', pbWidth);

  //Progress bars in Path Menu
  var wikipage = window.location.pathname;
  wikipage = wikipage.split('/');

  var path = $('#pathNameTxt').text();
  var NoCs = 0;
  var NoQs = 0;

  $.getJSON('/userData.php', {
    action: 'updProgressBar',
    wgUserName: wgUserName,
    path: path,
    wikipage: wikipage[2]
  }, function (d) {
    if (d.corr.length > 0) {
      NoCs = parseInt(d.corr[0].correct);
      NoQs = parseInt(d.maxCor[0].maxCor);
      var maxWidthp = 29.2;
      var pbWidthp = parseFloat(maxWidthp) * NoCs / NoQs;
      $('#' + wikipage[2]).css('width', pbWidthp);
    }
  });
}

function goBaby() {
  var qu = $(this).parents('.qu, .ht, .err');
  var lsUse = ((qu[0].getAttribute('class') != 'ht') && ($(qu[0]).find('.ans').length > 0));
  var lsName = wgPageName + '_' + $(this).parents('form').attr('id');
  var sql = qu.find('textarea.sql').val();
  var parlst = $('.params').text().split(';');
  var params = {};
  for (var i = 0; i < parlst.length; i++) {
    var pair = parlst[i].split(':');
    params[pair[0]] = pair[1];
  }
  qu.find('.res').addClass('waiting');
  $.ajax({
    url: '/sqlgo.pl',
    cache: false,
    'type': 'post',
    dataType: 'json',
    data: {
      sql: sql.replace(/\xA0/g, ' '), //Mediawiki inserts &nbsp; before a %. We need to change it back to a space.CM 13/6/12
      format: 'json',
      question: $('.id', qu).text(),
      wgUserName: wgUserName,
      cookie: $.cookie('oliver'),
      page: wgPageName,
      server: $('#engine').val(),
      setup: $('.setup', qu).text().replace(/\xA0/g, ' '),
      tidy: $('.tidy', qu).text().replace(/\xA0/g, ' '),
      answer: $('.ans', qu).text().replace(/\xA0/g, ' '),
      schema: params['schema']
    },
    success: function (d) {
      var res = qu.find('.res');
      res.empty().removeClass('waiting')
      if (d.error) {
        res.append($('<h1/>', {
          text: 'SQLZoo System Error:'
        }))
        res.append($('<div/>', {
          text: d.error
        }))
        return;
      }
      var headerPresent = false;
      for (var i = 0; i < d.sql.length; i++) {
        if (!d || !d.sql || !d.sql[i]) {
          res.append($('<h1/>', {
            text: 'SQLZoo System Error:'
          }))
          res.append($('<div/>', {
            text: "Problem with d or d.sql or d.sql[0]"
          }))
          return;
        }
        if (d.sql[i].error) {
          res.append($('<h1/>', {
            text: 'Error:'
          }))
          res.append($('<div/>', {
            text: d.sql[i].error
          }))
          return;
        }
        var legend = "Result:";
        if (d.score && d.answer && d.answer.length == 1 && d.answer[0].fields) {
          if (d.score == 100)
            legend = showCorrect(qu);
          else if (d.answer[0].fields.length > d.sql[0].fields.length)
            legend = 'Too few columns';
          else if (d.answer[0].fields.length < d.sql[0].fields.length)
            legend = 'Too many columns';
          else if (d.answer[0].rows.length > d.sql[0].rows.length)
            legend = 'Too few rows';
          else if (d.answer[0].rows.length < d.sql[0].rows.length)
            legend = 'Too many rows';
        }
        if (!headerPresent) {
          res.append($('<h1/>', {
            text: legend
          }));
          headerPresent = true;
        }
        var t = mkTable(d.sql[i]);
        t.addClass('sqlmine')
          .appendTo(res);
        if (d.answer && d.answer.length > 0 && d.score < 100) {
          res.append($('<div/>', {
              text: 'Show correct result',
              'class': 'showtxt'
            })
            .click(function () {
              $(this).next().show('slow');
            })
          );
          var a = mkTable(d.answer[0]);
          a.addClass('sqlans');
          a.appendTo(res);
        }
      } //End of success of goBaby
    },
    error: function (jqXHR, textStatus, errorThrown) {
      qu.find('.res').empty().removeClass('waiting')
        .append($('<h1/>', {
          'class': 'syserr',
          text: 'SQLZOO system error:'
        }))
        .append($('<div/>', {
          text: textStatus
        }))
        .append($('<div/>', {
          text: errorThrown
        }))
        .append($('<div/>').html(jqXHR.responseText))
    }
  });
  return false;
} //GoBaby
function showCorrect(qu) {
  var legend = 'Correct answer';
  var def = $('.def', qu);
  if ($(".qcorrect", qu).length == 0) {
    var qcorr = $('<div/>', {
      'class': 'qcorrect',
      'title': 'You have answered this question correctly.'
    });
    def.before(qcorr);
  }
  return legend;
}

function maxlen(l) {
  var r = 0;
  for (var i = 0; i < l.length; i++)
    r = Math.max(r, l[i].length);
  return r;
}

function truncate(s) {
  if (s.length < 15) return s;
  return s.substring(0, 13) + "..";
}

function mkTable(a) {
  var t = $('<table/>');
  t.append($('<tr/>'));
  var isnum = [];
  if (!a.fields || !a.rows) return t;
  for (var i = 0; i < a.fields.length; i++) {
    $('tr', t).append($('<th/>', {
      text: truncate(a.fields[i])
    }));
    var allNum = 1;
    for (var j = 0; j < a.rows.length; j++) {
      if (a.rows[j] && a.rows[j][i] && (typeof a.rows[j][i] == "string") && !a.rows[j][i].match(/^[0-9.]*$/))
        allNum = 0;
    }
    isnum.push(allNum);
  }
  for (var j = 0; j < a.rows.length; j++) {
    var tr = $('<tr/>').appendTo(t);
    for (var k = 0; k < a.rows[j].length; k++) {
      var td = $('<td/>', {
        text: a.rows[j][k]
      });
      if (isnum[k]) td.addClass('r');
      td.appendTo(tr);
    }
  }
  return t;
}

/* ======================= Designer js starts here */

// the following scripts should not be present here - they should be linked as external files !!!

// this script helps to manage browser inconsistency across different os
function css_browser_selector(u) {
  var ua = u.toLowerCase(),
    is = function (t) {
      return ua.indexOf(t) > -1
    }, g = 'gecko',
    w = 'webkit',
    s = 'safari',
    o = 'opera',
    m = 'mobile',
    h = document.documentElement,
    b = [(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? g + ' ff2' : is('firefox/3.5') ? g + ' ff3 ff3_5' : is('firefox/3.6') ? g + ' ff3 ff3_6' : is('firefox/3') ? g + ' ff3' : is('gecko/') ? g : is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 : (/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) : is('konqueror') ? 'konqueror' : is('blackberry') ? m + ' blackberry' : is('android') ? m + ' android' : is('chrome') ? w + ' chrome' : is('iron') ? w + ' iron' : is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') : is('mozilla/') ? g : '', is('j2me') ? m + ' j2me' : is('iphone') ? m + ' iphone' : is('ipod') ? m + ' ipod' : is('ipad') ? m + ' ipad' : is('mac') ? 'mac' : is('darwin') ? 'mac' : is('webtv') ? 'webtv' : is('win') ? 'win' + (is('windows nt 6.0') ? ' vista' : '') : is('freebsd') ? 'freebsd' : (is('x11') || is('linux')) ? 'linux' : '', 'js'];
  c = b.join(' ');
  h.className += ' ' + c;
  return c;
};
css_browser_selector(navigator.userAgent);

// display site description
// display site logo
$(function () {
  $('<a/>', {
    href: 'http://sqlzoo.net/w/index.php',
    id: 'mp-logo',
    title: 'Zoo You!'
  })
    .append($('<img/>', {
      id: 'logoImg',
      src: '/design/sql_zoo_logo05.png',
      alt: 'SQLzoo logo'
    }))
    .appendTo($('#mw-head-base'))
  $("#mp-logo").append(" <h2 id='logo-desc'>Interactive <span>SQL <span>Tutorial</span></span></h2>");
  // assemble and display main nav menu
  //Original dropdown menu starts from here or backup common.js_29.7.13.js
  var ml1 = [
    ['1 SELECT basics', 'SELECT_basics', 'Some simple queries to get you started'],
    ['2 SELECT from WORLD', 'SELECT_from_WORLD_Tutorial', 'Finding facts about countries'],
    ['3 SELECT from Nobel', 'SELECT_from_Nobel_Tutorial', 'More practice with SELECT statements'],
    ['4 SELECT within SELECT', 'SELECT_within_SELECT_Tutorial', 'Using the results of one query inside another'],
    ['5 SUM and COUNT', 'SUM_and_COUNT', 'Apply aggregate functions'],
    ['6 JOIN', 'The_JOIN_operation', 'Gathering data from more than one table'],
    ['7 More JOIN', 'More_JOIN_operations', 'Getting data from the movie database'],
    ['8 Using NULL', 'Using_Null', 'Dealing with missing data'],
    ['9 Self JOIN', 'Self_join', 'Dealing with missing data'],
    ['10 SQL Quizzes', 'Tutorial_Quizzes', 'Test your knowledge with multiple choice quizzes']
  ];
  var mm1 = $('<ul/>', {
    id: 'mm1',
    'class': 'dropdown mm_sub'
  });
  //Adding progress bar to the menu
  for (var i = 0; i < ml1.length; i++) {
    var maxWidth = 50; // adjust the value so that it fits menu well
    var NoQ = localStorage.getItem(ml1[i][1] + '_numberOfQuestions');
    if (!NoQ) NoQ = 1;
    var NoC = localStorage.getItem(ml1[i][1] + '_numberOfCorrect');
    if (!NoC) NoC = 0;
    var pbWidth = parseFloat(maxWidth) * NoC / NoQ;
    var mprogbar = $('<div/>', {
      'class': 'progressbarbg1'
    }).append($('<div/>', {
      'class': 'progressbar1',
      'id': ml1[i][1],
      css: {
        'width': pbWidth
      }
    }));
    mm1.append($('<li/>').append($('<a/>', {
      href: '/wiki/' + ml1[i][1],
      text: ml1[i][0]
    })).append(ml1[i][2]).append(mprogbar));
  }
  var mm2 = $('<ul/>', {
    id: 'mm2',
    'class': 'dropdown mm_sub'
  });
  mm2.append('<li><a href="/wiki/AdventureWorks">1 AdventureWorks</a> Flogging sports gear. Assessment for CO22008 2007/8</li>');
  mm2.append('<li><a href="/wiki/Neeps">2 Neeps</a> A timetable database</li>');
  mm2.append('<li><a href="/wiki/Musicians">3 Musicians</a> Concerts and compositions</li>');
  mm2.append('<li><a href="/wiki/Southwind">4 Southwind</a> Buying and selling</li>');
  mm2.append('<li><a href="/wiki/Dressmaker">5 Dressmaker</a> Constructing clothing</li>');
  mm2.append('<li><a href="/wiki/Congestion Charging">6 Congestion Charging</a> Monitoring traffic (old questions)</li>');

  var mm3 = $('<ul/>', {
    id: 'mm3',
    'class': 'dropdown mm_sub'
  });
  mm3.append('<li><a href="/wiki/SELECT_Reference">SELECT</a>How to read the data from a database.</li>');
  mm3.append('<li><a href="/wiki/CREATE_and_DROP_Reference">CREATE and DROP</a>How to create tables, indexes, views and other things. How to get rid of them.</li>');
  mm3.append('<li><a href="/wiki/INSERT_and_DELETE_Reference">INSERT and DELETE</a>How to put records into a table, change them and how to take them out again.</li>');
  mm3.append('<li><a href="/wiki/DATE_and_TIME_Reference">DATE and TIME</a>How to work with dates; adding, subtracting and formatting.</li>');
  mm3.append('<li><a href="/wiki/Functions_Reference">Functions</a>How to use string functions, logical functions and mathematical functions.</li>');
  mm3.append('<li><a href="/wiki/Users_Reference">Users</a>How to create users, GRANT and DENY access, get at other peoples tables. How to find processes and kill them.</li>');
  mm3.append('<li><a href="/wiki/Meta_Data_Reference">Meta Data</a>How to find out what tables and columns exist. How to count and limit the rows return.</li>');
  mm3.append('<li><a href="/wiki/Hacks_Reference">SQL Hacks</a>Useful SQL hacks .</li>');

  var mm = $('<ul/>', {
    id: 'main_menu'
  }).appendTo('#mw-head-base');
  mm.append('<li id="mm1"><a href="/" class="navlink">Tutorials</a></li>');
  mm.append('<li id="mm2"><a href="/" class="navlink">Assessments</a></li>');
  mm.append('<li id="mm3"><a href="/" class="navlink">Reference</a></li>');

  $('#mm1').append(mm1);
  $('#mm2').append(mm2);
  $('#mm3').append(mm3);

  $('#main_menu').wrap('<div id="navigation_horiz" />');
  $('#navigation_horiz').naviDropDown({
    dropDownWidth: '35em'
  });

  // stick on top elements that need to be visible
  $("#main_menu").addClass("stickableMenu");
  $("#p-Reference").addClass("stickableRef");
  $(".ref_section").addClass("stickableDbRef");
});

$(document).scroll(function () {
  var useFixedMenu = $(document).scrollTop() > 175;
  $('.stickableMenu').toggleClass('fixedMenu', useFixedMenu);

  //    var useFixedRef = $(document).scrollTop() > 275;
  //    $('.stickableRef').toggleClass('fixedRef', useFixedRef);

  $('.stickableDbRef').toggleClass('fixedDbRef', $(document).scrollTop() > 275);
});

// swap classes on external links to change their side icons
$(function () {
  $(".external").addClass("zoo_external");
  $(".external").removeClass("external");
});

//Deal with variations in the "how to" scripts
$(function(){
  $('div.ht').each(function(){
    var lnglst = $('.def',this);
    var varlst = [];
    if (lnglst.length>1){
      $('.def',this).each(function(){
        var clist = $(this).attr('class').split(' ');
        for(var i=0;i<clist.length;i++)
          if (clist[i].length>2 && clist[i].substr(0,2)=='e-')
            varlst.push({engine:clist[i].substr(2),val:$(this)})
      });
    }
    if (varlst.length>0){
      var msg = $('<div/>',{'class':'variations'});
      msg.append($('<div/>',{text:'There are variations'}));
      for(var i=0;i<varlst.length;i++){
        $('<div/>',{'class':'a-'+varlst[i].engine})
          .append($('<div/>',{text:varlst[i].engine}))
          .append(varlst[i].val.clone().removeClass('def'))
          .appendTo(msg);
      }
    }
    $(this).append(msg);
  })
})

$(function () {
  // Insert tables into Quiz distractors
  var qq = $('.question');
  for (var i = 0; i < qq.length; i++) {
    var q = $(qq[i]);
    var distractors = "ABCDE";
    for (var j = 0; j < distractors.length; j++) {
      var tans = $('table caption:contains("Table-' + distractors[j] + '")', q).parents('table').addClass('innerTable');
      if (tans.length > 0) {
        var ttd = $('table tr td:contains("Table-' + distractors[j] + '")', q).addClass('innerTable');
        if (ttd.length > 0) {
          ttd.empty();
          ttd.append(tans);
        }
      }
    }
  }
  $('input.check').each(function (i, e) {
    $(this).attr('id', 'quiz_d_' + i);
  });
  $('tr.proposal').each(function (i, e) {
    var tds = $('td', $(this));
    var html1 = $(tds[1]).html();
    $(tds[1]).html($('<label/>', {
      html: html1,
      'for': $('input', $(this)).attr('id')
    }));
  })

  // Find labels which contains "query-" to add class for css
  $("label:contains('Query-')").addClass('labelAns'); //contains Query-
  $(".quizQuestions table.object tr.proposal label").not($('.quizQuestions table.object tr.proposal label div.mw-geshi').parent()).not($('.quizQuestions table.object tr.proposal label table.innerTable').parent()).addClass('labelAns');

  // Find radioButtons with title="Right" to highlight the Right results in Quizzes
  $("input:radio[title=Right]").each(function () {
    $(this).parents(':eq(1)').children().addClass("right");
  });

  // Find radioButtons with title="Wrong" to highlight the Right results in Quizzes
  $("input:radio[title=Wrong][checked=checked]").each(function () {
    $(this).parents(':eq(1)').children().addClass("wrong");
  });

  $("input:radio[title=Wrong]").not(':checked').each(function () {
    $(this).parents(':eq(1)').children().addClass("right");
  })
})

$(function () {
  // Toggle Class when the answer is selected - Istvan
  $('.quizQuestions table.object tr.proposal').click(function () {
    var rbtnId = $(this).find('label').attr('for');
    if ($("#" + rbtnId).attr("checked") == "checked") {
      $(this).children().addClass('picked');
      //Store data in QUIZLOG table
      var cookie = wgUserName;
      var question = $(this).parents('.question').children('.header').text().split('.'); //question[0]
      question = question[0].replace(/[^a-z0-9,]/gi, '');
      question = wgPageName + "#" + question + ".";
      var txt = $(this).children('.sign.picked').children().val().split(""); //p0-A; p1-B; p2-C; p3-D; p4-E;
      var results = ["A", "B", "C", "D", "E"];
      txt = results[txt[1]];
      var score = null;
      $.getJSON('/userData.php', {
        action: 'recordChoice',
        wikipage: wgPageName,
        cookie: wgUserName,
        question: question,
        txt: txt,
        score: score,
        user: wgUserName
      }, function (e) {})
    }
    $(".check").not(':checked').parent().parent().children().removeClass("picked");
  });

  var quiz = window.location.href.split("#");

  var indx = $.inArray("quiz0", quiz);
  if (indx > -1) {
    //Selecting input checked and answered right 
    wikipage = wgPageName;
    cookie = wgUserName;
    //whn = now();
    var results = ["A", "B", "C", "D", "E"];
    score = "100";
    user = wgUserName;
    var questionArr = [];
    var txtArr = [];

    $('.quizQuestions table.object tr.proposal').children('.sign.right').children('input[type=radio]:checked').each(function () {

      question = $(this).attr('name').split(""); //question[1] this is the question number on the wikipage
      question = parseInt(question[1]) + 1;
      question = wgPageName + "#" + question + ".";
      txt = $(this).val().split(""); //This is the answer
      txt = results[txt[1]];

      txtArr.push(txt);
      questionArr.push(question);

    });
    var txtStr = JSON.stringify(txtArr);
    var questStr = JSON.stringify(questionArr);
    txtStr = txtStr.replace(/[^a-z0-9,_#.]/gi, '');
    questStr = questStr.replace(/[^a-z0-9,_#.]/gi, '');
    $.getJSON('/userData.php', {
      action: 'updateAnswers',
      wikipage: wgPageName,
      cookie: wgUserName,
      question: questStr,
      txt: txtStr,
      score: score,
      user: wgUserName
    }, function (e) {
      console.log("cool");
    })
    console.log("end");
  }
})

//Connor 23/7/12 creates the labels for the multiple choice questions allowing them to be highlighted.

//Analytics code
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-33860668-1']);
_gaq.push(['_trackPageview']);

(function () {
  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(ga, s);
})();



// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend(jQuery.easing, {
  def: 'easeOutQuad',
  swing: function (x, t, b, c, d) {
    //alert(jQuery.easing.default);
    return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
  },
  easeInQuad: function (x, t, b, c, d) {
    return c * (t /= d) * t + b;
  },
  easeOutQuad: function (x, t, b, c, d) {
    return -c * (t /= d) * (t - 2) + b;
  },
  easeInOutQuad: function (x, t, b, c, d) {
    if ((t /= d / 2) < 1) return c / 2 * t * t + b;
    return -c / 2 * ((--t) * (t - 2) - 1) + b;
  },
  easeInCubic: function (x, t, b, c, d) {
    return c * (t /= d) * t * t + b;
  },
  easeOutCubic: function (x, t, b, c, d) {
    return c * ((t = t / d - 1) * t * t + 1) + b;
  },
  easeInOutCubic: function (x, t, b, c, d) {
    if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
    return c / 2 * ((t -= 2) * t * t + 2) + b;
  },
  easeInQuart: function (x, t, b, c, d) {
    return c * (t /= d) * t * t * t + b;
  },
  easeOutQuart: function (x, t, b, c, d) {
    return -c * ((t = t / d - 1) * t * t * t - 1) + b;
  },
  easeInOutQuart: function (x, t, b, c, d) {
    if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
    return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
  },
  easeInQuint: function (x, t, b, c, d) {
    return c * (t /= d) * t * t * t * t + b;
  },
  easeOutQuint: function (x, t, b, c, d) {
    return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
  },
  easeInOutQuint: function (x, t, b, c, d) {
    if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
    return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
  },
  easeInSine: function (x, t, b, c, d) {
    return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
  },
  easeOutSine: function (x, t, b, c, d) {
    return c * Math.sin(t / d * (Math.PI / 2)) + b;
  },
  easeInOutSine: function (x, t, b, c, d) {
    return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
  },
  easeInExpo: function (x, t, b, c, d) {
    return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
  },
  easeOutExpo: function (x, t, b, c, d) {
    return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
  },
  easeInOutExpo: function (x, t, b, c, d) {
    if (t == 0) return b;
    if (t == d) return b + c;
    if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
    return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
  },
  easeInCirc: function (x, t, b, c, d) {
    return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
  },
  easeOutCirc: function (x, t, b, c, d) {
    return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
  },
  easeInOutCirc: function (x, t, b, c, d) {
    if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
    return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
  },
  easeInElastic: function (x, t, b, c, d) {
    var s = 1.70158;
    var p = 0;
    var a = c;
    if (t == 0) return b;
    if ((t /= d) == 1) return b + c;
    if (!p) p = d * .3;
    if (a < Math.abs(c)) {
      a = c;
      var s = p / 4;
    } else var s = p / (2 * Math.PI) * Math.asin(c / a);
    return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
  },
  easeOutElastic: function (x, t, b, c, d) {
    var s = 1.70158;
    var p = 0;
    var a = c;
    if (t == 0) return b;
    if ((t /= d) == 1) return b + c;
    if (!p) p = d * .3;
    if (a < Math.abs(c)) {
      a = c;
      var s = p / 4;
    } else var s = p / (2 * Math.PI) * Math.asin(c / a);
    return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
  },
  easeInOutElastic: function (x, t, b, c, d) {
    var s = 1.70158;
    var p = 0;
    var a = c;
    if (t == 0) return b;
    if ((t /= d / 2) == 2) return b + c;
    if (!p) p = d * (.3 * 1.5);
    if (a < Math.abs(c)) {
      a = c;
      var s = p / 4;
    } else var s = p / (2 * Math.PI) * Math.asin(c / a);
    if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
    return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
  },
  easeInBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c * (t /= d) * t * ((s + 1) * t - s) + b;
  },
  easeOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
  },
  easeInOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
    return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
  },
  easeInBounce: function (x, t, b, c, d) {
    return c - jQuery.easing.easeOutBounce(x, d - t, 0, c, d) + b;
  },
  easeOutBounce: function (x, t, b, c, d) {
    if ((t /= d) < (1 / 2.75)) {
      return c * (7.5625 * t * t) + b;
    } else if (t < (2 / 2.75)) {
      return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
    } else if (t < (2.5 / 2.75)) {
      return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
    } else {
      return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
    }
  },
  easeInOutBounce: function (x, t, b, c, d) {
    if (t < d / 2) return jQuery.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b;
    return jQuery.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b;
  }
});

/**
 * hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
 * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
 *
 * @param  f  onMouseOver function || An object with configuration options
 * @param  g  onMouseOut function  || Nothing (use configuration options object)
 * @author    Brian Cherne <brian@cherne.net>
 */
(function ($) {
  $.fn.hoverIntent = function (f, g) {
    var cfg