<commit_before>//This function is going to take an input of all classes in a semester and all classes taken so far
// and choose x classes to
// attend and return the scheduled classes with these added.
function course(level,courseName,courseNumber, creditHours)
{
    this.courseName = name;
    this.level = level;
    this.courseNumber = courseNumber;
    this.creditHours = creditHours;
    //All of these can be undefined. If a variable is undefined, it is considered to mean
    //Any course of that level. This can be used for the requirements var
}

function restriction(dayOrNight, maxHours){
    this.dayOrNight = dayOrNight;
    this.maxHours = maxHours;
}

function scheduleSemesterClasses(courseLimit, availableCourses, availableStartingIndex, coursesTaken, takenStartingIndex){
    var takenIndex = takenStartingIndex;
    var outList = [];
    for(var availableIndex = availableStartingIndex; availableIndex < availableCourses.length; availableIndex++){
        while( takenIndex < coursesTaken.length && availableCourses[availableIndex].courseNumber > coursesTaken[takenIndex].courseNumber){ // make sure that we are comparing the closest higher course taken next
            takenIndex++;
        }
        if((takenIndex >= coursesTaken.length || coursesTaken.length == 0 || coursesTaken[takenIndex].courseNumber != availableCourses[availableIndex].courseNumber) && courseLimit == 1){
            //if this course hasn't been taken
            outList.push([availableCourses[availableIndex]])
        }else if(takenIndex >= coursesTaken.length || coursesTaken[takenIndex].courseNumber != availableCourses[availableIndex].courseNumber){
            outList = outList.concat(permutate(availableCourses[availableIndex], scheduleSemesterClasses(courseLimit-1, availableCourses, availableIndex+1, coursesTaken, takenIndex)));
        }
    }

    return outList;
}

function permutate(courseToPerm, listToPerm){
    //courseToPerm is an int
    //listToPerm is an Array of Arrays of ints
    var outList = [];
    for(var x =0; x < listToPerm.length; x++){
        outList.push([courseToPerm].concat(listToPerm[x]));
    }

    return outList;
}

//This is the main function of the program
function scheduleAll(totalCourses, coursesPerSemester, coursesAvailable, requirementsIn){

    var requirements = new Object();
    requirements = requirementsIn;
    if(requirements.useTest == true){
        //setting the default
        var arrayOfReqTitles = ["reqCourseNumbers", "preReqCourseNumbers", "dayOfWeekPreference", "reqPerSemesterCourseNumbers", "reqCourseAtLeast"]
        requirements.reqCourse = ["4250","5130"];
        requirements.reqCourse.sort();
        requirements.preReqs = [["4010","5010"]];
        requirements.greaterThan= [[6000, 1], [5000, 6]];
        requirements.coursesPerSemester = [2,1,3];
        requirements.semesterLimit = 10;
        requirements.waived = ["4010"];
        requirements.startDate = [2014, "Fall"];
	requirements.preferences = [0, -1];
        requirements.reqCoursePerSemester = [["4250"],["5130"]];
        requirements.minCoursesBase = 3; //No less than 3 courses per semester
        requirements.minCoursesPerSemester = [1,2,3]; // No less than 1 course in the 1st semester Both of these do not count for the final semester
    }

    return scheduleAllRecursive(totalCourses, coursesPerSemester, coursesAvailable, [], 0, requirements);
}

function scheduleAllRecursive(totalCourses, coursesPerSemester, coursesAvailable, coursesTaken, currentSemesterIndex, requirements){
    var courseNumberAvailableList = [];
    var courseNumberTakenList = [];
    var seasonList = ["Spring", "Fall"];
    var startDate = [2014, "Fall"];
    if(requirements.startDate != undefined){
        startDate = requirements.startDate;
    }
    var numberOfCoursesToTake = totalCourses;
    var minNumberOfCoursesToTake = 0;

    if(requirements.minCoursesBase != undefined){
        minNumberOfCoursesToTake = requirements.minCoursesBase-1;
    }

    if(requirements.minCoursesPerSemester != undefined &&  requirements.minCoursesPerSemester[currentSemesterIndex] != undefined){
        minNumberOfCoursesToTake = requirements.minCoursesPerSemester[currentSemesterIndex]-1;
    }

    var potentialSolutions = [];
    potentialSolutions.push([]);

    if(requirements.semesterLimit != undefined && currentSemesterIndex >= requirements.semesterLimit){
        return []; //Do not continue down this branch if we are searching past the semester limit
    }

    if(requirements.waived != undefined && currentSemesterIndex == 0){
        coursesTaken = coursesTaken.concat(createWaived(requirements.waived));
        totalCourses = totalCourses + requirements.waived.length;
    }

    var semesterIndex = currentSemesterIndex;
    var courseLimitCurrentSemester = coursesPerSemester;

    //Set unavailable courses. The prereqs aren't filled or you just cant take them this semester
    var unavailableCourses = [];
    unavailableCourses = unavailableCourses.concat(doesntCompletePreReqs(coursesTaken,requirements));

    if(requirements.coursesPerSemester != undefined && requirements.coursesPerSemester[currentSemesterIndex] != undefined){
        courseLimitCurrentSemester = requirements.coursesPerSemester[currentSemesterIndex];
    }

    if(coursesTaken.length > 0 && numberOfCoursesToTake-coursesTaken[0].length < courseLimitCurrentSemester){
        courseLimitCurrentSemester = numberOfCoursesToTake-coursesTaken[0].length;
    }

    if(minNumberOfCoursesToTake >= courseLimitCurrentSemester){
        minNumberOfCoursesToTake = courseLimitCurrentSemester-1;
    }

    //set coursesAvailable list
    courseNumberAvailableList = getCoursesAvailableThisSemester(coursesAvailable, startDate, semesterIndex, seasonList, requirements.preferences);

    if(courseNumberAvailableList.length == 0){
        console.log("Hitting the end of the schedule data. Result will be bound to the dataset.");
    }

    var takenAndNoPreReq =[];
    if(unavailableCourses.length > 0 ){
        takenAndNoPreReq = coursesTaken.concat(unavailableCourses);
        takenAndNoPreReq.sort(function(a,b){
            return parseInt(a.courseNumber) - parseInt(b.courseNumber);
        });
    }else{
        takenAndNoPreReq = coursesTaken;
    }

    var solutionPermutationsForIndexY = [];
    for(var numberOfCoursesIndex = courseLimitCurrentSemester; numberOfCoursesIndex > minNumberOfCoursesToTake; numberOfCoursesIndex--){
        var semesterPermOfSameLength = scheduleSemesterClasses(numberOfCoursesIndex, courseNumberAvailableList, 0 , takenAndNoPreReq, 0);
        if(requirements.reqCoursePerSemester != undefined && requirements.reqCoursePerSemester[currentSemesterIndex] != undefined){
            semesterPermOfSameLength = filterRequirements(semesterPermOfSameLength, requirements.reqCoursePerSemester[currentSemesterIndex], semesterPermOfSameLength[0].length);
        }
        solutionPermutationsForIndexY = solutionPermutationsForIndexY.concat(combineTakenAndNew(coursesTaken,semesterPermOfSameLength));
    }
    //FILTER FOR REQ'S HERE ( if solutionPermutationsForIndexY has anything left in it, break, we have a solution)
    //solutionPermutationsForIndexY = filterSemesterRequirements(solutionPermutationsForIndexY, requirements);

    var filteredSolution = filterCurrentBranch(solutionPermutationsForIndexY, requirements, numberOfCoursesToTake); // This is going to return an array of length 2;
    if(filteredSolution[0].length > 0){
        return removeWaived(filteredSolution[0]);
    }

    solutionPermutationsForIndexY = filteredSolution[1];
    //inductive step
    for(var y = 0; y < solutionPermutationsForIndexY.length; y++){

        var returnedAnswer = scheduleAllRecursive(totalCourses, coursesPerSemester, coursesAvailable, solutionPermutationsForIndexY[y], semesterIndex+1, requirements)
        if(returnedAnswer.length > 0){
            return returnedAnswer;
        }
    }

    return [];
}

function doesntCompletePreReqs(coursesIn, requirements){
    var outList = [];
    var failList = [];
    var passedList = []
    if(requirements.preReqs != undefined && coursesIn.length > 0){
        //Here we go through each prereq and see if it's been satisfied. If it hasn't it gets added to the outlist
        for(var reqIndex=0; reqIndex < requirements.preReqs.length; reqIndex++){
            //now we check 1 particular requirement
            var preReqsPassed = true;
            for(var preReqIndex=1; preReqIndex < requirements.preReqs[reqIndex].length; preReqIndex++){
                if(!courseNumberInCourseList(coursesIn, requirements.preReqs[reqIndex][preReqIndex])){
                    preReqsPassed = false;
                }
            }
            if(preReqsPassed){
                passedList.push(requirements.preReqs[reqIndex]);
            }else{
                failList.push(requirements.preReqs[reqIndex]);
            }
        }
        passedList.sort(function(a,b){
            return parseInt(a[0]) - parseInt(b[0]);
        });
        failList.sort(function(a,b){
            return parseInt(a[0]) - parseInt(b[0]);
        });
        var passedIndex = 0;
        for(var failListIndex = 0; failListIndex < failList.length; failListIndex++){
            if(failListIndex == 0 || failList[failListIndex][0] != failList[failListIndex-1][0]){
                while(passedIndex < passedList.length && failList[failListIndex][0] > passedList[passedIndex][0]){ // make sure that we are comparing the closest higher course taken next
                    passedIndex++;
                }
                if(passedIndex >= passedList.length ||  passedList.length == 0 || passedList[passedIndex][0] != failList[failListIndex][0]){
                    var newBlankCourse = new Object();
                    newBlankCourse.courseNumber = failList[failListIndex][0];
                    outList.push(newBlankCourse);
                }
            }
        }
    }else if(requirements.preReqs != undefined){
        for(var outListIndex = 0; outListIndex < requirements.preReqs.length; outListIndex++){
            var newBlankCourse = new Object();
            newBlankCourse.courseNumber = requirements.preReqs[outListIndex][0];
            outList.push(newBlankCourse);
        }
    }

    return outList;
}

function createWaived(courseNumList){
    var outList =[]
    for(var outListIndex = 0; outListIndex < courseNumList.length; outListIndex++){
        var newBlankCourse = new Object();
        newBlankCourse.courseNumber = courseNumList[outListIndex];
        newBlankCourse.waived = true;
        outList.push(newBlankCourse);
    }
    return outList;
}

function filterCurrentBranch(scheduleArrayIn, requirements, numberOfCoursesToTake){
    var returnSolution = [];
    var scheduleArray = filterGreaterThan(scheduleArrayIn, requirements, numberOfCoursesToTake);
    scheduleArray = filterRequirements(scheduleArray, requirements.reqCourse, numberOfCoursesToTake);

    if(scheduleArray.length > 0 && scheduleArray[0].length == numberOfCoursesToTake){
        returnSolution = scheduleArray[0];
    }

    return [returnSolution, scheduleArray];
}

function filterRequirements(scheduleArrayIn, requiredCourses, numberOfCoursesToTake){
    var reqCoursePass;
    var reqCoursePassCount;
    var returnSchedule = [];
    var scheduleArray = scheduleArrayIn;
    if(requiredCourses != undefined && requiredCourses.length > 0){
        for(var scheduleIndex=0; scheduleIndex < scheduleArray.length; scheduleIndex++){
            reqCoursePassCount = 0;
            for(var reqCourseIndex=0; reqCourseIndex < requiredCourses.length; reqCourseIndex++){
                for (var courseIndex =0; courseIndex < scheduleArray[scheduleIndex].length; courseIndex++){
                    if(scheduleArray[scheduleIndex][courseIndex].courseNumber == requiredCourses[reqCourseIndex]){
                        reqCoursePassCount++;
                        break;//look for the next required course
                    }
                }
            }
            if((requiredCourses.length - reqCoursePassCount) + scheduleArray[scheduleIndex].length <= numberOfCoursesToTake){
                returnSchedule.push(scheduleArray[scheduleIndex]);
            }
        }
    }else{
        returnSchedule = scheduleArray;
    }

    return returnSchedule;
}

function removeWaived(schedule){
    var outList =[]
    for(var outListIndex = 0; outListIndex < schedule.length; outListIndex++){
        if(schedule[outListIndex].waived != true){
            outList.push(schedule[outListIndex]);
        }
    }

    return outList;
}

function filterGreaterThan(scheduleArrayIn, requirements, numberOfCoursesToTake){
    var reqCoursePass;
    var reqCoursePassCount = [];
    var returnSchedule = [];
    var returnSolution = [];
    if(requirements.greaterThan != undefined && requirements.greaterThan.length > 0){
        for(var scheduleIndex=0; scheduleIndex < scheduleArrayIn.length; scheduleIndex++){
            reqCoursePassCount = [];
            for(var reqCourseIndex=0; reqCourseIndex < requirements.greaterThan.length; reqCourseIndex++){
                reqCoursePassCount.push(0);
                for (var courseIndex =0; courseIndex < scheduleArrayIn[scheduleIndex].length; courseIndex++){
                    if(parseInt(scheduleArrayIn[scheduleIndex][courseIndex].courseNumber) >= requirements.greaterThan[reqCourseIndex][0]){
                        reqCoursePassCount[reqCoursePassCount.length-1]++;
                    }
                }
            }
            var schedulePass = true;
            for(var reqCoursePassCountIndex = 0; reqCoursePassCountIndex < reqCoursePassCount.length; reqCoursePassCountIndex++){
                if(requirements.greaterThan[reqCoursePassCountIndex][1] - reqCoursePassCount[reqCoursePassCountIndex] > numberOfCoursesToTake - scheduleArrayIn[scheduleIndex].length){
                    schedulePass = false;
                }
            }

            if(schedulePass){
                returnSchedule.push(scheduleArrayIn[scheduleIndex]);
            }
        }
    }else{
        returnSchedule = scheduleArrayIn;
    }

    return returnSchedule;
}

function courseNumberInCourseList(courseList, courseNumberToFind){
    for(var courseIndex = 0 ; courseIndex < courseList.length; courseIndex++){
        if(courseList[courseIndex].courseNumber == courseNumberToFind){
            return true;
        }
    }
    return false;
}

function combineTakenAndNew(takenCourses, newCourses){
    //taken []
    //new [[]]
    var outList = [];
    for(var x =0; x < newCourses.length; x++){
        outList.push(takenCourses.concat(newCourses[x]));
    }
    for(var y=0; y < outList.length; y++){
        outList[y] = outList[y].sort(function(a,b){
            return parseInt(a.courseNumber) - parseInt(b.courseNumber);
        });
    }

    return outList;

}

function getCoursesAvailableThisSemester(coursesAvailable, startDate, semesterIndex, seasonList, preferences){
    var coursesAvailableReturn =[];
    var currentYear = startDate[0] + parseInt((semesterIndex+seasonList.indexOf(startDate[1]))/seasonList.length);
    var currentMonth =  seasonList[(seasonList.indexOf(startDate[1]) + semesterIndex)%seasonList.length];
    if(preferences === undefined)
	preferences = [0, -1];
    for(var x = 0; x < coursesAvailable.length; x++){
        if(coursesAvailable[x].year == currentYear && coursesAvailable[x].semester == currentMonth){
            //If these courses have a schedule component
            if(coursesAvailable[x].day != "" && coursesAvailable[x].time != "") {
                //If we have preferences (preferences only matter if we have a schedule component)
                if(preferences[0] == 1 || preferences[1] >= 0) {
                    //Check time preference
                    if(preferences[0] == 1) {
                        //If it isn't offered in the evening, throw it out
                        if(coursesAvailable[x].time.indexOf("E") == -1) continue;
                    }
                    //Check day preference
                    if(preferences[1] == 0) {
                        if(coursesAvailable[x].day.indexOf("MW") == -1) continue;
                    } else if(preferences[1] == 1) {
                        if(coursesAvailable[x].day.indexOf("TR") == -1) continue;
                    }
                }
                //If we haven't "continue"d, then we haven't violated anything, add it
                coursesAvailableReturn.push(coursesAvailable[x]);
            } else
                coursesAvailableReturn.push(coursesAvailable[x]);
        }
    }
    coursesAvailableReturn.sort(function(a,b){
        return parseInt(a.courseNumber) - parseInt(b.courseNumber);
    });
    return coursesAvailableReturn;
}
<commit_msg>Support for A-B courses and restricted courses<commit_after>//This function is going to take an input of all classes in a semester and all classes taken so far
// and choose x classes to
// attend and return the scheduled classes with these added.
function course(level,courseName,courseNumber, creditHours)
{
    this.courseName = name;
    this.level = level;
    this.courseNumber = courseNumber;
    this.creditHours = creditHours;
    //All of these can be undefined. If a variable is undefined, it is considered to mean
    //Any course of that level. This can be used for the requirements var
}

function restriction(dayOrNight, maxHours){
    this.dayOrNight = dayOrNight;
    this.maxHours = maxHours;
}

function scheduleSemesterClasses(courseLimit, availableCourses, availableStartingIndex, coursesTaken, takenStartingIndex){
    var takenIndex = takenStartingIndex;
    var outList = [];
    for(var availableIndex = availableStartingIndex; availableIndex < availableCourses.length; availableIndex++){
        while( takenIndex < coursesTaken.length && availableCourses[availableIndex].courseNumber > coursesTaken[takenIndex].courseNumber){ // make sure that we are comparing the closest higher course taken next
            takenIndex++;
        }
        if((takenIndex >= coursesTaken.length || coursesTaken.length == 0 || coursesTaken[takenIndex].courseNumber != availableCourses[availableIndex].courseNumber) && courseLimit == 1){
            //if this course hasn't been taken
            outList.push([availableCourses[availableIndex]])
        }else if(takenIndex >= coursesTaken.length || coursesTaken[takenIndex].courseNumber != availableCourses[availableIndex].courseNumber){
            outList = outList.concat(permutate(availableCourses[availableIndex], scheduleSemesterClasses(courseLimit-1, availableCourses, availableIndex+1, coursesTaken, takenIndex)));
        }
    }

    return outList;
}

function permutate(courseToPerm, listToPerm){
    //courseToPerm is an int
    //listToPerm is an Array of Arrays of ints
    var outList = [];
    for(var x =0; x < listToPerm.length; x++){
        outList.push([courseToPerm].concat(listToPerm[x]));
    }

    return outList;
}

//This is the main function of the program
function scheduleAll(totalCourses, coursesPerSemester, coursesAvailable, requirementsIn){

    var requirements = new Object();
    requirements = requirementsIn;
    if(requirements.useTest == true){
        //setting the test. This might not work, but there is basic usage here for all options
        requirements.reqCourse = ["4250","5130"];
        requirements.reqCourse.sort();
        requirements.preReqs = [["4010","5010"]];
        requirements.greaterThan= [[6000, 1], [5000, 6]];
        requirements.coursesPerSemester = [2,1,3];
        requirements.semesterLimit = 10;
        requirements.waived = ["4010"];
        requirements.startDate = [2014, "Fall"];
		requirements.preferences = [0, -1];
        requirements.reqCoursePerSemester = [["4250"],["5130"]];
        requirements.minCoursesBase = 3; //No less than 3 courses per semester
        requirements.minCoursesPerSemester = [1,2,3]; // No less than 1 course in the 1st semester Both of these do not count for the final semester
        requirements.restrictCourseBySemester = [[],["4250","5130"], ["4010"]]
    }

    return scheduleAllRecursive(totalCourses, coursesPerSemester, coursesAvailable, [], 0, requirements);
}

function scheduleAllRecursive(totalCourses, coursesPerSemester, coursesAvailable, coursesTaken, currentSemesterIndex, requirements){
    var courseNumberAvailableList = [];
    var courseNumberTakenList = [];
    var seasonList = ["Spring", "Fall"];
    var startDate = [2014, "Fall"];
    if(requirements.startDate != undefined){
        startDate = requirements.startDate;
    }
    var numberOfCoursesToTake = totalCourses;
    var minNumberOfCoursesToTake = 0;

    if(requirements.minCoursesBase != undefined){
        minNumberOfCoursesToTake = requirements.minCoursesBase-1;
    }

    if(requirements.minCoursesPerSemester != undefined &&  requirements.minCoursesPerSemester[currentSemesterIndex] != undefined){
        minNumberOfCoursesToTake = requirements.minCoursesPerSemester[currentSemesterIndex]-1;
    }

    var potentialSolutions = [];
    potentialSolutions.push([]);

    if(requirements.semesterLimit != undefined && currentSemesterIndex >= requirements.semesterLimit){
        return []; //Do not continue down this branch if we are searching past the semester limit
    }

    if(requirements.waived != undefined && currentSemesterIndex == 0){
        coursesTaken = coursesTaken.concat(numberListToBlankCourseList(requirements.waived));
        totalCourses = totalCourses + requirements.waived.length;
    }

    var semesterIndex = currentSemesterIndex;
    var courseLimitCurrentSemester = coursesPerSemester;

    //--------------------------------------------------------------------------------------------
    //Set unavailable courses. The prereqs aren't filled or you just cant take them this semester
    var unavailableCourses = [];
    unavailableCourses = unavailableCourses.concat(doesntCompletePreReqs(coursesTaken,requirements));

    if(requirements.restrictCourseBySemester != undefined && requirements.restrictCourseBySemester[currentSemesterIndex] != undefined){
    	unavailableCourses = unavailableCourses.concat(numberListToBlankCourseList(requirements.restrictCourseBySemester[currentSemesterIndex]));
    }

    //--------------------------------------------------------------------------------------------

    //Set the course upper and lower limits for classes this semester
    //----------------------------------------------------------------------------------------------
    if(requirements.coursesPerSemester != undefined && requirements.coursesPerSemester[currentSemesterIndex] != undefined){
        courseLimitCurrentSemester = requirements.coursesPerSemester[currentSemesterIndex];
    }

    if(coursesTaken.length > 0 && numberOfCoursesToTake-coursesTaken[0].length < courseLimitCurrentSemester){
        courseLimitCurrentSemester = numberOfCoursesToTake-coursesTaken[0].length;
    }

    if(minNumberOfCoursesToTake >= courseLimitCurrentSemester){
        minNumberOfCoursesToTake = courseLimitCurrentSemester-1;
    }
    //----------------------------------------------------------------------------------------------

    //set coursesAvailable list
    courseNumberAvailableList = getCoursesAvailableThisSemester(coursesAvailable, startDate, semesterIndex, seasonList, requirements.preferences);

    if(courseNumberAvailableList.length == 0){
        console.log("Hitting the end of the schedule data. Result will be bound to the dataset.");
    }

    var takenAndNoPreReq =[];
    if(unavailableCourses.length > 0 ){
        takenAndNoPreReq = coursesTaken.concat(unavailableCourses);
        takenAndNoPreReq.sort(function(a,b){
            return parseCourseNumber(a.courseNumber) - parseCourseNumber(b.courseNumber);
        });
    }else{
        takenAndNoPreReq = coursesTaken;
    }

    var solutionPermutationsForIndexY = [];
    for(var numberOfCoursesIndex = courseLimitCurrentSemester; numberOfCoursesIndex > minNumberOfCoursesToTake; numberOfCoursesIndex--){
        var semesterPermOfSameLength = scheduleSemesterClasses(numberOfCoursesIndex, courseNumberAvailableList, 0 , takenAndNoPreReq, 0);
        if(requirements.reqCoursePerSemester != undefined && requirements.reqCoursePerSemester[currentSemesterIndex] != undefined){
            semesterPermOfSameLength = filterRequirements(semesterPermOfSameLength, requirements.reqCoursePerSemester[currentSemesterIndex], semesterPermOfSameLength[0].length);
        }
        solutionPermutationsForIndexY = solutionPermutationsForIndexY.concat(combineTakenAndNew(coursesTaken,semesterPermOfSameLength));
    }
    //FILTER FOR REQ'S HERE ( if solutionPermutationsForIndexY has anything left in it, break, we have a solution)
    //solutionPermutationsForIndexY = filterSemesterRequirements(solutionPermutationsForIndexY, requirements);

    var filteredSolution = filterCurrentBranch(solutionPermutationsForIndexY, requirements, numberOfCoursesToTake); // This is going to return an array of length 2;
    if(filteredSolution[0].length > 0){
        return removeWaived(filteredSolution[0]);
    }

    solutionPermutationsForIndexY = filteredSolution[1];
    //inductive step
    for(var y = 0; y < solutionPermutationsForIndexY.length; y++){

        var returnedAnswer = scheduleAllRecursive(totalCourses, coursesPerSemester, coursesAvailable, solutionPermutationsForIndexY[y], semesterIndex+1, requirements)
        if(returnedAnswer.length > 0){
            return returnedAnswer;
        }
    }

    return [];
}

function doesntCompletePreReqs(coursesIn, requirements){
    var outList = [];
    var failList = [];
    var passedList = []
    if(requirements.preReqs != undefined && coursesIn.length > 0){
        //Here we go through each prereq and see if it's been satisfied. If it hasn't it gets added to the outlist
        for(var reqIndex=0; reqIndex < requirements.preReqs.length; reqIndex++){
            //now we check 1 particular requirement
            var preReqsPassed = true;
            for(var preReqIndex=1; preReqIndex < requirements.preReqs[reqIndex].length; preReqIndex++){
                if(!courseNumberInCourseList(coursesIn, requirements.preReqs[reqIndex][preReqIndex])){
                    preReqsPassed = false;
                }
            }
            if(preReqsPassed){
                passedList.push(requirements.preReqs[reqIndex]);
            }else{
                failList.push(requirements.preReqs[reqIndex]);
            }
        }
        passedList.sort(function(a,b){
            return parseCourseNumber(a[0]) - parseCourseNumber(b[0]);
        });
        failList.sort(function(a,b){
            return parseCourseNumber(a[0]) - parseCourseNumber(b[0]);
        });
        var passedIndex = 0;
        for(var failListIndex = 0; failListIndex < failList.length; failListIndex++){
            if(failListIndex == 0 || failList[failListIndex][0] != failList[failListIndex-1][0]){
                while(passedIndex < passedList.length && failList[failListIndex][0] > passedList[passedIndex][0]){ // make sure that we are comparing the closest higher course taken next
                    passedIndex++;
                }
                if(passedIndex >= passedList.length ||  passedList.length == 0 || passedList[passedIndex][0] != failList[failListIndex][0]){
                    var newBlankCourse = new Object();
                    newBlankCourse.courseNumber = failList[failListIndex][0];
                    outList.push(newBlankCourse);
                }
            }
        }
    }else if(requirements.preReqs != undefined){
        for(var outListIndex = 0; outListIndex < requirements.preReqs.length; outListIndex++){
            var newBlankCourse = new Object();
            newBlankCourse.courseNumber = requirements.preReqs[outListIndex][0];
            outList.push(newBlankCourse);
        }
    }

    return outList;
}

function numberListToBlankCourseList(courseNumList){
    var outList =[]
    for(var outListIndex = 0; outListIndex < courseNumList.length; outListIndex++){
        var newBlankCourse = new Object();
        newBlankCourse.courseNumber = courseNumList[outListIndex];
        newBlankCourse.waived = true;
        outList.push(newBlankCourse);
    }
    return outList;
}

function filterCurrentBranch(scheduleArrayIn, requirements, numberOfCoursesToTake){
    var returnSolution = [];
    var scheduleArray = filterGreaterThan(scheduleArrayIn, requirements, numberOfCoursesToTake);
    scheduleArray = filterRequirements(scheduleArray, requirements.reqCourse, numberOfCoursesToTake);

    if(scheduleArray.length > 0 && scheduleArray[0].length == numberOfCoursesToTake){
        returnSolution = scheduleArray[0];
    }

    return [returnSolution, scheduleArray];
}

function filterRequirements(scheduleArrayIn, requiredCourses, numberOfCoursesToTake){
    var reqCoursePass;
    var reqCoursePassCount;
    var returnSchedule = [];
    var scheduleArray = scheduleArrayIn;
    if(requiredCourses != undefined && requiredCourses.length > 0){
        for(var scheduleIndex=0; scheduleIndex < scheduleArray.length; scheduleIndex++){
            reqCoursePassCount = 0;
            for(var reqCourseIndex=0; reqCourseIndex < requiredCourses.length; reqCourseIndex++){
                for (var courseIndex =0; courseIndex < scheduleArray[scheduleIndex].length; courseIndex++){
                    if(scheduleArray[scheduleIndex][courseIndex].courseNumber == requiredCourses[reqCourseIndex]){
                        reqCoursePassCount++;
                        break;//look for the next required course
                    }
                }
            }
            if((requiredCourses.length - reqCoursePassCount) + scheduleArray[scheduleIndex].length <= numberOfCoursesToTake){
                returnSchedule.push(scheduleArray[scheduleIndex]);
            }
        }
    }else{
        returnSchedule = scheduleArray;
    }

    return returnSchedule;
}

function removeWaived(schedule){
    var outList =[]
    for(var outListIndex = 0; outListIndex < schedule.length; outListIndex++){
        if(schedule[outListIndex].waived != true){
            outList.push(schedule[outListIndex]);
        }
    }

    return outList;
}

function parseCourseNumber(courseNumberString){
	var courseNumberOut = parseInt(courseNumberString);
	if(courseNumberString != undefined && courseNumberString.indexOf('B') != -1){
		courseNumberOut += .5;
	}
	return courseNumberOut;
}

function filterGreaterThan(scheduleArrayIn, requirements, numberOfCoursesToTake){
    var reqCoursePass;
    var reqCoursePassCount = [];
    var returnSchedule = [];
    var returnSolution = [];
    if(requirements.greaterThan != undefined && requirements.greaterThan.length > 0){
        for(var scheduleIndex=0; scheduleIndex < scheduleArrayIn.length; scheduleIndex++){
            reqCoursePassCount = [];
            for(var reqCourseIndex=0; reqCourseIndex < requirements.greaterThan.length; reqCourseIndex++){
                reqCoursePassCount.push(0);
                for (var courseIndex =0; courseIndex < scheduleArrayIn[scheduleIndex].length; courseIndex++){
                    if(parseCourseNumber(scheduleArrayIn[scheduleIndex][courseIndex].courseNumber) >= requirements.greaterThan[reqCourseIndex][0]){
                        reqCoursePassCount[reqCoursePassCount.length-1]++;
                    }
                }
            }
            var schedulePass = true;
            for(var reqCoursePassCountIndex = 0; reqCoursePassCountIndex < reqCoursePassCount.length; reqCoursePassCountIndex++){
                if(requirements.greaterThan[reqCoursePassCountIndex][1] - reqCoursePassCount[reqCoursePassCountIndex] > numberOfCoursesToTake - scheduleArrayIn[scheduleIndex].length){
                    schedulePass = false;
                }
            }

            if(schedulePass){
                returnSchedule.push(scheduleArrayIn[scheduleIndex]);
            }
        }
    }else{
        returnSchedule = scheduleArrayIn;
    }

    return returnSchedule;
}

function courseNumberInCourseList(courseList, courseNumberToFind){
    for(var courseIndex = 0 ; courseIndex < courseList.length; courseIndex++){
        if(courseList[courseIndex].courseNumber == courseNumberToFind){
            return true;
        }
    }
    return false;
}

function combineTakenAndNew(takenCourses, newCourses){
    //taken []
    //new [[]]
    var outList = [];
    for(var x =0; x < newCourses.length; x++){
        outList.push(takenCourses.concat(newCourses[x]));
    }
    for(var y=0; y < outList.length; y++){
        outList[y] = outList[y].sort(function(a,b){
            return parseCourseNumber(a.courseNumber) - parseCourseNumber(b.courseNumber);
        });
    }

    return outList;

}

function getCoursesAvailableThisSemester(coursesAvailable, startDate, semesterIndex, seasonList, preferences){
    var coursesAvailableReturn =[];
    var currentYear = startDate[0] + parseInt((semesterIndex+seasonList.indexOf(startDate[1]))/seasonList.length);
    var currentMonth =  seasonList[(seasonList.indexOf(startDate[1]) + semesterIndex)%seasonList.length];
    if(preferences === undefined)
	preferences = [0, -1];
    for(var x = 0; x < coursesAvailable.length; x++){
        if(coursesAvailable[x].year == currentYear && coursesAvailable[x].semester == currentMonth){
            //If these courses have a schedule component
            if(coursesAvailable[x].day != "" && coursesAvailable[x].time != "") {
                //If we have preferences (preferences only matter if we have a schedule component)
                if(preferences[0] == 1 || preferences[1] >= 0) {
                    //Check time preference
                    if(preferences[0] == 1) {
                        //If it isn't offered in the evening, throw it out
                        if(coursesAvailable[x].time.indexOf("E") == -1) continue;
                    }
                    //Check day preference
                    if(preferences[1] == 0) {
                        if(coursesAvailable[x].day.indexOf("MW") == -1) continue;
                    } else if(preferences[1] == 1) {
                        if(coursesAvailable[x].day.indexOf("TR") == -1) continue;
                    }
                }
                //If we haven't "continue"d, then we haven't violated anything, add it
                coursesAvailableReturn.push(coursesAvailable[x]);
            } else
                coursesAvailableReturn.push(coursesAvailable[x]);
        }
    }
    coursesAvailableReturn.sort(function(a,b){
        return parseCourseNumber(a.courseNumber) - parseCourseNumber(b.courseNumber);
    });
    return coursesAvailableReturn;
}
<|endoftext|>


<commit_before>/*(function() {
	var app = angular.module('SportScheduler', ['SportScheduler-User', 'SportScheduler-Facility']);

})();*/
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: ''
		};

		$scope.userGetPath = '/users/' + $scope.user.fbUserId;
		$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.image;

		$scope.submit = function() {

		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(sessionStorage.getItem("loggedIn")){
				$scope.user.firstName = sessionStorage.getItem("first_name");
				$scope.user.lastName = sessionStorage.getItem("last_name");
				$scope.user.email = sessionStorage.getItem("email");
				$scope.user.fbUserId = sessionStorage.getItem("id");
				$scope.user.image = sessionStorage.getItem("image");
			}
		};

		/*$scope.setUser = function(firstName, lastName, email, id, image){
			$scope.user.firstName = firstName;
			$scope.user.lastName = lastName;
			$scope.user.email = email;
			$scope.user.fbUserId = id;
			$scope.user.image = image;
		};*/

		$scope.get = function() {
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = JSON.parse(data);
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.phone = userVals.phone;
						$scope.user.image = userVals.picture;
					}
				});
		};

		$scope.put = function() {
			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', function($scope){
 		$scope.facilities = [
 			{
				name: 'Richards Building - BYU',
				hours: '6:00 am - 9:45 pm Mon-Sat',
				phone: '(801) 422-3644',
				images: "../assets/rb.jpg"

			},
			{
				name: '24 Hour Fitness',
				hours: '6:00 am - 12:00 pm Mon-Sat',
				phone: '(801) 224-2096',
				images: "../assets/24Hour.jpg"

			},
			{
					name: 'Orem Recreation Center',
					hours: '5:00 am - 10:00 pm Mon-Fri 7:00 am - 7:00 pm Sat',
					phone: '(801) 852-6600',
					images: "../assets/OremRec.jpg"

				},
				{
					name: 'Provo Recreation Center',
					hours: '5:00 am - 10:00 pm Mon-Fri 7:00 am - 8:00 pm Sat',
					phone: '(801) 229-7154',
					images: "../assets/ProvoRec.jpg"

				}

		];

	}]);

	app.controller('CourtController', ['$scope', function($scope){
	 		$scope.courts = [
				{
					name: 'Bulldog',
					image: "../assets/rb.jpg",
					hours: ['7 am','8 am','9 am','10 am','11 am','12 pm','1 pm','2 pm','3 pm','4 pm','5 pm','6 pm','7 pm'],
					hoursOfOp: [
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0]
						],
				}

			];
		}]);

})();

// var myApp = angular.module('SportScheduler',[])
//    .config(function($routeProvider) {
//        $routeProvider
//                .when('/homePage', {templateUrl: "views/homePage.html", controller: "homeCtrl"})
//                .when('/login', {templateUrl: "views/login.html", controller: "loginCtrl"})
//                .when('/project/:projectId', {templateUrl: "views/project.html", controller: "projectCtrl"})
//                .when('/editproject/:projectId', {templateUrl: "views/editproject.html", controller: "editProjectCtrl"})
//                .otherwise({redirectTo: '/home'});
//    });<commit_msg>fixed error in conditional in if statement<commit_after>/*(function() {
	var app = angular.module('SportScheduler', ['SportScheduler-User', 'SportScheduler-Facility']);

})();*/
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: ''
		};

		$scope.userGetPath = '/users/' + $scope.user.fbUserId;
		$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.image;

		$scope.submit = function() {

		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(sessionStorage.getItem("loggedIn") === "true"){
				$scope.user.firstName = sessionStorage.getItem("first_name");
				$scope.user.lastName = sessionStorage.getItem("last_name");
				$scope.user.email = sessionStorage.getItem("email");
				$scope.user.fbUserId = sessionStorage.getItem("id");
				$scope.user.image = sessionStorage.getItem("image");
			}
		};

		/*$scope.setUser = function(firstName, lastName, email, id, image){
			$scope.user.firstName = firstName;
			$scope.user.lastName = lastName;
			$scope.user.email = email;
			$scope.user.fbUserId = id;
			$scope.user.image = image;
		};*/

		$scope.get = function() {
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = JSON.parse(data);
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.phone = userVals.phone;
						$scope.user.image = userVals.picture;
					}
				});
		};

		$scope.put = function() {
			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', function($scope){
 		$scope.facilities = [
 			{
				name: 'Richards Building - BYU',
				hours: '6:00 am - 9:45 pm Mon-Sat',
				phone: '(801) 422-3644',
				images: "../assets/rb.jpg"

			},
			{
				name: '24 Hour Fitness',
				hours: '6:00 am - 12:00 pm Mon-Sat',
				phone: '(801) 224-2096',
				images: "../assets/24Hour.jpg"

			},
			{
					name: 'Orem Recreation Center',
					hours: '5:00 am - 10:00 pm Mon-Fri 7:00 am - 7:00 pm Sat',
					phone: '(801) 852-6600',
					images: "../assets/OremRec.jpg"

				},
				{
					name: 'Provo Recreation Center',
					hours: '5:00 am - 10:00 pm Mon-Fri 7:00 am - 8:00 pm Sat',
					phone: '(801) 229-7154',
					images: "../assets/ProvoRec.jpg"

				}

		];

	}]);

	app.controller('CourtController', ['$scope', function($scope){
	 		$scope.courts = [
				{
					name: 'Bulldog',
					image: "../assets/rb.jpg",
					hours: ['7 am','8 am','9 am','10 am','11 am','12 pm','1 pm','2 pm','3 pm','4 pm','5 pm','6 pm','7 pm'],
					hoursOfOp: [
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0],
							[0, 0, 0, 0, 0, 0, 0]
						],
				}

			];
		}]);

})();

// var myApp = angular.module('SportScheduler',[])
//    .config(function($routeProvider) {
//        $routeProvider
//                .when('/homePage', {templateUrl: "views/homePage.html", controller: "homeCtrl"})
//                .when('/login', {templateUrl: "views/login.html", controller: "loginCtrl"})
//                .when('/project/:projectId', {templateUrl: "views/project.html", controller: "projectCtrl"})
//                .when('/editproject/:projectId', {templateUrl: "views/editproject.html", controller: "editProjectCtrl"})
//                .otherwise({redirectTo: '/home'});
//    });<|endoftext|>


<commit_before>var G5 = Ember.Application.create();

// Router
G5.Router.map(function() {
  this.resource('apps', function(){
    this.resource('app', { path: ':app_id' });
  });
});

G5.AppsRoute = Ember.Route.extend({
  model: function() {
    return G5.App.find();
  }
});

// Controllers
G5.AppController = Ember.ObjectController.extend({
  sortProperties: ['name'],
  addDyno: function(app) {
    app.set('dynos', app.get('dynos')+1);
    app.save()
  },
  removeDyno: function(app) {
    app.set('dynos', app.get('dynos')-1);
    app.save()
  },
  removeAllDynos: function(app) {
    app.set('dynos', 0);
    app.save()
  }
});

// Models
DS.RESTAdapter.reopen({
  namespace: 'heroku'
});

G5.Store = DS.Store.extend();

G5.App = DS.Model.extend({
  name: DS.attr('string'),
  dynos: DS.attr('number')
});
<commit_msg>sorts apps by amount of dynos<commit_after>var G5 = Ember.Application.create();

// Router
G5.Router.map(function() {
  this.resource('apps', function(){
    this.resource('app', { path: ':app_id' });
  });
});

G5.AppsRoute = Ember.Route.extend({
  model: function() {
    return G5.App.find();
  }
});

// Controllers
G5.AppsController = Ember.ArrayController.extend({
  sortProperties: ['dynos'],
  sortAscending: false
});

G5.AppController = Ember.ObjectController.extend({
  addDyno: function(app) {
    app.set('dynos', app.get('dynos')+1);
    app.save()
  },
  removeDyno: function(app) {
    app.set('dynos', app.get('dynos')-1);
    app.save()
  },
  removeAllDynos: function(app) {
    app.set('dynos', 0);
    app.save()
  }
});

// Models
DS.RESTAdapter.reopen({
  namespace: 'heroku'
});

G5.Store = DS.Store.extend();

G5.App = DS.Model.extend({
  name: DS.attr('string'),
  dynos: DS.attr('number')
});
<|endoftext|>


<commit_before>var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']);<commit_msg>typo fix<commit_after>var app = angular.module("app", ['nvd3ChartDirectives']);<|endoftext|>


<commit_before>$(document).ajaxStart(function() {
  NProgress.start();
});

$(document).ajaxStop(function() {
  NProgress.done();
});

$.ajaxSetup({
  headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});

$.pjax.defaults.timeout = 1200;

$(document).pjax('.js-pjax', '#pjax_container');

$(document).on('pjax:send', function(e) {
  $('#pjax_container').css('opacity', '.5');
});

$(document).on('pjax:complete', function() {
  $('#pjax_container').css('opacity', 1);
  $('.fotorama').fotorama();

  initOnLoadAndPjax();
});

$(document).ready(function() {
  $('.tip').tooltip();

  $(document).on('dblclick', '.js-dblclick-edit', function() {
    document.location = $(this).data('dblclick-url');
  });

  $('.js-deferred-load').each(function() {
    $(this).load($(this).data('deferred-url'));
  });

  $(document).on('click', '.js-confirm', function() {
    return confirm($(this).data('confirm'));
  });

  $(document).on('click', '.js-ajax', function(e) {
    e.preventDefault();

    $('.js-ajax').removeClass('active');
    $(this).addClass('active');

    var container = $(this).data('ajax-container') || '#ajax_container';
    var url = $(this).data('ajax-url') || $(this).attr('href');

    $(container).data('deferred-url', url);
    $(container).load(url);
  });

  // Проигрывание гифок по клику
  $(document).on('click', '.js-gif-click', function(e) {
    e.preventDefault();

    var $img = $('img', this);
    var src = $img.attr('src');
    var gif = $(this).attr('href');

    if (src != gif) {
      $img.data('static', src).attr('src', gif);
    } else {
      $img.attr('src', $img.data('static'));
    }
  });

  // Выбрать все
  $(document).on('click', '.js-select-all', function() {
    var is_checked = $(this).prop('checked');
    var $selector = $($(this).data('selector'));
    $selector.prop('checked', is_checked);
  });

  // Выбрать все
  $(document).on('click', '.js-select-all', function() {
    var is_checked = $(this).prop('checked');
    var $selector = $($(this).data('selector'));
    $selector.prop('checked', is_checked);
  });

  // Операции над несколькими записями
  $(document).on('submit', '.js-batch-form', function(e) {
    e.preventDefault();

    var $form = $(this);
    var ids = $($form.data('selector') + ':checked').serialize();

    $.post($form.data('url'), $form.serialize() + '&' + ids, function(data) {
      if (data.redirect) {
        document.location = data.redirect;
      }
    });
  });

  // Горячие клавиши
  var shortcuts_enabled = true;

  $(document).on('focus', 'input,textarea,select', function() {
    shortcuts_enabled = false
  })

  $(document).on('blur', 'input,textarea,select', function() {
    shortcuts_enabled = true
  });

  if ($(".js-shortcuts-items").size()) {
    var shortcuts_items = $(".js-shortcuts-items .shortcuts-item");

    $(window).scroll(function() {
      var active_start_position = window.pageYOffset + 0;
      var active_end_position = window.pageYOffset + 50;

      shortcuts_items.each(function(index, item) {
        var shortcuts_item = $(item);
        var shortcuts_item_position = shortcuts_item.offset().top + 20;

        if (active_start_position < shortcuts_item_position && shortcuts_item_position < active_end_position) {
          if (shortcuts_item.hasClass("focus")) {} else {
            $(".js-shortcuts-items .shortcuts-item.focus").removeClass("focus");
            shortcuts_item.addClass("focus")
          }
        }
      })
    })
  }

  $(document).on('keyup', 'body', function(e) {
    var not_meta_key = !e.altKey && !e.ctrlKey && !e.metaKey;

    if (shortcuts_enabled) {
      if ((e.altKey || e.ctrlKey || e.metaKey) && e.which == 37) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_prev_page")
      }
      if ((e.altKey || e.ctrlKey || e.metaKey) && e.which == 39) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_next_page")
      }
    }
  });

  $("body").on('keypress', function(e) {
    var not_meta_key = !e.altKey && !e.ctrlKey && !e.metaKey;
    if (shortcuts_enabled) {
      // if ((e.which == 47 || e.which == 46) && not_meta_key) {
      //   e.preventDefault();
      //   $(document).trigger("shortcuts.focus_to_search")
      // }
      if ((e.which == 104 || e.which == 1088) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_first_post")
      }
      if ((e.which == 108 || e.which == 1076) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_last_post")
      }
      if ((e.which == 106 || e.which == 1086) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_next_post")
      }
      if ((e.which == 107 || e.which == 1083) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_prev_post")
      }
    }
  });

  // $(document).bind("shortcuts.focus_to_search", function(event, form) {
  //   $(".nav_panel .tab_menu").click();
  //   $('.global_search_form input[name="q"]').focus()
  // });

  $(document).bind("shortcuts.to_next_page", function() {
    var $link = $('#next_page')
    var url = $link.attr("href")

    if (typeof url !== "undefined") {
      if ($link.hasClass('js-pjax')) {
        $.pjax({ url: url, container: '#pjax_container' })
      } else {
        document.location.href = url
      }
    }
  });

  $(document).bind("shortcuts.to_prev_page", function() {
    var $link = $('#previous_page');
    var url = $link.attr("href")

    if (typeof url !== "undefined") {
      if ($link.hasClass('js-pjax')) {
        $.pjax({ url: url, container: '#pjax_container' })
      } else {
        document.location.href = url
      }
    }
  });

  $(document).bind("shortcuts.to_first_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item", shortcuts_items).first().hasClass("focus")) {
        $(document).trigger("shortcuts.to_prev_page")
      } else {
        $(".shortcuts-item.focus", shortcuts_items).removeClass("focus");
        $(".shortcuts-item", shortcuts_items).first().addClass("focus")
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  $(document).bind("shortcuts.to_last_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item", shortcuts_items).last().hasClass("focus")) {
        $(document).trigger("shortcuts.to_next_page")
      } else {
        $(".shortcuts-item.focus", shortcuts_items).removeClass("focus");
        $(".shortcuts-item", shortcuts_items).last().addClass("focus")
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  $(document).bind("shortcuts.to_next_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item.focus", shortcuts_items).size() == 0) {
        $(".shortcuts-item", shortcuts_items).first().addClass("focus")
      } else {
        var shortcuts_item = $(".shortcuts-item.focus", shortcuts_items);
        var next_shortcuts_item = shortcuts_item.next();

        if (next_shortcuts_item.size() == 0) {
          $(document).trigger("shortcuts.to_next_page")
        } else {
          shortcuts_item.removeClass("focus");
          next_shortcuts_item.addClass("focus")
        }
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  $(document).bind("shortcuts.to_prev_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item.focus", shortcuts_items).size() == 0) {
        $(".shortcuts-item", shortcuts_items).last().addClass("focus")
      } else {
        var shortcuts_item = $(".shortcuts-item.focus", shortcuts_items);
        var prev_shortcuts_item = shortcuts_item.prev();

        if (prev_shortcuts_item.size() == 0) {
          $(document).trigger("shortcuts.to_prev_page")
        } else {
          shortcuts_item.removeClass("focus");
          prev_shortcuts_item.addClass("focus")
        }
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  initOnLoadAndPjax();
});

function initOnLoadAndPjax() {
  // Прилипшие заголовки таблиц
  $('.js-float-thead').floatThead();
}
<commit_msg>Исправление работы подсказок при pjax-запросах<commit_after>$(document).ajaxStart(function() {
  NProgress.start();
});

$(document).ajaxStop(function() {
  NProgress.done();
});

$.ajaxSetup({
  headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});

$.pjax.defaults.timeout = 1200;

$(document).pjax('.js-pjax', '#pjax_container');

$(document).on('pjax:send', function(e) {
  $('#pjax_container').css('opacity', '.5');
});

$(document).on('pjax:complete', function() {
  $('#pjax_container').css('opacity', 1);
  $('.fotorama').fotorama();

  initOnLoadAndPjax();
});

$(document).ready(function() {
  $(document).on('dblclick', '.js-dblclick-edit', function() {
    document.location = $(this).data('dblclick-url');
  });

  $('.js-deferred-load').each(function() {
    $(this).load($(this).data('deferred-url'));
  });

  $(document).on('click', '.js-confirm', function() {
    return confirm($(this).data('confirm'));
  });

  $(document).on('click', '.js-ajax', function(e) {
    e.preventDefault();

    $('.js-ajax').removeClass('active');
    $(this).addClass('active');

    var container = $(this).data('ajax-container') || '#ajax_container';
    var url = $(this).data('ajax-url') || $(this).attr('href');

    $(container).data('deferred-url', url);
    $(container).load(url);
  });

  // Проигрывание гифок по клику
  $(document).on('click', '.js-gif-click', function(e) {
    e.preventDefault();

    var $img = $('img', this);
    var src = $img.attr('src');
    var gif = $(this).attr('href');

    if (src != gif) {
      $img.data('static', src).attr('src', gif);
    } else {
      $img.attr('src', $img.data('static'));
    }
  });

  // Выбрать все
  $(document).on('click', '.js-select-all', function() {
    var is_checked = $(this).prop('checked');
    var $selector = $($(this).data('selector'));
    $selector.prop('checked', is_checked);
  });

  // Выбрать все
  $(document).on('click', '.js-select-all', function() {
    var is_checked = $(this).prop('checked');
    var $selector = $($(this).data('selector'));
    $selector.prop('checked', is_checked);
  });

  // Операции над несколькими записями
  $(document).on('submit', '.js-batch-form', function(e) {
    e.preventDefault();

    var $form = $(this);
    var ids = $($form.data('selector') + ':checked').serialize();

    $.post($form.data('url'), $form.serialize() + '&' + ids, function(data) {
      if (data.redirect) {
        document.location = data.redirect;
      }
    });
  });

  // Горячие клавиши
  var shortcuts_enabled = true;

  $(document).on('focus', 'input,textarea,select', function() {
    shortcuts_enabled = false
  })

  $(document).on('blur', 'input,textarea,select', function() {
    shortcuts_enabled = true
  });

  if ($(".js-shortcuts-items").size()) {
    var shortcuts_items = $(".js-shortcuts-items .shortcuts-item");

    $(window).scroll(function() {
      var active_start_position = window.pageYOffset + 0;
      var active_end_position = window.pageYOffset + 50;

      shortcuts_items.each(function(index, item) {
        var shortcuts_item = $(item);
        var shortcuts_item_position = shortcuts_item.offset().top + 20;

        if (active_start_position < shortcuts_item_position && shortcuts_item_position < active_end_position) {
          if (shortcuts_item.hasClass("focus")) {} else {
            $(".js-shortcuts-items .shortcuts-item.focus").removeClass("focus");
            shortcuts_item.addClass("focus")
          }
        }
      })
    })
  }

  $(document).on('keyup', 'body', function(e) {
    var not_meta_key = !e.altKey && !e.ctrlKey && !e.metaKey;

    if (shortcuts_enabled) {
      if ((e.altKey || e.ctrlKey || e.metaKey) && e.which == 37) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_prev_page")
      }
      if ((e.altKey || e.ctrlKey || e.metaKey) && e.which == 39) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_next_page")
      }
    }
  });

  $("body").on('keypress', function(e) {
    var not_meta_key = !e.altKey && !e.ctrlKey && !e.metaKey;
    if (shortcuts_enabled) {
      // if ((e.which == 47 || e.which == 46) && not_meta_key) {
      //   e.preventDefault();
      //   $(document).trigger("shortcuts.focus_to_search")
      // }
      if ((e.which == 104 || e.which == 1088) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_first_post")
      }
      if ((e.which == 108 || e.which == 1076) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_last_post")
      }
      if ((e.which == 106 || e.which == 1086) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_next_post")
      }
      if ((e.which == 107 || e.which == 1083) && not_meta_key) {
        e.preventDefault();
        $(document).trigger("shortcuts.to_prev_post")
      }
    }
  });

  // $(document).bind("shortcuts.focus_to_search", function(event, form) {
  //   $(".nav_panel .tab_menu").click();
  //   $('.global_search_form input[name="q"]').focus()
  // });

  $(document).bind("shortcuts.to_next_page", function() {
    var $link = $('#next_page')
    var url = $link.attr("href")

    if (typeof url !== "undefined") {
      if ($link.hasClass('js-pjax')) {
        $.pjax({ url: url, container: '#pjax_container' })
      } else {
        document.location.href = url
      }
    }
  });

  $(document).bind("shortcuts.to_prev_page", function() {
    var $link = $('#previous_page');
    var url = $link.attr("href")

    if (typeof url !== "undefined") {
      if ($link.hasClass('js-pjax')) {
        $.pjax({ url: url, container: '#pjax_container' })
      } else {
        document.location.href = url
      }
    }
  });

  $(document).bind("shortcuts.to_first_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item", shortcuts_items).first().hasClass("focus")) {
        $(document).trigger("shortcuts.to_prev_page")
      } else {
        $(".shortcuts-item.focus", shortcuts_items).removeClass("focus");
        $(".shortcuts-item", shortcuts_items).first().addClass("focus")
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  $(document).bind("shortcuts.to_last_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item", shortcuts_items).last().hasClass("focus")) {
        $(document).trigger("shortcuts.to_next_page")
      } else {
        $(".shortcuts-item.focus", shortcuts_items).removeClass("focus");
        $(".shortcuts-item", shortcuts_items).last().addClass("focus")
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  $(document).bind("shortcuts.to_next_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item.focus", shortcuts_items).size() == 0) {
        $(".shortcuts-item", shortcuts_items).first().addClass("focus")
      } else {
        var shortcuts_item = $(".shortcuts-item.focus", shortcuts_items);
        var next_shortcuts_item = shortcuts_item.next();

        if (next_shortcuts_item.size() == 0) {
          $(document).trigger("shortcuts.to_next_page")
        } else {
          shortcuts_item.removeClass("focus");
          next_shortcuts_item.addClass("focus")
        }
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  $(document).bind("shortcuts.to_prev_post", function() {
    var shortcuts_items = $(".js-shortcuts-items");

    if (shortcuts_items.size()) {
      if ($(".shortcuts-item.focus", shortcuts_items).size() == 0) {
        $(".shortcuts-item", shortcuts_items).last().addClass("focus")
      } else {
        var shortcuts_item = $(".shortcuts-item.focus", shortcuts_items);
        var prev_shortcuts_item = shortcuts_item.prev();

        if (prev_shortcuts_item.size() == 0) {
          $(document).trigger("shortcuts.to_prev_page")
        } else {
          shortcuts_item.removeClass("focus");
          prev_shortcuts_item.addClass("focus")
        }
      }

      $.scrollTo($(".shortcuts-item.focus", shortcuts_items), 200, {
        axis: "y"
      })
    }
  });

  initOnLoadAndPjax();
});

function initOnLoadAndPjax() {
  // Прилипшие заголовки таблиц
  $('.js-float-thead').floatThead();

  // Подсказки
  $('.tip').tooltip();
}
<|endoftext|>


<commit_before>/**
* @preserve HTML5 Shiv 3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=s.elements;return"string"==typeof a?a.split(" "):a}function e(a){var b=r[a[p]];return b||(b={},q++,a[p]=q,r[q]=b),b}function f(a,c,d){if(c||(c=b),k)return c.createElement(a);d||(d=e(c));var f;return f=d.cache[a]?d.cache[a].cloneNode():o.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!f.canHaveChildren||n.test(a)||f.tagUrn?f:d.frag.appendChild(f)}function g(a,c){if(a||(a=b),k)return a.createDocumentFragment();c=c||e(a);for(var f=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)f.createElement(h[g]);return f}function h(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return s.shivMethods?f(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(s,b.frag)}function i(a){a||(a=b);var d=e(a);return!s.shivCSS||j||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),k||h(a,d),a}var j,k,l="3.7.1",m=a.html5||{},n=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,o=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,p="_html5shiv",q=0,r={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",j="hidden"in a,k=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){j=!0,k=!0}}();var s={elements:m.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:l,shivCSS:m.shivCSS!==!1,supportsUnknownElements:k,shivMethods:m.shivMethods!==!1,type:"default",shivDocument:i,createElement:f,createDocumentFragment:g};a.html5=s,i(b)}(this,document);<commit_msg>Delete html5shiv.min.js<commit_after><|endoftext|>


<commit_before>
var clickevt = (Modernizr.touch) ? "touchstart" : "click";
var BASE = "http://ebh.herokuapp.com";

Handlebars.registerHelper('ifBoth', function(v1, v2, options) {
  if(v1 && v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});

Handlebars.registerHelper('bitterness', function(ibu){
	return 100 * (ibu/110);
});
Handlebars.registerHelper('bitternessText', function(ibu){
	var perc = 100 * (ibu/110);
	if (ibu <= 10){
		return "very low";
	} else if (ibu > 10 && ibu <= 30){
		return "low";
	} else if (ibu > 30 && ibu <= 40){
		return "medium";
	} else if (ibu > 40 && ibu <= 60){
		return "high medium";
	} else if (ibu > 60 && ibu <= 80){
		return "high";
	} else {
		return "very high";
	}

});

$.ajaxSetup({
	cache : false,
	data : {
		"withBreweries" : "Y"
	}
});
var theRequest;

var listhtml = "";
function getBeerList(h,p,page,query){
	var data;
	$("#index").fadeIn(); $("#single").fadeOut();
	if (!h) h = "";
	if (!p) p = 1;
	if (!page) page = "recommended";
	if (!query) query = "";

	$.getJSON("/me", function(data){
		console.log(data);
		if (page=="recommended"){
			data = {method : "beers", "order" : "status", "abv":"7,12", "ibu":"20,50", "p":p};
		// } else if (page=="recommended"){
			// data = {method : "beers", "order": "availableId", "sort" :"DESC", "p":p};
		} else if (page=="atoz"){
			data = {method : "beers", "order": "name", "sort" :"ASC", "p":p};
		} else if (page=="popular"){
			// These are the most recently updated... So they must be popular, right?
			var ts = Math.round((new Date()).getTime() / 1000) - (86400*4);
			data = {method : "beers", "since": ts, "sort" :"ASC", "p":p};
		} else if (page=="seasonal"){
			// grab those spring beers, dog
			data = {method : "beers", "availableId": 5, "order" : "abv", "sort" :"DESC", "p":p};
		} else if (page=="cellar"){
			var ids = "";
			$(data.drinks).each(function(i,el){
				ids += el.api_id + ",";
			})
			data = {method : "beers", "ids": ids, "sort" :"ASC", "p":p};
		} else if (page=="purchases"){
			data = {method : "beers", "ids": "Qx1hbt,R0MvCF,iLlMCb,FYS1Qj,y3lFdg,CfJ0cK,AXqmST,NoNhan,f9WbNU,x6bRxw,", "sort" :"ASC", "p":p};
		} else if (page=="search"){
			data = {method : "search", "q": query, "p":p};
		}

		theRequest = $.getJSON(BASE, data, function(data){
			var ctx = {
				beers : data.data
			}
			var source = $("#beer-list").html();
			var tpl = Handlebars.compile(source);
			h += tpl(ctx);
			var fragment = document.createDocumentFragment();
			var d = document.createElement("div");
			d.innerHTML=h;
			if ($(d).find("li").length < 60 && data.currentPage < data.numberOfPages){
				$("#beerlist").append(h);
				$(".loading-text").remove();
				return getBeerList(h,p+1,page,query);
			} else {
				$("#beerlist").append(h);
			}
		});
	})
}
getBeerList(listhtml, 1, "recommended");

$("nav").on(clickevt, "a", function(e){
	if (!$(this).is(".logout")){
		e.preventDefault();
	} else { return true; }
	if (theRequest){
		theRequest.abort();
	}
	var el = this;
	if (!$(this).is(".current")){
		$(el).addClass("current").siblings().removeClass("current");
		var sec = $(el).attr("href").replace("#", "");
		$("#logo small").html(sec[0].toUpperCase() + sec.slice(1));
		$("#beerlist").empty().html("
Loading...
");
		getBeerList("", 1, sec);
		$("#contain").removeClass("nav-open");
		$(".nav-switch").removeClass("open");
	} else {
		// do nothing.
	}
});
$(".nav-switch").on(clickevt, function(e){

	if ($(this).hasClass("open")){
		$(this).removeClass("open");
		$("#contain").removeClass("nav-open");
	} else {
		$(this).addClass("open");
		$("#contain").addClass("nav-open");
	}
})
$(".search-switch i").on(clickevt, function(e){
	$(e.target).parent().toggleClass("on");
});

var tout;
$("input[name=search-input]").on("keyup", function(){
	clearTimeout(tout);
	if (theRequest){
		theRequest.abort();
	}
	$("#logo small").html("Search")
	$("#beerlist").empty().html("
Loading...
");
	tout = setTimeout(function(){
		getBeerList("", 1, "search", $("input[name=search-input]").val());
	}, 300);
});

function goToSingle(ev){
	if (!ev){
		var hash = document.location.hash;
	} else {
		if (!$(ev.target).is("a")){
			var t = $(ev.target).parents("a");
		} else {
			var t = $(ev.target);
		}
		var hash = $(t).attr("href");
	}
	$("#index").fadeOut();
	var id = hash.split("/")[hash.split("/").length-1];
	var data = { method : "beer/"+id }
	theRequest.abort();
	theRequest = $.getJSON(BASE, data, function(data){
		var ctx = data.data;
		var source = $("#single-beer").html();
		var tpl = Handlebars.compile(source);
		var h = tpl(ctx);
		$("#single").html(h).fadeIn();
		var rating = Math.round(Math.random() * 5);
		var i = 0;
		var h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").first().prepend("
"+h+"
");

			rating = Math.round(Math.random() * 5);
			i = 0;
			h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").last().prepend("
"+h+"
");
	});
}

$("body").on(clickevt, ".single-link", goToSingle);
$(document).ready(function(){
	if (document.location.hash.split("/")[1] == "beer"){
		goToSingle();
	}
});
$("body").on(clickevt, ".back", function(e){
	e.preventDefault();
	$("#single").fadeOut(function(){$("#single").empty();});
	$("#index").fadeIn();
});
$("body").on(clickevt, ".styleinfo a", function(e){
	e.preventDefault();
	$(e.target).toggleClass("open");
	$(e.target).parent().next("p").slideToggle();
});
$("body").on("submit", "#add-a-review", function(e){
	e.preventDefault();
	var username = $("input[name='username']").val();
	var comments = $("textarea[name='comments']").val();
	var comment = "
"
                            +"
"
                                +"
"+username+"
"
                                +""
                                +"
"+comments+"
"
                            +"
"
                        +"
"
                        +"
";
    $(".reviews").append(comment);
});

$("body").on(clickevt, ".add-beer", function(e){
	var id = $(this).data("api_id");
	var button = $(this);
	$.post("/cellar/add", {"api_id" : id}, function(data){
		var json = $.parseJSON(data);
		console.log(json);
		if (json.message == "Successfully added drink."){
			button.html(" Added to cellar!").removeClass("add-beer");
		}
	});
})<commit_msg>adding respond to photo<commit_after>
var clickevt = (Modernizr.touch) ? "touchstart" : "click";
var BASE = "http://ebh.herokuapp.com";

Handlebars.registerHelper('ifBoth', function(v1, v2, options) {
  if(v1 && v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});

Handlebars.registerHelper('bitterness', function(ibu){
	return 100 * (ibu/110);
});
Handlebars.registerHelper('bitternessText', function(ibu){
	var perc = 100 * (ibu/110);
	if (ibu <= 10){
		return "very low";
	} else if (ibu > 10 && ibu <= 30){
		return "low";
	} else if (ibu > 30 && ibu <= 40){
		return "medium";
	} else if (ibu > 40 && ibu <= 60){
		return "high medium";
	} else if (ibu > 60 && ibu <= 80){
		return "high";
	} else {
		return "very high";
	}

});

$.ajaxSetup({
	cache : false,
	data : {
		"withBreweries" : "Y"
	}
});
var theRequest;

var listhtml = "";
function getBeerList(h,p,page,query){
	var data;
	$("#index").fadeIn(); $("#single").fadeOut();
	if (!h) h = "";
	if (!p) p = 1;
	if (!page) page = "recommended";
	if (!query) query = "";

	$.getJSON("/me", function(data){
		console.log(data);
		if (page=="recommended"){
			data = {method : "beers", "order" : "status", "abv":"7,12", "ibu":"20,50", "p":p};
		// } else if (page=="recommended"){
			// data = {method : "beers", "order": "availableId", "sort" :"DESC", "p":p};
		} else if (page=="atoz"){
			data = {method : "beers", "order": "name", "sort" :"ASC", "p":p};
		} else if (page=="popular"){
			// These are the most recently updated... So they must be popular, right?
			var ts = Math.round((new Date()).getTime() / 1000) - (86400*4);
			data = {method : "beers", "since": ts, "sort" :"ASC", "p":p};
		} else if (page=="seasonal"){
			// grab those spring beers, dog
			data = {method : "beers", "availableId": 5, "order" : "abv", "sort" :"DESC", "p":p};
		} else if (page=="cellar"){
			var ids = "";
			$(data.drinks).each(function(i,el){
				ids += el.api_id + ",";
			})
			data = {method : "beers", "ids": ids, "sort" :"ASC", "p":p};
		} else if (page=="purchases"){
			data = {method : "beers", "ids": "Qx1hbt,R0MvCF,iLlMCb,FYS1Qj,y3lFdg,CfJ0cK,AXqmST,NoNhan,f9WbNU,x6bRxw,", "sort" :"ASC", "p":p};
		} else if (page=="search"){
			data = {method : "search", "q": query, "p":p};
		}

		theRequest = $.getJSON(BASE, data, function(data){
			var ctx = {
				beers : data.data
			}
			var source = $("#beer-list").html();
			var tpl = Handlebars.compile(source);
			h += tpl(ctx);
			var fragment = document.createDocumentFragment();
			var d = document.createElement("div");
			d.innerHTML=h;
			if ($(d).find("li").length < 60 && data.currentPage < data.numberOfPages){
				$("#beerlist").append(h);
				$(".loading-text").remove();
				return getBeerList(h,p+1,page,query);
			} else {
				$("#beerlist").append(h);
			}
		});
	})
}
getBeerList(listhtml, 1, "recommended");

$("nav").on(clickevt, "a", function(e){
	if (!$(this).is(".logout")){
		e.preventDefault();
	} else { return true; }
	if (theRequest){
		theRequest.abort();
	}
	var el = this;
	if (!$(this).is(".current")){
		$(el).addClass("current").siblings().removeClass("current");
		var sec = $(el).attr("href").replace("#", "");
		$("#logo small").html(sec[0].toUpperCase() + sec.slice(1));
		$("#beerlist").empty().html("
Loading...
");
		getBeerList("", 1, sec);
		$("#contain").removeClass("nav-open");
		$(".nav-switch").removeClass("open");
	} else {
		// do nothing.
	}
});
$(".nav-switch").on(clickevt, function(e){

	if ($(this).hasClass("open")){
		$(this).removeClass("open");
		$("#contain").removeClass("nav-open");
	} else {
		$(this).addClass("open");
		$("#contain").addClass("nav-open");
	}
})
$(".search-switch i").on(clickevt, function(e){
	$(e.target).parent().toggleClass("on");
});

var tout;
$("input[name=search-input]").on("keyup", function(){
	clearTimeout(tout);
	if (theRequest){
		theRequest.abort();
	}
	$("#logo small").html("Search")
	$("#beerlist").empty().html("
Loading...
");
	tout = setTimeout(function(){
		getBeerList("", 1, "search", $("input[name=search-input]").val());
	}, 300);
});

function goToSingle(ev){
	if (!ev){
		var hash = document.location.hash;
	} else {
		if (!$(ev.target).is("a")){
			var t = $(ev.target).parents("a");
		} else {
			var t = $(ev.target);
		}
		var hash = $(t).attr("href");
	}
	$("#index").fadeOut();
	var id = hash.split("/")[hash.split("/").length-1];
	var data = { method : "beer/"+id }
	theRequest.abort();
	theRequest = $.getJSON(BASE, data, function(data){
		var ctx = data.data;
		var source = $("#single-beer").html();
		var tpl = Handlebars.compile(source);
		var h = tpl(ctx);
		$("#single").html(h).fadeIn();
		var rating = Math.round(Math.random() * 5);
		var i = 0;
		var h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").first().prepend("
"+h+"
");

			rating = Math.round(Math.random() * 5);
			i = 0;
			h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").last().prepend("
"+h+"
");
	});
}

$("body").on(clickevt, ".single-link", goToSingle);
$(document).ready(function(){
	if (document.location.hash.split("/")[1] == "beer"){
		goToSingle();
	}
});
$("body").on(clickevt, ".back", function(e){
	e.preventDefault();
	$("#single").fadeOut(function(){$("#single").empty();});
	$("#index").fadeIn();
});
$("body").on(clickevt, ".styleinfo a", function(e){
	e.preventDefault();
	$(e.target).toggleClass("open");
	$(e.target).parent().next("p").slideToggle();
});
$("body").on("submit", "#add-a-review", function(e){
	e.preventDefault();
	var username = $("input[name='username']").val();
	var comments = $("textarea[name='comments']").val();
	var comment = "
"
                            +"
"
                                +"
"+username+"
"
                                +""
                                +"
"+comments+"
"
                            +"
"
                        +"
"
                        +"
";
    $(".reviews").append(comment);
});

$("body").on(clickevt, ".add-beer", function(e){
	var id = $(this).data("api_id");
	var button = $(this);
	$.post("/cellar/add", {"api_id" : id}, function(data){
		var json = $.parseJSON(data);
		console.log(json);
		if (json.message == "Successfully added drink."){
			button.html(" Added to cellar!").removeClass("add-beer");
		}
	});
})
$("body").on("change", "input[type=file]", function(e){
	document.location.hash = "#/beer/5nEJRc";
	goToSingle();
});<|endoftext|>


<commit_before>(function(global) {
  'use strict';
  var app = global.app || {};
  var m = global.m;

  var timeAxisView = function(ctrl) {
    var daysAgo = ctrl.daysAgo();
    var daysAfter = ctrl.daysAfter();
    var pixelsPerDay = ctrl.pixelsPerDay();

    var height = 31;

    var monthMarkerViews = [];
    var now = Date.now();
    for (var di = -daysAgo, dlen = daysAfter + 1; di < dlen; di++) {
      var date = new Date(now + di * 86400000);
      if (date.getDate() !== 1)
        continue;
      var month = date.getMonth() + 1;
      var showYear = (month === 1 || month === 4 || month === 7 || month === 10);
      var x = (di + daysAgo) * pixelsPerDay;
      var width = showYear ? 60 : 20;
      var text = showYear ? date.getFullYear() + '/' + month : month;
      monthMarkerViews.push(m('g.month', [
        m('line', {
          x1: x,
          y1: 0,
          x2: x,
          y2: height
        }),
        m('rect', {
          x: x - (showYear ? 30 : 10),
          y: 5,
          width: width,
          height: 20,
          rx: 5,
          ry: 5
        }),
        m('text', {
          x: x,
          y: 20
        }, text)
      ]));
    }

    return m('div.time-axis.unselectable', {
      config: function(element, isInitialized) {
        if (isInitialized)
          return;
        ctrl.dispatchEvent({
          type: 'init',
          element: element
        });
      }
    }, [
      m('svg', {
        width: (daysAfter + daysAgo + 1) * pixelsPerDay + 1,
        height: height
      }, [
        m('defs',[
          m('pattern', {
            id: 'time-axis-pattern',
            x: 0,
            y: 0,
            width: pixelsPerDay,
            height: height,
            patternUnits: 'userSpaceOnUse'
          }, [
            m('line', {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: height
            })
          ])
        ]),
        m('rect.background', {
          x: 0,
          y: 0,
          width: '100%',
          height: height,
          config: function(element, isInitialized, context) {
            if (!isInitialized)
              return;
            if (context.pixelsPerDay !== pixelsPerDay) {
              // set fill attribute to redraw time axis pattern for IE
              element.setAttribute('fill', '');
            }
            context.pixelsPerDay = pixelsPerDay;
          }
        }),
        monthMarkerViews,
        m('rect.today', {
          x: daysAgo * pixelsPerDay,
          y: 0,
          width: pixelsPerDay,
          height: height
        })
      ])
    ]);
  };

  app.timeAxisView = timeAxisView;
  global.app = app;
})(this);<commit_msg>Refactor time-axis-view<commit_after>(function(global) {
  'use strict';
  var app = global.app || {};
  var m = global.m;
  var util = global.util;

  var startOfDay = util.startOfDay;
  var addDays = util.addDays;

  var timeAxisView = function(ctrl) {
    var daysAgo = ctrl.daysAgo();
    var daysAfter = ctrl.daysAfter();
    var pixelsPerDay = ctrl.pixelsPerDay();

    var height = 31;

    return m('div.time-axis.unselectable', {
      config: function(element, isInitialized) {
        if (isInitialized)
          return;
        ctrl.dispatchEvent({
          type: 'init',
          element: element
        });
      }
    }, [
      m('svg', {
        width: (daysAfter + daysAgo + 1) * pixelsPerDay + 1,
        height: height
      }, [
        m('defs',[
          m('pattern', {
            id: 'time-axis-pattern',
            x: 0,
            y: 0,
            width: pixelsPerDay,
            height: height,
            patternUnits: 'userSpaceOnUse'
          }, [
            m('line', {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: height
            })
          ])
        ]),
        m('rect.background', {
          x: 0,
          y: 0,
          width: '100%',
          height: height,
          config: function(element, isInitialized, context) {
            if (!isInitialized)
              return;
            if (context.pixelsPerDay !== pixelsPerDay) {
              // set fill attribute to redraw time axis pattern for IE
              element.setAttribute('fill', '');
            }
            context.pixelsPerDay = pixelsPerDay;
          }
        }),
        monthMarkerViews(daysAgo, daysAfter, pixelsPerDay, height),
        m('rect.today', {
          x: daysAgo * pixelsPerDay,
          y: 0,
          width: pixelsPerDay,
          height: height
        })
      ])
    ]);
  };

  var monthMarkerViews = function(daysAgo, daysAfter, pixelsPerDay, height) {
    var views = [];
    var today = startOfDay();
    for (var di = -daysAgo, dlen = daysAfter + 1; di < dlen; di++) {
      var date = addDays(today, di);
      if (date.getDate() !== 1)
        continue;
      var month = date.getMonth() + 1;
      var showYear = (month === 1 || month === 4 || month === 7 || month === 10);
      var x = (di + daysAgo) * pixelsPerDay;
      var width = showYear ? 60 : 20;
      var text = showYear ? date.getFullYear() + '/' + month : month;
      views.push(m('g.month', [
        m('line', {
          x1: x,
          y1: 0,
          x2: x,
          y2: height
        }),
        m('rect', {
          x: x - (showYear ? 30 : 10),
          y: 5,
          width: width,
          height: 20,
          rx: 5,
          ry: 5
        }),
        m('text', {
          x: x,
          y: 20
        }, text)
      ]));
    }
    return views;
  };

  app.timeAxisView = timeAxisView;
  global.app = app;
})(this);<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Visually groups sets of buttons, checks, radios, etc.
//>>label: Controlgroups
//>>group: Forms
//>>css.structure: ../../css/structure/jquery.mobile.controlgroup.css
//>>css.theme: ../../css/themes/default/jquery.mobile.theme.css

define( [ "jquery",
	"../jquery.mobile.buttonMarkup",
	"./forms/button",
	"../jquery.mobile.widget" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

	$.widget( "mobile.controlgroup", $.mobile.widget, {
		options: {
			shadow: false,
			excludeInvisible: true,
			type: "vertical",
			mini: false,
			initSelector: ":jqmData(role='controlgroup')"
		},

		_create: function() {
			var $el = this.element,
				ui = {
					inner: $( "

" ),
					legend: $( "

" )
				},
				grouplegend = $el.children( "legend" ),
				groupcontrols = $el.children( ".ui-controlgroup-controls" ),
				self = this;

			// Apply the proto
			$el.wrapInner( ui.inner );
			if ( grouplegend.length ) {
				ui.legend.append( grouplegend ).insertBefore( $el.children( 0 ) );
			}
			$el.addClass( "ui-corner-all ui-controlgroup" );

			$.each( this.options, function( key, value ) {
				// Cause initial options to be applied by their handler by temporarily setting the option to undefined
				// - the handler then sets it to the initial value
				self.options[ key ] = undefined;
				self._setOption( key, value, true );
			});

			this.refresh();
		},

		_flipClasses: function( els, flCorners  ) {
			els.removeClass( "ui-controlgroup-last" )
				.buttonMarkup( { corners: false, shadow: false } )
				.eq( 0 ).buttonMarkup( { corners: flCorners[ 0 ], cornerstyle: "group" } )
				.end()
				.last().buttonMarkup( { corners: flCorners[ 1 ], cornerstyle: "group" } ).addClass( "ui-controlgroup-last" );
		},

		_setOption: function( key, value ) {
			var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );

			if ( this[ setter ] !== undefined ) {
				this[ setter ]( value );
			}

			this._super( "_setOption", key, value );
			this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
		},

		_setType: function( value ) {
			this.element
				.removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" )
				.addClass( "ui-controlgroup-" + value );
			this.options.type = value;
			this.refresh();
		},

		_setShadow: function( value ) {
			this.element.toggleClass( "ui-shadow", value );
		},

		_setMini: function( value ) {
			this.element.toggleClass( "ui-mini", value );
		},

		refresh: function() {
			var els = this.element
				.find( ".ui-btn" + ( this.options.excludeInvisible ? ":visible" : "" ) )
				.not( '.ui-slider-handle' ),
				corners = [ true, true ];

			if ( els.length > 1 ) {
				corners = ( this.options.type === "horizontal" ? [ "left", "right" ] : [ "top", "bottom" ] );
			}

			this._flipClasses( els, corners );
		}
	});

	$( document ).bind( "pagecreate create", function( e )  {
		$.mobile.controlgroup.prototype.enhanceWithin( e.target, true );
	});
})(jQuery);
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>[controlgroup] Was using wrong calling convention for this._super()<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Visually groups sets of buttons, checks, radios, etc.
//>>label: Controlgroups
//>>group: Forms
//>>css.structure: ../../css/structure/jquery.mobile.controlgroup.css
//>>css.theme: ../../css/themes/default/jquery.mobile.theme.css

define( [ "jquery",
	"../jquery.mobile.buttonMarkup",
	"./forms/button",
	"../jquery.mobile.widget" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

	$.widget( "mobile.controlgroup", $.mobile.widget, {
		options: {
			shadow: false,
			excludeInvisible: true,
			type: "vertical",
			mini: false,
			initSelector: ":jqmData(role='controlgroup')"
		},

		_create: function() {
			var $el = this.element,
				ui = {
					inner: $( "

" ),
					legend: $( "

" )
				},
				grouplegend = $el.children( "legend" ),
				groupcontrols = $el.children( ".ui-controlgroup-controls" ),
				self = this;

			// Apply the proto
			$el.wrapInner( ui.inner );
			if ( grouplegend.length ) {
				ui.legend.append( grouplegend ).insertBefore( $el.children( 0 ) );
			}
			$el.addClass( "ui-corner-all ui-controlgroup" );

			$.each( this.options, function( key, value ) {
				// Cause initial options to be applied by their handler by temporarily setting the option to undefined
				// - the handler then sets it to the initial value
				self.options[ key ] = undefined;
				self._setOption( key, value, true );
			});

			this.refresh();
		},

		_flipClasses: function( els, flCorners  ) {
			els.removeClass( "ui-controlgroup-last" )
				.buttonMarkup( { corners: false, shadow: false } )
				.eq( 0 ).buttonMarkup( { corners: flCorners[ 0 ], cornerstyle: "group" } )
				.end()
				.last().buttonMarkup( { corners: flCorners[ 1 ], cornerstyle: "group" } ).addClass( "ui-controlgroup-last" );
		},

		_setOption: function( key, value ) {
			var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );

			if ( this[ setter ] !== undefined ) {
				this[ setter ]( value );
			}

			this._super( key, value );
			this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
		},

		_setType: function( value ) {
			this.element
				.removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" )
				.addClass( "ui-controlgroup-" + value );
			this.options.type = value;
			this.refresh();
		},

		_setShadow: function( value ) {
			this.element.toggleClass( "ui-shadow", value );
		},

		_setMini: function( value ) {
			this.element.toggleClass( "ui-mini", value );
		},

		refresh: function() {
			var els = this.element
				.find( ".ui-btn" + ( this.options.excludeInvisible ? ":visible" : "" ) )
				.not( '.ui-slider-handle' ),
				corners = [ true, true ];

			if ( els.length > 1 ) {
				corners = ( this.options.type === "horizontal" ? [ "left", "right" ] : [ "top", "bottom" ] );
			}

			this._flipClasses( els, corners );
		}
	});

	$( document ).bind( "pagecreate create", function( e )  {
		$.mobile.controlgroup.prototype.enhanceWithin( e.target, true );
	});
})(jQuery);
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>