(function ($) {

$(document).ready(function(){
  activateMegaMenu();
  preparePopUps();
  $("#edit-captcha-response").attr("autocomplete", "off");
  loadCourseProgramCache();
  prepareAutoCompletes();
});

var IE = (navigator.userAgent.indexOf('MSIE') != -1);


function activateMegaMenu(){

  if (!document.getElementById){
    return;
  }
  
  if (!document.getElementsByTagName('ul')){
    return;
  }

  if (!document.getElementsByTagName('li')){
    return;
  }

  var lists = document.getElementsByTagName('ul');

  for (var i=0; i<lists.length; i++){

    if (lists[i].className == 'megamenu'){
    
      var item = lists[i].getElementsByTagName('li');
      
      for (var j=0; j<item.length; j++){
      
        if (item[j].className.indexOf('firstlevel') != -1){
          item[j].onmouseover = function(){
          
            if (IE){
              /*
              this.style.MsFilter = '"progid:DXImageTransform.Microsoft.gradient(startColorstr=#efffffff, endColorstr=#efffffff)"';
              this.style.filter = 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#efffffff, endColorstr=#efffffff)';
              */
              this.style.backgroundColor = 'rgb(255, 255, 255)';
            }else{
              this.style.backgroundColor = 'rgba(255, 255, 255, 0.95)';
            }
            
            if (this.id.indexOf('sub-header') != -1){
              this.style.borderRight = '1px solid #ccc';
              this.style.borderLeft = '1px solid #ccc';
              this.style.padding = '0px 14px 0px 10px';
            }
            
            var link = this.getElementsByTagName('a')[0];
            link.style.color = '#EE3224';
            link.style.backgroundImage = 'none';
            openMegaMenu(this, true);
          }
          item[j].onmouseout = function(){
            openMegaMenu(this, false);
          }
        }   
      }	     
    }
  }	

  if (!document.getElementsByTagName('div')){
    return;
  }
  
  var divs = document.getElementsByTagName('div');

  for (var i=0; i<divs.length; i++){
  
    if (divs[i].className == 'flyout'){
      divs[i].onmouseout = function(){
       stillActive(false);
      }
      divs[i].onmouseover = function(){
       stillActive(true);
      }
     
      var close = divs[i].getElementsByTagName('span')[0];
      
      close.onclick = function(){
        clearTimeout(timer);
        $('#'+menu_object+'_flyout').stop(true, true);
        active = false;
        hideFlyOut(false);
      }
    }
  }	
}



// A few variables.
var menu_object = '';
var active = false;
var timer;

// Hide the flyout.
function hideFlyOut(animate){
  if (!active){
    var flyout = document.getElementById(menu_object);
    
    /*
    if (IE){
      
      flyout.style.MsFilter = '"progid:DXImageTransform.Microsoft.gradient(startColorstr=#00ffffff, endColorstr=#00ffffff)"';
      flyout.style.filter = 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#00ffffff, endColorstr=#00ffffff)';
      
    }else{
      flyout.style.backgroundColor = 'transparent';
    }
    */
    
    flyout.style.backgroundColor = 'transparent';
    
    var link = flyout.getElementsByTagName('a')[0];
    link.style.color = '#fff';
    
    if (flyout.className.indexOf('parent') != -1){
      link.style.background = 'url(http://dce.uwinnipegcourses.ca/sites/all/themes/uwc/images/arrowDown.gif)';
    }
    
    link.style.backgroundPosition = 'right bottom';
    link.style.backgroundRepeat = 'no-repeat';

    if (menu_object.indexOf('sub-header') != -1){
      flyout.style.borderRight = 'none';
      flyout.style.borderLeft = 'none';
      flyout.style.padding = '0px 15px 0px 11px';
    }
    
    $('#'+menu_object+'_flyout').hide();
    
    /*            
    if (animate){
      $('#'+menu_object+'_flyout').slideUp('25');
    }else{
      $('#'+menu_object+'_flyout').hide();
    }
    */
  }
}

// Set values depending on whether or not the flyout is still active.
function stillActive(still_active){
  if (still_active){
    active = true;
    clearTimeout(timer);
  }else{
    active = false;
    timer = setTimeout(function (){hideFlyOut(true)}, 500);
  }
}

// This shows the flyout menu
function openMegaMenu(menu, hovering){
 
  // If the menu is different than the last and the menu_object is not in it's initial value.
  if ((menu.id != menu_object) && (menu_object != '')){
    clearTimeout(timer);
    //$('#'+menu_object+'_flyout').stop(true, true);
    active = false;
    hideFlyOut(false);
  }
  
  // Assign the global variable.
  menu_object = menu.id;
  
  // If the mouse is overtop the button, show the flyout.
  if (hovering){
    clearTimeout(timer);
    $('#'+menu_object+'_flyout').show();
    active = true;
  }else{ // Otherwise set the time out and then hide it.
    active = false;
    timer = setTimeout(function (){hideFlyOut(true)}, 500);
  }
}

function preparePopUps(){

  if (!document.getElementById){
    return;
  }
  
  if (!document.getElementsByTagName('a')){
    return;
  }
  
  var links = document.getElementsByTagName('a');
  
  for (var i=0; i<links.length; i++){
  
   if (links[i].className.indexOf('popup') != -1){
     links[i].onclick = function(){
       var pop_up = open(this.getAttribute('href'));
	     pop_up.focus;
	     return false;
     }
   }
  }	
}




//////////AUTOCOMPLETE FUNCTIONALITY//////////////

// Loads the cached JSON object containg all program and courses for autocomplete.
function loadCourseProgramCache() {

  // Set the feed URL.
  var src = 'http://dce.uwinnipegcourses.ca/sites/default/files/cache/coursePrograms.js';   
  
  // Get the head element and create a script element.       
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  
  // Set the attributes and append it to the head.
  script.setAttribute('src', src);
  script.setAttribute('type', 'text/javascript');
  head.appendChild(script);  
            
}


// Set the search fields.
function prepareAutoCompletes(){

  if (document.getElementById('search-form')){
  
    var form = document.getElementById('search-form');
    var inputs = form.getElementsByTagName('input');

    form.onsubmit = function(){
    
      var autocomplete = document.getElementById('autocomplete');
      
      if (autocomplete){
        
        var items = autocomplete.getElementsByTagName('li');
        
        for (var i=0; i<items.length; i++){
          if (items[i].className.indexOf('selected') != -1){
            var link = items[i].getElementsByTagName('a')[0].getAttribute('href');
            window.location = link;
            return false;
          }
        }
      }
    };
    
    for (var i=0; i<inputs.length; i++){
     if (inputs[i].id == 'edit-keys'){
       inputs[i].setAttribute('class', 'form-autocomplete');
       inputs[i].setAttribute('autocomplete', 'off');
       new Uwc.jsAC(inputs[i]);
       break;
     }
    }	
  }
  
  if (document.getElementById('search-block-form')){
  
    var form = document.getElementById('search-block-form');
    var inputs = form.getElementsByTagName('input');
    
    form.onsubmit = function(){
    
      var autocomplete = document.getElementById('autocomplete');
      
      if (autocomplete){
        
        var items = autocomplete.getElementsByTagName('li');
        
        for (var i=0; i<items.length; i++){
          if (items[i].className.indexOf('selected') != -1){
            var link = items[i].getElementsByTagName('a')[0].getAttribute('href');
            window.location = link;
            return false;
          }
        }
      }
    };

    for (var i=0; i<inputs.length; i++){
     if (inputs[i].className.indexOf('form-autocomplete') != -1){
       new Uwc.jsAC(inputs[i]);
     }
    }	
  } 

}



/**
 * An AutoComplete object
 */
function Uwc(){}

Uwc.jsAC = function (input) {
    var ac = this;
    this.input = input;
  
    $(this.input)
      .keydown(function (event) { return ac.onkeydown(this, event); })
      .keyup(function (event) { ac.onkeyup(this, event); })
      .blur(function () { ac.hidePopup(); });

};


/**
 * Handler for the "keydown" event
 */
Uwc.jsAC.prototype.onkeydown = function (input, e) {
  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 40: // down arrow
      this.selectDown();
      return false;
    case 38: // up arrow
      this.selectUp();
      return false;
    default: // all other keys
      return true;
  }
};

/**
 * Handler for the "keyup" event
 */
Uwc.jsAC.prototype.onkeyup = function (input, e) {

  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 16: // shift
    case 17: // ctrl
    case 18: // alt
    case 20: // caps lock
    case 33: // page up
    case 34: // page down
    case 35: // end
    case 36: // home
    case 37: // left arrow
    case 38: // up arrow
    case 39: // right arrow
    case 40: // down arrow
      return true;

    case 9:  // tab
    case 13: // enter
    case 27: // esc
      this.hidePopup(e.keyCode);
      return true;

    default: // all other keys
      if (input.value.length > 0)
        this.populatePopup();
      else
        this.hidePopup(e.keyCode);
      return true;
  }
};

/**
 * Puts the currently highlighted suggestion into the autocomplete field
 */
Uwc.jsAC.prototype.select = function (node) {
  this.input.value = node.autocompleteValue;
};

/**
 * Highlights the next suggestion
 */
Uwc.jsAC.prototype.selectDown = function () {
  if (this.selected && this.selected.nextSibling) {
    this.highlight(this.selected.nextSibling);
  }
  else {
    var lis = $('li', this.popup);
    if (lis.size() > 0) {
      this.highlight(lis.get(0));
    }
  }
};

/**
 * Highlights the previous suggestion
 */
Uwc.jsAC.prototype.selectUp = function () {
  if (this.selected && this.selected.previousSibling) {
    this.highlight(this.selected.previousSibling);
  }
};

/**
 * Highlights a suggestion
 */
Uwc.jsAC.prototype.highlight = function (node) {
  if (this.selected) {
    $(this.selected).removeClass('selected');
  }
  $(node).addClass('selected');
  this.selected = node;
};

/**
 * Unhighlights a suggestion
 */
Uwc.jsAC.prototype.unhighlight = function (node) {
  $(node).removeClass('selected');
  this.selected = false;
};

/**
 * Hides the autocomplete suggestions
 */
Uwc.jsAC.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    this.input.value = this.selected.autocompleteValue;
  }
  // Hide popup
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function() { $(popup).remove(); });
  }
  this.selected = false;
};

/**
 * Positions the suggestions popup and starts a search
 */
Uwc.jsAC.prototype.populatePopup = function () {
  // Show popup
  if (this.popup) {
    $(this.popup).remove();
  }
  this.selected = false;
  this.popup = document.createElement('div');
  this.popup.id = 'autocomplete';
  this.popup.owner = this;
  $(this.popup).css({
    marginTop: this.input.offsetHeight +'px',
    width: '300px',
    display: 'none'
  });
  $(this.input).before(this.popup);

  this.search(this.input.value);
};


// Compare the entered term with the names in the cache and build an array of 6 matches.
Uwc.jsAC.prototype.search = function (string) {
  
  var matches = new Array();  
  var matchPositions = new Array();
  var maxResults = 12;
  var count = 0;
  
  string = string.toLowerCase();
  
  // For every course/program
  for (key in coursePrograms){

    // Determine the position of the match 
    var position = key.toLowerCase().indexOf(string);
    
    // Continue if not found.
    if (position == -1){
      continue;
    }

    // Establish array if it does not exist.
    if (typeof matchPositions[key.toLowerCase().indexOf(string)] == 'undefined'){
      matchPositions[position] = new Array();
    }
    
    matchPositions[position][key] = coursePrograms[key];

  }
  
  // For each match position...
  positionLoop:
  for (var i=0; i<matchPositions.length; i++){
  
    // If an array exists for that position...
    if (typeof matchPositions[i] != 'undefined'){
      
      // Loop through and assign to new match array.
      for (key in matchPositions[i]){
      
        matches[key] = coursePrograms[key];
        count++;
        
        // Break out of top loop when max results reached.
        if (count == maxResults){
          break positionLoop;
        }    
      
      }
    }
  }

  this.found(matches);
  
};

/**
 * Fills the suggestion popup with any matches received
 */
Uwc.jsAC.prototype.found = function (matches) {
  // If no value in the textfield, do not show the popup.
  if (!this.input.value.length) {
    return false;
  }

  // Prepare matches
  var ul = document.createElement('ul');
  var ac = this;
  for (key in matches) {
    var li = document.createElement('li');
    $(li)
      .html('<div>'+ matches[key] +'</div>')
      .mousedown(function () { ac.select(this); })
      .mouseover(function () { ac.highlight(this); })
      .mouseout(function () { ac.unhighlight(this); });
    li.autocompleteValue = key;
    $(ul).append(li);
  }

  // Show popup with matches, if any
  if (this.popup) {
    if (ul.childNodes.length > 0) {
      $(this.popup).empty().append(ul).show();
    }
    else {
      $(this.popup).css({visibility: 'hidden'});
      this.hidePopup();
    }
  }
};

}(jQuery));;

