<commit_before>/* Examples
 * */

Examples.push({
    name: "Bill Calculator",
    fxn : "100*(salary - rent - studentloans - carpayments - grocery-spendingmoney-retirement) - netflix -tivo -petfood -gas-electric + 100*(subleaseincome + stockportfolio)",
    url : "salary-rent-studentloans-carpayments-grocery-spendingmoney-retirement-netflix-tivo-petfood-gas-electric+subleaseincome+stockportfolio=0:0:0:0:0:0:0:7:0:0:0:0:0:0:{8000:3400:500:600:1000:500:1000:27:30:200:500:200:1000:1000:}100:100:50:50:20:10:100:3:3:20:30:10:100:50:[4000:400:100:250:300:500:300:13:12:100:120:90:600:100:;0:1:1:1:1:1:1:1:1:1:1:1:1:1:'Bill%20Calculator]"
});

Examples.push({
    name: "Drake Equation",
    fxn : "StarFormationRate * StarsWithPlanets * LifeSustainingPlanets * PlanetsWhichActuallyDevelopLife * PlanetsWithIntelligentLife * CivilizationsWithDetectors * DurationOfSpaceSignals",
    url : "StarFormationRate*StarsWithPlanets*LifeSustainingPlanets*PlanetsWhichActuallyDevelopLife*PlanetsWithIntelligentLife*CivilizationsWithDetectors*DurationOfSpaceSignals=0:0:0:0:0:0:0:{20:1:10:1:1:1:20:}1:0.1:1:0.1:0.1:0.1:1:[10:0.5:2:1:0.1:0.1:10:;1:1:1:1:1:1:1:'Drake%20Equation]"

    });

Examples.push({
    name: "Monthly Loan Payments Calculator",
    fxn : "Princpial*((rate/1200)*(1 + rate/1200)^Months)/((1 + rate/1200)^Months - 1)",
    url : "Princpial*((rate/1200)*(1+rate/1200)^Months)/((1+rate/1200)^Months-1)=0:0:0:{200:100:100:}10:1:1:[110:9:23:;1:1:1:'Loan%20Calculator]"
});

Examples.push({
    name: "Gravity",
    fxn : "GravConstant * massOne * massTwo / distance^2",
    url : "GravConstant*massOne*massTwo/distance^2=0:0:0:0:{20:100:100:100:}0.01:1:1:1:[8.73:29:19:3:;1:1:1:1:'Gravity]"
});

Examples.push({
    name: "E = mc^2",
    fxn : "mass*(300*1000*1000)^2",
    url : "mass*(300*1000*1000)^2=0:{100:}1:[20:;1:'Einstein]"
});

Examples.push({
    name: "Area of Circle",
    fxn : "pi * radius^2",
    url : "pi*radius^2=0:{100:}1:[13:;1:'Circle%20Area]"
});

Examples.push({
    name: "Circumference of a Circle",
    fxn : "2*pi*radius",
    url : "2*pi*radius=0:{100:}1:[13:;1:'Circle%20Circumference]"
});

Examples.push({
    name: "Flake Equation (xkcd.com/718)",
    fxn : "7*1000^3 * (CrazyPeople + Misinterpret)/10000 * TellProbability/10 * NumberPeopleTold * FirstHandRetellings * IgnoredDataProbability/10 * WiderAudienceFraction/100",
    url : "7*1000^3*(CrazyPeople+Misinterpret)/10000*TellProbability/10*NumberPeopleTold*FirstHandRetellings*IgnoredDataProbability/10*WiderAudienceFraction/100=0:0:0:0:0:0:0:{10:10:10:100:100:10:100:}1:1:1:1:1:1:1:[1:1:1:10:10:9:1:;1:1:1:1:1:1:1:'Flake%20Equation%20(XKCD)]"
});

Examples.push({
    name: "Dateable Ages (xkcd.com/314)",
    fxn : "Age/2 + 7",
    url : "Age/2+7=18:{126:}1:[27:;1:'Who%20Can%20You%20Date]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Straight) (xkcd.com/216)",
    fxn : "SameSex*(AllCast - SameSex)",
    url : "SameSex*(AllCast-SameSex)=0:0:{100:100:}1:1:[17:44:;1:1:'Romantic%20Pairings]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Gay) (xkcd.com/216)",
    fxn : "AllCast*(AllCast - 1)/2 + SameSex*(SameSex - AllCast)",
    url : "AllCast*(AllCast-1)/2+SameSex*(SameSex-AllCast)=0:0:{100:100:}1:1:[45:25:;1:1:'Romantic%20Pairings]"
});

Examples.push({
    name: "Post-Game Seasonal Batting Average",
    fxn : "(SeasonBats * (SeasonalAverage/100) + Hits)/(SeasonBats + TimesAtBat)",
    url : "(SeasonBats*(SeasonalAverage/100)+Hits)/(SeasonBats+TimesAtBat)=0:0:0:0:{100:100:100:13:}1:1:1:1:[40:60:81:13:;1:1:1:1:'Post%20Game%20Batting%20Average]"
});

Examples.push({
    name: "Focal Length",
    fxn : "(ObjectDistance * LensToImageDistance)/(ObjectDistance + LensToImageDistance)",
    url : "(ObjectDistance*LensToImageDistance)/(ObjectDistance+LensToImageDistance)=0:0:{100:100:}1:1:[37:20:;1:1:'Focal%20Length]"
});

Examples.push({
    name: "Population Growth",
    fxn : "LastYearPopulation + LastYearPopulation*(ReprodiveRate - Attrition)",
    url : "LastYearPopulation+LastYearPopulation*(ReprodiveRate-Attrition)=0:0:0:{10000:1:1:}1:0.01:0.01:[4162:0.37:0.16:;0:1:1:'Population%20Growth]"
});

Examples.push({
    name: "Fiber Optic Response Time",
    fxn : "ProcessingTime + (2*Distance)/(200*(1000^2))",
    url : "ProcessingTime+(2*Distance)/(200*(1000^2))=0:0:{100:100:}1:1:[12:40:;1:1:'Fiber%20Response%20Time]"
});

Examples.push({
    name: "Watts",
    fxn : "Amps * Volts",
    url : "Amps*Volts=0:0:{100:100:}0.01:0.01:[41.04:28.32:;1:1:'Watts]"
});

Examples.push({
    name: "Velocity",
    fxn : "InitialVelocity + Acceleration*Time",
    url : "InitialVelocity+Acceleration*Time=0:0:0:{100:100:100:}1:0.1:1:[42:9.8:10:;1:1:1:'Velocity]"
});

Examples.push({
    name: "Position of a Moving Object",
    fxn : "InitialPosition + InitialVelocity*Time + 1/2 * acceleration * Time^2",
    url : "InitialPosition+InitialVelocity*Time+1/2*acceleration*Time^2=0:0:0:0:{100:100:100:100:}1:1:0.1:0.1:[18:41:31:9.8:;1:1:1:1:'Position]"
});

Examples.push({
    name: "Torque",
    fxn : "radius * force * sin(angle)",
    url : "radius*force*sin(angle)=0:0:-360:{100:100:360:}1:1:1:[19:53:69:;1:1:1:'Torque]"
});

Examples.push({
    name: "Surface Area of Cylinder",
    fxn : "2*pi*radius*length + 2*pi*radius^2",
    url : "2*pi*radius*length+2*pi*radius^2=0:0:{100:100:}1:1:[31:17:;1:1:'Surface%20Area]"
});

Examples.push({
    name: "First Order Derivitive of x^n",
    fxn : "n*x^(n-1)",
    url : "n*x^(n-1)=0:0:{100:100:}1:1:[7:1:;1:1:'Derivative%20of%20x^N]"
});

Examples.push({
    name: "First Order Integral of x^n dx",
    fxn : "1/(n+1) * x^(n+1) + C",
    url : "1/(n+1)*x^(n+1)+C=0:0:0:{100:100:100:}1:1:1:[14:2:10:;1:1:1:'First%20Order%20Integral]"
});

Examples.push({
    name: "Glomerular Filtration Rate (Creatinine Clearance CCr) (Kidney Filtration Rate)",
    fxn : "(CreatineConcentration * FlowRate)/PlasmaConcentration",
    url : "(CreatineConcentration*FlowRate)/PlasmaConcentration=0:0:0:{100:100:100:}1:1:1:[53:31:10:;1:1:1:'Glomular%20Filtration]"
});

Examples.push({
    name: "IPAT Environmental Impact Equation",
    fxn : "Population * Affluence * Technology",
    url : "Population*Affluence*Technology=0:0:0:{100:100:100:}1:1:1:[20:40:31:;1:1:1:'IPAT]"
});

Examples.push({
    name: "Vertical Change Delta for a Weighted String between 2 Points",
    fxn : "sqrt(((StringLength + PointsDistance)/2)*((StringLength - PointsDistance)/2))",
    url : "sqrt(((StringLength+PointsDistance)/2)*((StringLength-PointsDistance)/2))=0:0:{100:100:}1:1:[33:18:;1:1:'Weighed%20String]"
});

Examples.push({
    name: "Gaussian",
    fxn : "a * e^(-1*((x-b)^2/2*c^2))",
    url : "a*e^(-1*((x-b)^2/2*c^2))=0:0:0:0:{100:100:100:100:}1:1:1:1:[8:30:17:5:;1:1:1:1:'Gaussian]"
});

Examples.push({
    name: "Mechanical Work",
    fxn : "1/2 * mass * (secondVelocity^2 - firstVelocity^2)",
    url : "1/2*mass*(secondVelocity^2-firstVelocity^2)=0:0:0:{100:100:100:}1:1:1:[71:34:42:;1:1:1:'Mechanical%20Work]"
});

Examples.push({
    name: "Procrastination Equation",
    fxn : "ExpectationOfSuccess*ValueofCompletion / (ImmediacyOfTask * PersonalDelaySensitivity)",
    url : "ExpectationOfSuccess*ValueofCompletion/(ImmediacyOfTask*PersonalDelaySensitivity)=0:0:0:0:{100:100:100:100:}1:1:1:1:[6:9:6:11:;1:1:1:1:'Procrastination%20Likelihood]"
});

Examples.push({
    name: "Pressure Loss via Friction",
    fxn : "FrictionCoefficient * (length / hydraulicDiameter) * (density * velocity^2 /2)",
    url : "FrictionCoefficient*(length/hydraulicDiameter)*(density*velocity^2/2)=0:0:0:0:0:{0.5:100:100:100:100:}0.001:1:1:1:1:[0.029:13:25:14:20:;1:1:1:1:1:'Pressure%20Loss]"
});

Examples.push({
    name: "Lorentz Factor",
    fxn : "1 / sqrt(1-(velocity^2/c^2))",
    url : "1/sqrt(1-(velocity^2/c^2))=0:290000000:{10000:310000000:}1:[4798:299792458:;1:100:'Lorentz%20Factor]"
});

Examples.push({
    name: "Euclidean Distance in 2D",
    fxn : "sqrt((xTwo-xOne)^2 + (yTwo-yOne)^2)",
    url : "sqrt((xTwo-xOne)^2+(yTwo-yOne)^2)=0:0:0:0:{100:100:100:100:}1:1:1:1:[27:53:40:53:;1:1:1:1:'Euclidean%20Distance]"
});

Examples.push({
    name: "Quadratic Equation (First Solution)",
    fxn : "(-x + sqrt(b^2 - 4*a*c))/2*a",
    url : "(-x+sqrt(b^2-4*a*c))/2*a=0:0:0:0:{100:100:100:100:}1:1:1:1:[5:22:3:5:;1:1:1:1:'Quadratic%20Graph]"
});
Examples.push({
    name: "Complex Parenthesis Function",
    fxn : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))",
    url : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))=-100:-10:-4:{100:100:100:}1:1:1:[-85:-2:15:;1:1:1:'Complex%20Function]"
});
<commit_msg>Testing examples fix<commit_after>/* Examples
 * */

Examples.push({
    name: "Bill Calculator",
    fxn : "100*(salary - rent - studentloans - carpayments - grocery-spendingmoney-retirement) - netflix -tivo -petfood -gas-electric + 100*(subleaseincome + stockportfolio)",
    url : "salary-rent-studentloans-carpayments-grocery-spendingmoney-retirement-netflix-tivo-petfood-gas-electric+subleaseincome+stockportfolio=0:0:0:0:0:0:0:7:0:0:0:0:0:0:{8000:3400:500:600:1000:500:1000:27:30:200:500:200:1000:1000:}100:100:50:50:20:10:100:3:3:20:30:10:100:50:[4000:400:100:250:300:500:300:13:12:100:120:90:600:100:;0:1:1:1:1:1:1:1:1:1:1:1:1:1:'Bill%20Calculator]"
});

Examples.push({
    name: "Drake Equation",
    fxn : "StarFormationRate * StarsWithPlanets * LifeSustainingPlanets * PlanetsWhichActuallyDevelopLife * PlanetsWithIntelligentLife * CivilizationsWithDetectors * DurationOfSpaceSignals",
    url : "StarFormationRate*StarsWithPlanets*LifeSustainingPlanets*PlanetsWhichActuallyDevelopLife*PlanetsWithIntelligentLife*CivilizationsWithDetectors*DurationOfSpaceSignals=0:0:0:0:0:0:0:{20:1:10:1:1:1:20:}1:0.1:1:0.1:0.1:0.1:1:[10:0.5:2:1:0.1:0.1:10:;1:1:1:1:1:1:1:'Drake%20Equation]"

    });

Examples.push({
    name: "Monthly Loan Payments Calculator",
    fxn : "Princpial*((rate/1200)*(1 + rate/1200)^Months)/((1 + rate/1200)^Months - 1)",
    url : "Princpial*((rate/1200)*(1+rate/1200)^Months)/((1+rate/1200)^Months-1)=0:0:0:{200:100:100:}10:1:1:[110:9:23:;1:1:1:'Loan%20Calculator]"
});

Examples.push({
    name: "Gravity",
    fxn : "GravConstant * massOne * massTwo / distance^2",
    url : "GravConstant*massOne*massTwo/distance^2=0:0:0:0:{20:100:100:100:}0.01:1:1:1:[8.73:29:19:3:;1:1:1:1:'Gravity]"
});

Examples.push({
    name: "E = mc^2",
    fxn : "mass*(300*1000*1000)^2",
    url : "mass*(300*1000*1000)^2=0:{100:}1:[20:;1:;Einstein]"
});

Examples.push({
    name: "Area of Circle",
    fxn : "pi * radius^2",
    url : "pi*radius^2=0:{100:}1:[13:;1:'Circle%20Area]"
});

Examples.push({
    name: "Circumference of a Circle",
    fxn : "2*pi*radius",
    url : "2*pi*radius=0:{100:}1:[13:;1:'Circle%20Circumference]"
});

Examples.push({
    name: "Flake Equation (xkcd.com/718)",
    fxn : "7*1000^3 * (CrazyPeople + Misinterpret)/10000 * TellProbability/10 * NumberPeopleTold * FirstHandRetellings * IgnoredDataProbability/10 * WiderAudienceFraction/100",
    url : "7*1000^3*(CrazyPeople+Misinterpret)/10000*TellProbability/10*NumberPeopleTold*FirstHandRetellings*IgnoredDataProbability/10*WiderAudienceFraction/100=0:0:0:0:0:0:0:{10:10:10:100:100:10:100:}1:1:1:1:1:1:1:[1:1:1:10:10:9:1:;1:1:1:1:1:1:1:'Flake%20Equation%20(XKCD)]"
});

Examples.push({
    name: "Dateable Ages (xkcd.com/314)",
    fxn : "Age/2 + 7",
    url : "Age/2+7=18:{126:}1:[27:;1:'Who%20Can%20You%20Date]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Straight) (xkcd.com/216)",
    fxn : "SameSex*(AllCast - SameSex)",
    url : "SameSex*(AllCast-SameSex)=0:0:{100:100:}1:1:[17:44:;1:1:'Romantic%20Pairings]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Gay) (xkcd.com/216)",
    fxn : "AllCast*(AllCast - 1)/2 + SameSex*(SameSex - AllCast)",
    url : "AllCast*(AllCast-1)/2+SameSex*(SameSex-AllCast)=0:0:{100:100:}1:1:[45:25:;1:1:'Romantic%20Pairings]"
});

Examples.push({
    name: "Post-Game Seasonal Batting Average",
    fxn : "(SeasonBats * (SeasonalAverage/100) + Hits)/(SeasonBats + TimesAtBat)",
    url : "(SeasonBats*(SeasonalAverage/100)+Hits)/(SeasonBats+TimesAtBat)=0:0:0:0:{100:100:100:13:}1:1:1:1:[40:60:81:13:;1:1:1:1:'Post%20Game%20Batting%20Average]"
});

Examples.push({
    name: "Focal Length",
    fxn : "(ObjectDistance * LensToImageDistance)/(ObjectDistance + LensToImageDistance)",
    url : "(ObjectDistance*LensToImageDistance)/(ObjectDistance+LensToImageDistance)=0:0:{100:100:}1:1:[37:20:;1:1:'Focal%20Length]"
});

Examples.push({
    name: "Population Growth",
    fxn : "LastYearPopulation + LastYearPopulation*(ReprodiveRate - Attrition)",
    url : "LastYearPopulation+LastYearPopulation*(ReprodiveRate-Attrition)=0:0:0:{10000:1:1:}1:0.01:0.01:[4162:0.37:0.16:;0:1:1:'Population%20Growth]"
});

Examples.push({
    name: "Fiber Optic Response Time",
    fxn : "ProcessingTime + (2*Distance)/(200*(1000^2))",
    url : "ProcessingTime+(2*Distance)/(200*(1000^2))=0:0:{100:100:}1:1:[12:40:;1:1:'Fiber%20Response%20Time]"
});

Examples.push({
    name: "Watts",
    fxn : "Amps * Volts",
    url : "Amps*Volts=0:0:{100:100:}0.01:0.01:[41.04:28.32:;1:1:'Watts]"
});

Examples.push({
    name: "Velocity",
    fxn : "InitialVelocity + Acceleration*Time",
    url : "InitialVelocity+Acceleration*Time=0:0:0:{100:100:100:}1:0.1:1:[42:9.8:10:;1:1:1:'Velocity]"
});

Examples.push({
    name: "Position of a Moving Object",
    fxn : "InitialPosition + InitialVelocity*Time + 1/2 * acceleration * Time^2",
    url : "InitialPosition+InitialVelocity*Time+1/2*acceleration*Time^2=0:0:0:0:{100:100:100:100:}1:1:0.1:0.1:[18:41:31:9.8:;1:1:1:1:'Position]"
});

Examples.push({
    name: "Torque",
    fxn : "radius * force * sin(angle)",
    url : "radius*force*sin(angle)=0:0:-360:{100:100:360:}1:1:1:[19:53:69:;1:1:1:'Torque]"
});

Examples.push({
    name: "Surface Area of Cylinder",
    fxn : "2*pi*radius*length + 2*pi*radius^2",
    url : "2*pi*radius*length+2*pi*radius^2=0:0:{100:100:}1:1:[31:17:;1:1:'Surface%20Area]"
});

Examples.push({
    name: "First Order Derivitive of x^n",
    fxn : "n*x^(n-1)",
    url : "n*x^(n-1)=0:0:{100:100:}1:1:[7:1:;1:1:'Derivative%20of%20x^N]"
});

Examples.push({
    name: "First Order Integral of x^n dx",
    fxn : "1/(n+1) * x^(n+1) + C",
    url : "1/(n+1)*x^(n+1)+C=0:0:0:{100:100:100:}1:1:1:[14:2:10:;1:1:1:'First%20Order%20Integral]"
});

Examples.push({
    name: "Glomerular Filtration Rate (Creatinine Clearance CCr) (Kidney Filtration Rate)",
    fxn : "(CreatineConcentration * FlowRate)/PlasmaConcentration",
    url : "(CreatineConcentration*FlowRate)/PlasmaConcentration=0:0:0:{100:100:100:}1:1:1:[53:31:10:;1:1:1:'Glomular%20Filtration]"
});

Examples.push({
    name: "IPAT Environmental Impact Equation",
    fxn : "Population * Affluence * Technology",
    url : "Population*Affluence*Technology=0:0:0:{100:100:100:}1:1:1:[20:40:31:;1:1:1:'IPAT]"
});

Examples.push({
    name: "Vertical Change Delta for a Weighted String between 2 Points",
    fxn : "sqrt(((StringLength + PointsDistance)/2)*((StringLength - PointsDistance)/2))",
    url : "sqrt(((StringLength+PointsDistance)/2)*((StringLength-PointsDistance)/2))=0:0:{100:100:}1:1:[33:18:;1:1:'Weighed%20String]"
});

Examples.push({
    name: "Gaussian",
    fxn : "a * e^(-1*((x-b)^2/2*c^2))",
    url : "a*e^(-1*((x-b)^2/2*c^2))=0:0:0:0:{100:100:100:100:}1:1:1:1:[8:30:17:5:;1:1:1:1:'Gaussian]"
});

Examples.push({
    name: "Mechanical Work",
    fxn : "1/2 * mass * (secondVelocity^2 - firstVelocity^2)",
    url : "1/2*mass*(secondVelocity^2-firstVelocity^2)=0:0:0:{100:100:100:}1:1:1:[71:34:42:;1:1:1:'Mechanical%20Work]"
});

Examples.push({
    name: "Procrastination Equation",
    fxn : "ExpectationOfSuccess*ValueofCompletion / (ImmediacyOfTask * PersonalDelaySensitivity)",
    url : "ExpectationOfSuccess*ValueofCompletion/(ImmediacyOfTask*PersonalDelaySensitivity)=0:0:0:0:{100:100:100:100:}1:1:1:1:[6:9:6:11:;1:1:1:1:'Procrastination%20Likelihood]"
});

Examples.push({
    name: "Pressure Loss via Friction",
    fxn : "FrictionCoefficient * (length / hydraulicDiameter) * (density * velocity^2 /2)",
    url : "FrictionCoefficient*(length/hydraulicDiameter)*(density*velocity^2/2)=0:0:0:0:0:{0.5:100:100:100:100:}0.001:1:1:1:1:[0.029:13:25:14:20:;1:1:1:1:1:'Pressure%20Loss]"
});

Examples.push({
    name: "Lorentz Factor",
    fxn : "1 / sqrt(1-(velocity^2/c^2))",
    url : "1/sqrt(1-(velocity^2/c^2))=0:290000000:{10000:310000000:}1:[4798:299792458:;1:100:'Lorentz%20Factor]"
});

Examples.push({
    name: "Euclidean Distance in 2D",
    fxn : "sqrt((xTwo-xOne)^2 + (yTwo-yOne)^2)",
    url : "sqrt((xTwo-xOne)^2+(yTwo-yOne)^2)=0:0:0:0:{100:100:100:100:}1:1:1:1:[27:53:40:53:;1:1:1:1:'Euclidean%20Distance]"
});

Examples.push({
    name: "Quadratic Equation (First Solution)",
    fxn : "(-x + sqrt(b^2 - 4*a*c))/2*a",
    url : "(-x+sqrt(b^2-4*a*c))/2*a=0:0:0:0:{100:100:100:100:}1:1:1:1:[5:22:3:5:;1:1:1:1:'Quadratic%20Graph]"
});
Examples.push({
    name: "Complex Parenthesis Function",
    fxn : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))",
    url : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))=-100:-10:-4:{100:100:100:}1:1:1:[-85:-2:15:;1:1:1:'Complex%20Function]"
});
<|endoftext|>


<commit_before>var functionRun = false;

function feedback() {
    $("#feedbackModal").modal("open");
    if (functionRun != true) {
        functionRun = true;
        var productQty;
        var serviceQty;
        var message;
        $(".prdQty input").on("change", function (e) {
            productQty = $(this).attr("rate")
        })
        $(".servQty input").on("change", function (e) {
            serviceQty = $(this).attr("rate")
        })
        $("#sendFeedback").click(function (e) {
            M.toast({
                html: 'Sending feedback...'
            })
            doFetch({
                action: 'storeFeed',
                uid: localStorage.getItem('bits-user-name'),
                speed: productQty,
                quality: serviceQty,
                text: $("#feedbackText").val()
            }).then(function (e) {
                if (e.status == "ok") {
                    M.toast({
                        html: 'Feed back sent successfully'
                    })
                    $("#feedbackModal").modal("close")
                }
            })
        })
    }
}
<commit_msg>feedback update<commit_after>var functionRun = false;

function feedback() {
    $("#feedbackModal").modal("open");
    if (functionRun != true) {
        functionRun = true;
        var productQty;
        var serviceQty;
        var message;
        $(".prdQty input").on("change", function (e) {
            productQty = $(this).attr("rate")
        })
        $(".servQty input").on("change", function (e) {
            serviceQty = $(this).attr("rate")
        })
        $("#sendFeedback").click(function (e) {
            M.toast({
                html: 'Sending feedback...'
            })
            doFetch({
                action: 'storeFeed',
                uid: localStorage.getItem('bits-user-name'),
                speed: productQty,
                quality: serviceQty,
                text: $("#feedbackText").val()
            }).then(function (e) {
                if (e.status == "ok") {
                    M.toast({
                        html: 'Feed back sent successfully'
                    })
                    $("#feedbackModal").modal("close")
                } else {
                    M.toast({
                        html: 'Error! Try again later'
                    })
                }
            })
        })
    }
}
<|endoftext|>


<commit_before>// ffs/wizard module
if (typeof turbo === "undefined") turbo={};

turbo.ffs.free = function() {

  var freeFormQuery = {};
  var presets;

  // load presets
  (function loadPresets() {
    var presets_file = "data/iD_presets.json";
    try {
      $.ajax(presets_file,{async:false,dataType:"json"}).success(function(data){
        presets = data;
      }).error(function(){
        throw new Error();
      });
    } catch(e) {
      console.log("failed to load presets file: "+presets_file);
    }
  })();
  // load preset translations
  (function loadPresetTranslations() {
    var language = i18n.getLanguage();
    // skip English, as the preset file already includes all terms. (todo: is that so?)
    if (language == "en") return;
    var translation_file = "data/iD_presets_"+language+".json";
    try {
      $.ajax(translation_file,{async:false,dataType:"json"}).success(function(data){
        // load translated names and terms into presets object
        _.each(data, function(translation, preset) {
          preset = presets[preset];
          preset.translated = true;
          // save original preset name under alternative terms
          if (!preset.terms) preset.terms = [];
          preset.terms.unshift(preset.name);
          // save translated preset name
          preset.name = translation.name;
          // add new terms
          preset.terms = translation.terms.split(",")
            .map(function(term) { return term.trim(); })
            .concat(preset.terms);
        });
      }).error(function(){
        throw new Error();
      });
    } catch(e) {
      console.log("failed to load preset translations file: "+translation_file);
    }
  })();

  freeFormQuery.get_query_clause = function(condition) {
    // search presets for ffs term
    var search = condition.free;
    var candidates = _.values(presets).filter(function(preset) {
      // todo: other languages?
      if (preset.searchable===false) return false;
      return preset.name === search || // todo: case-insensitive, little fuzzyness
             (preset.terms && preset.terms.indexOf(search) >= 0);
    });
    if (candidates.length === 0)
      return false;
    candidates.sort(function(a,b) {
      return a.name===search - b.name===search;
    });
    // todo: what if multiple candidates match?
    var preset = candidates[0];
    var types = [];
    preset.geometry.forEach(function(g) {
      switch (g) {
        case "point":
        case "vertex":
          types.push("node");
          break;
        case "line":
          types.push("way");
          break;
        case "area":
          types.push("way");
          types.push("relation")
          break;
      }
    });
    return {
      types: _.uniq(types),
      conditions: _.map(preset.tags, function(v,k) {
        return {
          query: v==="*" ? "key" : "eq",
          key: k,
          val: v
        };
      })
    };
  }

  return freeFormQuery;
};<commit_msg>case-insensitive preset search<commit_after>// ffs/wizard module
if (typeof turbo === "undefined") turbo={};

turbo.ffs.free = function() {

  var freeFormQuery = {};
  var presets;

  // load presets
  (function loadPresets() {
    var presets_file = "data/iD_presets.json";
    try {
      $.ajax(presets_file,{async:false,dataType:"json"}).success(function(data){
        presets = data;
        _.each(presets, function(preset) {
          preset.name = preset.name.toLowerCase();
          preset.terms = !preset.terms ? [] : preset.terms.map(function(term) {return term.toLowerCase();});
        });
      }).error(function(){
        throw new Error();
      });
    } catch(e) {
      console.log("failed to load presets file: "+presets_file);
    }
  })();
  // load preset translations
  (function loadPresetTranslations() {
    var language = i18n.getLanguage();
    // skip English, as the preset file already includes all terms. (todo: is that so?)
    if (language == "en") return;
    var translation_file = "data/iD_presets_"+language+".json";
    try {
      $.ajax(translation_file,{async:false,dataType:"json"}).success(function(data){
        // load translated names and terms into presets object
        _.each(data, function(translation, preset) {
          preset = presets[preset];
          preset.translated = true;
          // save original preset name under alternative terms
          preset.terms.unshift(preset.name);
          // save translated preset name
          preset.name = translation.name.toLowerCase();
          // add new terms
          preset.terms = translation.terms.split(",")
            .map(function(term) { return term.trim().toLowerCase(); })
            .concat(preset.terms);
        });
      }).error(function(){
        throw new Error();
      });
    } catch(e) {
      console.log("failed to load preset translations file: "+translation_file);
    }
  })();

  freeFormQuery.get_query_clause = function(condition) {
    // search presets for ffs term
    var search = condition.free.toLowerCase();
    var candidates = _.values(presets).filter(function(preset) {
      // todo: other languages?
      if (preset.searchable===false) return false;
      return preset.name === search || // todo: little fuzzyness
             (preset.terms.indexOf(search) >= 0);
    });
    if (candidates.length === 0)
      return false;
    candidates.sort(function(a,b) {
      return a.name===search - b.name===search;
    });
    // todo: what if multiple candidates match?
    var preset = candidates[0];
    var types = [];
    preset.geometry.forEach(function(g) {
      switch (g) {
        case "point":
        case "vertex":
          types.push("node");
          break;
        case "line":
          types.push("way");
          break;
        case "area":
          types.push("way");
          types.push("relation")
          break;
      }
    });
    return {
      types: _.uniq(types),
      conditions: _.map(preset.tags, function(v,k) {
        return {
          query: v==="*" ? "key" : "eq",
          key: k,
          val: v
        };
      })
    };
  }

  return freeFormQuery;
};<|endoftext|>


<commit_before>$( document ).ready(function() {
    var SERVER_URL = "http://hackabooth.jovanoski.net:8080";
    var currentPhotoUris = [];
    var row = $('.row');

    var generatePhotoHtml = function(photoUrl){
        var photoUrl = SERVER_URL + photoUrl;
        var gridPhotoUrl = photoUrl + '&grid=1';
        var photoHTML = [
            '
',
                '',
                    '',
                '',
          '
'
        ];
        return photoHTML.join('');
    };

    function getRecentPhotos() {
        $.ajax({
            url : SERVER_URL + "/recent_images",
            type : "GET",
            crossDomain: true,
            success : processPhotos,
            error: function(){
                var timeout = setTimeout(function(){
                    getRecentPhotos();
                    clearTimeout(timeout);
                }, 5000);
            }
        });
    };

    function processPhotos(responsePhotoUris) {
        var newPhotoUris = responsePhotoUris.filter(function(i) {return currentPhotoUris.indexOf(i) < 0;});
        if(newPhotoUris.length > 0) {
            $.each(newPhotoUris, function(i, photoUrl){
                if (i < 3){
                    var photoHtml = generatePhotoHtml(photoUrl);
                    row.append(photoHtml);
                    currentPhotoUris.push(photoUrl);
                }
            });
        }
        var timeout = setTimeout(function(){
            getRecentPhotos();
            clearTimeout(timeout);
        }, 5000);
    }
//    var swapThumbnailData = function(link){
//        var image = link.children("img");
//        var pom = image.attr("src");
//
//        image.attr("src", link.attr("href"));
//        link.attr("href", pom);
//    };
//    $('.container').on('click', '.thumbnail', function(e){
//        e.preventDefault();
//        var link = $(this);
//        if(!link.hasClass("grid")){
//            swapThumbnailData(link);
//            link.addClass("grid");
//        }
//    });
//
//    $('.container').on('click', '.grid', function(e){
//        e.preventDefault();
//        var link = $(this);
//        swapThumbnailData(link);
//        link.removeClass("grid");
//    });

    getRecentPhotos();
});<commit_msg>console output<commit_after>$( document ).ready(function() {
    var SERVER_URL = "http://hackabooth.jovanoski.net:8080";
    var currentPhotoUris = [];
    var row = $('.row');

    var generatePhotoHtml = function(photoUrl){
        var photoUrl = SERVER_URL + photoUrl;
        var gridPhotoUrl = photoUrl + '&grid=1';
        var photoHTML = [
            '
',
                '',
                    '',
                '',
          '
'
        ];
        return photoHTML.join('');
    };

    function getRecentPhotos() {
        console.log("getting stuff");
        $.ajax({
            url : SERVER_URL + "/recent_images",
            type : "GET",
            crossDomain: true,
            success : processPhotos,
            error: function(){
                var timeout = setTimeout(function(){
                    getRecentPhotos();
                    clearTimeout(timeout);
                }, 5000);
            }
        });
    };

    function processPhotos(responsePhotoUris) {
        var newPhotoUris = responsePhotoUris.filter(function(i) {return currentPhotoUris.indexOf(i) < 0;});
        if(newPhotoUris.length > 0) {
            $.each(newPhotoUris, function(i, photoUrl){
                if (i < 3){
                    var photoHtml = generatePhotoHtml(photoUrl);
                    row.append(photoHtml);
                    currentPhotoUris.push(photoUrl);
                }
            });
        }
        var timeout = setTimeout(function(){
            getRecentPhotos();
            clearTimeout(timeout);
        }, 5000);
    }
//    var swapThumbnailData = function(link){
//        var image = link.children("img");
//        var pom = image.attr("src");
//
//        image.attr("src", link.attr("href"));
//        link.attr("href", pom);
//    };
//    $('.container').on('click', '.thumbnail', function(e){
//        e.preventDefault();
//        var link = $(this);
//        if(!link.hasClass("grid")){
//            swapThumbnailData(link);
//            link.addClass("grid");
//        }
//    });
//
//    $('.container').on('click', '.grid', function(e){
//        e.preventDefault();
//        var link = $(this);
//        swapThumbnailData(link);
//        link.removeClass("grid");
//    });

    getRecentPhotos();
});<|endoftext|>


<commit_before>var getGradient = function () {
    var red1 = Math.floor(Math.random() * 256);
    var green1 = Math.floor(Math.random() * 256);
    var blue1 = Math.floor(Math.random() * 256);

    var red2 = Math.floor(Math.random() * 256);
    var green2 = Math.floor(Math.random() * 256);
    var blue2 = Math.floor(Math.random() * 256);

    var rgb1 = 'rgb(' + red1 + ',' + green1 + ',' + blue1 + ')';
    var rgb2 = 'rgb(' + red2 + ',' + green2 + ',' + blue2 + ')';

    var webkitLinearGradient = '-webkit-linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';
    var linearGradient = 'linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';

    $('body').css('background-color', rgb1);
    $('button').css('background-color', rgb1);
    $('#quote').css('color', rgb1);
    $('#author').css('color', rgb1);
};<commit_msg>Add backgroundcolor for a<commit_after>var getGradient = function () {
    var red1 = Math.floor(Math.random() * 256);
    var green1 = Math.floor(Math.random() * 256);
    var blue1 = Math.floor(Math.random() * 256);

    var red2 = Math.floor(Math.random() * 256);
    var green2 = Math.floor(Math.random() * 256);
    var blue2 = Math.floor(Math.random() * 256);

    var rgb1 = 'rgb(' + red1 + ',' + green1 + ',' + blue1 + ')';
    var rgb2 = 'rgb(' + red2 + ',' + green2 + ',' + blue2 + ')';

    var webkitLinearGradient = '-webkit-linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';
    var linearGradient = 'linear-gradient(to left,' + rgb1 + ',' + rgb2 + ')';

    $('body').css('background-color', rgb1);
    $('button').css('background-color', rgb1);
    $('a').css('background-color', rgb1);
    $('#quote').css('color', rgb1);
    $('#author').css('color', rgb1);
};<|endoftext|>


<commit_before>(function(window){

	if('function' === typeof window.highlight)
	{
		window.highlight.sql=[
			{
				'class':'string',
				'match':/(b?"(?:[^"]|\\")*"|b?'(?:[^']|\\')*')(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'number',
				'match':/(?![a-z_])([+\-]?\d+(?:\.\d+)?)(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'comment',
				'match':/((?:\/\/|\-\-\s|#)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*\*\/)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'name',
				'match':/(`[^`]+`)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'keyword',
				//the keyword replace must have an aditional check (`(?!\()` after the name), due to the function replace()
				'match':/\b(accessible|add|all|alter|analyze|and|as|asc|asensitive|before|between|bigint|binary|blob|both|by|call|cascade|case|change|char|character|check|collate|column|condition|constraint|continue|convert|create|cross|current_date|current_time|current_timestamp|current_user|cursor|database|databases|day_hour|day_microsecond|day_minute|day_second|dec|decimal|declare|default|delayed|delete|desc|describe|deterministic|distinct|distinctrow|div|double|drop|dual|each|else|elseif|enclosed|escaped|exists|exit|explain|false|fetch|float|float4|float8|for|force|foreign|from|fulltext|generated|get|grant|group|having|high_priority|hour_microsecond|hour_minute|hour_second|if|ignore|in|index|infile|inner|inout|insensitive|insert|int|int1|int2|int3|int4|int8|integer|interval|into|io_after_gtids|io_before_gtids|is|iterate|join|key|keys|kill|leading|leave|left|like|limit|linear|lines|load|localtime|localtimestamp|lock|long|longblob|longtext|loop|low_priority|master_bind|master_ssl_verify_server_cert|match|maxvalue|mediumblob|mediumint|mediumtext|middleint|minute_microsecond|minute_second|mod|modifies|natural|nonblocking|not|no_write_to_binlog|null|numeric|on|optimize|optimizer_costs|option|optionally|or|order|out|outer|outfile|parse_gcol_expr|partition|precision|primary|procedure|purge|range|read|reads|read_write|real|references|regexp|release|rename|repeat|replace(?!\()|require|resignal|restrict|return|revoke|right|rlike|schema|schemas|second_microsecond|select|sensitive|separator|set|show|signal|smallint|spatial|specific|sql|sqlexception|sqlstate|sqlwarning|sql_big_result|sql_calc_found_rows|sql_small_result|ssl|starting|stored|straight_join|table|terminated|then|tinyblob|tinyint|tinytext|to|trailing|trigger|true|undo|union|unique|unlock|unsigned|update|usage|use|using|utc_date|utc_time|utc_timestamp|values|varbinary|varchar|varcharacter|varying|virtual|when|where|while|with|write|xor|year_month|zerofill)\b/gi,
				'replace':window.highlight.default_replace
			},
			{
				'class':'func',
				'match':/\b([a-z_][a-z_\d]*)\b(?=\()/gi,
				'replace':window.highlight.default_replace
			},
			{
				//assumes that all missing matches are table/column names
				'class':'name',
				'match':/\b([a-z\_][a-z_\d]*)\b/gi,
				'replace':window.highlight.default_replace
			}
		];
	}

})(Function('return this')());
<commit_msg>Added variable matching, improved table name matching.<commit_after>(function(window){

	if('function' === typeof window.highlight)
	{
		window.highlight.sql=[
			{
				'class':'string',
				'match':/(b?"(?:[^"]|\\")*"|b?'(?:[^']|\\')*')(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'number',
				'match':/(?![a-z_]+)([+\-]?\d+(?:\.\d+)?)(?=[\b\s\(\),])/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'comment',
				'match':/((?:\/\/|\-\-\s|#)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*\*\/)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'name',
				'match':/(`[^`]+`)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'var',
				'match':/(@@?[a-z_][a-z_\d]*)/g,
				'replace':window.highlight.default_replace
			},
			{
				'class':'keyword',
				//the keyword replace must have an aditional check (`(?!\()` after the name), due to the function replace()
				'match':/\b(accessible|add|all|alter|analyze|and|as|asc|asensitive|before|between|bigint|binary|blob|both|by|call|cascade|case|change|char|character|check|collate|column|condition|constraint|continue|convert|create|cross|current_date|current_time|current_timestamp|current_user|cursor|database|databases|day_hour|day_microsecond|day_minute|day_second|dec|decimal|declare|default|delayed|delete|desc|describe|deterministic|distinct|distinctrow|div|double|drop|dual|each|else|elseif|enclosed|escaped|exists|exit|explain|false|fetch|float|float4|float8|for|force|foreign|from|fulltext|generated|get|grant|group|having|high_priority|hour_microsecond|hour_minute|hour_second|if|ignore|in|index|infile|inner|inout|insensitive|insert|int|int1|int2|int3|int4|int8|integer|interval|into|io_after_gtids|io_before_gtids|is|iterate|join|key|keys|kill|leading|leave|left|like|limit|linear|lines|load|localtime|localtimestamp|lock|long|longblob|longtext|loop|low_priority|master_bind|master_ssl_verify_server_cert|match|maxvalue|mediumblob|mediumint|mediumtext|middleint|minute_microsecond|minute_second|mod|modifies|natural|nonblocking|not|no_write_to_binlog|null|numeric|on|optimize|optimizer_costs|option|optionally|or|order|out|outer|outfile|parse_gcol_expr|partition|precision|primary|procedure|purge|range|read|reads|read_write|real|references|regexp|release|rename|repeat|replace(?!\()|require|resignal|restrict|return|revoke|right|rlike|schema|schemas|second_microsecond|select|sensitive|separator|set|show|signal|smallint|spatial|specific|sql|sqlexception|sqlstate|sqlwarning|sql_big_result|sql_calc_found_rows|sql_small_result|ssl|starting|stored|straight_join|table|terminated|then|tinyblob|tinyint|tinytext|to|trailing|trigger|true|undo|union|unique|unlock|unsigned|update|usage|use|using|utc_date|utc_time|utc_timestamp|values|varbinary|varchar|varcharacter|varying|virtual|when|where|while|with|write|xor|year_month|zerofill)\b/gi,
				'replace':window.highlight.default_replace
			},
			{
				'class':'func',
				'match':/\b([a-z_][a-z_\d]*)\b(?=\()/gi,
				'replace':window.highlight.default_replace
			},
            {
                'class':'name',
                'match':/\b([a-z\_][a-z_\d]*)\b/gi,
                'replace':window.highlight.default_replace
            }
		];
	}

})(Function('return this')());
<|endoftext|>


<commit_before>/* global EHM: true, EH: true*/
EHM.factory('auth', function($location, $http, error, storage) {
  var auth = {};

  auth.validTime = 2419200000; // Four weeks in milliseconds according to Google.

  auth.login = function(credentials) {
    if(credentials.username && credentials.password) {
      $http.post(EH.url.apikey, credentials).success(function(obj) {
        if (!EH.isset(obj.value) || !EH.isset(obj.value.apikey)) {
          error.setHeader('Receive bad data, try again later').show();
          return;
        }
        auth.logginUser({
          'username': credentials.username,
          'apikey': obj.value.apikey,
          'loggedin': true,
          'time': EH.time()
        });
        $location.path('/upcoming');
      }).error(function(data, status) {
        if (status === 401) {
          error.setHeader('Wrong username and/or password').show();
        } else if (status === 403) {
          error.setHeader('Your account is not activated').show();
        } else {
          error.setHeader('Can not connect to the server, try again later').show();
        }
      });
    } else {
      error.setHeader('Please fill in your username and password').show();
    }
  };

  auth.logout = function() {
    storage.removeItem('user');
    $location.path('/login');
  };

  auth.isLoggedIn = function() {
    var user = auth.getUser();
    if (user && user.loggedin) {
      return user.loggedin;
    }
  };

  auth.getUser = function() {
    return storage.refresh('user', auth.validTime);
  };

  auth.logginUser = function(user) {
    return storage.set('user', user, auth.validTime);
  };

  return auth;
});
<commit_msg>Shuld return false<commit_after>/* global EHM: true, EH: true*/
EHM.factory('auth', function($location, $http, error, storage) {
  var auth = {};

  auth.validTime = 2419200000; // Four weeks in milliseconds according to Google.

  auth.login = function(credentials) {
    if(credentials.username && credentials.password) {
      $http.post(EH.url.apikey, credentials).success(function(obj) {
        if (!EH.isset(obj.value) || !EH.isset(obj.value.apikey)) {
          error.setHeader('Receive bad data, try again later').show();
          return;
        }
        auth.logginUser({
          'username': credentials.username,
          'apikey': obj.value.apikey,
          'loggedin': true,
          'time': EH.time()
        });
        $location.path('/upcoming');
      }).error(function(data, status) {
        if (status === 401) {
          error.setHeader('Wrong username and/or password').show();
        } else if (status === 403) {
          error.setHeader('Your account is not activated').show();
        } else {
          error.setHeader('Can not connect to the server, try again later').show();
        }
      });
    } else {
      error.setHeader('Please fill in your username and password').show();
    }
  };

  auth.logout = function() {
    storage.removeItem('user');
    $location.path('/login');
  };

  auth.isLoggedIn = function() {
    var user = auth.getUser();
    if (user && user.loggedin) {
      return user.loggedin;
    }
    return false;
  };

  auth.getUser = function() {
    return storage.refresh('user', auth.validTime);
  };

  auth.logginUser = function(user) {
    return storage.set('user', user, auth.validTime);
  };

  return auth;
});
<|endoftext|>


<commit_before>function Game(debug) {
  this.debug = debug || false;
  this.load();
}

Game.prototype = {
  load: function () {
    var toLoad = 2; // 1 for sprite, 1 for audio
    var loaded = 0;

    var loadedCallback = function () {
      if (++loaded === toLoad) this.initialize();
    }.bind(this);

    $.getJSON('res/sprites.json', function (sprites) {
      this.spriteLoader = new Sprites(sprites);
      this.spriteLoader.preload(loadedCallback);
      this.sprites = this.spriteLoader.getSprites();
    }.bind(this));

    $.getJSON('res/sounds.json', function (sounds) {
      this.audio = new Audio(sounds);
      this.audio.preload(loadedCallback);
    }.bind(this));
  },

  initialize: function () {
    this.canvas = $('#canvas')[0];
    this.decalCanvas = $('#persistent-canvas')[0];
    this.renderer = new Renderer(this, this.canvas, this.decalCanvas);

    this.running = true;
    this.gameOver = false;
    this.tickRate = 60;
    this.age = 0;
    this.fpsCounter = 0;
    this.center = { x: this.canvas.width / 2, y: this.canvas.height / 2 };

    this.resources = {
      game:    this,
      sprites: this.sprites,
      sounds:  this.sounds
    };

    this.player = new Player(this.resources, { x: this.center.x, y: this.center.y });
    this.entities = [this.player];
    this.friendlies = [this.player];
    this.enemies = [];

    this.upgradeCount = {};
    this.upgrades = new Upgrades(this);

    this.levelNumber = 0;
    this.level = null;
    this.levels = new Levels(this).levels;

    this.gold = 50;

    this.dayLength = 1440;
    this.timeOfDay = 0;
    this.dayRatio = 0;

    this.ui = new UI(this);

    // Debug variables
    if (this.debug) {
      this.lastAge = this.age;
      setInterval(this.updateDebugInfo.bind(this), 1000);
    }

    setInterval(this.step.bind(this), 1000 / this.tickRate);
    this.draw();
  },

  step: function () {
    if (this.running && !this.gameOver) {
      this.age++;

      // Do not add bullets to spatial hash. Do all checking in individual
      // bullets against enemies.
      // For performance:
      //   1. We don't want to check bullets against other bullets as they
      //      will not collide (and are usually near each other).
      //   2. Updating the spatial hash for individual objects is painful
      //      so we recreate it each frame. More expensive with many bullets.
      this.spatialHash = new SpatialHash(Math.ceil(this.canvas.width / 50));
      var i;
      for (i = 0; i < this.enemies.length; i++) {
        var enemy = this.enemies[i];
        this.spatialHash.add(enemy.x, enemy.y, enemy);
      }
      for (i = 0; i < this.friendlies.length; i++) {
        var friendly = this.friendlies[i];
        this.spatialHash.add(friendly.x, friendly.y, friendly);
      }

      for (i = 0; i < this.entities.length; i++) {
        this.entities[i].tick();
        this.entities[i].executeUpgrades();
        this.entities[i].tock();
      }

      // Culling
      this.entities = this.entities.filter(this.getMarkedForDeletion);
      this.friendlies = this.friendlies.filter(this.getMarkedForDeletion);
      this.enemies = this.enemies.filter(this.getMarkedForDeletion);

      // Time of day
      this.timeOfDay = this.age % this.dayLength;
      this.dayRatio = 1 - this.timeOfDay / this.dayLength;

      // UI
      if (this.age % 30 === 0) this.ui.tick();
      if (this.age % 120 === 0) this.ui.scaleCanvas();

      // Levels
      if (!_.isObject(this.level) || this.level.over) {
        this.levelNumber++;
        this.level = this.levels[this.levelNumber];
      } else {
        this.level.tock();
        this.level.tick();
      }
    }
  },

  // Optimisation for culling; cache function
  getMarkedForDeletion: function (ent) {
    return !ent.markedForDeletion;
  },

  draw: function () {
    if (this.running) {
      // Update scaling only once per second.
      if (++this.fpsCounter === 1) this.ui.scaleCanvas();
      this.renderer.draw();
      this.animationRequestId = requestAnimationFrame(this.draw.bind(this));
    } else {
      cancelAnimationFrame(this.animationRequestId);
    }
  },

  setBackground: function (canvasbg, documentbg) {
    $('#persistent-canvas').css('background-image', 'url(' + canvasbg + ')');
    $('body').css('background-image', 'url(' + documentbg + ')');
  },

  upgrade: function (upgradeName, args) {
    var upgrade = this.upgrades.list[upgradeName];

    if (upgrade.isConstraintsMet(this)) {
      args = args || [];
      upgrade.effect.call(this, args);

      if (!Util.isDefined(this.upgradeCount[upgrade.name])) {
        this.upgradeCount[upgrade.name] = 1;
      } else {
        this.upgradeCount[upgrade.name]++;
      }

      if (Util.isDefined(upgrade.gameUpgradeIcon)) {
        this.ui.addGameUpgradeIcon(upgrade.gameUpgradeIcon.icon, upgrade.gameUpgradeIcon.tooltip);
      }
    }
  },

  addEntity: function (entity, type) {
    this.entities.push(entity);
    type = type || 'entity';
    switch (type) {
      case 'enemy': this.enemies.push(entity); break;
      case 'friendly': this.friendlies.push(entity); break;
      default: /* noop */ break;
    }
  },

  addPowerup: function (entity) {
    entity.alignment = 'enemy';
    this.addEntity(entity, 'enemy');
  },

  spawnEnemy: function (enemy) {
    var spawn = {};
    var minDistanceAway = 300;
    var maxAttempts = 100;
    var attempts = 0;

    do {
      spawn = { x: _.random(this.canvas.width), y: _.random(this.canvas.height) };
    } while (
      Util.distanceBetween(spawn, this.player) < minDistanceAway &&
      attempts++ < maxAttempts);

    if (attempts < maxAttempts) {
      enemy.x = spawn.x;
      enemy.y = spawn.y;
      this.addEntity(enemy, 'enemy');
    }
  },

  addGold: function (amount) {
    this.gold += amount;
    this.ui.updateGold();
  },

  subtractGold: function (amount) {
    this.gold -= amount;
    this.ui.updateGold();
    this.audio.play('coin');
  },

  updateDebugInfo: function () {
    var reduction = this.audio.compressor.reduction;
    var reductionLevel = reduction && parseFloat(reduction) ? reduction : reduction.value;

    $('#debug').html(
      '
' + this.fpsCounter + ' FPS
' +
      '
' + (this.age - this.lastAge) + ' ticks/s
' +
      '
' + this.entities.length + ' entities
' +
      '
' + this.friendlies.length + ' friendlies
' +
      '
' + this.enemies.length + ' enemies
' +
      '
' + this.player.health + ' player health
' +
      '
' + (reductionLevel ? reductionLevel.toFixed(2) : '?') + ' compressor reduction
'
    );

    this.lastAge = this.age;
    this.fpsCounter = 0;
  }
};
<commit_msg>Make enemies spawn from outside the map as well<commit_after>function Game(debug) {
  this.debug = debug || false;
  this.load();
}

Game.prototype = {
  load: function () {
    var toLoad = 2; // 1 for sprite, 1 for audio
    var loaded = 0;

    var loadedCallback = function () {
      if (++loaded === toLoad) this.initialize();
    }.bind(this);

    $.getJSON('res/sprites.json', function (sprites) {
      this.spriteLoader = new Sprites(sprites);
      this.spriteLoader.preload(loadedCallback);
      this.sprites = this.spriteLoader.getSprites();
    }.bind(this));

    $.getJSON('res/sounds.json', function (sounds) {
      this.audio = new Audio(sounds);
      this.audio.preload(loadedCallback);
    }.bind(this));
  },

  initialize: function () {
    this.canvas = $('#canvas')[0];
    this.decalCanvas = $('#persistent-canvas')[0];
    this.renderer = new Renderer(this, this.canvas, this.decalCanvas);

    this.running = true;
    this.gameOver = false;
    this.tickRate = 60;
    this.age = 0;
    this.fpsCounter = 0;
    this.center = { x: this.canvas.width / 2, y: this.canvas.height / 2 };

    this.resources = {
      game:    this,
      sprites: this.sprites,
      sounds:  this.sounds
    };

    this.player = new Player(this.resources, { x: this.center.x, y: this.center.y });
    this.entities = [this.player];
    this.friendlies = [this.player];
    this.enemies = [];

    this.upgradeCount = {};
    this.upgrades = new Upgrades(this);

    this.levelNumber = 0;
    this.level = null;
    this.levels = new Levels(this).levels;

    this.gold = 50;

    this.dayLength = 1440;
    this.timeOfDay = 0;
    this.dayRatio = 0;

    this.ui = new UI(this);

    // Debug variables
    if (this.debug) {
      this.lastAge = this.age;
      setInterval(this.updateDebugInfo.bind(this), 1000);
    }

    setInterval(this.step.bind(this), 1000 / this.tickRate);
    this.draw();
  },

  step: function () {
    if (this.running && !this.gameOver) {
      this.age++;

      // Do not add bullets to spatial hash. Do all checking in individual
      // bullets against enemies.
      // For performance:
      //   1. We don't want to check bullets against other bullets as they
      //      will not collide (and are usually near each other).
      //   2. Updating the spatial hash for individual objects is painful
      //      so we recreate it each frame. More expensive with many bullets.
      this.spatialHash = new SpatialHash(Math.ceil(this.canvas.width / 50));
      var i;
      for (i = 0; i < this.enemies.length; i++) {
        var enemy = this.enemies[i];
        this.spatialHash.add(enemy.x, enemy.y, enemy);
      }
      for (i = 0; i < this.friendlies.length; i++) {
        var friendly = this.friendlies[i];
        this.spatialHash.add(friendly.x, friendly.y, friendly);
      }

      for (i = 0; i < this.entities.length; i++) {
        this.entities[i].tick();
        this.entities[i].executeUpgrades();
        this.entities[i].tock();
      }

      // Culling
      this.entities = this.entities.filter(this.getMarkedForDeletion);
      this.friendlies = this.friendlies.filter(this.getMarkedForDeletion);
      this.enemies = this.enemies.filter(this.getMarkedForDeletion);

      // Time of day
      this.timeOfDay = this.age % this.dayLength;
      this.dayRatio = 1 - this.timeOfDay / this.dayLength;

      // UI
      if (this.age % 30 === 0) this.ui.tick();
      if (this.age % 120 === 0) this.ui.scaleCanvas();

      // Levels
      if (!_.isObject(this.level) || this.level.over) {
        this.levelNumber++;
        this.level = this.levels[this.levelNumber];
      } else {
        this.level.tock();
        this.level.tick();
      }
    }
  },

  // Optimisation for culling; cache function
  getMarkedForDeletion: function (ent) {
    return !ent.markedForDeletion;
  },

  draw: function () {
    if (this.running) {
      // Update scaling only once per second.
      if (++this.fpsCounter === 1) this.ui.scaleCanvas();
      this.renderer.draw();
      this.animationRequestId = requestAnimationFrame(this.draw.bind(this));
    } else {
      cancelAnimationFrame(this.animationRequestId);
    }
  },

  setBackground: function (canvasbg, documentbg) {
    $('#persistent-canvas').css('background-image', 'url(' + canvasbg + ')');
    $('body').css('background-image', 'url(' + documentbg + ')');
  },

  upgrade: function (upgradeName, args) {
    var upgrade = this.upgrades.list[upgradeName];

    if (upgrade.isConstraintsMet(this)) {
      args = args || [];
      upgrade.effect.call(this, args);

      if (!Util.isDefined(this.upgradeCount[upgrade.name])) {
        this.upgradeCount[upgrade.name] = 1;
      } else {
        this.upgradeCount[upgrade.name]++;
      }

      if (Util.isDefined(upgrade.gameUpgradeIcon)) {
        this.ui.addGameUpgradeIcon(upgrade.gameUpgradeIcon.icon, upgrade.gameUpgradeIcon.tooltip);
      }
    }
  },

  addEntity: function (entity, type) {
    this.entities.push(entity);
    type = type || 'entity';
    switch (type) {
      case 'enemy': this.enemies.push(entity); break;
      case 'friendly': this.friendlies.push(entity); break;
      default: /* noop */ break;
    }
  },

  addPowerup: function (entity) {
    entity.alignment = 'enemy';
    this.addEntity(entity, 'enemy');
  },

  spawnEnemy: function (enemy) {
    var spawn = {};
    var minDistanceAway = 300;
    var maxAttempts = 100;
    var attempts = 0;
    var margin = 400;

    do {
      spawn = {
        x: _.random(this.canvas.width + margin * 2) - margin,
        y: _.random(this.canvas.height + margin * 2) - margin
      };
    } while (
      Util.distanceBetween(spawn, this.player) < minDistanceAway &&
      attempts++ < maxAttempts);

    if (attempts < maxAttempts) {
      enemy.x = spawn.x;
      enemy.y = spawn.y;
      this.addEntity(enemy, 'enemy');
    }
  },

  addGold: function (amount) {
    this.gold += amount;
    this.ui.updateGold();
  },

  subtractGold: function (amount) {
    this.gold -= amount;
    this.ui.updateGold();
    this.audio.play('coin');
  },

  updateDebugInfo: function () {
    var reduction = this.audio.compressor.reduction;
    var reductionLevel = reduction && parseFloat(reduction) ? reduction : reduction.value;

    $('#debug').html(
      '
' + this.fpsCounter + ' FPS
' +
      '
' + (this.age - this.lastAge) + ' ticks/s
' +
      '
' + this.entities.length + ' entities
' +
      '
' + this.friendlies.length + ' friendlies
' +
      '
' + this.enemies.length + ' enemies
' +
      '
' + this.player.health + ' player health
' +
      '
' + (reductionLevel ? reductionLevel.toFixed(2) : '?') + ' compressor reduction
'
    );

    this.lastAge = this.age;
    this.fpsCounter = 0;
  }
};
<|endoftext|>


<commit_before>(function() {

    var config = {
        enabled: true,
        margin: {
            left: 10,
            right: 10,
            top: 10,
            bottom: 10
        },
        stackPosition: {
            x: 0,
            y: 0
        },
        indexAttribute: 'data-index',
        stickyClass: 'sticky',
        distroDelay: 200,
        distroSelector: null,
        duration: 300,
        easing: 'ease'
    };

    config.tile = {
        indexAttribute: config.indexAttribute,
        stickyClass: config.stickyClass,
        perspective: 10000,
        thickness: 0.0001,
        modal: {
            x: null,
            y: null,
            z: 5000
        }
    };

    var callbacks = {
        onTileInclude: function() {},
        onTileExclude: function() {},
        beforeFilter: function() {},
        afterFilter: function() {},
        beforeSort: function() {},
        afterSort: function() {}
    };

    window.linoleum = function( selector , options ) {

        var els = document.querySelectorAll( selector );

        if (els.length < 1) {
            throw 'Error: You must pass a valid selector to the linoleum constructor.';
        }

        $.extend( this , callbacks );
        this.options = $.extend( true , config , ( options || {} ));
        this.listeners = {};

        var tiles = [];

        Array.prototype.forEach.call( els , function( element , i ) {
            tiles.push( new linoleum.tile( element , this.options.tile ));
            var index = element.dataset[ this.options.indexAttribute ];
            if (typeof index === 'undefined') {
                element.setAttribute( this.options.indexAttribute , i );
            }
        }.bind( this ));

        var that = $.extend( tiles , this );

        if (!that.options.enabled) {
            that.disable();
        }
        else {
            that.enable();
        }

        that.stickyIndexes = getStickyIndexes( that );

        return that;
    };

    linoleum.prototype = {

        distribute: function( selector , options , callback ) {

            selector = selector || this.distroSelector;

            if (!this._setView( 'distribute' )) {
                return;
            }

            if (this.count( true ) < 1) {
                return;
            }

            if (!selector || selector === '') {
                throw 'Error: You must pass a valid selector to linoleum.distribute.';
            }

            this.distroSelector = selector;

            if (!document.querySelector( selector )) {
                throw 'Error: You must pass a valid selector to linoleum.distribute.';
            }

            this._startListen( 'sizer' );

            options = $.extend({
                margin: this.options.margin,
                duration: this.options.duration,
                easing: this.options.easing
            }, (options || {}));

            var grid = _distribute( this , options , function() {
                this.enable();
                callback.call( this );
            });

            this.Columns = grid.Columns;
            this.Rows = grid.Rows;
            this.sizeSizer();

            return this;
        },

        stack: function( position , options , callback ) {

            if (!this._setView( 'stack' )) {
                return;
            }

            this._stopListen( 'sizer' );

            position = $.extend( config.stackPosition , (position || {}));

            options = $.extend({
                duration: this.options.duration,
                easing: this.options.easing
            }, (options || {}));

            callback = callback || function() {};

            var t = null;

            for (var i = 0; i < this.count( true ); i++) {
                if (this[i].view !== 'home') {
                    t = i;
                    break;
                }
            }

            if (t !== null) {
                this[t].setView( 'home' , options , function() {
                    _stack( this , position , options , function() {
                        //this.sizeSizer();
                        callback.apply( this , arguments );
                    });
                }.bind( this ));
            }
            else {
                _stack( this , position , options , function() {
                    //this.sizeSizer();
                    callback.apply( this , arguments );
                });
            }

            return this;
        },

        sort: function( func ) {

            func = func || function() { return 0; };

            var that = this;

            that.beforeSort();

            var sticky = that.getSticky();
            var tiles = that.getTiles().sort( func );

            sticky.forEach(function( tile , i ) {
                var index = that.stickyIndexes[i];
                tiles.splice( index , 0 , tile );
            });

            $.extend( that , tiles );

            that.afterSort();
        },

        filter: function( exclude ) {

            exclude = exclude || [];

            var that = this;

            that.beforeFilter();

            that.forEach(function( tile ) {

                if (tile.isSticky()) {
                    return;
                }

                var i = tile.getIndex();

                if (exclude.indexOf( i ) >= 0) {
                    tile.exclude();
                    that.onTileExclude( tile );
                }
                else if (!tile.isIncluded()) {
                    tile.include();
                    that.onTileInclude( tile );
                }
            });

            that.afterFilter();
        },

        count: function( countExcluded ) {
            countExcluded = (typeof countExcluded !== 'undefined' ? countExcluded : false);
            var count = 0;
            this.forEach(function( tile ) {
                if (tile.isIncluded() || countExcluded) {
                    count++;
                }
            });
            return count;
        },

        getTiles: function( getSticky ) {
            getSticky = (typeof getSticky !== 'undefined' ? getSticky : false);
            var list = [];
            this.forEach(function( tile ) {
                if (!tile.isSticky() || getSticky) {
                    list.push( tile );
                }
            });
            return list;
        },

        getSticky: function() {
            var list = [];
            this.forEach(function( tile ) {
                if (tile.isSticky()) {
                    list.push( tile );
                }
            });
            return list;
        },

        getIncluded: function() {
            var list = [];
            this.forEach(function( tile ) {
                if (tile.isIncluded()) {
                    list.push( tile );
                }
            });
            return list;
        },

        getExcluded: function() {
            var list = [];
            this.forEach(function( tile ) {
                if (!tile.isIncluded()) {
                    list.push( tile );
                }
            });
            return list;
        },

        _setView: function ( view ) {

            if (this.view === view) {
                return true;
            }

            this._stopListen( this.view );

            if (view === 'distribute') {
                this._activate();
            }
            else {
                this._deactivate();
            }

            this._startListen( view );
            this.view = view;

            return true;
        },

        _startListen: function( type ) {

            if (this.listeners[ type ] || typeof listeners[ type ] !== 'function') {
                return;
            }

            this.listeners[ type ] = listeners[ type ].bind( this );
            startListen[ type ].call( this , this.listeners[ type ] );
        },

        _stopListen: function( type ) {

            if (!type) {
                return;
            }

            if (!this.listeners[ type ] || typeof listeners[ type ] !== 'function') {
                return;
            }

            stopListen[ type ].call( this , this.listeners[ type ] );
            delete this.listeners[ type ];
        },

        isEnabled: function() {
            return this.enabled === true;
        },

        enable: function() {

            this.forEach(function( tile ) {
                tile.enable();
            });

            this.enabled = true;
        },

        disable: function( evenActive ) {

            this.forEach(function( tile ) {
                if (!evenActive && $(tile).hasClass( 'active' )) {
                    return;
                }
                tile.disable();
            });

            this.enabled = false;
        },

        _activate: function() {
            $(this).css( 'pointer-events' , '' );
        },

        _deactivate: function() {
            $(this).css( 'pointer-events' , 'none' );
        },

        sizeSizer: function( options ) {

            if (typeof this.Rows === 'undefined') {
                return;
            }

            options = $.extend({
                margin: this.options.margin
            } , ( options || {} ));

            var parent = document.querySelector( this.distroSelector );
            var totalY = getTotalY( this , this.Rows , options );

            $(parent).children( '.sizer' ).css( 'height' , totalY + 'px' );
        },

        destroy: function() {
            this._stopListen( this.view );
            this._stopListen( 'sizer' );
        }
    };

    function getStickyIndexes( instance ) {
        var sticky = [];
        instance.forEach(function( tile ) {
            if (tile.isSticky()) {
                sticky.push( tile.getIndex() );
            }
        });
        return sticky;
    }

    function _stack( instance , translate , options , callback ) {

        var xformTile = $.extend({
            type: 'transform',
            translate: translate,
        }, options );

        var xformInner = $.extend({
            type: 'transform',
            rotate: {x: 1, a: 80}
        }, options );

        var completed = 0;

        function position( tile , resolve ) {
            resolve = resolve || function() {};
            $(tile).hx( xformTile );
            $(tile).find( '.inner' )
            .hx( xformInner )
            .done( resolve );
        }

        function exec() {

            var targetSet = instance.getIncluded();
            var promiseSet = [];

            targetSet.forEach(function( tile ) {
                promiseSet.push(
                    new Promise(function( resolve ) {
                        position( tile , resolve );
                    })
                );
            });

            Promise.all( promiseSet ).then( callback.bind( instance ));
        }

        exec();
    }

    function _distribute( instance , options , callback ) {

        callback = callback || function() {};
        var parent = document.querySelector( instance.distroSelector );
        var containerDims = parent.getBoundingClientRect();
        var Columns = 0;
        var Rows = 0;
        var completed = 0;

        function position( tile , row , col , resolve ) {

            resolve = resolve || function() {};

            var ox = getCenterOffsetX( instance , tile , Columns , options );

            var t = {
                x: (col * tile.dims.width) + (options.margin.left * (col + 1)) + (options.margin.right * (col + 1)) + ox,
                y: (row * tile.dims.height) + (options.margin.bottom * row) + (options.margin.top * (row + 1))
            };

            tile.setHome( t );

            $(tile).hx({
                type: 'transform',
                translate: t,
                easing: options.easing,
                duration: options.duration
            });

            $(tile).find( '.inner' ).hx({
                type: 'transform',
                rotate: null,
                duration: options.duration,
                easing: options.easing
            })
            .done( resolve );
        }

        function exec() {

            var totalX = getTotalX( instance , options );
            Columns = getCols( instance , totalX , containerDims );
            Rows = getRows( instance , Columns );

            var i = 0;
            var targetSet = instance.getIncluded();
            var promiseSet = [];

            for (var row = 0; row < Rows; row++) {
                for (var col = 0; col < Columns; col++) {

                    if (i >= instance.count()) {
                        continue;
                    }

                    promiseSet.push(
                        new Promise(function( resolve ) {
                            position( targetSet[i] , row , col , resolve );
                        })
                    );

                    i++;
                }
            }

            Promise.all( promiseSet ).then( callback.bind( instance ));
        }

        exec();

        return {
            Columns: Columns,
            Rows: Rows
        };
    }

    function getCenterOffsetX( instance , tile , cols , options ) {
        var parent = document.querySelector( instance.distroSelector );
        var parentDims = parent.getBoundingClientRect();
        var marginX = options.margin.left + options.margin.right;
        return (parentDims.width - (tile.dims.width * cols) - (marginX * (cols + 1))) / 2;
    }

    function getTotalX( instance , options ) {
        var marginX = options.margin.left + options.margin.right;
        return (instance[0].dims.width * instance.count()) + (marginX * (instance.count() + 1));
    }

    function getTotalY( instance , rows , options ) {
        var marginY = options.margin.top + options.margin.bottom;
        return (instance[0].dims.height * rows) + (marginY * (rows + 1));
    }

    function getInstanceX( instance , totalX ) {
        return totalX / instance.count();
    }

    function getInstanceY( rows , totalY ) {
        return totalY / rows;
    }

    function getRows( instance , cols ) {
        return Math.ceil( instance.count() / cols );
    }

    function getCols( instance , totalX , containerDims ) {

        var instX = getInstanceX( instance , totalX );
        var cols = 0;

        while ((cols * instX) < containerDims.width) {
            cols++;
        }

        if ((cols * instX) > containerDims.width) {
            cols -= 1;
        }

        return cols;
    }

    var listeners = {

        distribute: function( e ) {

            var parent = document.querySelector( this.distroSelector );
            var dims = parent.getBoundingClientRect();

            var totalX = getTotalX( this , this.options );
            var cols = getCols( this , totalX , dims );

            if (this.Columns === cols) {
                var opt = $.extend( {} , this.options , {
                    duration: 0,
                    fallback: false
                });
                _distribute( this , opt );
                return;
            }

            var optionSet = null;

            var handle = function() {
                var grid = _distribute( this , optionSet );
                this.Columns = grid.Columns;
                this.Rows = grid.Rows;
                this.sizeSizer();
            }.bind( this );

            if (this.options.distroDelay) {

                optionSet = this.options;
                var timeout = setTimeout( handle , this.options.distroDelay );

                $(window).on( 'resize orientationchange' , function timer() {
                    $(window).off( 'resize orientationchange' , timer );
                    clearTimeout( timeout );
                });
            }
            else {

                optionSet = {
                    duration: 0,
                    fallback: false,
                    margin: this.options.margin
                };

                $(window).on( 'resize orientationchange' , handle );
            }
        },

        sizer: function( e ) {

            var parent = document.querySelector( this.distroSelector );
            var dims = parent.getBoundingClientRect();
            var top = parseInt(getComputedStyle( parent ).top , 10 );

            function size( h ) {
                h = ((typeof h !== 'undefined' && typeof h !== 'object') ? h : ($(window).height() - dims.top - $(window).scrollTop()));
                $(parent).children( '.sizer' ).css( 'min-height' , h + 'px' );
            }

            size();
        }
    };

    var startListen = {

        distribute: function( listener ) {
            $(window).on( 'resize orientationchange' , listener );
        },

        sizer: function( listener ) {
            $(window).on( 'resize orientationchange' , listener );
            listener();
        }
    };

    var stopListen = {

        distribute: function( listener ) {
            $(window).off( 'resize orientationchange' , listener );
        },

        sizer: function( listener ) {
            $(window).off( 'resize orientationchange' , listener );
        }
    };

}());

<commit_msg>making setMinHeight optional<commit_after>(function() {

    var config = {
        enabled: true,
        margin: {
            left: 10,
            right: 10,
            top: 10,
            bottom: 10
        },
        stackPosition: {
            x: 0,
            y: 0
        },
        indexAttribute: 'data-index',
        stickyClass: 'sticky',
        distroDelay: 200,
        distroSelector: null,
        duration: 300,
        setMinHeight: false,
        easing: 'ease'
    };

    config.tile = {
        indexAttribute: config.indexAttribute,
        stickyClass: config.stickyClass,
        perspective: 10000,
        thickness: 0.0001,
        modal: {
            x: null,
            y: null,
            z: 5000
        }
    };

    var callbacks = {
        onTileInclude: function() {},
        onTileExclude: function() {},
        beforeFilter: function() {},
        afterFilter: function() {},
        beforeSort: function() {},
        afterSort: function() {}
    };

    window.linoleum = function( selector , options ) {

        var els = document.querySelectorAll( selector );

        if (els.length < 1) {
            throw 'Error: You must pass a valid selector to the linoleum constructor.';
        }

        $.extend( this , callbacks );
        this.options = $.extend( true , config , ( options || {} ));
        this.listeners = {};

        var tiles = [];

        Array.prototype.forEach.call( els , function( element , i ) {
            tiles.push( new linoleum.tile( element , this.options.tile ));
            var index = element.dataset[ this.options.indexAttribute ];
            if (typeof index === 'undefined') {
                element.setAttribute( this.options.indexAttribute , i );
            }
        }.bind( this ));

        var that = $.extend( tiles , this );

        if (!that.options.enabled) {
            that.disable();
        }
        else {
            that.enable();
        }

        that.stickyIndexes = getStickyIndexes( that );

        return that;
    };

    linoleum.prototype = {

        distribute: function( selector , options , callback ) {

            selector = selector || this.distroSelector;

            if (!this._setView( 'distribute' )) {
                return;
            }

            if (this.count( true ) < 1) {
                return;
            }

            if (!selector || selector === '') {
                throw 'Error: You must pass a valid selector to linoleum.distribute.';
            }

            this.distroSelector = selector;

            if (!document.querySelector( selector )) {
                throw 'Error: You must pass a valid selector to linoleum.distribute.';
            }

            this._startListen( 'sizer' );

            options = $.extend({
                margin: this.options.margin,
                duration: this.options.duration,
                easing: this.options.easing
            }, (options || {}));

            var grid = _distribute( this , options , function() {
                this.enable();
                callback.call( this );
            });

            this.Columns = grid.Columns;
            this.Rows = grid.Rows;
            this.sizeSizer();

            return this;
        },

        stack: function( position , options , callback ) {

            if (!this._setView( 'stack' )) {
                return;
            }

            this._stopListen( 'sizer' );

            position = $.extend( config.stackPosition , (position || {}));

            options = $.extend({
                duration: this.options.duration,
                easing: this.options.easing
            }, (options || {}));

            callback = callback || function() {};

            var t = null;

            for (var i = 0; i < this.count( true ); i++) {
                if (this[i].view !== 'home') {
                    t = i;
                    break;
                }
            }

            if (t !== null) {
                this[t].setView( 'home' , options , function() {
                    _stack( this , position , options , function() {
                        //this.sizeSizer();
                        callback.apply( this , arguments );
                    });
                }.bind( this ));
            }
            else {
                _stack( this , position , options , function() {
                    //this.sizeSizer();
                    callback.apply( this , arguments );
                });
            }

            return this;
        },

        sort: function( func ) {

            func = func || function() { return 0; };

            var that = this;

            that.beforeSort();

            var sticky = that.getSticky();
            var tiles = that.getTiles().sort( func );

            sticky.forEach(function( tile , i ) {
                var index = that.stickyIndexes[i];
                tiles.splice( index , 0 , tile );
            });

            $.extend( that , tiles );

            that.afterSort();
        },

        filter: function( exclude ) {

            exclude = exclude || [];

            var that = this;

            that.beforeFilter();

            that.forEach(function( tile ) {

                if (tile.isSticky()) {
                    return;
                }

                var i = tile.getIndex();

                if (exclude.indexOf( i ) >= 0) {
                    tile.exclude();
                    that.onTileExclude( tile );
                }
                else if (!tile.isIncluded()) {
                    tile.include();
                    that.onTileInclude( tile );
                }
            });

            that.afterFilter();
        },

        count: function( countExcluded ) {
            countExcluded = (typeof countExcluded !== 'undefined' ? countExcluded : false);
            var count = 0;
            this.forEach(function( tile ) {
                if (tile.isIncluded() || countExcluded) {
                    count++;
                }
            });
            return count;
        },

        getTiles: function( getSticky ) {
            getSticky = (typeof getSticky !== 'undefined' ? getSticky : false);
            var list = [];
            this.forEach(function( tile ) {
                if (!tile.isSticky() || getSticky) {
                    list.push( tile );
                }
            });
            return list;
        },

        getSticky: function() {
            var list = [];
            this.forEach(function( tile ) {
                if (tile.isSticky()) {
                    list.push( tile );
                }
            });
            return list;
        },

        getIncluded: function() {
            var list = [];
            this.forEach(function( tile ) {
                if (tile.isIncluded()) {
                    list.push( tile );
                }
            });
            return list;
        },

        getExcluded: function() {
            var list = [];
            this.forEach(function( tile ) {
                if (!tile.isIncluded()) {
                    list.push( tile );
                }
            });
            return list;
        },

        _setView: function ( view ) {

            if (this.view === view) {
                return true;
            }

            this._stopListen( this.view );

            if (view === 'distribute') {
                this._activate();
            }
            else {
                this._deactivate();
            }

            this._startListen( view );
            this.view = view;

            return true;
        },

        _startListen: function( type ) {

            if (this.listeners[ type ] || typeof listeners[ type ] !== 'function') {
                return;
            }

            this.listeners[ type ] = listeners[ type ].bind( this );
            startListen[ type ].call( this , this.listeners[ type ] );
        },

        _stopListen: function( type ) {

            if (!type) {
                return;
            }

            if (!this.listeners[ type ] || typeof listeners[ type ] !== 'function') {
                return;
            }

            stopListen[ type ].call( this , this.listeners[ type ] );
            delete this.listeners[ type ];
        },

        isEnabled: function() {
            return this.enabled === true;
        },

        enable: function() {

            this.forEach(function( tile ) {
                tile.enable();
            });

            this.enabled = true;
        },

        disable: function( evenActive ) {

            this.forEach(function( tile ) {
                if (!evenActive && $(tile).hasClass( 'active' )) {
                    return;
                }
                tile.disable();
            });

            this.enabled = false;
        },

        _activate: function() {
            $(this).css( 'pointer-events' , '' );
        },

        _deactivate: function() {
            $(this).css( 'pointer-events' , 'none' );
        },

        sizeSizer: function( options ) {

            if (typeof this.Rows === 'undefined') {
                return;
            }

            options = $.extend({
                margin: this.options.margin
            } , ( options || {} ));

            var parent = document.querySelector( this.distroSelector );
            var totalY = getTotalY( this , this.Rows , options );

            $(parent).children( '.sizer' ).css( 'height' , totalY + 'px' );
        },

        destroy: function() {
            this._stopListen( this.view );
            this._stopListen( 'sizer' );
        }
    };

    function getStickyIndexes( instance ) {
        var sticky = [];
        instance.forEach(function( tile ) {
            if (tile.isSticky()) {
                sticky.push( tile.getIndex() );
            }
        });
        return sticky;
    }

    function _stack( instance , translate , options , callback ) {

        var xformTile = $.extend({
            type: 'transform',
            translate: translate,
        }, options );

        var xformInner = $.extend({
            type: 'transform',
            rotate: {x: 1, a: 80}
        }, options );

        var completed = 0;

        function position( tile , resolve ) {
            resolve = resolve || function() {};
            $(tile).hx( xformTile );
            $(tile).find( '.inner' )
            .hx( xformInner )
            .done( resolve );
        }

        function exec() {

            var targetSet = instance.getIncluded();
            var promiseSet = [];

            targetSet.forEach(function( tile ) {
                promiseSet.push(
                    new Promise(function( resolve ) {
                        position( tile , resolve );
                    })
                );
            });

            Promise.all( promiseSet ).then( callback.bind( instance ));
        }

        exec();
    }

    function _distribute( instance , options , callback ) {

        callback = callback || function() {};
        var parent = document.querySelector( instance.distroSelector );
        var containerDims = parent.getBoundingClientRect();
        var Columns = 0;
        var Rows = 0;
        var completed = 0;

        function position( tile , row , col , resolve ) {

            resolve = resolve || function() {};

            var ox = getCenterOffsetX( instance , tile , Columns , options );

            var t = {
                x: (col * tile.dims.width) + (options.margin.left * (col + 1)) + (options.margin.right * (col + 1)) + ox,
                y: (row * tile.dims.height) + (options.margin.bottom * row) + (options.margin.top * (row + 1))
            };

            tile.setHome( t );

            $(tile).hx({
                type: 'transform',
                translate: t,
                easing: options.easing,
                duration: options.duration
            });

            $(tile).find( '.inner' ).hx({
                type: 'transform',
                rotate: null,
                duration: options.duration,
                easing: options.easing
            })
            .done( resolve );
        }

        function exec() {

            var totalX = getTotalX( instance , options );
            Columns = getCols( instance , totalX , containerDims );
            Rows = getRows( instance , Columns );

            var i = 0;
            var targetSet = instance.getIncluded();
            var promiseSet = [];

            for (var row = 0; row < Rows; row++) {
                for (var col = 0; col < Columns; col++) {

                    if (i >= instance.count()) {
                        continue;
                    }

                    promiseSet.push(
                        new Promise(function( resolve ) {
                            position( targetSet[i] , row , col , resolve );
                        })
                    );

                    i++;
                }
            }

            Promise.all( promiseSet ).then( callback.bind( instance ));
        }

        exec();

        return {
            Columns: Columns,
            Rows: Rows
        };
    }

    function getCenterOffsetX( instance , tile , cols , options ) {
        var parent = document.querySelector( instance.distroSelector );
        var parentDims = parent.getBoundingClientRect();
        var marginX = options.margin.left + options.margin.right;
        return (parentDims.width - (tile.dims.width * cols) - (marginX * (cols + 1))) / 2;
    }

    function getTotalX( instance , options ) {
        var marginX = options.margin.left + options.margin.right;
        return (instance[0].dims.width * instance.count()) + (marginX * (instance.count() + 1));
    }

    function getTotalY( instance , rows , options ) {
        var marginY = options.margin.top + options.margin.bottom;
        return (instance[0].dims.height * rows) + (marginY * (rows + 1));
    }

    function getInstanceX( instance , totalX ) {
        return totalX / instance.count();
    }

    function getInstanceY( rows , totalY ) {
        return totalY / rows;
    }

    function getRows( instance , cols ) {
        return Math.ceil( instance.count() / cols );
    }

    function getCols( instance , totalX , containerDims ) {

        var instX = getInstanceX( instance , totalX );
        var cols = 0;

        while ((cols * instX) < containerDims.width) {
            cols++;
        }

        if ((cols * instX) > containerDims.width) {
            cols -= 1;
        }

        return cols;
    }

    var listeners = {

        distribute: function( e ) {

            var parent = document.querySelector( this.distroSelector );
            var dims = parent.getBoundingClientRect();

            var totalX = getTotalX( this , this.options );
            var cols = getCols( this , totalX , dims );

            if (this.Columns === cols) {
                var opt = $.extend( {} , this.options , {
                    duration: 0,
                    fallback: false
                });
                _distribute( this , opt );
                return;
            }

            var optionSet = null;

            var handle = function() {
                var grid = _distribute( this , optionSet );
                this.Columns = grid.Columns;
                this.Rows = grid.Rows;
                this.sizeSizer();
            }.bind( this );

            if (this.options.distroDelay) {

                optionSet = this.options;
                var timeout = setTimeout( handle , this.options.distroDelay );

                $(window).on( 'resize orientationchange' , function timer() {
                    $(window).off( 'resize orientationchange' , timer );
                    clearTimeout( timeout );
                });
            }
            else {

                optionSet = {
                    duration: 0,
                    fallback: false,
                    margin: this.options.margin
                };

                $(window).on( 'resize orientationchange' , handle );
            }
        },

        sizer: function( e ) {

            var parent = document.querySelector( this.distroSelector );
            var dims = parent.getBoundingClientRect();
            var top = parseInt(getComputedStyle( parent ).top , 10 );

            function size( h ) {
                h = ((typeof h !== 'undefined' && typeof h !== 'object') ? h : ($(window).height() - dims.top - $(window).scrollTop()));
                $(parent).children( '.sizer' ).css( 'min-height' , h + 'px' );
            }

            if (this.options.setMinHeight) {
                size();
            }
        }
    };

    var startListen = {

        distribute: function( listener ) {
            $(window).on( 'resize orientationchange' , listener );
        },

        sizer: function( listener ) {
            $(window).on( 'resize orientationchange' , listener );
            listener();
        }
    };

    var stopListen = {

        distribute: function( listener ) {
            $(window).off( 'resize orientationchange' , listener );
        },

        sizer: function( listener ) {
            $(window).off( 'resize orientationchange' , listener );
        }
    };

}());

<|endoftext|>


<commit_before>var map;
var infowindow;
var latitude;
var longitude;
var myLatLng;

console.log("hello");
getLocation();
window.setTimeout(initialize, 3000);

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setLatLong);
    } else {
        window.alert("Geolocation is not supported by this browser.");
    }
}

function setLatLong(position) {
  latitude = position.coords.latitude;
  longitude = position.coords.longitude;
  myLatLng = new google.maps.LatLng(latitude, longitude);
  // var myLocation = new google.maps.Marker({
  //   position: myLatLng,
  //   map: map,
  // });
}

function initialize() {
  // var centerMap = new google.maps.LatLng(lat, longit);
  // myLatLng = new google.maps.LatLng(37.784586999999995, -122.397551);

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: myLatLng,
    zoom: 12
  });

  var request = {
    location: myLatLng,
    radius: 8000,
    types: ['bar'],
    open_now: 'true',
  };
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var image = './imgs/beer_icon.png';
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    icon: image
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name + ", " + place.rating + " stars");
    infowindow.open(map, this);
  });
}

<commit_msg>Update location.js<commit_after>var map;
var infowindow;
var latitude;
var longitude;
var myLatLng;

console.log("hello");
getLocation();
window.setTimeout(initialize, 3000);

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setLatLong);
    } else {
        window.alert("Geolocation is not supported by this browser.");
    }
}

function setLatLong(position) {
  latitude = position.coords.latitude;
  longitude = position.coords.longitude;
  myLatLng = new google.maps.LatLng(latitude, longitude);
   var myLocation = new google.maps.Marker({
     position: myLatLng,
     map: map,
   });
}

function initialize() {
  // var centerMap = new google.maps.LatLng(lat, longit);
  // myLatLng = new google.maps.LatLng(37.784586999999995, -122.397551);

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: myLatLng,
    zoom: 12
  });

  var request = {
    location: myLatLng,
    radius: 8000,
    types: ['bar'],
    open_now: 'true',
  };
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var image = './imgs/beer_icon.png';
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    icon: image
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name + ", " + place.rating + " stars");
    infowindow.open(map, this);
  });
}

<|endoftext|>