
function showCLD(id){
  $("#debug").html("showing " + id);
}

$.fn.extend( {
  courses : function() {

    // private variables
    var celem = this;
    var day_b = [], days = [], current = $(".chosen-subject"), time_b = [], times = [];
    var results_table = $("#results-table");
    
    var offset=0, currentlast=0;
    var first_page = $(".first-page");
    var next_page = $(".next-page");
    var prev_page = $(".prev-page");
    var last_page = $(".last-page");
    var current_info = $("#current-info");
    var top_pager = $("#top-pager");
    var bottom_pager = $("#bottom-pager");
    var all = document.getElementById("all-c");
    var _all = $(all);
    
    var searchterm = $("#search-term");
    var tutor = $("#tutor-id").val();
    var institute = $("#institute-id").val();
    var group = $("#group-id").val();
    var current_search, classes;
    var results = celem.find("#results");
    var subjects = celem.find("#subjects");
    var _clg = $("#course-loading");
    var toggleRunningCourses = $("#toggleshowrunning");
    var includeRunning = false;
    var coursekey =$("#courses_key");
    var all=$("#all");
    
    
    function hideCourseLoading() {
      _clg.css( {
        display : 'none'
      });
      all.trigger("resize");
    }

    function courseLoading() {
      _clg.css( {
        'display' : 'block'
      });
    }

    function showPagination(datas){
      lastonpage = parseInt(datas.offset) + parseInt(datas.count);
      offset = parseInt(datas.offset);
      total=parseInt(datas.total)
      currentlast =total -20;
      //if (offset==0 && lastonpage>=total)
      //{
      //}
      //else
      //{
        top_pager.css('display','block');
        bottom_pager.css('display','block');
        current_info.html("Showing " + offset + " to " + lastonpage + " of " + total + " listings");
      //}
      
      if (lastonpage>=total){
        last_page.addClass("disabled");
        next_page.addClass("disabled");
        
      }
      else
      {
        last_page.removeClass("disabled");
        next_page.removeClass("disabled");
        next_page.bind("click",function(){offset = offset+20; search(false);});
        last_page.bind("click",function(){offset = currentlast; search(false);});
      }
      if (offset == 0)
      {
        first_page.addClass("disabled");
        prev_page.addClass("disabled");
      }
      else
      {
        first_page.removeClass("disabled");
        prev_page.removeClass("disabled");
        first_page.bind("click",function(){search(true);});
        prev_page.bind("click",function(){if (offset<20){offset=0}else {offset = offset-20}; search(false);});
      }
    }
    
    function loadTableList(datas) {
      
      var courses = datas.courses;
      var showkey = false;
      results_table.empty();
      if (courses.length > 0)
      {
        showPagination(datas);
         
      for (x in courses) {
        data = courses[x];
        results_table.append("<tr course-id='" + data["id"]
            + "' class='course-line'><td colspan=2>" + data['name'] + "</td><td colspan=2 class='t-right tutor' href='" 
            + _b_url + "common_ajax/showTutor/"+ data['tutor_id'] + "'>"
            + data['tutor'] + "</td></tr>");
        text = "";
        listings = data["listings"];
        for (y in listings) {
          listing = listings[y];
          if (listing['started']==true){
            classes = "listing-line old";
          }else
          {
            classes = "listing-line";
          }
          if (listing['status']>1)
          {
            classes = classes+" strikethrough";
          }
        
          showkey = showkey || listing['has_discounts'];
            
          text = text + "<tr course-listing-id='" + listing["id"]
              + "' class='"+classes
              + "' href='" + _b_url + "common_ajax/showCourse/"+ listing["id"] +"'><td>" + listing['start_date']
              + "</td><td>" + listing['type'] + "</td><td>" + listing['times'] + "</td><td class='t-right'>"
              + listing['price'] + ((listing['has_discounts'])?"*":"")  + "</td></tr>";
        }
        results_table.append(text);
        
        if (showkey){
          coursekey.css({display:"block"});
        }else
        {
          coursekey.css({display:"none"});
        }
      }
      }
      else
      {
        coursekey.css({display:"none"});
        results_table.append("<tr><td id='results-empty'>No courses have been found that match given criteria.</td></tr>");
      }
      results_table.find(".listing-line").each(function (){$(this).dialog()});
      results_table.find(".tutor").each(function (){$(this).dialog()});
    }

    // methods
    function toggle(bools, elems, i) {
      bools[i] = !bools[i];
      if (bools[i]) {
        elems[i].addClass("selected");
        if (i == 1 || !bools[i - 1]) {
          elems[i].addClass("selected-start");
        } else if (i != 1) {
          elems[i - 1].removeClass("selected-end");
        }

        if (i == 7 || !bools[i + 1]) {
          elems[i].addClass("selected-end");
        } else if (i != bools.length) {
          elems[i + 1].removeClass("selected-start");
        }
      } else {
        elems[i].removeClass("selected");
        if (i == 1 || !bools[i - 1]) {
          elems[i].removeClass("selected-start");
        } else if (i != 1) {
          elems[i - 1].addClass("selected-end");
        }

        if (i == 7 || !bools[i + 1]) {
          elems[i].removeClass("selected-end");
        } else if (i != bools.length) {
          elems[i + 1].addClass("selected-start");
        }
      }
      search(true);
      return false;
    }
    
    function search(resetoffset) {
      top_pager.css('display','none');
      bottom_pager.css('display','none');
      first_page.unbind("click");
      last_page.unbind("click");
      next_page.unbind("click");
      prev_page.unbind("click");
      if (resetoffset){
        offset=0;
      }
      var data = {};
      
      data["offset"] = offset;
      
      if (tutor)
        data["tutor"] = tutor;
      if (institute)
        data["institute"] = institute;
      if (group)
        data["group"] = group;
      if (searchterm)
        data["search"] = searchterm.val();
      
      if (current)
        data["subject"] = current.attr("id");
      
      if (includeRunning)
        data['include_running'] = true;

      var all_times = true;
      for ( var i = 1; i < 8; i++) {
        if (days[i]){
          data["day_" + i] = "1";
          all_times = false;
        }
      }

      var timesarry = new Array();
      for ( var i = 1; i < 6; i++) {
        if (times[i]){
          data["time_" + i] = "1";
          all_times = false;
        }
      }
      
      if (all_times){
        _all.addClass("selected")
        _all.addClass("selected-start");
        _all.addClass("selected-end");
      }
      else{
        _all.removeClass("selected")
        _all.removeClass("selected-start");
        _all.removeClass("selected-end");
      }

      if (current_search) {
        current_search.cancel();
      }

      current_search = {
        cancelled : false,
        performSearch : function() {
          results_table.empty();
          courseLoading();
          var ts = this;
          $.getJSON(_b_url + "common_ajax/course_search_ajax", data, function(
              retdata) {
            if (!ts.cancelled) {
              loadTableList(retdata);
              hideCourseLoading();
            }
            
          });
        },
        cancel : function() {
          this.cancelled = true;
        }
      };

      current_search.performSearch();

    }
    
    function subject(c, e) {
      if (current) {
        current.removeClass("chosen-subject");
      }
      c.addClass("chosen-subject");
      c.addClass("expanded");
      // c.find("ul").css('display', 'block');
      current = c;
      search(true);
      resizeSubjects();
      return false;
    }
    
    function choose(bools, elems, i) {
      bools[i] = true;

      for ( var j = 1; j < bools.length; j++) {
        if (i == j) {
          elems[j].addClass("selected")
          elems[j].addClass("selected-start");
          elems[j].addClass("selected-end");
        } else {
          bools[j] = false;
          elems[j].removeClass("selected")
          elems[j].removeClass("selected-start");
          elems[j].removeClass("selected-end");
        }
      }
      search(true);
      return false;
    }
    
    
    function clearSearch(){
      
      // clear days
      for ( var j = 1; j < days.length; j++){
        days[j] = false;
        day_b[j].removeClass("selected")
        day_b[j].removeClass("selected-start");
        day_b[j].removeClass("selected-end");
      }
      // clear times
      for ( var j = 1; j < times.length; j++){
        times[j] = false;
        time_b[j].removeClass("selected")
        time_b[j].removeClass("selected-start");
        time_b[j].removeClass("selected-end");
      }
      search(true);
      
    }

    function setupTopLink(id, bools, elems, num) {
      var elem = document.getElementById(id);
      var _elem = $(elem);
      elem.onselectstart = function() {
        return false
      };
      return _elem.cornered("").bind("click", function() {
        return toggle(bools, elems, num)
      }).bind("dblclick", function() {
        return choose(bools, elems, num)
      }).bind("mouseenter",function(){
        _elem.addClass("hovering");
      }).bind("mouseleave",function(){
        _elem.removeClass("hovering");
      });
    }

    // constructor
    days[1] = false;
    days[2] = false;
    days[3] = false;
    days[4] = false;
    days[5] = false;
    days[6] = false;
    days[0] = false;
    times[1] = false;
    times[2] = false;
    times[3] = false;
     
    results.cornered("");

    day_b[1] = setupTopLink("mon", days, day_b, 1);
    day_b[2] = setupTopLink("tue", days, day_b, 2);
    day_b[3] = setupTopLink("wed", days, day_b, 3);
    day_b[4] = setupTopLink("thu", days, day_b, 4);
    day_b[5] = setupTopLink("fri", days, day_b, 5);
    day_b[6] = setupTopLink("sat", days, day_b, 6);
    day_b[7] = setupTopLink("sun", days, day_b, 7);
    
    time_b[1] = setupTopLink("am", times, time_b, 1);
    time_b[2] = setupTopLink("pm", times, time_b, 2);
    time_b[3] = setupTopLink("night", times, time_b, 3);

    all.onselectstart = function() {
      return false
    };
    _all.cornered("").bind("click", function() {
      return clearSearch();
    }).bind("mouseenter",function(){
      _all.addClass("hovering");
    }).bind("mouseleave",function(){
      _all.removeClass("hovering");
    });
    
    toggleRunningCourses.bind("click", function(){
      includeRunning = !includeRunning;
      if (includeRunning)
      {
        toggleRunningCourses.html("Hide Started");
      }
      else
      {
        toggleRunningCourses.html("Show Started");
      }
      search(true);
    });
    
    function resizeSubjects(){
      var height = subjects.height() + 60;
      if (height>250){
        results.css("min-height",height);
      }
      else
      {
        results.css("min-height",250);
      }
    }
    
    subjects.find("li").cornered("").each(function() {
      
      var _this = $(this);
      _this.children("span").children("a.expander").bind("click", 
            function() {
          _this.toggleClass("expanded");
          resizeSubjects();
          return false;});
    
      _this.bind("click", function() {
        return subject(_this);
      });
      
      _this.bind("dblclick", function() {
        _this.toggleClass("expanded");
        resizeSubjects();
        return false;
      });
        
      this.onselectstart = function() {
        return false;
      };
      var _t = $(this).children("span");
      _t.bind("mouseenter",function(){
        _t.addClass("hovering");
      }).bind("mouseleave",function(){
        _t.removeClass("hovering");
      })
    });

    celem.css( {
      'display' : 'block'
    });
    search(true);
    window['search']=function(searchterm, issubject){
      if (issubject){
        current=$("<div id='s_"+searchterm+"'></div>");
      }
      else
      {
        if (searchterm=="")
        {
          current=null;
        }
        else
        {
          current=$("<div id='search'></div>");
        }
      }
      search(true);
    };
  }
});

$(document).ready(function() {
  
  if ($("#courses").length > 0) {
    $("#courses").cornered("c").courses();
  }
});

