﻿//======================================================================
//	CLASS FINDER
//======================================================================
this.ClassFinder = new ClassFinder();
this.filter = new Filter();
var instructorsObj;

function Filter()
{
     var locationIds = "";
     var weekdays = "";
     var classIds = "";
     var instructorIds = "";
}

function ClassFinder() {

    this.tableMaxRows = 10;
    this.currentPageNum = 1;
    this.totalPages = 1;
    
    this.INSTRUCTORS_TEXT = "Type Instructor's Name";
    
    var sections = ["citySection","locationSection","preferenceSection",];
    var sectionHeaders = ["citySectionHeader","locationSectionHeader","preferenceSectionHeader",];
    
    var currentLocationNameArr;
    this.currentCityName = "";
    
	///
	/// Initializes the code
	///
    this.init = function() {
       
        window.ClassFinder.addTableParsers();
        window.ClassFinder.hidePreferenceLoader();
        window.ClassFinder.hideLocationLoader();
        window.ClassFinder.hideCityLoader();
        
        this.initSections();

		/* Read class finder preference, if set, don't load the city section */
		var cookieCity = readCookie('classfindercity');
		if(cookieCity == null)
		{
			this.showSection("citySection");
		}
        window.filter.weekdays = $("#cbxWeekdayAll").get(0).value;
		/*
        $("#ddlInstructors").change(function() {
            window.filter.instructorIds = this.value;
            window.ClassFinder.filterResults();
        });
        */	
		        
        $("#ddlClass").change(function() {
            var locClassesIds="";
            $("#ddlClass option:selected").each(function() {            
                if (this.value.length > 1)       
				{		
					locClassesIds += this.value;
					locClassesIds += ",";			
				}
            });
			
			if(locClassesIds.length > 0)
			{
            window.filter.classIds = locClassesIds;
            window.ClassFinder.filterResults();
			}
			else
			{			
				$("#ddlClass").get(0).selectedIndex = 0;
                window.filter.classIds = "";
                window.ClassFinder.filterResults();
			}
        });
        
        $("#ddlCategory").change(function() {
            if (this.value.length > 1)
            {				
                $.getJSON("/json.ashx?method=GetClassesByCategory&catId=" + this.value,
                    function(data) 
					{
                        $("#ddlClass").html("")
                            .append("<option value=\"\">Select Class</option>")
                            .append("<option value=\"\"></option>");
                        
                        $(data.results.classes).each(function(i) {
                            $("#ddlClass").append("<option value=\"" + data.results.classes[i].id + "\">" + data.results.classes[i].name + "</option>");
						});						
					});
             }
             else
             {
                $("#ddlCategory").get(0).selectedIndex = 0;
                $("#ddlClass").get(0).selectedIndex = 0;
                window.filter.classIds = "";
                window.ClassFinder.filterResults();
              
				  $("#ddlClass").html("")
                            .append("<option value=\"\">Select Class</option>")
                            .append("<option value=\"\"></option>");
             }
        });     
        
		
        $("#preferenceSection .weekdays input:checkbox").each(function(i) {

            $(this).click(function() {
				$("#cbxWeekdayAll").get(0).checked = false;
                window.ClassFinder.processWeekdayClick($(this).get(0));
            });
        });
		
		$("#cbxWeekdayAll").unbind("click").click(function() {
			$("#preferenceSection .weekdays input:checkbox").each(function() {
				if (this.name != 'cbxWeekdayAll')
				{
					this.checked = false;
				}
			});
			
			window.ClassFinder.processWeekdayClick($("#cbxWeekdayAll").get(0));
		});
        
        $("#ddlLocations").change(function(i) {
			if (this[this.selectedIndex].value != '') {
				createCookie('classfindercity',this.value,365);
				window.ClassFinder.showSection("locationSection");
                window.ClassFinder.resetFilters();
                window.ClassFinder.currentCityName = this[this.selectedIndex].text;
                window.ClassFinder.currentLocationNameArr = new Array();
                
                //$("#locationSection").append("<img src=\"/assets/images/common_section/rings.gif\" id=\"rings\" />");
                $("#locationSection").html("");
                
                window.ClassFinder.showCityLoader();
                //$("#locationSection").append("<div id=\"loader\" class=\"clearfix\"><img src=\"/assets/images/common_section/rings.gif\" /> <span>Loading...</span></div>").hide().slideDown(250).fadeIn(1000);
                
                $.getJSON("/json.ashx?method=GetLocationsByCityId&locId=" + this.value,
                    function(data){
                    
                       window.ClassFinder.appendLocations(data);
                });
            }
        });

		/* Read class finder cookie preference, if set, load the city */
		if(cookieCity != null)
		{
			$("#ddlLocations").get(0).value = cookieCity;
			$('#ddlLocations').trigger('change');
		}
    }
	
	///
	/// Processes the click event when weekday checkbox is fired
	///
	this.processWeekdayClick = function(t)
	{
		
		if (t.checked)
		{
			if(window.filter.weekdays =="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday")
			window.filter.weekdays = t.value;
			
			
			if (window.filter.weekdays == undefined || window.filter.weekdays.indexOf(t.value, 0) < 0)
			{
				if (window.filter.weekdays == undefined || window.filter.weekdays.length <= 0)
				{
					window.filter.weekdays = t.value;
				}
				else
				{
					window.filter.weekdays += ',' + t.value;
				}
			}
			
			if (t.name.toString() === "cbxWeekdayAll")
			{
				window.filter.weekdays = t.value;
				
			}
			
			
			
			
		}
		else
		{
			
			var str = window.filter.weekdays.replace(',' + t.value,'');
			str = str.replace(t.value,'');
			str = str.replace(',,',',');
				
			window.filter.weekdays = str;
			
			//if all checkboxes are unchecked, select all
			var allUnchecked = true;
			 $("#preferenceSection .weekdays input:checkbox").each(function(i) {
				if (this.checked) allUnchecked = false;
			 });
			 
			 if (allUnchecked) $("#cbxWeekdayAll").get(0).checked = true;
			
		}
		
		window.ClassFinder.filterResults();
	}
    
	///
	/// builds the location section
	///
    this.appendLocations = function(data) {
        
        window.ClassFinder.activateSectionHeader("#citySectionHeader");
        window.ClassFinder.hideCityLoader();
        var cities = data.results.cities;
        
        $("#locationSection").html("");
        $("#locationSection").append("<ul id=\"optionsList\" class='optionsList'></ul>");
        
        $("#ddlLocations").get(0).selectedIndex = 0;
        
		
        $(cities).each(function(i) {
            $("#optionsList").append("<li><input type=\"checkbox\" id=\"cbxCity" + i + "\" name=\"cbxCity" + i + "\" value=\"" + cities[i].id + "\" /><label for=\"cbxCity" + i + "\"> " + cities[i].name + "</label></li>");
            $("#cbxCity" + i).click(window.ClassFinder.processCity);
        });
		
		var cityIds = "";
		for (var i=0; i < cities.length; i++)
		{
			if (i > 0) { cityIds += ","; }
			cityIds += cities[i].id;
		}
		
		// create the all checkbox
		$("#optionsList").append("<li><input type=\"checkbox\" id=\"cbxCityAll\" name=\"cbxCityAll\" value=\"" + cityIds + "\" /><label for=\"cbxCityAll\"> All</label></li>");
        $("#cbxCityAll").click(window.ClassFinder.processCityAll);

    }
	
	this.processCityAll = function() {
		// uncheck all checkboxes
		$("#optionsList input").each(function() {
			this.checked = false;
		});
		
		$("#cbxCityAll").get(0).checked = true;
		
		window.ClassFinder.cityChecked();
	}
	
	this.processCity = function() {
		// uncheck all box
		$("#cbxCityAll").get(0).checked = false;
		
		window.ClassFinder.cityChecked();
	}
	this.cityChecked = function() {
		
		
		// window.ClassFinder.showLocationLoader();
		
		//window.ClassFinder.currentCityName = "";
		var locIds = "";
		$("#optionsList input:checkbox").each(function() {
			var locName =$.trim($("label",$(this).parent()).html());
			if (this.checked)
			{
				if (locIds != "")
				{
					locIds += ",";
				}
				locIds += this.value;
				
				if (locName.toLowerCase() == "all")
				{
				    $("#optionsList input:checkbox").each(function() {
			            var lc =$.trim($("label",$(this).parent()).html());
			            if (lc.toLowerCase() != "all") {
			                window.ClassFinder.currentLocationNameArr.push(lc);
			            }
			        });
				    
				    window.ClassFinder.currentLocationNameArr = unique(window.ClassFinder.currentLocationNameArr);
			
				}
				else
				{
				    window.ClassFinder.currentLocationNameArr.push(locName);
				    window.ClassFinder.currentLocationNameArr = unique(window.ClassFinder.currentLocationNameArr);
			
			    }
			}
			else
			{
				$(window.ClassFinder.currentLocationNameArr).each(function(i, val)
				{
					
					
					if (this == locName) {
					  
						window.ClassFinder.currentLocationNameArr.remove(i);
					}
				});
			}
		});
	   
		if (!$("#locationSection").is(':visible'))
		{
			$("#locationSection").hide().slideDown(250).fadeIn(1000);
		}
		window.filter.locationIds = locIds;
		window.ClassFinder.buildResultsSection();
		window.ClassFinder.buildCityBreadcrumb();
	}
	
	this.resetCityBreadcrumb = function()
	{
		//	window.ClassFinder.currentCityName = "";
	    window.ClassFinder.currentLocationNameArr = new Array();
		$("#resultCityLocation").html("").append(" - ");
	}
	
	this.buildCityBreadcrumb = function()
	{
		$("#resultCityLocation").html("")
            .append(window.ClassFinder.currentCityName + " - ");
        
		// breadcrumb
        $(window.ClassFinder.currentLocationNameArr).each(function(i, val) {
            if (i > 0) {
                $("#resultCityLocation").append(", ");
            }
            $("#resultCityLocation").append(val);
                
        });
	}
    
   
    ///
	/// Builds the preference and results section
	///
	this.buildResultsSection = function() {


	    if (window.filter.locationIds == "") {
	        window.ClassFinder.showPreferenceLoader();
	        window.ClassFinder.resetFormElements();
	    }
	    else {
	        window.ClassFinder.showPreferenceLoader();
	        $.ajax({
	            url: "/json.ashx?method=GetClassesAndInstructorsByLocationId" + window.ClassFinder.getFilteredString(),
	            dataType: "json",
	            success: function(data) {

	                window.ClassFinder.hidePreferenceLoader();
	                var classEvents = data.results.classEvents;
	                var classes = data.results.classes;
	                var categories = data.results.categories;
	                var instructors = data.results.instructors;
	                window.instructorsObj = instructors;

	                var instructorsNameArr = new Array();
	                //to clear it out
	               // var pp = $("#txtInstructors").parent();
	               // pp.html("");
	               // pp.html("<input type=\"text\" id=\"txtInstructors\" value=\"\" />");
	                
	                for (var j = 0; j < instructors.length; j++) {
	                    instructorsNameArr.push(instructors[j].name);
	                }


	                $("#txtInstructors").autocompleteArray(
						instructorsNameArr,
						{
						    delay: 10,
						    minChars: 1,
						    matchSubset: 1,
						    onItemSelect: window.ClassFinder.selectItem,
						    onFindValue: window.ClassFinder.findValue,
						    autoFill: false,
						    maxItemsToShow: 10
						}
					);


	                if (!$("#preferenceSection").is(':visible')) {
	                    window.ClassFinder.activateSectionHeader("#locationSectionHeader");
	                    window.ClassFinder.activateSectionHeader("#preferenceSectionHeader");


	                    $("#ddlClass").html("")
							.append("<option value=\"\">Select Class</option>")
							.append("<option value=\"\"></option>");



	                    $("#txtInstructors").get(0).value = window.ClassFinder.INSTRUCTORS_TEXT;
	                    $("#txtInstructors").focus(function() {
	                        $(this).get(0).value = "";
	                    });

	                    $("#txtInstructors").blur(function() {
	                        if ($(this).get(0).value == "") {
	                            $(this).get(0).value = window.ClassFinder.INSTRUCTORS_TEXT;
	                            window.filter.instructorIds = null;
	                            window.ClassFinder.filterResults();
	                        }
	                    });



	                    $("#ddlCategory").html("")
							.append("<option value=\"\">Select Category</option>")
							.append("<option value=\"\"></option>");

	                    $(categories).each(function(i) {
	                        $("#ddlCategory").append("<option value=\"" + categories[i].id + "\">" + categories[i].name + "</option>");
	                    });

	                    $("#preferenceSection").hide().slideDown(500).fadeIn(1000);
	                }
	                var t = window.ClassFinder.getFilteredString();
	                window.ClassFinder.rebuildResultsTable(data);

	            },
	            error: function(XMLHttpRequest, textStatus, errorThrown) {
	                window.ClassFinder.hidePreferenceLoader();

	            }

	        });
	    }

	}
    
	///
	/// resets the filters to empty
	///
    this.resetFilters = function() {
        window.filter.weekdays = '';
        window.filter.instructorIds = '';
        window.filter.classIds = '';
        
        $("#preferenceSection .weekdays input:checkbox").each(function() {
            this.checked = false;
        });
        
        $("#cbxWeekdayAll").get(0).checked = true;
        
    }
    
	function ResetResultTable()
	{
	   
       $("#tblTempResult tbody").html("");
       $('#tblResults th').removeClass('headerSortDown');
       $('#tblResults th').removeClass('headerSortUp');
       $('#tblResults').find('th').eq(0).addClass('headerSortDown');

	   $("#spnSort").html("");
	   $("#spnSort").html("0|0");
	}
	///
	/// filters the results
	///
    this.filterResults = function() {
        
	   ResetResultTable();
	   window.ClassFinder.showPreferenceLoader();
        $.getJSON("/json.ashx?method=GetClassesAndInstructorsByLocationId" +  window.ClassFinder.getFilteredString(),
            function(data) {				
				ResetResultTable();
                window.ClassFinder.hidePreferenceLoader();
                window.ClassFinder.rebuildResultsTable(data);
               
                
        });
		
    }
	
	this.getFilteredString = function() {
		var filtersPath = "";
		
		if (window.filter.locationIds != '' && window.filter.locationIds != undefined)
        {
            filtersPath = "&locIds=" + window.filter.locationIds;
        }
        
        if (window.filter.weekdays != '' && window.filter.weekdays != undefined)
        {
            filtersPath += "&days=" + window.filter.weekdays;
        }
        
        if (window.filter.classIds != '' && window.filter.classIds != undefined)
        {
            filtersPath += "&classId=" + window.filter.classIds;
        }
        if (window.filter.instructorIds != '' && window.filter.instructorIds != undefined)
        {
            filtersPath += "&instructorId=" + window.filter.instructorIds;
        }
		if($("#spnSort").html() != "")
		{
			var sortText = $("#spnSort").html();
			var sortOrder = sortText.split("|")[1] == 0 ? "asc" : "desc";
	        filtersPath += "&sortExp=" + sortText.split("|")[0] + "&sortdir=" + sortOrder;
		}
        
        $("#btnDownload").unbind("mouseover").mouseover(function(){ 
            this.style.cursor = "pointer"; 
        }).unbind("mouseout").mouseout(function(){ 
            this.style.cursor = "auto"; 
        }).unbind("click").click(function() {
			var filterPath = window.ClassFinder.getFilteredString();
            open('/PdfHandlers/ClassFinderPdf.aspx?x=1' + filterPath,'YourCrunchClasses');
        }); 
		
		return filtersPath;
	}
    this.currentClassEvents = {};
    
	///
	/// rebuilds the table
	///
	this.rebuildResultsTable = function(data) {

		ResetResultTable();

	    window.ClassFinder.currentClassEvents = data.results.classEvents;
	    var classes = data.results.classes;
	    var categories = data.results.categories;
	    var instructors = data.results.instructors;

	    window.ClassFinder.totalPages = Math.ceil(data.results.classEvents.length / window.ClassFinder.tableMaxRows);

        window.ClassFinder.gotoPage(1);

        window.ClassFinder.sortResultTable();
	    var x = window.ClassFinder.getFilteredString();

	}

    function GetDayAsDigit(day)
    {
        switch(day.toLowerCase())
        {
            case "saturday":
                  return 6;
            case "friday":
                  return 5;
            case "thursday":
                  return 4;
            case "wednesday":
                  return 3;
            case "tuesday":
                  return 2;
            case "monday":
                  return 1;
            case "sunday":
                  return 0;
            default:
                    return 0;
        }
    }
    
    function GetTimeAsDigit(time)
    {
		var	tHour = parseInt(time.split(":")[0]);
        var mTime = time.indexOf("PM") > 0 && (tHour < 12)  ? (tHour + 12) :  tHour;
		mTime +=  time.split(":")[1];
        mTime = mTime.replace(' ', '');
		mTime = mTime.replace('AM', '').replace('PM', '');

		return mTime;
    }
	this.gotoPage = function(pageNum) {

	    window.ClassFinder.currentPageNum = pageNum;

	    // populate table
	    var tblResult = $("#tblTempResult")[0];
	    
	    // $("#tblResults").html("<tbody></tbody>");
	    var tableStrArray = new Array();
	    var maxNum = window.ClassFinder.tableMaxRows * window.ClassFinder.currentPageNum;
	    var altz = "even";
	    var numInView = 0;
        if(tblResult != undefined && tblResult.rows.length > 2)
        {
                for (var i = 1; i <= tblResult.rows.length; i++) {

	                    var val = tblResult.rows[i];
	                    if (val != null)
	                     {
                            if(i <= maxNum && i >= maxNum - window.ClassFinder.tableMaxRows)
                            {
                                tableStrArray[i] = "<tr class=\"" + altz + "\">";
                                
	                        }
	                        else
	                        {
	                           tableStrArray[i] = "<tr style=\"display:none\" class=\"" + altz + "\">"; 
	                        }

	                        if (altz == "even") { altz = "odd"; } else { altz = "even"; }

	                        tableStrArray[i] +=
					        "<td>" + val.cells[0].innerHTML + "</td>" +
					        "<td>" + val.cells[1].innerHTML + "</td>" +
						    "<td><a href=\"#\" class=\"popupLink\" popupcontentid=\"description_" + i + "\" popuptitle=\"Class Description\">" + val.cells[2].childNodes[0].innerHTML + "</a></td>" +
	                        // "<td>" + val.name + "</td>" +
					        "<td>" + val.cells[3].innerHTML + "</td>" +
					        "<td>" + val.cells[4].innerHTML + "</td>" +
					        "<td>" + val.cells[5].innerHTML + "</td>" +
					        "<td class=\"hidden\" id=\"description_" + i + "\">" + val.cells[6].innerHTML + "</td>" +
					        "</tr>";

	                        numInView++;
	                    } // end of val
	                } 
        }
        else
        {
             for (var i = 0; i <= window.ClassFinder.currentClassEvents.length; i++) {

	            var val = window.ClassFinder.currentClassEvents[i];
	            
	            if (val != null) 
	            {
                    if(i <= maxNum && i >= maxNum - window.ClassFinder.tableMaxRows)
                    {
                        tableStrArray[i] = "<tr class=\"" + altz + "\">";
	                }
	                else
	                {
	                   tableStrArray[i] = "<tr style=\"display:none\" class=\"" + altz + "\">"; 
	                }

                    if (altz == "even") { altz = "odd"; } else { altz = "even"; }
                    tableStrArray[i] += 
			        "<td>" + "<span style=\"display: none\">" + GetDayAsDigit(val.day) + "</span>" + val.day + "</td>" +
			        "<td>" + "<span style=\"display: none\">" + GetTimeAsDigit(val.time) + "</span>"  + val.time + "</td>" +
			        "<td><a href=\"#\" class=\"popupLink\" popupcontentid=\"description_" + i + "\" popuptitle=\"Class Description\">" + val.name + "</a></td>" +
                    // "<td>" + val.name + "</td>" +
			        "<td>" + val.instructor + "</td>" +
			        "<td>" + val.duration + " min</td>" +
			        "<td>" + window.ClassFinder.currentCityName + " - " + val.location + "</td>" +
			        "<td class=\"hidden\" id=\"description_" + i + "\"><ul><li><ul><li>" + val.description + "</li></ul></li></ul></td>" +
			        "</tr>";

                  numInView++;
	            }
	        //}
	     }
	   }
	   
	    

	    if (window.ClassFinder.currentClassEvents.length > 10) {
	        $("#pager").show();
	    }
	    else {
	        $("#pager").hide();
	    }

	    if (numInView > 0) {
	        $("#btnDownload").show();
	    }
	    else {
	        $("#btnDownload").hide();
	    }
	    $("#tblResults tbody").remove();
	    $("#tblResults").append("<tbody></tbody>");
        //$("#tblResults tbody").html("");
	    $("#tblResults tbody").html(tableStrArray.join(''));
	    tableStrArray = null;
	    window.ClassFinder.updatePager();

	    namespace.popup.init();

	}

	// currentPageNum, tableMaxRows, totalPages
	this.maxItemsInPagerDisplay = 10;
	this.updatePager = function() {
	    $("#pager .pagedisplay").html("");
	    $("#pager .prev a").unbind("click").click(function() {
	        window.ClassFinder.gotoPage(window.ClassFinder.currentPageNum - 1);
	        return false;
	    });

	    $("#pager .next a").unbind("click").click(function() {
	        window.ClassFinder.gotoPage(window.ClassFinder.currentPageNum + 1);
	        return false;
	    });

	    var intLastPage = window.ClassFinder.totalPages;
	    var intFirstPage = 1;
	    var intLastPage = window.ClassFinder.totalPages;
	    if (window.ClassFinder.totalPages > window.ClassFinder.maxItemsInPagerDisplay) {
	        intLastPage = window.ClassFinder.maxItemsInPagerDisplay;
	        if (window.ClassFinder.currentPageNum + 1 > window.ClassFinder.maxItemsInPagerDisplay) {
	            intFirstPage = window.ClassFinder.currentPageNum - 5;
	            intLastPage = window.ClassFinder.currentPageNum + 5;
	            if (intLastPage > window.ClassFinder.totalPages) {
	                intLastPage = window.ClassFinder.totalPages;
	                intFirstPage = intLastPage - window.ClassFinder.maxItemsInPagerDisplay;
	            }

	        }
	        
	        if (window.ClassFinder.currentPageNum > window.ClassFinder.totalPages - window.ClassFinder.maxItemsInPagerDisplay &&
	            window.ClassFinder.currentPageNum > window.ClassFinder.maxItemsInPagerDisplay) {
	            intFirstPage = window.ClassFinder.totalPages - window.ClassFinder.maxItemsInPagerDisplay;
	            intLastPage = window.ClassFinder.totalPages;
	        }

	        

	    }

	    for (var i = intFirstPage; i <= intLastPage; i++) {
	        var act = "";
	        if (i == window.ClassFinder.currentPageNum) { act = "active"; }
	        $("#pager .pagedisplay").append('<a href="#" class="' + act + '" onclick="window.ClassFinder.gotoPage(' + i + '); return false;">' + i + '</a>');

	    }
	}
	 
	this.resetFormElements = function() {
		window.ClassFinder.resetFilters();
		window.ClassFinder.resetCityBreadcrumb();
		window.ClassFinder.hidePreferenceLoader();
		$("#tblResults tbody").remove();
        $("#tblResults").append("<tbody></tbody>");
		$("#pager").hide();
		$("#btnDownload").hide();
	 }
    
	
	///
	/// Initializes each section
	///
    this.initSections = function() {
        
        $(sections).each(function(i) {
            $("#" + this).css('width','830px').hide();
        });
        
        $("#btnSearch").bind("mouseenter", function() {
            this.style.cursor = 'pointer';
        });
        $("#btnSearch").bind("mouseleave", function() {
             this.style.cursor = 'default';
        });
            
        $("#btnSearch").click(function() {
            //TODO: search
        });
    }
    
	///
	/// activates the section header by passing the name
	///
    this.activateSectionHeader = function(sectionHeaderName)
    {
        
        $(sectionHeaderName).bind("mouseenter", function() {
            this.style.cursor = 'pointer';
        });
        $(sectionHeaderName).bind("mouseleave", function() {
             this.style.cursor = 'default';
        });
        
        $(sectionHeaderName).unbind('click').click(function() {
            window.ClassFinder.showSection(this.id.replace('Header',''));
        });
    
    }

	///
	/// shows the section
	///
    this.showSection = function(section) {
       $(sectionHeaders).each(function(i) {
            
            var sec = $("#" + this);
            if (sec.is(':visible'))
            {
                $("#" + this.replace('Header','')).slideUp(500);
            }
       });
      
      var sec = $("#" + section);
      if (!sec.is(':visible'))
      {
        $("#" + section).slideDown(500);
      }
      
      
    }
	
	///
	/// SHOW and HIDE loaders
	///
    this.showPreferenceLoader = function() {
        $("#preferenceLoader").show();
                
    }
    
    this.hidePreferenceLoader = function() {
        $("#preferenceLoader").hide();
    }
     this.showCityLoader = function() {
        $("#cityLoader").show();
                
    }
    
    this.hideCityLoader = function() {
        $("#cityLoader").hide();
    }
     this.showLocationLoader = function() {
        $("#locationLoader").show();
                
    }
    
    this.hideLocationLoader = function() {
        $("#locationLoader").hide();
    }

	///
	/// custom table parsers
	///
    this.addTableParsers = function() {
        /****************************
        * TABLE SORTER PARSER
        *****************************/
        // add parser through the tablesorter addParser method 
        $.tablesorter.addParser({ 
            // set a unique id 
            id: 'days', 
            is: function(s) { 
                // return false so this parser is not auto detected 
                return false; 
            }, 
            format: function(s) { 
                // format your data for normalization 
                return s.toLowerCase().replace(/saturday/,6).replace(/friday/,5).replace(/thursday/,4).replace(/wednesday/,3).replace(/tuesday/,2).replace(/monday/,1).replace(/sunday/,0); 
            }, 
            // set type, either numeric or text 
            type: 'numeric' 
        }); 
    }
    
    this.sortResultTable = function() {
        $(function()
        {
         $("#tblResults")
         .tablesorter();
        }
        );
    }
    this.selectItem = function(li)
    {
        window.ClassFinder.findValue(li);
    }
    
    this.findValue = function(li)
    {
        
	    var sValue = li.selectValue;
        var t = "";
    	
        for (var i = 0; i < instructorsObj.length; i++)
        {
            if (sValue == instructorsObj[i].name)
            {
                t = instructorsObj[i].id;
            }
        }
        window.filter.instructorIds = t;
        window.ClassFinder.filterResults();
    }
}



$(document).ready(function() {
    
   ClassFinder.init();
});



/**
 * Removes duplicates in the array 'a'
 * @author Johan Känngård, http://dev.kanngard.net
 */
function unique(a) {
	tmp = new Array(0);
	for(i=0;i<a.length;i++){
		if(!contains(tmp, a[i])){
			tmp.length+=1;
			tmp[tmp.length-1]=a[i];
		}
	}
	return tmp;
}

/**
 * Returns true if 's' is contained in the array 'a'
 * @author Johan Känngård, http://dev.kanngard.net
 */
function contains(a, e) {
	for(j=0;j<a.length;j++)if(a[j]==e)return true;
	return false;
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

// cookie funtions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}