var catSearchTimeout; var userSearchTimeout; var programSearchTimeout;
var catSearchDelay = 800; var userSearchDelay = 800;; var programSearchDelay = 800;
var catMinSearchLen = 3; var userMinSearchLen = 0;

$(document).ready(function() {
  //Widget Twisties
  $('.twist-click').click(function() {
    $($(this).attr('href')).toggle();
    $(this).toggleClass('twist-down');
    return false;
  });

  //Profile popup
  $('#header-profile-link').click(function() {
    openPopup({ popup: '#user_profile_popup' });
    $('#user_profile_popup_frame').attr('src', baseUrl+"profile");
    return false;
  });
  if($('#header-profile-link').hasClass('needupdate')) $('#header-profile-link').click();

  $('#advkeywords_search').click(function() {
    var query = $('#advkeywords_input').val();
    if(query != null && query.length > 0) {
      var mod = "&m=" + $("input[name=keywords_modifier]:checked").val();
      if(mod == "&m=any") mod = "";

      var typeArray = new Array();
      if($('#keywords_type_module').is(':checked')) typeArray.push($('#keywords_type_module').val());
      if($('#keywords_type_video').is(':checked')) typeArray.push($('#keywords_type_video').val());
      if($('#keywords_type_chapter').is(':checked')) typeArray.push($('#keywords_type_chapter').val());
      var type = "";
      if(typeArray.length > 0 && typeArray.length < 3)
        type = "&t=" + typeArray.join(",");

      var catVal = $('#keywords_cat').val();
      var cat = "";
      if(catVal != null && catVal.length)
        cat = "&c=" + catVal;

      document.location.href = baseUrl+"search?q=" + query + mod + type + cat;
    }
    return false;
  })
  $('#advkeywords_input').keyup(function(e) {
    if(e.keyCode == 13) $('#advkeywords_search').click();
  });

  //Category List
  $('#category_button').click(function() {
    Category.viewAll();
    return false;
  });
  $('#category_input').keydown(function(event) {
    if (event.keyCode == 9) return;
    clearTimeout(catSearchTimeout);

    if(event.keyCode == 13) {
      Category.search($('#category_input').val());
      return false;
    }

    catSearchTimeout = setTimeout(function() {
      var searchTerm = $('#category_input').val();
      if(searchTerm.length >= catMinSearchLen)
        Category.search(searchTerm);
    }, catSearchDelay);
  })

  //Welcome message
  $('#welcome-link').click(function() {
    if($('#message-body').is(':visible')) {
      $('#message-body').hide();
      $(this).find('span').text('Show');
      $.cookie("score-welcome-visible", "false", { expires: 30 });
    } else {
      $('#message-body').show();
      $(this).find('span').text('Hide');
      $.cookie("score-welcome-visible", "true", { expires: 30 });
    }
    return false;
  });

  //Search popup
  $('#adv_search').click(function() {
    openPopup({ popup: '#search_popup' });

    //Load up the categories list
    $catsel = $("select#keywords_cat");
    if($catsel.children().length == 1) {
      $.getJSON(baseUrl+"category/json", null, function(j){
        var options = '<option value="">[ All Categories ]</option>';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
        }
        $("select#keywords_cat").html(options);
      });
    }
    return false;
  });

  //Forgot Password popup
  $('#forgot-pwd-link').click(function() {
    $('#forgot_pwd_frame').attr('src', baseUrl+"forgot/password");
    openPopup({ popup: '#forgot_pwd_popup' });
    return false;
  });

  //About popup
  $('#about-link').click(function() {
    $("#about_popup").load(baseUrl+"about", null, function(responseText, textStatus, XMLHttpRequest) {
      if(XMLHttpRequest.status == 403) {
        go_home();
        return;
      }
      openPopup({ popup: '#about_popup' });
    });
    return false;
  });

  //Contributors popup
  $('#contrib-link').click(function() {
    $("#about_popup").load(baseUrl+"about/contributors", function(responseText, textStatus, XMLHttpRequest) {
      if(XMLHttpRequest.status == 403) {
        go_home();
        return;
      }
      openPopup({ popup: '#about_popup' });
    });
    return false;
  });

  //Assignment admin popup
  $('#add-assignment-link').click(function() {
    $('#assignment-step1').click();
    $('#admin_assignement_popup_frame').attr('src', baseUrl+"assignment/create");
    openPopup({ popup: '#admin_assignement_popup' });
    return false;
  });
  $('.edit-assignment-link').live('click', function() {
    $('#assignment-step1').click();
    var id = $(this).attr('href').substring(1);
    $('#admin_assignement_popup_frame').attr('src', baseUrl+"assignment/update/"+id);
    openPopup({ popup: '#admin_assignement_popup' });
    return false;
  });
  $('.assignment-step').click(function() {
    $this = $(this);

    if(top.frames["admin_assignement_popup_frame"].goToStep)
      top.frames["admin_assignement_popup_frame"].goToStep($this.attr('href'));

    $(".current").removeClass("current")
    $this.addClass("current")
    $("#pop_title").html($this.attr("title"))
    centerPopup()
    return false;
  });

  //Edit Welcome popup
  $('#update-welcome-link').click(function() {
    openPopup({ popup: '#welcome_message_popup' });
    $('#welcome_message_popup_frame').attr('src', baseUrl+"message/update/welcome");
    return false;
  });

  //Message popup
  $('#add-message-link').click(function() {
    $('#message_popup_frame').attr('src', baseUrl+"message/create");
    openPopup({ popup: '#message_popup' });
    return false;
  });
  $('.edit-message-link').live('click', function() {
    var id = $(this).attr('href').substring(1);
    $('#message_popup_frame').attr('src', baseUrl+"message/update/"+id);
    openPopup({ popup: '#message_popup' });
    return false;
  });

  //User search
  $('#user-search-input').keydown(function(event) {
    if (event.keyCode == 9 || event.keyCode == 13) return;
    clearTimeout(userSearchTimeout);
    userSearchTimeout = setTimeout(runUserSearch, userSearchDelay);
  })
  $('#user-search-program, #user-search-sort, #user-field, #user-role, #user-year').change(runUserSearch);

  //Program search
  $('#program-search-input').keydown(function(event) {
    if (event.keyCode == 9 || event.keyCode == 13) return;
    clearTimeout(programSearchTimeout);
    programSearchTimeout = setTimeout(Program.search, programSearchDelay);
  })
  $('#program-search-sort').change(Program.search);

  //Other
  loadTabs();
});

function runUserSearch() {
  var searchTerm = $('#user-search-input').val();
  if(searchTerm.length >= userMinSearchLen) {
    var program = ($('#programid') || $('#programid').val().length >= 1) ?
      '&p=' + $('#programid').val() :
      '';

    var sort = $('#user-search-sort').val();
    if(sort.length > 0) sort = '&s=' + sort;

    var field = $('#user-field').val();
    if(field.length > 0) field = '&f=' + field;

    var role = $('#user-role').val();
    if(role.length > 0) role = '&r=' + role;

    var year = $('#user-year').val();
    if(year.length > 0) year = '&y=' + year;

    $("#user-list")
      .html('<p>Searching...</p>')
      .load(baseUrl+"profile/search?q=" + searchTerm + sort + field + role + year + program, function(responseText, textStatus, XMLHttpRequest) {
        if(XMLHttpRequest.status == 403) {
          go_home();
          return;
        }
        //$("#category-list").highlight(searchTerm);
      });
  }
}
function runProgramSearch() {
  Program.search();
}

function showBox(box, button) {
  //hide opened boxe and close button
  $('.grey_box').hide()
  $('.close_button').hide()

  //show the box and close button that we want to be opened
  $(box).show()
  $(button).show()
}

function hideBox() {
  //hide opened boxe and close button
  $('.grey_box').hide()
  $('.close_button').hide()
}


//Tabs
function loadTabs() {
  if($('.tab_link')) {
    var tabs = $('.tab_link')
    var active_tab = $('.tab_link.active')

    if($(active_tab).attr("rel"))
      $($(active_tab).attr("rel")).show()

    for(i=0; i<tabs.length; i++) {
      $(tabs[i]).click(function(){
        $(tabs).removeClass("active")
        $(this).addClass("active")

        $('.tab_content').hide()
        $($(this).attr("rel")).show()
        //return false
      })
    }

    //Check of a non-default tab selection
    var hash = window.location.hash;
    if(!hash || hash.length == 0) hash = '#lrnobj';

    $('a.tab_link[href=' + hash + ']').click();
  }
}

//End Tabs

// Popup
var popup_created = 0
//var temps = new Array()

function disablePopup(){
  $("#popup_overlay").fadeOut(200)
  $(curPopup).fadeOut(200)
  $(window).unbind('resize', function() {
    centerPopup()
  })
  return false
}

function centerPopup(){
  $(curPopup).centerInClient();
}

var curPopup = null;
function openPopup(options) {
  curPopup = options.popup;
  
  centerPopup()
  $(window).bind('resize', function() {
    centerPopup()
  })

  $("#popup_overlay").css({
    "opacity": "0.8"
  })
  $('#popup_overlay').fadeIn(200)
  $(curPopup).fadeIn(200)

  $("#popup_overlay").click(function(){
    disablePopup()
  })
}

//End Popup

function showT(tab, t) {
    $('.about_tabs a').removeClass('active')
    $('.tab_popup_box').hide()

    $(t).addClass('active')
    $(tab).show()
}

var User = {
  addResident: function() {
    $('#user_profile_popup_frame').attr('src', baseUrl+"profile/create/resident");
    $('#user_profile_popup .popup_title').text('Add Resident');
    openPopup({ popup: '#user_profile_popup' });
  },
  addOther: function() {
    $('#user_profile_popup_frame').attr('src', baseUrl+"profile/create/other");
    $('#user_profile_popup .popup_title').text('Add Other');
    openPopup({ popup: '#user_profile_popup' });
  },
  edit: function(id) {
    $('#user_profile_popup_frame').attr('src', baseUrl+"profile/update/"+id);
    $('#user_profile_popup .popup_title').text('Edit Profile');
    openPopup({ popup: '#user_profile_popup' });
  },
  del: function(id) {
    Ajax.del("profile/delete/"+id, {}, "person", function() {
      $('#person_'+id).remove();
    });
  }
}

var Category = {
  search: function(term) {
    $this = this;
    $this.toggleWait();
    $("#category-list")
      .load(baseUrl+"category?q=" + term, function(responseText, textStatus, XMLHttpRequest) {
        if(XMLHttpRequest.status == 403) {
          go_home();
          return;
        }
        $this.highlight(term);
        $this.showPopDown();
        $this.toggleWait();
      });
  },
  viewAll: function() {
    $this = this;
    $this.toggleWait();
    $('#category_input').val('');
    $("#category-list").load(baseUrl+"category", function(responseText, textStatus, XMLHttpRequest) {
      if(XMLHttpRequest.status == 403) {
        go_home();
        return;
      }
      $this.showPopDown();
      $this.toggleWait();
    });
  },
  toggleWait: function() {
    $('#category-tab').toggleClass('wait');
  },
  showPopDown: function() {
    if(!$('#category_box').is(':visible'))
      showBox('#category_box', '#category_close_button');
  },
  highlight: function(term) {
    $("#category-list").highlight(term);
  }
}

var Contributor = {
  showModules: function(item) {
    item.find('ul').toggleClass('show');
  }
}

var Message = {
  del: function(id) {
     Ajax.del("message/delete/"+id, {}, "message", function() {
      $('#message_'+id).remove();
    });
  }
}

var Assignment = {
  filter: function(showAll) {
    $.cookie("score-assign-showall", showAll ? "true" : "false", { expires: 30 });
    window.location.href = window.location.href;
  },
  del: function(id) {
    Ajax.del("assignment/delete/"+id, {}, "assignment", function() {
      $('#assignment_'+id).remove();
    });
  }
}

var Program = {
  add: function() {
    $('#program_popup_frame').attr('src', baseUrl+"program/create");
    openPopup({ popup: '#program_popup' });
  },
  edit: function(id) {
    $('#program_popup_frame').attr('src', baseUrl+"program/update/"+id);
    openPopup({ popup: '#program_popup' });
  },
  searchUsers: function(id) {
    $('#program-widget-form #programid').val(id);
    $('#program-widget-form').submit();
  },
  searchPrograms: function() {
    document.location.href = document.location.href;
  },
  search: function() {
    var minLength = 1;

    var searchTerm = $('#program-search-input').val();
    //if(searchTerm.length >= minLength) {
      var sort = $('#program-search-sort').val();
      if(sort.length > 0) sort = '&s=' + sort;

      $("#program-list")
      .html('<p>Searching...</p>')
      .load(baseUrl+"program/search?q=" + searchTerm + sort, function(responseText, textStatus, XMLHttpRequest) {
        if(XMLHttpRequest.status == 403) {
          go_home();
          return;
        }
        //$("#category-list").highlight(searchTerm);
      });
    //}
  }
}

var Content = {
  add: function() {
    $('#acontent_popup_frame').attr('src', baseUrl+"content/create");
    openPopup({
      popup: '#acontent_popup'
    });
  },
  update: function() {
    $('#ucontent_popup_frame').attr('src', baseUrl+"content/update");
    openPopup({
      popup: '#ucontent_popup'
    });
  },
  remove: function() {
    $('#dcontent_popup_frame').attr('src', baseUrl+"content/delete");
    openPopup({
      popup: '#dcontent_popup'
    });
  }
}

var Ajax = {
  del: function(urlPart, data, msgPart, callback) {
    if(confirm('Are you sure you want to delete the '+msgPart+'? This operation cannot be undone.')) {
      $.ajax({
        type: "POST",
        data: data,
        url: baseUrl+urlPart,
        success: function(data){
          if(data == 'success')
            if(typeof callback == "function") {
              if(typeof args == "object") {
                callback.apply();
              } else {
                callback.call();
              }
            }
          else
            alert('There was an error while trying to delete the '+msgPart+'.');
        },
        error: function() {
          alert('There was an error while trying to delete the '+msgPart+'.');
        }
      });
    }
  }
}

function change_parent_url(url) {
  document.location = url;
}

function go_home() {
  document.location = baseUrl;
}