From 7203ec18bf3d8af2e60ef501430842f400eff34a Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Wed, 7 Nov 2012 11:10:15 +0600 Subject: [PATCH 01/11] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20submodule=20=D0=A1=D0=BA=D0=BE=D0=BF=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BB=20=D0=BF=D1=80=D0=B5=D0=B4=D1=8A=D0=B8?= =?UTF-8?q?=D0=B4=D1=83=D1=89=D0=B8=D0=B9=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=20=D0=9F=D0=BE=D1=87=D1=82=D0=B8=20=D1=81=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D1=81=D1=82=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitmodules | 3 + Task/Scripts/BaseEvent.js | 122 ++++++++++++ Task/Scripts/Collection.js | 50 +++++ Task/Scripts/Event.js | 89 +++++++++ Task/Scripts/Model.js | 39 ++++ Task/Scripts/test/BaseEventTest.html | 18 ++ Task/Scripts/test/BaseEventTest.js | 259 ++++++++++++++++++++++++++ Task/Scripts/test/CollectionTest.html | 15 ++ Task/Scripts/test/CollectionTest.js | 76 ++++++++ Task/Scripts/test/EventTest.html | 16 ++ Task/Scripts/test/EventTest.js | 127 +++++++++++++ Task/Scripts/test/ModelTest.html | 15 ++ Task/Scripts/test/ModelTest.js | 43 +++++ Task/index.html | 49 +++++ Task/style.css | 19 ++ 15 files changed, 940 insertions(+) create mode 100644 .gitmodules create mode 100644 Task/Scripts/BaseEvent.js create mode 100644 Task/Scripts/Collection.js create mode 100644 Task/Scripts/Event.js create mode 100644 Task/Scripts/Model.js create mode 100644 Task/Scripts/test/BaseEventTest.html create mode 100644 Task/Scripts/test/BaseEventTest.js create mode 100644 Task/Scripts/test/CollectionTest.html create mode 100644 Task/Scripts/test/CollectionTest.js create mode 100644 Task/Scripts/test/EventTest.html create mode 100644 Task/Scripts/test/EventTest.js create mode 100644 Task/Scripts/test/ModelTest.html create mode 100644 Task/Scripts/test/ModelTest.js create mode 100644 Task/index.html create mode 100644 Task/style.css diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..7715e64 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "qunit"] + path = qunit + url = git://github.com/jquery/qunit.git diff --git a/Task/Scripts/BaseEvent.js b/Task/Scripts/BaseEvent.js new file mode 100644 index 0000000..b5eed43 --- /dev/null +++ b/Task/Scripts/BaseEvent.js @@ -0,0 +1,122 @@ +/*global Collection: true*/ + +/** + * Shell for "sql" operations with Array Events. + * @prototype {Collection} + * @constructor + * @method {pastEventBase} - Создает BaseEvent с пропущенными событиями + * @method {pastEventBase} - Создает BaseEvent с грядущими событиями + * @method {nowEventBase} - Создает BaseEvent с текущими событиями + * @method {withFriend} - Создает BaseEvent с событиями, в которых принимал участие определенный человек + * @method {getEventAfterDay} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через день + * @method {getEventAfterWeek} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через неделю + * @method {getEventAfterMonth} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через месяц + * @method {getEventFromPeriod} - Создает BaseEvent с событиями, которые лежат между двумы датами [fromDate, toDate] + * @method {getEventAfterMonth} - Создает BaseEvent с теми же событиями, но отсортированными по убыванию звезд + * @method {getEventAfterMonth} - Создает BaseEvent с теми же событиями, но отсортироваными по возрастанию даты + * @example - Смотри файл с тестами... + */ +function BaseEvent(events) { + "use strict"; + Collection.call(this, events); + this.events = events; +} +BaseEvent.prototype = Object.create(Collection.prototype, { + constructor: { + value: BaseEvent, + enumerable: false, + writable: true, + configurable: true + } +}); +//пропущенные, текущие, будущие события +BaseEvent.prototype.pastEventBase = function () { + "use strict"; + var currentDate = new Date(); + return this.filter(function (event) { + return event.end.getTime() < currentDate.getTime(); + }); +}; +BaseEvent.prototype.nextEventBase = function () { + "use strict"; + var currentDate = new Date(); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); +}; +BaseEvent.prototype.nowEventBase = function () { + "use strict"; + var currentDate = new Date(); + return this.filter(function (event) { + return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime()); + }); +}; +//событие с участием друга (Друг отношение рефлексивное ^^) +BaseEvent.prototype.withFriend = function (myFriend) { + "use strict"; + return this.filter(function (event) { + return event.parties.some(function (party) { + return party.name === myFriend.name; + }); + }); +}; +// События через период времени день, неделя, месяц +BaseEvent.prototype.getEventAfterWeek = function () { + "use strict"; + var currentDate = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); +}; +BaseEvent.prototype.getEventAfterDay = function () { + "use strict"; + var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); +}; +BaseEvent.prototype.getEventAfterMonth = function () { + "use strict"; + var currentDate = new Date(); + if (currentDate.getMonth() === 11) { + currentDate = new Date(currentDate.getFullYear() + 1, 0, currentDate.getDay()); + } else { + currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDay()); + } + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); +}; +// События за период +BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) { + "use strict"; + return this.filter(function (event) { + return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime()); + }); +}; +BaseEvent.prototype.sortByStars = function (ascending) { + "use strict"; + var comparer = function compare(a, b) { + if (a.stars > b.stars) { + return -1; + } + if (a.stars < b.stars) { + return 1; + } + return 0; + }; + return this.sortBy(comparer, ascending); +}; +BaseEvent.prototype.sortByDate = function (ascending) { + "use strict"; + var comparer = function compare(a, b) { + if (a.start.getTime() < b.start.getTime()) { + return -1; + } + if (a.start.getTime() > b.start.getTime()) { + return 1; + } + return 0; + }; + return this.sortBy(comparer, ascending); +}; \ No newline at end of file diff --git a/Task/Scripts/Collection.js b/Task/Scripts/Collection.js new file mode 100644 index 0000000..40ee9dd --- /dev/null +++ b/Task/Scripts/Collection.js @@ -0,0 +1,50 @@ +/*global Collection: true*/ + +/** + * Creates an instance of Event. + * + * @param {data} - start elements of collection + * @field {items} - elements of collection + * @method {add} - add element in current collection and return it + * @method {filter} - filter elements of current collection and return it + * @method {sortBy} - sort elements of current collection and return it + */ +Collection = function (otherItems) { + "use strict"; + var item; + this.items = []; + for (item in otherItems) { + if (otherItems.hasOwnProperty(item)) { + this.items.push(otherItems[item]); + } + } +}; +Collection.prototype.add = function (obj) { + "use strict"; + var newEvents = this.items.concat([obj]); + return new Collection(newEvents); +}; +Collection.prototype.filter = function (selector) { + "use strict"; + var newItems = this.items.filter(selector); + return new Collection(newItems); +}; +Collection.prototype.sortBy = function (comparator, isInvert) { + "use strict"; + var newItems = [].concat(this.items); + if (newItems.length === 0) { + return []; + } + if (comparator) { + if (isInvert) { + newItems.sort(function (a, b) { + return -1 * comparator(a, b); + }); + } else { + newItems.sort(comparator); + } + } else { + newItems.sort(); + } + return new Collection(newItems); +}; \ No newline at end of file diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js new file mode 100644 index 0000000..fea46bd --- /dev/null +++ b/Task/Scripts/Event.js @@ -0,0 +1,89 @@ +/*global Model: true*/ +/** + * Creates an instance of Event. + * + * @prototype {Model} + * @param {data} - is start event + * @field {start} - is start event + * @field {end} - is end event + * @field {id} - is id + * @field {location} - location - is gps and name of event's place + * @field {participants} - participants - array of participants + * @field {stars} - is assess the importance of the event + * @field {cost} - is price for entry + * @method {setLocation} - is setter for location's field + * @method {leaveMark} - is setter for stars's field (0,1,2,3,4,5 - validate value) + */ +function Event(data) { + "use strict"; + this.id = Math.random(); + this.location = { + "gps": {x: 0, y: 0}, + "nameLocation": "Earth" + }; + this.stars = 0; + this.cost = 0; + this.parties = []; + Model.call(this, data); + this.validate(this); + this.setLocation(this.location); + this.leaveMark(this.stars); +} +Event.prototype = Object.create(Model.prototype, { + constructor: { + value: Event, + enumerable: false, + writable: true, + configurable: true + } +}); +Event.prototype.dateValidator = function (date) { + "use strict"; + if (Object.prototype.toString.call(date) === "[object Date]") { + if (!isNaN(date.getTime())) { + return true; + } + } + return false; +}; +Event.prototype.setLocation = function (gps, name) { + "use strict"; + if (typeof gps !== "undefined" && typeof gps.x !== "undefined" && typeof gps.y !== "undefined" && typeof name === "string") { + this.location.gps = gps; + this.location.nameLocation = name; + } else { + this.location = { + "gps" : {"x" : 0, "y" : 0}, + "nameLocation" : "Earth" + }; + } +}; +Event.prototype.leaveMark = function (stars) { + "use strict"; + if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) { + stars = 0; + } + if (stars > 5) { + stars = 5; + } + stars = (stars - (stars % 1)); //обрезаем дробную часть + this.stars = stars; +}; +Event.prototype.validate = function (event) { + "use strict"; + if (event.cost < 0) { + throw new Error("Цена за вход не может быть отрицательной"); + } + if (!Array.isArray(event.parties)) { + throw new Error("Участники - это массив"); + } + if (event.parties.some(function (party) { + return !party.name; + }) + ) { + throw new Error("У одного из участников нет поля <ИМЯ>"); + } + if (event.end < event.start) { + throw new Error("Даты начала и конца перепутаны"); + } +}; \ No newline at end of file diff --git a/Task/Scripts/Model.js b/Task/Scripts/Model.js new file mode 100644 index 0000000..572c751 --- /dev/null +++ b/Task/Scripts/Model.js @@ -0,0 +1,39 @@ + +/** + * Abstract class for Event + * + * @param {data} - start elements of collection + * @field {items} - elements of collection + * @method {get} - get value of field + * @method {set} - set attributes + * @method {validate} - validate + */ +var Model = function (data) { + "use strict"; + var nameField; + for (nameField in data) { + this[nameField] = data[nameField]; + } +}; +Model.prototype.set = function (attributes) { + "use strict"; + var nameAttr; + for (nameAttr in attributes) { + if (attributes.hasOwnProperty(nameAttr)) { + if (typeof this[nameAttr] !== "undefined") { + this[nameAttr] = attributes[nameAttr]; + } + } + } +}; +Model.prototype.get = function (attribute) { + "use strict"; + if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") { + return; //return undefined; + } + return this[attribute]; +}; +Model.prototype.validate = function () { + "use strict"; + throw new Error('this is Abstract method'); +}; \ No newline at end of file diff --git a/Task/Scripts/test/BaseEventTest.html b/Task/Scripts/test/BaseEventTest.html new file mode 100644 index 0000000..e4de052 --- /dev/null +++ b/Task/Scripts/test/BaseEventTest.html @@ -0,0 +1,18 @@ + + + + + + + + + + + + +

QUnit test env

+

+

+
    + + \ No newline at end of file diff --git a/Task/Scripts/test/BaseEventTest.js b/Task/Scripts/test/BaseEventTest.js new file mode 100644 index 0000000..8554015 --- /dev/null +++ b/Task/Scripts/test/BaseEventTest.js @@ -0,0 +1,259 @@ +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global initTestBase: true*/ +/*global Event: true*/ +module("test simple SQL"); +test('pastEventBase()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, pastEventbase; + Date = function () { + return new RealDate("September 13, 2012 12:00:00"); + }; + pastEventbase = testBase.pastEventBase(); + equal(pastEventbase.items.length, 2); + ok(pastEventbase.items.some(function (event) { + return event.id === 15; + })); + ok(pastEventbase.items.some(function (event) { + return event.id === 17; + })); + Date = RealDate; +}); +test('nextEventBase()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, nextEventBase; + Date = function () { + return new RealDate("November 1, 2012 12:00:00"); + }; + nextEventBase = testBase.nextEventBase(); + equal(nextEventBase.items.length, 2); + ok(nextEventBase.items.some(function (event) { + return event.id === 19; + })); + ok(nextEventBase.items.some(function (event) { + return event.id === 20; + })); + Date = RealDate; +}); +test('nowEventBase()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, nowEventbase; + Date = function () { + return new RealDate("September 13, 2012 12:00:00"); + }; + nowEventbase = testBase.nowEventBase(); + equal(nowEventbase.items.length, 1); + ok(nowEventbase.items.some(function (event) { + return event.id === 16; + })); + Date = RealDate; +}); +test('withFriend("Alexander.Mangin")', function () { + "use strict"; + var testBase = initTestBase(), eventWithFriendBase = testBase.withFriend({name: "Alexander.Mangin"}); + equal(eventWithFriendBase.items.length, 1); + ok(eventWithFriendBase.items.some(function (event) { + return event.id === 16; + })); +}); +test('getEventAfterMonth()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, eventAfterMonthbase; + Date = function (param1, param2, param3) { + if (param1 && param2 && param3) { + return new RealDate(param1, param2, param3); + } + return new RealDate("October 1, 2012 12:00:00"); + }; + eventAfterMonthbase = testBase.getEventAfterMonth(); + equal(eventAfterMonthbase.items.length, 2); + ok(eventAfterMonthbase.items.some(function (event) { + return event.id === 19; + })); + ok(eventAfterMonthbase.items.some(function (event) { + return event.id === 20; + })); + Date = RealDate; +}); +test('getEventAfterDay()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, eventAfterDaybase; + Date = function (param1, param2, param3) { + if (param1 && param2 && param3) { + return new RealDate(param1, param2, param3); + } + return new RealDate("November 1, 2012 12:00:00"); + }; + eventAfterDaybase = testBase.getEventAfterDay(); + equal(eventAfterDaybase.items.length, 2); + ok(eventAfterDaybase.items.some(function (event) { + return event.id === 19; + })); + ok(eventAfterDaybase.items.some(function (event) { + return event.id === 20; + })); + Date = RealDate; +}); +test('getEventAfterWeek()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, eventAfterWeekbase; + Date = function (param1) { + if (param1) { + return new RealDate(param1); + } + return new RealDate("October 28, 2012 12:00:00"); + }; + eventAfterWeekbase = testBase.getEventAfterWeek(); + equal(eventAfterWeekbase.items.length, 1); + ok(eventAfterWeekbase.items.some(function (event) { + return event.id === 19; + })); + Date = RealDate; +}); +test('getEventFromPeriod(from,to)', function () { + "use strict"; + var testBase = initTestBase(), result; + result = testBase.getEventFromPeriod(new Date("September 12 2012 00:00:00"), new Date("September 14 2012 00:00:00")); + equal(result.items.length, 1); + ok(result.items.some(function (event) { + return event.id === 16; + })); +}); +test('sortByStar()', function () { + "use strict"; + var testBase = initTestBase(), sortByStarsEventbase = testBase.sortByStars(); + equal(testBase.items.length, sortByStarsEventbase.items.length); + ok(sortByStarsEventbase.items[0].stars === 5); + ok(sortByStarsEventbase.items[1].stars === 5); +}); +test('sortByDate()', function () { + "use strict"; + var testBase = initTestBase(), sortByDateEventbase = testBase.sortByDate(); + equal(testBase.items.length, sortByDateEventbase.items.length); + ok(sortByDateEventbase.items[0].id === 15); + ok(sortByDateEventbase.items[1].id === 17); +}); +function initTestBase() { + "use strict"; + var bestOfSweetsDateStart = new Date("October 10, 2012 00:00:00"), + bestOfSweetsDateFinish = new Date("October 14, 2012 23:59:59"), + bestOfSweets = new Event({"start": bestOfSweetsDateStart, "end": bestOfSweetsDateFinish, "name": "BestOfSweets", "id": 1}), + сirioDeNazareDateStart = new Date("October 8, 2012 00:00:00"), + сirioDeNazareDateFinish = new Date("October 15, 2012 23:59:59"), + сirioDeNazare = new Event({"start": сirioDeNazareDateStart, "end": сirioDeNazareDateFinish, "name": "Cirio De Nazare", "id": 2}), + vinesDayDateStart = new Date("October 4, 2012 00:00:00"), + vinesDayDateFinish = new Date("October 6, 2012 23:59:59"), + vinesDay = new Event({"start": vinesDayDateStart, "end": vinesDayDateFinish, "name": "День вина", "id": 3}), + theBlackCountryDateStart = new Date("October 31, 2012 00:00:00"), + theBlackCountryDateFinish = new Date("November 1, 2012 23:59:59"), + theBlackCountry = new Event({"start": theBlackCountryDateStart, "end": theBlackCountryDateFinish, "name": 'Вкус "Черной страны"', "id": 4}), + oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), + oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), + oktoberFest = new Event({"start": oktoberFestDateStart, "end": oktoberFestDateFinish, "name": 'OktoberFest', "id": 5}), + francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), + francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), + francfurtBook = new Event({"start": francfurtBookDateStart, "end": francfurtBookDateFinish, "name": 'Франкфуртская международная книжная ярмарка', "id": 6}), + aidaDateStart = new Date("October 12, 2012 00:00:00"), + aidaDateFinish = new Date("October 27, 2012 23:59:59"), + aida = new Event({"start": aidaDateStart, "end": aidaDateFinish, "name": '"Аида" у великих пирамид, Гиза', "id": 7}), + paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), + paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), + paradeOfLove = new Event({"start": paradeOfLoveDateStart, "end": paradeOfLoveDateFinish, "name": 'Парад любви', "id": 8}), + sukkotDateStart = new Date("October 3, 2012 00:00:00"), + sukkotDateFinish = new Date("October 3, 2012 23:59:59"), + sukkot = new Event({"start": sukkotDateStart, "end": sukkotDateFinish, "name": 'Парад любви', "id": 9}), + fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), + fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), + fishFestival = new Event({"start": fishFestivalDateStart, "end": fishFestivalDateFinish, "name": 'Фестиваль рыбы', "id": 10}), + chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), + chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), + chocolateFestival = new Event({"start": chocolateFestivalDateStart, "end": chocolateFestivalDateFinish, "name": 'Фестиваль "Еврошоколад"', "id": 11}), + digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), + digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), + digitalArtFestival = new Event({"start": digitalArtFestivalDateStart, "end": digitalArtFestivalDateFinish, "name": 'Фестиваль цифрового исскуства', "id": 12}), + fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), + fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), + fatherDays = new Event({"start": fatherDaysDateStart, "end": fatherDaysDateFinish, "name": 'Дни наследия', "id": 13}), + bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), + bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), + bearWeekend = new Event({"start": bearWeekendDateStart, "end": bearWeekendDateFinish, "name": 'Bear Weekends', "id": 14}), + teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), + teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), + teaFestival = new Event({"start": teaFestivalDateStart, "end": teaFestivalDateFinish, "name": 'Фестиваль Чая', "id": 15}), + programmerDayDateStart = new Date("September 13, 2012 00:00:00"), + programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), + programmerDay = new Event({"start": programmerDayDateStart, "end": programmerDayDateFinish, "name": 'День программмиста', "id": 16}), + knowDayDateStart = new Date("September 1, 2012 00:00:01"), + knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), + knowDayDate = new Event({"start": knowDayDateStart, "end": knowDayDateDateFinish, "name": 'День знаний', "id": 17}), + teacherDayDateStart = new Date("October 5, 2012 00:00:00"), + teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), + teacherDay = new Event({"start": teacherDayDateStart, "end": teacherDayDateFinish, "name": 'День учителя', "id": 18}), + securiteDayDateStart = new Date("November 5, 2012 00:00:00"), + securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), + securiteDay = new Event({"start": securiteDayDateStart, "end": securiteDayDateFinish, "name": 'День защиты информации', "id": 19}), + nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), + nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), + nationUnition = new Event({"start": nationUnitionDateStart, "end": nationUnitionDateDateFinish, "name": 'День нароного единства', "id": 20}); + bestOfSweets.setLocation({"gps": { + "x": 15, "y": 189}, "name": "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"}); + bestOfSweets.leaveMark(2); + сirioDeNazare.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Бразилия, Белен, Фестиваль Cirio De Nazare"}); + сirioDeNazare.leaveMark(1); + vinesDay.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Венгрия, Мор, День вина"}); + vinesDay.leaveMark(5); + theBlackCountry.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Великобритания, Дадли, Вкус 'Черной страны'"}); + theBlackCountry.leaveMark(3); + oktoberFest.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Германия, Мюнхен, OktoberFest"}); + oktoberFest.leaveMark(1); + programmerDay.parties = [{name: "Pupkin"}, {"name": "Alex.IDontKnow"}]; + francfurtBook.setLocation({"gps": { + x : 45, y : 133}, "name" : "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"}); + francfurtBook.leaveMark(1); + aida.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Египет, ?, Аида у великих пирамид, Гиза"}); + aida.leaveMark(3); + paradeOfLove.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Израль, Тель-Авиве, Парад любви"}); + paradeOfLove.leaveMark(1); + sukkot.setLocation({"gps": { + "x": 45, y : 133}, "name": "Израль, Иерусалиме, праздник Суккот"}); + sukkot.leaveMark(4); + fishFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Испания, О Грове, Фестиваль рыбы"}); + fishFestival.leaveMark(5); + chocolateFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": 'Италия, Перуджа, Фестиваль "Еврошоколад"'}); + chocolateFestival.leaveMark(1); + digitalArtFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Австрия, Линц, Фестиваль Цифрового Исскуства"}); + digitalArtFestival.leaveMark(3); + fatherDays.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Бельгия, Антверпене, Дни наследия"}); + fatherDays.leaveMark(4); + bearWeekend.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Бельгия, Брюссель, Bear Weekends"}); + bearWeekend.leaveMark(2); + teaFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Россия, Москва, Фестиваль чая"}); + programmerDay.setLocation({"gps" :{ + "x": 45, "y": 133}, "name": "Вселенная, Земля, День программиста"}); + programmerDay.parties = [{name: "Alexander.Mangin"}, {"name": "Alex.IDontKnow"}]; + knowDayDate.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День знаний"}); + teacherDay.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День учителя"}); + securiteDay.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День защиты информации"}); + nationUnition.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День народного единства"}); +return new BaseEvent([bestOfSweets, сirioDeNazare, vinesDay, theBlackCountry, oktoberFest, francfurtBook + , aida, paradeOfLove, sukkot, fishFestival, chocolateFestival, digitalArtFestival, fatherDays, + bearWeekend, teaFestival, programmerDay, knowDayDate, teacherDay, securiteDay, nationUnition]); +} \ No newline at end of file diff --git a/Task/Scripts/test/CollectionTest.html b/Task/Scripts/test/CollectionTest.html new file mode 100644 index 0000000..fdbff42 --- /dev/null +++ b/Task/Scripts/test/CollectionTest.html @@ -0,0 +1,15 @@ + + + + + + + + + +

    QUnit test env

    +

    +

    +
      + + \ No newline at end of file diff --git a/Task/Scripts/test/CollectionTest.js b/Task/Scripts/test/CollectionTest.js new file mode 100644 index 0000000..6e7b14c --- /dev/null +++ b/Task/Scripts/test/CollectionTest.js @@ -0,0 +1,76 @@ +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global deepEqual: true*/ +/*global initTestBase: true*/ +/*global Event: true*/ +/*global Collection: true*/ +module("Конструктор"); +test("Конструктор", function () { + "use strict"; + var newCollection = new Collection([1, 2, 3, 4]); + deepEqual(newCollection.items, [1, 2, 3, 4]); +}); +module("Add(model)"); +test("Добавление элемента в пустую коллекцию", function () { + "use strict"; + var newCollection = new Collection(); + newCollection = newCollection.add(1); + deepEqual(newCollection.items, [1]); +}); +test("Добавление элемента в не пустую коллекцию", function () { + "use strict"; + var newCollection = new Collection([2]); + newCollection = newCollection.add(1); + deepEqual(newCollection.items, [2, 1]); +}); +module("filter(function)"); +test("Пример использование filter", function () { + "use strict"; + var newCollection = new Collection([1, 2, 3, 4, 5, 6]); + newCollection = newCollection.filter(function (element) {return (element % 2 === 0); }); + + deepEqual(newCollection.items, [2, 4, 6]); +}); +module("sortBy(function)"); +test("С использование своего компаратора, без инвертирования результата", function () { + "use strict"; + var newCollection = new Collection([{"id": 8}, {"id": 2}, {"id": 3}, + {"id": 4}, {"id": 14}, {"id": 9}]), + comparator = function (a, b) { + if (a.id > b.id) { + return 1; + } + if (a.id < b.id) { + return -1; + } + return 0; + }; + newCollection = newCollection.sortBy(comparator); + deepEqual(newCollection.items, [{"id": 2}, {"id": 3}, {"id": 4}, + {"id": 8}, {"id": 9}, {"id": 14}]); +}); +test("С использование своего компаратора, c инвертированием результата", function () { + "use strict"; + var newCollection = new Collection([{"id": 8}, {"id": 2}, {"id": 3}, + {"id": 4}, {"id": 14}, {"id": 9}]), + comparator = function (a, b) { + if (a.id > b.id) { + return 1; + } + if (a.id < b.id) { + return -1; + } + return 0; + }; + newCollection = newCollection.sortBy(comparator, true); + deepEqual(newCollection.items, [{"id": 14}, {"id": 9}, {"id": 8}, + {"id": 4}, {"id": 3}, {"id": 2}]); +}); +test("Сортировка по default", function () { + "use strict"; + var newCollection = new Collection([3, 2, 1]); + newCollection = newCollection.sortBy(); + deepEqual(newCollection.items, [1, 2, 3]); +}); \ No newline at end of file diff --git a/Task/Scripts/test/EventTest.html b/Task/Scripts/test/EventTest.html new file mode 100644 index 0000000..72eff13 --- /dev/null +++ b/Task/Scripts/test/EventTest.html @@ -0,0 +1,16 @@ + + + + + + + + + + +

      QUnit test env

      +

      +

      +
        + + \ No newline at end of file diff --git a/Task/Scripts/test/EventTest.js b/Task/Scripts/test/EventTest.js new file mode 100644 index 0000000..8d931e8 --- /dev/null +++ b/Task/Scripts/test/EventTest.js @@ -0,0 +1,127 @@ +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global deepEqual: true*/ +/*global initTestBase: true*/ +/*global Event: true*/ +/*global Collection: true*/ +/*global throws: true*/ +module("Tests of Event's constructor"); +test('Create event', function () { + "use strict"; + var dateToString = function (currentTime) { + var month = currentTime.getMonth() + 1, day = currentTime.getDate(), year = currentTime.getFullYear(); + return month + "/" + day + "/" + year; + }, currentTime = new Date(), testEvent = new Event({"start": currentTime}); + equal(dateToString(testEvent.start), dateToString(currentTime)); + testEvent = new Event({"start": new Date(1), "end": new Date(2)}); + ok(testEvent.start.getTime() < testEvent.end.getTime()); + throws(function () { + new Event({"start": new Date(2), "end": new Date(1)}); + }, + 'Error("Даты начала и конца перепутаны")' + ); + throws(function () { + new Event({"cost": -1}); + }, + 'Error("Цена за вход не может быть отрицательной")' + ); + throws(function () { + new Event({"parties": "NoArray"}); + }, + 'Error("Участники - это массив")' + ); + throws(function () { + new Event({"parties": ["sds"]}); + }, + 'Error("У одного из участников нет поля <ИМЯ>")' + ); + equal(new Event({"stars": 2}).stars, 2, "При присваивании звезд произошла ошибка"); + equal(new Event({"stars": 2.1}).stars, 2, "Функция устанавливающая звездочки не сработала"); +}); + +module("LeaveMark(number)"); +test('Передача не числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark("No number"); + equal(testEvent.stars, 0, 'Если звездочку передали в виде не числа, то 0'); +}); +test('Запуск без параметра', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(); + equal(testEvent.stars, 0, 'Если звездочку забыли объявить, то 0'); +}); +test('Передача отрицательного числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(-1); + equal(testEvent.stars, 0, 'Звездочка не может быть меньше 0'); +}); +test('Передача числа болешьшего 5', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(6); + equal(testEvent.stars, 5, 'Звездочка не может быть больше 5'); +}); +test('Передача корректного числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(3); + equal(testEvent.stars, 3, '0-5 звездочка не изменяется, если целая'); +}); +test('Передача дробного числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(3.124); + equal(testEvent.stars, 3, 'Звездочки - Int'); +}); + +module("SetLocation(location)"); +test('Gps - undef', function () { + "use strict"; + var testEvent = new Event({}), gps; + testEvent.setLocation(gps, ""); + deepEqual(testEvent.location, { + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "GPS - некорректный => установить значения по умолчанию"); +}); +test('Передача числа болешьшего 5', function () { + "use strict"; + var testEvent = new Event({}), gps; + testEvent.setLocation(gps, ""); + deepEqual(testEvent.location, { + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "GPS - некорректный => установить значения по умолчанию"); +}); +test('Передача объекта не являющимся gps', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.setLocation("Not gps", ""); + deepEqual(testEvent.location, { + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); +}); +test('Имя места - не строка', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.setLocation({"x": 0, "y": 0}, []); + deepEqual(testEvent.location, { + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "Название места не строка => установить значения по умолчанию"); +}); +test('Корректный тест', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.setLocation({"x": 1, "y": 2}, "Moon"); + deepEqual(testEvent.location, { + "gps": {"x": 1, "y": 2}, + "nameLocation": "Moon" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); +}); \ No newline at end of file diff --git a/Task/Scripts/test/ModelTest.html b/Task/Scripts/test/ModelTest.html new file mode 100644 index 0000000..f28a42d --- /dev/null +++ b/Task/Scripts/test/ModelTest.html @@ -0,0 +1,15 @@ + + + + + + + + + +

        QUnit test env

        +

        +

        +
          + + \ No newline at end of file diff --git a/Task/Scripts/test/ModelTest.js b/Task/Scripts/test/ModelTest.js new file mode 100644 index 0000000..81fa2b9 --- /dev/null +++ b/Task/Scripts/test/ModelTest.js @@ -0,0 +1,43 @@ +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global deepEqual: true*/ +/*global initTestBase: true*/ +/*global Event: true*/ +/*global Collection: true*/ +/*global Model: true*/ +/*global TestObject: true*/ +module("Create model"); +test('Проверка конструктора клонирования', function () { + "use strict"; + var model = new Model(new TestObject(1)); + equal(typeof model["myNumber"], "number", "Личный объект не скопировался"); + equal(typeof model["commonNumber"], "number", "Объекты прототипа не скопировались"); +}); +test('Проверка метода get()', function () { + "use strict"; + var model = new Model(new TestObject(1)); + equal(model.get("commonNumber"), 20, "Нет доступа к полям прототипа"); + equal(model.get("myNumber"), 1, "Нет доступа к личным полям"); + equal(typeof model.get({}), "undefined", "Объект не исполняет интерфейс"); + equal(typeof model.get("ТакогоПоляТочноНет"), "undefined", "несуществующее поле определено"); +}); +test('Проверка метода set()', function () { + "use strict"; + var model = new Model(new TestObject(1)); + model.set({"myNumber": 2}); + equal(typeof model.get("myNumber"), "number", "Присваение произошло с ошибкой"); + equal(model.get("myNumber"), 2, "Присвоение произошло с ошибкой"); + model.set({"commonNumber": 2}); + equal(TestObject.prototype.commonNumber, 20, "Присвоение испортило прототип"); + equal(model.get("commonNumber"), 2, "Ошибка при присвоении наследуемому полю через прототип"); +}); + +function TestObject (number) { + "use strict"; + this.myNumber = number; +} +TestObject.prototype.commonNumber = 20; + + diff --git a/Task/index.html b/Task/index.html new file mode 100644 index 0000000..6d9f46c --- /dev/null +++ b/Task/index.html @@ -0,0 +1,49 @@ + + + + + +
          +
          +
          +
          + + + Error1 +
          +
          + + + Error1 +
          +
          + + + Error1 +
          +
          + ? ( + + + ) + Error1 +
          +
          + + + + Error1 +
          +
          +
          +
          +
          1
          +
          2
          +
          2
          +
          2
          +
          2
          +
          2
          +
          +
          + + \ No newline at end of file diff --git a/Task/style.css b/Task/style.css new file mode 100644 index 0000000..5421379 --- /dev/null +++ b/Task/style.css @@ -0,0 +1,19 @@ +*{ + padding: 2; +} +#eventFactory { + float: left; + border:4px double black; +} +#eventList { + color: red; + overflow: hidden; + border:4px double black; +} +#AddInputs { + float: left; +} + +#messageErrorAddInputs { + overflow: hidden; +} \ No newline at end of file From 4288519015d06e72e5596d25b24b039d21f209c2 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 8 Nov 2012 20:11:31 +0600 Subject: [PATCH 02/11] =?UTF-8?q?=D0=90=D1=80=D0=BA=D1=85=20=D0=BA=D0=B0?= =?UTF-8?q?=D0=BA=20=D0=BF=D1=80=D0=B8=D0=BA=D0=BE=D0=BB=D1=8C=D0=BD=D0=BE?= =?UTF-8?q?=20=D1=81=D0=B2=D0=B5=D1=80=D1=81=D1=82=D0=B0=D0=BB=20TT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/index.html | 241 ++++++++++++++++++++++++++++++++++++++++++------ Task/style.css | 15 ++- 2 files changed, 228 insertions(+), 28 deletions(-) diff --git a/Task/index.html b/Task/index.html index 6d9f46c..6ea5178 100644 --- a/Task/index.html +++ b/Task/index.html @@ -4,45 +4,234 @@
          -
          -
          +
          +
          +
          + + + Error1 +
          +
          + + + Error1 +
          +
          + + + Error1 +
          +
          + ? ( + + ; + + ) + Error1 +
          +
          + + + Error1 +
          +
          + + + + Error1 +
          + +
          +
          :
          +
            +
          1. +
          2. +
          3. +
          - - - Error1 + +
          +
          +
          + +
          +
          +
          + +
          +
          + , ... +
          +
          + + +
          +
          + + +
          +
          + + +
          +
          + + +
          +
          + + + + +
          +
          +
          +
          + , ..
          - - - Error1 + +
          - - - Error1 + +
          - ? ( - - - ) - Error1 + +
          - - - - Error1 + +
          +
          + + + + +
          +
          +
          +
          + , .. +
          +
          + + +
          +
            +
          1. +
          2. +
          3. +
          +
          + +
          +
          +
          -
          1
          -
          2
          -
          2
          -
          2
          -
          2
          -
          2
          +
          +
          +
          +
          + 1 +
          +
          + 2 +
          +
          + 3 +
          +
          +
          +
          +
          +
          +
          + , (10,45) +
          +
          + , (11,49) +
          +
          +
          +
          +
          ^^
          +
          +
          + **** +
          +
          + ** +
          +
          + * +
          +
          +
          +
          +
          +
          +
          + 1.10.12 - 10.11.13 +
          +
          + 1.12.12 - 10.01.13 +
          +
          + 1.1.12 - 10.5.12 +
          +
          +
          +
          +
          +
          +
          + Free!!! +
          +
          + +
          +
          + 100500 +
          +
          +
          +
          +
          +
          +
          + +
          +
          + +
          +
          + +
          +
          +
          diff --git a/Task/style.css b/Task/style.css index 5421379..d8909d4 100644 --- a/Task/style.css +++ b/Task/style.css @@ -1,7 +1,6 @@ *{ - padding: 2; } -#eventFactory { +#ActionWithEventList { float: left; border:4px double black; } @@ -16,4 +15,16 @@ #messageErrorAddInputs { overflow: hidden; +} + +.Error { + color: red; +} + +.TitleAddEvent { + color: blue; +} +.ColonTable { + float: left; + overflow: hidden; } \ No newline at end of file From ae06e331a45194b821adb9ae6787697f5e0b66cb Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 04:53:39 +0600 Subject: [PATCH 03/11] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=BE?= =?UTF-8?q?.=20=D0=A1=D0=B5=D0=BB=20=D1=80=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D1=82=D1=8C=20+=20=D0=BF=D0=B8=D1=81=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B4=D0=BE=D0=BA=D0=B8=20+=20=D1=83=D0=B4?= =?UTF-8?q?=D0=BE=D0=B2=D0=BE=D0=BB=D0=B5=D1=82=D0=B2=D0=BE=D1=80=D1=8F?= =?UTF-8?q?=D1=82=D1=8C=20jsLint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/BaseEvent.js | 4 +- Task/Scripts/CalendaryErrorManager.js | 32 +++ Task/Scripts/Collection.js | 7 +- Task/Scripts/DOMErrorManager.js | 39 ++++ Task/Scripts/Event.js | 18 +- Task/Scripts/Model.js | 4 +- Task/Scripts/Validator.js | 88 ++++++++ Task/Scripts/calendary.js | 221 ++++++++++++++++++++ Task/Scripts/test/BaseEventTest.html | 4 +- Task/Scripts/test/BaseEventTest.js | 51 +++-- Task/Scripts/test/CollectionTest.html | 4 +- Task/Scripts/test/EventTest.html | 4 +- Task/Scripts/test/EventTest.js | 21 +- Task/Scripts/test/ModelTest.html | 4 +- Task/Scripts/testData.js | 100 +++++++++ Task/index.html | 279 ++++++++++---------------- Task/style.css | 7 +- 17 files changed, 663 insertions(+), 224 deletions(-) create mode 100644 Task/Scripts/CalendaryErrorManager.js create mode 100644 Task/Scripts/DOMErrorManager.js create mode 100644 Task/Scripts/Validator.js create mode 100644 Task/Scripts/calendary.js create mode 100644 Task/Scripts/testData.js diff --git a/Task/Scripts/BaseEvent.js b/Task/Scripts/BaseEvent.js index b5eed43..928d932 100644 --- a/Task/Scripts/BaseEvent.js +++ b/Task/Scripts/BaseEvent.js @@ -3,7 +3,7 @@ /** * Shell for "sql" operations with Array Events. * @prototype {Collection} - * @constructor + * @constructoro * @method {pastEventBase} - Создает BaseEvent с пропущенными событиями * @method {pastEventBase} - Создает BaseEvent с грядущими событиями * @method {nowEventBase} - Создает BaseEvent с текущими событиями @@ -19,7 +19,6 @@ function BaseEvent(events) { "use strict"; Collection.call(this, events); - this.events = events; } BaseEvent.prototype = Object.create(Collection.prototype, { constructor: { @@ -29,6 +28,7 @@ BaseEvent.prototype = Object.create(Collection.prototype, { configurable: true } }); +BaseEvent.prototype.constructor = BaseEvent; //пропущенные, текущие, будущие события BaseEvent.prototype.pastEventBase = function () { "use strict"; diff --git a/Task/Scripts/CalendaryErrorManager.js b/Task/Scripts/CalendaryErrorManager.js new file mode 100644 index 0000000..9bcf582 --- /dev/null +++ b/Task/Scripts/CalendaryErrorManager.js @@ -0,0 +1,32 @@ +var CalendaryErrorManager = function (errorClassName) { + DOMErrorManager.call(this, errorClassName); +} +CalendaryErrorManager.prototype = Object.create(DOMErrorManager.prototype, { + constructor: { + value: Event, + enumerable: false, + writable: true, + configurable: true + } +}); + +CalendaryErrorManager.prototype.changeTime = function (timer) { + var textError = Validator.isTimeInterval(timer); + this.changeTextError(timer, textError); +} +CalendaryErrorManager.prototype.changeCoordinate = function (coordinates) { + var textError = Validator.isCoordinate(coordinates); + this.changeTextError(coordinates, textError); +} +CalendaryErrorManager.prototype.changeImportantStringField = function (importantStringField) { + var textError = Validator.isImportantStringField(importantStringField,5,20); + this.changeTextError(importantStringField, textError); +} +CalendaryErrorManager.prototype.changePositiveNumber = function (positiveNumber) { + var textError = Validator.isPositiveNumber(positiveNumber); + this.changeTextError(positiveNumber, textError); +} +CalendaryErrorManager.prototype.changeStars = function (stars) { + var textError = Validator.isStars(stars); + this.changeTextError(stars, textError); +} \ No newline at end of file diff --git a/Task/Scripts/Collection.js b/Task/Scripts/Collection.js index 40ee9dd..f27b45b 100644 --- a/Task/Scripts/Collection.js +++ b/Task/Scripts/Collection.js @@ -19,15 +19,16 @@ Collection = function (otherItems) { } } }; +Collection.prototype.constructor = Collection Collection.prototype.add = function (obj) { "use strict"; var newEvents = this.items.concat([obj]); - return new Collection(newEvents); + return new this.constructor(newEvents); }; Collection.prototype.filter = function (selector) { "use strict"; var newItems = this.items.filter(selector); - return new Collection(newItems); + return new this.constructor(newItems); }; Collection.prototype.sortBy = function (comparator, isInvert) { "use strict"; @@ -46,5 +47,5 @@ Collection.prototype.sortBy = function (comparator, isInvert) { } else { newItems.sort(); } - return new Collection(newItems); + return new this.constructor(newItems); }; \ No newline at end of file diff --git a/Task/Scripts/DOMErrorManager.js b/Task/Scripts/DOMErrorManager.js new file mode 100644 index 0000000..f588af1 --- /dev/null +++ b/Task/Scripts/DOMErrorManager.js @@ -0,0 +1,39 @@ +var DOMErrorManager = function (errorClassName) { + this.errorClassName = errorClassName; +} +DOMErrorManager.prototype.isFieldWithError = function (element) { + var lastElement = element.querySelector("."+this.errorClassName); + return !!lastElement; +} +DOMErrorManager.prototype.setTextError = function (element, text) { + var newError = document.createElement("span"); + var newTextError = document.createTextNode(text); + newError.className = this.errorClassName; + newError.appendChild(newTextError); + element.appendChild(newError); +} +DOMErrorManager.prototype.removeTextError = function (element) { + var error = element.querySelector("."+this.errorClassName); + element.removeChild(error); +} +DOMErrorManager.prototype.changeTextError = function (element, errorText) { + var currentErrorState = this.isFieldWithError(element); + if (errorText === "") { + if (currentErrorState) { + this.removeTextError(element); + } + } + else + { + if (currentErrorState) { + this.removeTextError(element); + } + this.setTextError(element, errorText); + } +} +DOMErrorManager.prototype.removeAllChildren = function(element) { + var children = element.childNodes; + while(children.length) { + element.removeChild(children[0]) + } +} diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index fea46bd..2658547 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -26,8 +26,8 @@ function Event(data) { this.parties = []; Model.call(this, data); this.validate(this); - this.setLocation(this.location); - this.leaveMark(this.stars); + this.setLocation(this.location.gps, this.location.nameLocation); + this.stars = this.leaveMark(this.stars); } Event.prototype = Object.create(Model.prototype, { constructor: { @@ -67,7 +67,7 @@ Event.prototype.leaveMark = function (stars) { stars = 5; } stars = (stars - (stars % 1)); //обрезаем дробную часть - this.stars = stars; + return stars; }; Event.prototype.validate = function (event) { "use strict"; @@ -86,4 +86,14 @@ Event.prototype.validate = function (event) { if (event.end < event.start) { throw new Error("Даты начала и конца перепутаны"); } -}; \ No newline at end of file +}; +Event.prototype.locationToString = function() { + return this.location.nameLocation + ", (" + this.location.gps.x + ";" + this.location.gps.y + ")"; +} +Event.prototype.starsToString= function() { + var res = ""; + for(var i = 0; i < this.stars; i++) { + res += "*"; + } + return res; +} \ No newline at end of file diff --git a/Task/Scripts/Model.js b/Task/Scripts/Model.js index 572c751..2d18237 100644 --- a/Task/Scripts/Model.js +++ b/Task/Scripts/Model.js @@ -15,6 +15,8 @@ var Model = function (data) { this[nameField] = data[nameField]; } }; +Model.prototype.constructor = Model; + Model.prototype.set = function (attributes) { "use strict"; var nameAttr; @@ -36,4 +38,4 @@ Model.prototype.get = function (attribute) { Model.prototype.validate = function () { "use strict"; throw new Error('this is Abstract method'); -}; \ No newline at end of file +}; diff --git a/Task/Scripts/Validator.js b/Task/Scripts/Validator.js new file mode 100644 index 0000000..32d1c2b --- /dev/null +++ b/Task/Scripts/Validator.js @@ -0,0 +1,88 @@ +var Validator = { + "isTimeInterval" : function (divWithTimeInterval) { + var startDate = new Date(divWithTimeInterval.querySelector(".StartDate").value); + var finishDate = new Date(divWithTimeInterval.querySelector(".FinishDate").value); + var isDate = function (element) { + return Event.prototype.dateValidator(element); + } + if (!isDate(startDate) && !isDate(finishDate)) + return "Обе даты некорректны"; + if (!isDate(startDate)) + return "Дата начала события некорректна"; + if (!isDate(finishDate)) + return "Дата конца события некорректна"; + if (startDate.getTime()> finishDate.getTime()) { + return "Даты перепутаны местами"; + } + return ""; + }, + "isCoordinate" : function (divWithCoordinates) { + var xCoordinate = divWithCoordinates.querySelector(".XCoordinate").value; + var yCoordinate = divWithCoordinates.querySelector(".YCoordinate").value; + var isNumeric = function(element) { + return !isNaN(parseFloat(element)); + }; + if (!isNumeric(xCoordinate) && !isNumeric(yCoordinate)) { + return "Обе координаты некорректны"; + } + if (!isNumeric(xCoordinate)) { + return "Координата X - некорректна"; + } + if (!isNumeric(yCoordinate)) { + return "Координата Y - некорректна"; + } + return ""; + }, + + "isImportantStringField" : function (divWithImportantStringField, minSize, maxSize) { + minSize = minSize || 0; + maxSize = maxSize || -1; + if (minSize < 0) { + minSize = 0; + } + if (minSize> maxSize) { + maxSize = -1; + } + var importantStringField = divWithImportantStringField.querySelector(".ImportantStringField").value; + if (maxSize != -1) { + if (minSize > importantStringField.length || maxSize < importantStringField.length) { + return "Поле должно содержать от " + minSize + " до "+ maxSize + "символов"; + } + } + else { + if (minSize > importantStringField.length) { + return "Поле должно содержать как минимум "+minSize+" символов"; + } + } + return ""; + }, + "isStars" : function (divWithStarField) { + var starsField = parseFloat(divWithStarField.querySelector(".StarsField").value); + var isNumeric = function(element) { + return !isNaN(parseFloat(element.value)); + }; + if (isNaN(starsField)) { + return "В поле введено не число"; + } + if (starsField < 0 || starsField>5) { + return "Количество звезд 0-5"; + } + if (parseInt(starsField) !== starsField) { + return "Количество звезд целое число"; + } + return ""; + }, + + "isPositiveNumber" : function (divWithPositiveNumberField) { + var positiveNumberField = divWithPositiveNumberField.querySelector(" .PositiveNumber").value; + var isNumeric = function(element) { + return !isNaN(parseFloat(element)); + }; + if (!isNumeric(positiveNumberField)) { + return "В поле введено не число"; + } + if (parseFloat(positiveNumberField) < 0) { + return "В поле введено отрицательное число"; + } + return ""; +}} \ No newline at end of file diff --git a/Task/Scripts/calendary.js b/Task/Scripts/calendary.js new file mode 100644 index 0000000..f8c1876 --- /dev/null +++ b/Task/Scripts/calendary.js @@ -0,0 +1,221 @@ +var Calendary= function (who) { + this.whois = "Alex.Mangin"; + this.EventFactory = { + "timer" : document.getElementById("NewEventTimeInterval"), + "nameLocation" : document.getElementById("NewEventNameLocation"), + "coordinate" : document.getElementById("NewEventCoordinate"), + "stars" : document.getElementById("NewEventStars"), + "cost" : document.getElementById("NewEventCost"), + "parties" : document.querySelector("#NewEventPartiesList ol"), + }; + this.eventList = document.getElementById("eventList"); + this.eventBase = initTestBase(); + this.errorManager = new CalendaryErrorManager("Error"); + this.currentFilters = []; +} +Calendary.prototype.ApplyFilter = function(filters) { + var base = this.eventBase; + for(var i in filters) { + base = filters[i].call(base); + } + return base; +} +Calendary.prototype.CreateEvent = function() { + if (!this.isCorrecteNeedFields()) { + this.changeNeed(); + this.changeAddition(); + return + } + if (!this.isCorrecteAdditionFields()) { + if (!confirm('Некоторые незначительные поля некорректны, продолжить?')) { + this.changeAddition(); + return; + } + } + var parties = []; + var partyList = this.EventFactory.parties.querySelectorAll(" input"); + for(var i = 0; i - - + + diff --git a/Task/Scripts/test/BaseEventTest.js b/Task/Scripts/test/BaseEventTest.js index 8554015..08a2f05 100644 --- a/Task/Scripts/test/BaseEventTest.js +++ b/Task/Scripts/test/BaseEventTest.js @@ -5,6 +5,18 @@ /*global initTestBase: true*/ /*global Event: true*/ module("test simple SQL"); +test('add()', function () { + "use strict"; + var testBase = new BaseEvent([]), RealDate = Date, pastEventbase; + Date = function () { + return new RealDate("September 13, 2012 12:00:00"); + }; + testBase = testBase.add(new Event({"start": new Date(1),"end": new Date(2), "location":{"nameLocation":"123", "gps":{"x":1,"y":2}}})); + equal(testBase.items.length, 1); + ok(testBase instanceof BaseEvent); + ok(testBase instanceof Collection); + ok(true, true); +}); test('pastEventBase()', function () { "use strict"; var testBase = initTestBase(), RealDate = Date, pastEventbase; @@ -125,8 +137,9 @@ test('sortByStar()', function () { "use strict"; var testBase = initTestBase(), sortByStarsEventbase = testBase.sortByStars(); equal(testBase.items.length, sortByStarsEventbase.items.length); - ok(sortByStarsEventbase.items[0].stars === 5); - ok(sortByStarsEventbase.items[1].stars === 5); + ok(sortByStarsEventbase.items[0].id === 18); + ok(sortByStarsEventbase.items[1].id === 19); + ok(sortByStarsEventbase.items[2].id === 17); }); test('sortByDate()', function () { "use strict"; @@ -187,59 +200,59 @@ function initTestBase() { programmerDay = new Event({"start": programmerDayDateStart, "end": programmerDayDateFinish, "name": 'День программмиста', "id": 16}), knowDayDateStart = new Date("September 1, 2012 00:00:01"), knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), - knowDayDate = new Event({"start": knowDayDateStart, "end": knowDayDateDateFinish, "name": 'День знаний', "id": 17}), + knowDayDate = new Event({"start": knowDayDateStart, "end": knowDayDateDateFinish, "name": 'День знаний', "id": 17, "stars": 1}), teacherDayDateStart = new Date("October 5, 2012 00:00:00"), teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), - teacherDay = new Event({"start": teacherDayDateStart, "end": teacherDayDateFinish, "name": 'День учителя', "id": 18}), + teacherDay = new Event({"start": teacherDayDateStart, "end": teacherDayDateFinish, "name": 'День учителя', "id": 18, "stars": 5}), securiteDayDateStart = new Date("November 5, 2012 00:00:00"), securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), - securiteDay = new Event({"start": securiteDayDateStart, "end": securiteDayDateFinish, "name": 'День защиты информации', "id": 19}), + securiteDay = new Event({"start": securiteDayDateStart, "end": securiteDayDateFinish, "name": 'День защиты информации', "id": 19, "stars": 3}), nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), nationUnition = new Event({"start": nationUnitionDateStart, "end": nationUnitionDateDateFinish, "name": 'День нароного единства', "id": 20}); bestOfSweets.setLocation({"gps": { "x": 15, "y": 189}, "name": "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"}); - bestOfSweets.leaveMark(2); + сirioDeNazare.setLocation({"gps": { "x": 45, "y": 133}, "name": "Бразилия, Белен, Фестиваль Cirio De Nazare"}); - сirioDeNazare.leaveMark(1); + vinesDay.setLocation({"gps": { "x": 45, "y": 133}, "name": "Венгрия, Мор, День вина"}); - vinesDay.leaveMark(5); + theBlackCountry.setLocation({"gps": { "x": 45, "y": 133}, "name": "Великобритания, Дадли, Вкус 'Черной страны'"}); - theBlackCountry.leaveMark(3); + oktoberFest.setLocation({"gps": { "x": 45, "y": 133}, "name": "Германия, Мюнхен, OktoberFest"}); - oktoberFest.leaveMark(1); + programmerDay.parties = [{name: "Pupkin"}, {"name": "Alex.IDontKnow"}]; francfurtBook.setLocation({"gps": { x : 45, y : 133}, "name" : "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"}); - francfurtBook.leaveMark(1); + aida.setLocation({"gps": { "x": 45, "y": 133}, "name": "Египет, ?, Аида у великих пирамид, Гиза"}); - aida.leaveMark(3); + paradeOfLove.setLocation({"gps": { "x": 45, "y": 133}, "name": "Израль, Тель-Авиве, Парад любви"}); - paradeOfLove.leaveMark(1); + sukkot.setLocation({"gps": { "x": 45, y : 133}, "name": "Израль, Иерусалиме, праздник Суккот"}); - sukkot.leaveMark(4); + fishFestival.setLocation({"gps": { "x": 45, "y": 133}, "name": "Испания, О Грове, Фестиваль рыбы"}); - fishFestival.leaveMark(5); + chocolateFestival.setLocation({"gps": { "x": 45, "y": 133}, "name": 'Италия, Перуджа, Фестиваль "Еврошоколад"'}); - chocolateFestival.leaveMark(1); + digitalArtFestival.setLocation({"gps": { "x": 45, "y": 133}, "name": "Австрия, Линц, Фестиваль Цифрового Исскуства"}); - digitalArtFestival.leaveMark(3); + fatherDays.setLocation({"gps": { "x": 45, "y": 133}, "name": "Бельгия, Антверпене, Дни наследия"}); - fatherDays.leaveMark(4); + bearWeekend.setLocation({"gps": { "x": 45, "y": 133}, "name": "Бельгия, Брюссель, Bear Weekends"}); - bearWeekend.leaveMark(2); + teaFestival.setLocation({"gps": { "x": 45, "y": 133}, "name": "Россия, Москва, Фестиваль чая"}); programmerDay.setLocation({"gps" :{ diff --git a/Task/Scripts/test/CollectionTest.html b/Task/Scripts/test/CollectionTest.html index fdbff42..92d77b3 100644 --- a/Task/Scripts/test/CollectionTest.html +++ b/Task/Scripts/test/CollectionTest.html @@ -1,8 +1,8 @@  - - + + diff --git a/Task/Scripts/test/EventTest.html b/Task/Scripts/test/EventTest.html index 72eff13..8fb416e 100644 --- a/Task/Scripts/test/EventTest.html +++ b/Task/Scripts/test/EventTest.html @@ -1,8 +1,8 @@  - - + + diff --git a/Task/Scripts/test/EventTest.js b/Task/Scripts/test/EventTest.js index 8d931e8..681b30e 100644 --- a/Task/Scripts/test/EventTest.js +++ b/Task/Scripts/test/EventTest.js @@ -45,38 +45,35 @@ module("LeaveMark(number)"); test('Передача не числа', function () { "use strict"; var testEvent = new Event({}); - testEvent.leaveMark("No number"); - equal(testEvent.stars, 0, 'Если звездочку передали в виде не числа, то 0'); + equal(testEvent.leaveMark("не число"), 0, 'Если звездочку передали в виде не числа, то 0'); }); test('Запуск без параметра', function () { "use strict"; var testEvent = new Event({}); - testEvent.leaveMark(); - equal(testEvent.stars, 0, 'Если звездочку забыли объявить, то 0'); + + equal(testEvent.leaveMark(), 0, 'Если звездочку забыли объявить, то 0'); }); test('Передача отрицательного числа', function () { "use strict"; var testEvent = new Event({}); - testEvent.leaveMark(-1); - equal(testEvent.stars, 0, 'Звездочка не может быть меньше 0'); + equal(testEvent.leaveMark(-1), 0, 'Звездочка не может быть меньше 0'); }); test('Передача числа болешьшего 5', function () { "use strict"; var testEvent = new Event({}); - testEvent.leaveMark(6); - equal(testEvent.stars, 5, 'Звездочка не может быть больше 5'); + + equal(testEvent.leaveMark(6), 5, 'Звездочка не может быть больше 5'); }); test('Передача корректного числа', function () { "use strict"; var testEvent = new Event({}); - testEvent.leaveMark(3); - equal(testEvent.stars, 3, '0-5 звездочка не изменяется, если целая'); + + equal(testEvent.leaveMark(3), 3, '0-5 звездочка не изменяется, если целая'); }); test('Передача дробного числа', function () { "use strict"; var testEvent = new Event({}); - testEvent.leaveMark(3.124); - equal(testEvent.stars, 3, 'Звездочки - Int'); + equal(testEvent.leaveMark(3.124), 3, 'Звездочки - Int'); }); module("SetLocation(location)"); diff --git a/Task/Scripts/test/ModelTest.html b/Task/Scripts/test/ModelTest.html index f28a42d..5111961 100644 --- a/Task/Scripts/test/ModelTest.html +++ b/Task/Scripts/test/ModelTest.html @@ -1,8 +1,8 @@  - - + + diff --git a/Task/Scripts/testData.js b/Task/Scripts/testData.js new file mode 100644 index 0000000..45be18e --- /dev/null +++ b/Task/Scripts/testData.js @@ -0,0 +1,100 @@ +function initTestBase() { + "use strict"; + var bestOfSweetsDateStart = new Date("December 10, 2012 00:00:00"), + bestOfSweetsDateFinish = new Date("December 14, 2012 23:59:59"), + bestOfSweets = new Event({"start": bestOfSweetsDateStart, "end": bestOfSweetsDateFinish, "name": "BestOfSweets", "id": 1}), + сirioDeNazareDateStart = new Date("December 8, 2012 00:00:00"), + сirioDeNazareDateFinish = new Date("December 15, 2012 23:59:59"), + сirioDeNazare = new Event({"start": сirioDeNazareDateStart, "end": сirioDeNazareDateFinish, "name": "Cirio De Nazare", "id": 2}), + vinesDayDateStart = new Date("November 10, 2012 00:00:00"), + vinesDayDateFinish = new Date("November 15, 2012 23:59:59"), + vinesDay = new Event({"start": vinesDayDateStart, "end": vinesDayDateFinish, "name": "День вина", "id": 3}), + theBlackCountryDateStart = new Date("November 15, 2012 00:00:00"), + theBlackCountryDateFinish = new Date("December 1, 2012 23:59:59"), + theBlackCountry = new Event({"start": theBlackCountryDateStart, "end": theBlackCountryDateFinish, "name": 'Вкус "Черной страны"', "id": 4}), + oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), + oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), + oktoberFest = new Event({"start": oktoberFestDateStart, "end": oktoberFestDateFinish, "name": 'OktoberFest', "id": 5}), + francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), + francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), + francfurtBook = new Event({"start": francfurtBookDateStart, "end": francfurtBookDateFinish, "name": 'Франкфуртская международная книжная ярмарка', "id": 6}), + aidaDateStart = new Date("October 12, 2012 00:00:00"), + aidaDateFinish = new Date("October 27, 2012 23:59:59"), + aida = new Event({"start": aidaDateStart, "end": aidaDateFinish, "name": '"Аида" у великих пирамид, Гиза', "id": 7}), + paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), + paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), + paradeOfLove = new Event({"start": paradeOfLoveDateStart, "end": paradeOfLoveDateFinish, "name": 'Парад любви', "id": 8}), + sukkotDateStart = new Date("October 3, 2012 00:00:00"), + sukkotDateFinish = new Date("October 3, 2012 23:59:59"), + sukkot = new Event({"start": sukkotDateStart, "end": sukkotDateFinish, "name": 'Парад любви', "id": 9}), + fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), + fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), + fishFestival = new Event({"start": fishFestivalDateStart, "end": fishFestivalDateFinish, "name": 'Фестиваль рыбы', "id": 10}), + chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), + chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), + chocolateFestival = new Event({"start": chocolateFestivalDateStart, "end": chocolateFestivalDateFinish, "name": 'Фестиваль "Еврошоколад"', "id": 11}), + digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), + digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), + digitalArtFestival = new Event({"start": digitalArtFestivalDateStart, "end": digitalArtFestivalDateFinish, "name": 'Фестиваль цифрового исскуства', "id": 12}), + fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), + fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), + fatherDays = new Event({"start": fatherDaysDateStart, "end": fatherDaysDateFinish, "name": 'Дни наследия', "id": 13}), + bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), + bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), + bearWeekend = new Event({"start": bearWeekendDateStart, "end": bearWeekendDateFinish, "name": 'Bear Weekends', "id": 14}), + teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), + teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), + teaFestival = new Event({"start": teaFestivalDateStart, "end": teaFestivalDateFinish, "name": 'Фестиваль Чая', "id": 15}), + programmerDayDateStart = new Date("September 13, 2012 00:00:00"), + programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), + programmerDay = new Event({"start": programmerDayDateStart, "end": programmerDayDateFinish, "name": 'День программмиста', "id": 16}), + knowDayDateStart = new Date("September 1, 2012 00:00:01"), + knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), + knowDayDate = new Event({"start": knowDayDateStart, "end": knowDayDateDateFinish, "name": 'День знаний', "id": 17, "stars": 1}), + teacherDayDateStart = new Date("October 5, 2012 00:00:00"), + teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), + teacherDay = new Event({"start": teacherDayDateStart, "end": teacherDayDateFinish, "name": 'День учителя', "id": 18, "stars": 5}), + securiteDayDateStart = new Date("November 5, 2012 00:00:00"), + securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), + securiteDay = new Event({"start": securiteDayDateStart, "end": securiteDayDateFinish, "name": 'День защиты информации', "id": 19, "stars": 3}), + nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), + nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), + nationUnition = new Event({"start": nationUnitionDateStart, "end": nationUnitionDateDateFinish, "name": 'День нароного единства', "id": 20}); + bestOfSweets.setLocation({"x": 15, "y": 189}, "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"); + + сirioDeNazare.setLocation({"x": 45, "y": 133}, "Бразилия, Белен, Фестиваль Cirio De Nazare"); + + vinesDay.setLocation({"x": 45, "y": 133}, "Венгрия, Мор, День вина"); + + theBlackCountry.setLocation({"x": 45, "y": 133}, "Великобритания, Дадли, Вкус 'Черной страны'"); + + oktoberFest.setLocation({"x": 45, "y": 133}, "Германия, Мюнхен, OktoberFest"); + + programmerDay.parties = [{"name": "Pupkin"}, {"name": "Alex.IDontKnow"}]; + francfurtBook.setLocation({x : 45, y : 133}, "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"); + aida.setLocation({"x": 45, "y": 133}, "Египет, ?, Аида у великих пирамид, Гиза"); + paradeOfLove.setLocation({"x": 45, "y": 133}, "Израль, Тель-Авиве, Парад любви"); + + sukkot.setLocation({"x": 45, y : 133}, "Израль, Иерусалиме, праздник Суккот"); + + fishFestival.setLocation({"x": 45, "y": 133}, "Испания, О Грове, Фестиваль рыбы"); + + chocolateFestival.setLocation({"x": 45, "y": 133}, 'Италия, Перуджа, Фестиваль "Еврошоколад"'); + + digitalArtFestival.setLocation({"x": 45, "y": 133}, "Австрия, Линц, Фестиваль Цифрового Исскуства"); + + fatherDays.setLocation({"x": 45, "y": 133}, "Бельгия, Антверпене, Дни наследия"); + + bearWeekend.setLocation({"x": 45, "y": 133}, "Бельгия, Брюссель, Bear Weekends"); + + teaFestival.setLocation({"x": 45, "y": 133}, "Россия, Москва, Фестиваль чая"); + programmerDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День программиста"); + programmerDay.parties = [{"name": "Alexander.Mangin"}, {"name": "Alex.IDontKnow"}]; + knowDayDate.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День знаний"); + teacherDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День учителя"); + securiteDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День защиты информации"); + nationUnition.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День народного единства"); +return new BaseEvent([bestOfSweets, сirioDeNazare, vinesDay, theBlackCountry, oktoberFest, francfurtBook + , aida, paradeOfLove, sukkot, fishFestival, chocolateFestival, digitalArtFestival, fatherDays, + bearWeekend, teaFestival, programmerDay, knowDayDate, teacherDay, securiteDay, nationUnition]); +} \ No newline at end of file diff --git a/Task/index.html b/Task/index.html index 6ea5178..8056a8e 100644 --- a/Task/index.html +++ b/Task/index.html @@ -1,238 +1,169 @@ - + - +
          -
          - - - Error1 -
          -
          - - - Error1 -
          -
          - - - Error1 +
          +
          +
          + Начало + +
          +
          + Конец + +
          +
          +
          + Что + +
          -
          - ? ( - +
          + Где? ( + ; - + ) - Error1
          -
          - - - Error1 -
          -
          - - - - Error1 -
          - -
          -
          :
          -
            +
            + Важность + +
            +
            + Цена посещения + +
            +
            +
            Список участников:
            +
            - -
            + +
          - +
          - , ... + Показать события, которые ...
          - - + Вообще есть +
          - - + Будут завтра +
          - - + Будут через неделю +
          - - + Будут через месяц +
          -
          - - - - -
          - , .. + Показать события, которые ..
          - - + Вообще есть +
          - - + Уже прошли +
          - - + Идут в данный момент +
          - - + Будут идти +
          +
          +
          - - - - -
          + Какую сортировочку изволите? +
          +
          + Ни какую пожалуйста + +
          +
          + По звездам ^^ + +
          +
          + По дате + +
          - , .. + Показать события, в которых ..
          - - -
          +
          Участвуют мои друзья
          - +
          -
          -
          -
          -
          -
          - 1 -
          -
          - 2 -
          -
          - 3 -
          -
          -
          -
          -
          -
          -
          - , (10,45) -
          -
          - , (11,49) -
          -
          -
          -
          -
          ^^
          -
          -
          - **** -
          -
          - ** -
          -
          - * -
          -
          -
          -
          -
          -
          -
          - 1.10.12 - 10.11.13 -
          -
          - 1.12.12 - 10.01.13 -
          -
          - 1.1.12 - 10.5.12 -
          -
          -
          -
          -
          -
          -
          - Free!!! -
          -
          - -
          -
          - 100500 -
          -
          -
          -
          -
          -
          -
          - -
          -
          - -
          -
          - -
          -
          -
          -
          + + + + + + + + + + + + + + + + + + + + + + + +
          ЧтоЗвездочки ^^НачалоКонецСтоимостьУчастники
          sdfkjsjdfЧтоЗвездочки ^^НачалоКонецСУчастники
          + + + + + + + + + \ No newline at end of file diff --git a/Task/style.css b/Task/style.css index d8909d4..94d0f42 100644 --- a/Task/style.css +++ b/Task/style.css @@ -17,8 +17,13 @@ overflow: hidden; } -.Error { +.ErrorActivateOff { + visibility:hidden +} + +.ErrorActivateOn { color: red; + visibility:show } .TitleAddEvent { From cd25f24a9f47aacbfc6dd40de867f3f5987c6e76 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 08:09:00 +0600 Subject: [PATCH 04/11] =?UTF-8?q?=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D1=88=D0=BE=D0=B9=20=D1=80=D0=B5=D1=84=D0=B0=D0=BA=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=B8=D0=BD=D0=B3=20=D0=9F=D1=80=D0=BE=D1=88=D0=B5=D0=BB?= =?UTF-8?q?=20=D0=B1=D0=BE=D0=BB=D0=B5=D0=B5=20=D0=BC=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20jsLint=20=D0=9D=D0=B0=D0=BF=D0=B8=D1=81=D0=B0=D0=BB=20?= =?UTF-8?q?JS=20Doc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/BaseEvent.js | 59 +++-- Task/Scripts/CalendaryErrorManager.js | 34 ++- Task/Scripts/Collection.js | 32 ++- Task/Scripts/DOMErrorManager.js | 34 ++- .../Scripts/{Validator.js => DOMValidator.js} | 11 +- Task/Scripts/Event.js | 47 ++-- Task/Scripts/Model.js | 25 +- Task/Scripts/calendary.js | 224 ++++++++++-------- Task/Scripts/run.js | 45 ++++ Task/Scripts/testData.js | 3 +- Task/index.html | 3 +- 11 files changed, 358 insertions(+), 159 deletions(-) rename Task/Scripts/{Validator.js => DOMValidator.js} (78%) create mode 100644 Task/Scripts/run.js diff --git a/Task/Scripts/BaseEvent.js b/Task/Scripts/BaseEvent.js index 928d932..19dcf06 100644 --- a/Task/Scripts/BaseEvent.js +++ b/Task/Scripts/BaseEvent.js @@ -1,20 +1,9 @@ /*global Collection: true*/ /** - * Shell for "sql" operations with Array Events. - * @prototype {Collection} - * @constructoro - * @method {pastEventBase} - Создает BaseEvent с пропущенными событиями - * @method {pastEventBase} - Создает BaseEvent с грядущими событиями - * @method {nowEventBase} - Создает BaseEvent с текущими событиями - * @method {withFriend} - Создает BaseEvent с событиями, в которых принимал участие определенный человек - * @method {getEventAfterDay} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через день - * @method {getEventAfterWeek} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через неделю - * @method {getEventAfterMonth} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через месяц - * @method {getEventFromPeriod} - Создает BaseEvent с событиями, которые лежат между двумы датами [fromDate, toDate] - * @method {getEventAfterMonth} - Создает BaseEvent с теми же событиями, но отсортированными по убыванию звезд - * @method {getEventAfterMonth} - Создает BaseEvent с теми же событиями, но отсортироваными по возрастанию даты - * @example - Смотри файл с тестами... + * Создает оболочку над массивом событий, предоставляющую "sql" подобные операции + * @class Оболочка над массивом событий. + * @augments Collection */ function BaseEvent(events) { "use strict"; @@ -28,8 +17,15 @@ BaseEvent.prototype = Object.create(Collection.prototype, { configurable: true } }); +/** + *@field {BaseEvent} - ссылка на "родной" конструктор +*/ BaseEvent.prototype.constructor = BaseEvent; -//пропущенные, текущие, будущие события + +/** + *@function Возвращает новую оболочку, но уже только с прошедшими событиями + *@return {BaseEvent} +*/ BaseEvent.prototype.pastEventBase = function () { "use strict"; var currentDate = new Date(); @@ -37,6 +33,9 @@ BaseEvent.prototype.pastEventBase = function () { return event.end.getTime() < currentDate.getTime(); }); }; +/** + *@function Возвращает новую оболочку, но уже только с ненаступившими событиями +*/ BaseEvent.prototype.nextEventBase = function () { "use strict"; var currentDate = new Date(); @@ -44,6 +43,9 @@ BaseEvent.prototype.nextEventBase = function () { return event.start.getTime() > currentDate.getTime(); }); }; +/** + *@function Возвращает новую оболочку, но уже с событиями, которые идут в данный момент +*/ BaseEvent.prototype.nowEventBase = function () { "use strict"; var currentDate = new Date(); @@ -51,7 +53,10 @@ BaseEvent.prototype.nowEventBase = function () { return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime()); }); }; -//событие с участием друга (Друг отношение рефлексивное ^^) + +/** + *@function Возвращает новую оболочку, но уже с событиями, в которых участвует определенный человек +*/ BaseEvent.prototype.withFriend = function (myFriend) { "use strict"; return this.filter(function (event) { @@ -60,7 +65,9 @@ BaseEvent.prototype.withFriend = function (myFriend) { }); }); }; -// События через период времени день, неделя, месяц +/** + *@function Возвращает новую оболочку, но уже с событиями, которые будут через неделю +*/ BaseEvent.prototype.getEventAfterWeek = function () { "use strict"; var currentDate = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000); @@ -68,6 +75,9 @@ BaseEvent.prototype.getEventAfterWeek = function () { return event.start.getTime() > currentDate.getTime(); }); }; +/** + *@function Возвращает новую оболочку, но уже с событиями, которые будут через день +*/ BaseEvent.prototype.getEventAfterDay = function () { "use strict"; var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000); @@ -75,6 +85,9 @@ BaseEvent.prototype.getEventAfterDay = function () { return event.start.getTime() > currentDate.getTime(); }); }; +/** + *@function Возвращает новую оболочку, но уже с событиями, которые будут через месяц +*/ BaseEvent.prototype.getEventAfterMonth = function () { "use strict"; var currentDate = new Date(); @@ -87,13 +100,20 @@ BaseEvent.prototype.getEventAfterMonth = function () { return event.start.getTime() > currentDate.getTime(); }); }; -// События за период +/** + *@function Возвращает новую оболочку, но уже с событиями, которые будут в определенный период + *@param {Date} fromDate - начала периода + *@param {Date} toDate - конец периода +*/ BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) { "use strict"; return this.filter(function (event) { return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime()); }); }; +/** + *@function Возвращает новую оболочку c теми же событиями, но отсортированными по уменьшению количества звезд +*/ BaseEvent.prototype.sortByStars = function (ascending) { "use strict"; var comparer = function compare(a, b) { @@ -107,6 +127,9 @@ BaseEvent.prototype.sortByStars = function (ascending) { }; return this.sortBy(comparer, ascending); }; +/** + *@function Возвращает новую оболочку c теми же событиями, но отсортированными по дате +*/ BaseEvent.prototype.sortByDate = function (ascending) { "use strict"; var comparer = function compare(a, b) { diff --git a/Task/Scripts/CalendaryErrorManager.js b/Task/Scripts/CalendaryErrorManager.js index 9bcf582..e863ff7 100644 --- a/Task/Scripts/CalendaryErrorManager.js +++ b/Task/Scripts/CalendaryErrorManager.js @@ -1,4 +1,9 @@ -var CalendaryErrorManager = function (errorClassName) { +/** + * @class Класс содержит обработчики ошибок при изменении элементов DOM связанных с календорем + * @augments DOMErrorManager + */ + +var CalendaryErrorManager = function (errorClassName) { DOMErrorManager.call(this, errorClassName); } CalendaryErrorManager.prototype = Object.create(DOMErrorManager.prototype, { @@ -9,24 +14,39 @@ CalendaryErrorManager.prototype = Object.create(DOMErrorManager.prototype, { configurable: true } }); - +/** + * @function Обработчик ошибок объекта, содержащий начальное и конечное время + * @param {DOMdivElement} хранилище, содержащее таймер. + */ CalendaryErrorManager.prototype.changeTime = function (timer) { - var textError = Validator.isTimeInterval(timer); + var textError = DOMValidator.isTimeInterval(timer); this.changeTextError(timer, textError); } +/** + * @function Обработчик ошибок объекта, содержащий координаты + * @param {DOMdivElement} хранилище, содержащее координаты. + */ CalendaryErrorManager.prototype.changeCoordinate = function (coordinates) { - var textError = Validator.isCoordinate(coordinates); + var textError = DOMValidator.isCoordinate(coordinates); this.changeTextError(coordinates, textError); } +/** + * @function Обработчик ошибок объекта, содержащий важныее данные + * @param {DOMdivElement} хранилище, содержащее важное поле. + */ CalendaryErrorManager.prototype.changeImportantStringField = function (importantStringField) { - var textError = Validator.isImportantStringField(importantStringField,5,20); + var textError = DOMValidator.isImportantStringField(importantStringField, 5, 20); this.changeTextError(importantStringField, textError); } +/** + * @function Обработчик ошибок объекта, содержащий поле с положительным числом + * @param {DOMdivElement} хранилище, содержащее поле с положительным числом. + */ CalendaryErrorManager.prototype.changePositiveNumber = function (positiveNumber) { - var textError = Validator.isPositiveNumber(positiveNumber); + var textError = DOMValidator.isPositiveNumber(positiveNumber); this.changeTextError(positiveNumber, textError); } CalendaryErrorManager.prototype.changeStars = function (stars) { - var textError = Validator.isStars(stars); + var textError = DOMValidator.isStars(stars); this.changeTextError(stars, textError); } \ No newline at end of file diff --git a/Task/Scripts/Collection.js b/Task/Scripts/Collection.js index f27b45b..77907da 100644 --- a/Task/Scripts/Collection.js +++ b/Task/Scripts/Collection.js @@ -1,15 +1,11 @@ /*global Collection: true*/ /** - * Creates an instance of Event. - * - * @param {data} - start elements of collection - * @field {items} - elements of collection - * @method {add} - add element in current collection and return it - * @method {filter} - filter elements of current collection and return it - * @method {sortBy} - sort elements of current collection and return it - */ -Collection = function (otherItems) { + * Создает оболочка для хранения массива объектов с операциями по извлечению более конкретных элементов + * @class Оболочка для храения массива объектов + * @param {Array} элементы коллекции +*/ +var Collection = function (otherItems) { "use strict"; var item; this.items = []; @@ -19,17 +15,35 @@ Collection = function (otherItems) { } } }; +/** + * @field {Collection} хранит ссылку на родной конструктор + */ Collection.prototype.constructor = Collection +/** + * @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj + * @return {instanceof this.constructor} + */ Collection.prototype.add = function (obj) { "use strict"; var newEvents = this.items.concat([obj]); return new this.constructor(newEvents); }; +/** + * @function создает новую коллекцию элементов с отфильтрованными элементами + * @param {Function} - делегат + * @return {instanceof this.constructor} +*/ Collection.prototype.filter = function (selector) { "use strict"; var newItems = this.items.filter(selector); return new this.constructor(newItems); }; +/** + * @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj + * @param {Function} - компаратор + * @param {Function} - инвертировать, ли результат + * @return {instanceof this.constructor} + */ Collection.prototype.sortBy = function (comparator, isInvert) { "use strict"; var newItems = [].concat(this.items); diff --git a/Task/Scripts/DOMErrorManager.js b/Task/Scripts/DOMErrorManager.js index f588af1..b0928e3 100644 --- a/Task/Scripts/DOMErrorManager.js +++ b/Task/Scripts/DOMErrorManager.js @@ -1,21 +1,43 @@ -var DOMErrorManager = function (errorClassName) { +/** + + * @class * Класс содержит обработчики ошибок при изменении элементов DOM + */ +var DOMErrorManager = function (errorClassName) { this.errorClassName = errorClassName; } +/** + * @function Обработчик ошибок объекта, содержащий начальное и конечное время + * @param {DOMdivElement} хранилище, содержащее таймер. + */ DOMErrorManager.prototype.isFieldWithError = function (element) { var lastElement = element.querySelector("."+this.errorClassName); return !!lastElement; } +/** + * @function Устанавливает в передаваемый элемент ошибку + * @param {DOMdivElement} element на что устанавливаем ошибку. + * @param {String} text текст ошибки. + */ DOMErrorManager.prototype.setTextError = function (element, text) { - var newError = document.createElement("span"); - var newTextError = document.createTextNode(text); + var newError = document.createElement("span"), + newTextError = document.createTextNode(text); newError.className = this.errorClassName; newError.appendChild(newTextError); element.appendChild(newError); } +/** + * @function Стереть ошибку + * @param {DOMdivElement} element на что устанавливаем ошибку. + */ DOMErrorManager.prototype.removeTextError = function (element) { var error = element.querySelector("."+this.errorClassName); element.removeChild(error); } +/** + * @function Изменить или стереть ошибку в зависимости от того есть она или нет + * @param {DOMdivElement} element хранилище элемента + * @param {DOMdivElement} element текст сообщения с ошибкой + */ DOMErrorManager.prototype.changeTextError = function (element, errorText) { var currentErrorState = this.isFieldWithError(element); if (errorText === "") { @@ -31,9 +53,13 @@ DOMErrorManager.prototype.changeTextError = function (element, errorText) { this.setTextError(element, errorText); } } +/** + * @function Удалить всех детей элемента + * @param {DOMdivElement} хранилище детей + */ DOMErrorManager.prototype.removeAllChildren = function(element) { var children = element.childNodes; while(children.length) { element.removeChild(children[0]) } -} +} \ No newline at end of file diff --git a/Task/Scripts/Validator.js b/Task/Scripts/DOMValidator.js similarity index 78% rename from Task/Scripts/Validator.js rename to Task/Scripts/DOMValidator.js index 32d1c2b..eb9d540 100644 --- a/Task/Scripts/Validator.js +++ b/Task/Scripts/DOMValidator.js @@ -1,4 +1,13 @@ -var Validator = { +/** + * + * @namespace Пространство имен для DOM обработчиков ошибок + * @field {Function} isTimeInterval - проверяет валидно ли поле содержащее промежуток времени + * @field {Function} isCoordinate - проверяет валидно ли поле содержащая координаты двух мерного пространства + * @field {Function} isImportantStringField - проверяет валидно ли поле содержащая строку определенных размеров + * @field {Function} isStars - проверяет валидно ли поле содержащее рейтинг + * @field {Function} isPositiveNumber - проверяет валидно ли поле содержащее целое положительное число + */ +var DOMValidator = { "isTimeInterval" : function (divWithTimeInterval) { var startDate = new Date(divWithTimeInterval.querySelector(".StartDate").value); var finishDate = new Date(divWithTimeInterval.querySelector(".FinishDate").value); diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index 2658547..6c661f6 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -1,19 +1,13 @@ /*global Model: true*/ /** - * Creates an instance of Event. - * - * @prototype {Model} - * @param {data} - is start event - * @field {start} - is start event - * @field {end} - is end event - * @field {id} - is id - * @field {location} - location - is gps and name of event's place - * @field {participants} - participants - array of participants - * @field {stars} - is assess the importance of the event - * @field {cost} - is price for entry - * @method {setLocation} - is setter for location's field - * @method {leaveMark} - is setter for stars's field (0,1,2,3,4,5 - validate value) - */ + * Создает новое событие в календаре + * @class Событие в календаре + * @field {Number} - id Индификационный номер объекта по идее тут должен быть GUID + * @field {Object} - location объект содержащий локационные данные о событии + название события + * @field {Number} - реитинг + * @field {Number} - Цена посещения + * @augments Model +*/ function Event(data) { "use strict"; this.id = Math.random(); @@ -37,6 +31,10 @@ Event.prototype = Object.create(Model.prototype, { configurable: true } }); +/** + * @function Функция, проверяющая корректность даты + * @return {bool} +*/ Event.prototype.dateValidator = function (date) { "use strict"; if (Object.prototype.toString.call(date) === "[object Date]") { @@ -46,6 +44,11 @@ Event.prototype.dateValidator = function (date) { } return false; }; +/** + * @function set-ер установления локации события + * @field gps координаты в дву мерном пространстве + * @field название события +*/ Event.prototype.setLocation = function (gps, name) { "use strict"; if (typeof gps !== "undefined" && typeof gps.x !== "undefined" && typeof gps.y !== "undefined" && typeof name === "string") { @@ -58,6 +61,10 @@ Event.prototype.setLocation = function (gps, name) { }; } }; +/** + * @function Коррекция значения рейтинга + * @return {Number} 0,1,2,3,4,5 +*/ Event.prototype.leaveMark = function (stars) { "use strict"; if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) { @@ -69,6 +76,10 @@ Event.prototype.leaveMark = function (stars) { stars = (stars - (stars % 1)); //обрезаем дробную часть return stars; }; +/** + * @function Проверяет объект на корректность + * @field {Event} event - то что проверяем +*/ Event.prototype.validate = function (event) { "use strict"; if (event.cost < 0) { @@ -87,9 +98,17 @@ Event.prototype.validate = function (event) { throw new Error("Даты начала и конца перепутаны"); } }; +/** + * @function Функция, печатающие значение локационных данных объекта + * @return {String} [location], (x, y) +*/ Event.prototype.locationToString = function() { return this.location.nameLocation + ", (" + this.location.gps.x + ";" + this.location.gps.y + ")"; } +/** + * @function Функция, печатающие значение рейтинга в звездочках + * @return {String} ,*,**,***,****,***** +*/ Event.prototype.starsToString= function() { var res = ""; for(var i = 0; i < this.stars; i++) { diff --git a/Task/Scripts/Model.js b/Task/Scripts/Model.js index 2d18237..306a366 100644 --- a/Task/Scripts/Model.js +++ b/Task/Scripts/Model.js @@ -1,13 +1,8 @@  /** - * Abstract class for Event - * - * @param {data} - start elements of collection - * @field {items} - elements of collection - * @method {get} - get value of field - * @method {set} - set attributes - * @method {validate} - validate - */ + * @class Абстрактный класс объектов ООП + * @param {data} - копируемый объект +*/ var Model = function (data) { "use strict"; var nameField; @@ -15,8 +10,10 @@ var Model = function (data) { this[nameField] = data[nameField]; } }; -Model.prototype.constructor = Model; - +/** + * @function setter + * @param {Object} - присваиваемый объект +*/ Model.prototype.set = function (attributes) { "use strict"; var nameAttr; @@ -28,6 +25,11 @@ Model.prototype.set = function (attributes) { } } }; +/** + * @function getter + * @param {String} имя поля + * @return {Object} +*/ Model.prototype.get = function (attribute) { "use strict"; if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") { @@ -35,6 +37,9 @@ Model.prototype.get = function (attribute) { } return this[attribute]; }; +/** + * @function Проверяющая коррекцию объекта +*/ Model.prototype.validate = function () { "use strict"; throw new Error('this is Abstract method'); diff --git a/Task/Scripts/calendary.js b/Task/Scripts/calendary.js index f8c1876..be853f6 100644 --- a/Task/Scripts/calendary.js +++ b/Task/Scripts/calendary.js @@ -1,4 +1,17 @@ -var Calendary= function (who) { +/*global document: true*/ +/*global initTestBase: true*/ +/*global CalendaryErrorManager: true*/ +/** + * + * @namespace Пространство имен для календаря + * @field {EventFactory} объект, хранящий ссылки на inputы необходимые для создания нового события + * @field eventList ссылка на дом объект, хранящий список событий + * @field eventBase все события пользователя + * @field errorManager объект хранящий функции для валидации полей в дом и хранящий в себе некоторые тривиальные операции + * @field currentFilters фильтры наложенные на текущие события + */ +function Calendary() { + "use strict"; this.whois = "Alex.Mangin"; this.EventFactory = { "timer" : document.getElementById("NewEventTimeInterval"), @@ -6,21 +19,42 @@ "coordinate" : document.getElementById("NewEventCoordinate"), "stars" : document.getElementById("NewEventStars"), "cost" : document.getElementById("NewEventCost"), - "parties" : document.querySelector("#NewEventPartiesList ol"), + "parties" : document.querySelector("#NewEventPartiesList ol") }; this.eventList = document.getElementById("eventList"); this.eventBase = initTestBase(); this.errorManager = new CalendaryErrorManager("Error"); this.currentFilters = []; } -Calendary.prototype.ApplyFilter = function(filters) { - var base = this.eventBase; - for(var i in filters) { +/** + * @function - функция, возвращающая текущую базу событий, но с наложенными фильтрами + * @param {[Function]} фильтры в виде функции + * @return {BaseEvent} +*/ +Calendary.prototype.ApplyFilter = function (filters) { + "use strict"; + var base = this.eventBase, + i; + for (i = 0; i < filters.length; i += 1) { base = filters[i].call(base); } return base; } -Calendary.prototype.CreateEvent = function() { +/** + * @function - функция пытается создать событие из данных с формы +*/ + +Calendary.prototype.CreateEvent = function () { + "use strict"; + var parties = [], + partyList, + i, + eventDate, + inputs, + errors, + docfrag, + io, + input; if (!this.isCorrecteNeedFields()) { this.changeNeed(); this.changeAddition(); @@ -32,17 +66,19 @@ Calendary.prototype.CreateEvent = function() { return; } } - var parties = []; - var partyList = this.EventFactory.parties.querySelectorAll(" input"); - for(var i = 0; i - + + \ No newline at end of file From 794f9cbdafa172a62b20e3ffe036c844a6106fa0 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 08:42:18 +0600 Subject: [PATCH 05/11] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B4=D0=B2=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1?= =?UTF-8?q?=D0=BA=D0=B8=20=D1=83=D0=B1=D0=B8=D0=B2=D0=B0=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B1=D1=80=D0=B0=D1=83=D0=B7=D0=B5=D1=80=20)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/calendary.js | 29 +++++++++++++++-------------- Task/Scripts/run.js | 4 ++-- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/Task/Scripts/calendary.js b/Task/Scripts/calendary.js index be853f6..d229e55 100644 --- a/Task/Scripts/calendary.js +++ b/Task/Scripts/calendary.js @@ -35,7 +35,7 @@ Calendary.prototype.ApplyFilter = function (filters) { "use strict"; var base = this.eventBase, i; - for (i = 0; i < filters.length; i += 1) { + for (i = 0; i < filters.length; i = i + 1) { base = filters[i].call(base); } return base; @@ -67,7 +67,7 @@ Calendary.prototype.CreateEvent = function () { } } partyList = this.EventFactory.parties.querySelectorAll(" input"); - for ( i = 0; i < partyList.length; i += 1) { + for ( i = 0; i < partyList.length; i = i + 1) { if (partyList[i].value && partyList[i].value !== "") { parties.push({"name" : partyList[i].value}); } @@ -99,13 +99,13 @@ Calendary.prototype.CreateEvent = function () { } this.eventBase = this.eventBase.add(new Event(eventDate)); inputs = document.querySelectorAll('#eventFactory input'); - for (i = 0; i < inputs.length; i += 1) { + for (i = 0; i < inputs.length; i = i + 1) { if (inputs[i].type === "text" || inputs[i].type === "date") { inputs[i].value = ""; } } errors = document.querySelectorAll('#eventFactory .Error'); - for (i = 0; i < errors.length; i += 1) { + for (i = 0; i < errors.length; i = i + 1) { document.remove(errors); } this.errorManager.removeAllChildren(this.EventFactory.parties); @@ -114,7 +114,7 @@ Calendary.prototype.CreateEvent = function () { input = document.createElement("input"); input.type = "text"; io.appendChild(input); - for (i = 0; i < 3; i += 1) { + for (i = 0; i < 3; i = i + 1) { docfrag.appendChild(io.cloneNode(true)); } this.EventFactory.parties.appendChild(docfrag); @@ -130,14 +130,15 @@ Calendary.prototype.UpdateShowList = function () { var rowTable = document.createElement("tr"), cellTable = document.createElement("td"), i; - for (i = 0; i < 7; i += 1) { + for (i = 0; i < 7; i = i + 1) { rowTable.appendChild(cellTable.cloneNode(false)); } return rowTable; }()), listParty, n, - aDOMParty; + aDOMParty, + i; row.children[0].appendChild(document.createTextNode(number)); row.children[1].appendChild(document.createTextNode(event.locationToString())); row.children[2].appendChild(document.createTextNode(event.starsToString())); @@ -147,7 +148,7 @@ Calendary.prototype.UpdateShowList = function () { listParty = document.createElement("select"); for (i = 0; i < event.parties.length; i += 1) { aDOMParty = document.createElement("option"); - aDOMParty.appendChild(document.createTextNode(event.parties[n].name)); + aDOMParty.appendChild(document.createTextNode(event.parties[i].name)); listParty.appendChild(aDOMParty); } if (event.parties.length) { @@ -162,7 +163,7 @@ Calendary.prototype.UpdateShowList = function () { this.errorManager.removeAllChildren(this.eventList); newEventList = document.createDocumentFragment(); currentBase = this.ApplyFilter(this.currentFilters); - for (i = 0; i < currentBase.items.length; i += 1) { + for (i = 0; i < currentBase.items.length; i = i + 1) { event = currentBase.items[i]; newEventList.appendChild(createEventRow(i + 1, event)); } @@ -227,25 +228,25 @@ Calendary.prototype.updateFilter = function () { partys, nonEmptyParty, partyFilter; - for (i = 0; i < filterRadios.length; i += 1) { + for (i = 0; i < filterRadios.length; i = i + 1) { radioButton = filterRadios[i]; if (radioButton.checked && radioButton.checked === true && radioButton.value != "None") { - // var nameFunc = radioButton.value.toString(); + var nameFunc = radioButton.value.toString(); newFilters.push(function() { - return this[radioButton.value.toString()](); + return this[nameFunc](); }); } } partys = document.querySelectorAll("#FilterFriens input"); nonEmptyParty = []; - for (i = 0; i < partys.length; i += 1) { + for (i = 0; i < partys.length; i = i + 1) { if (partys[i].value != "") { nonEmptyParty.push(partys[i].value); } } partyFilter = function() { var base = this, i - for (i = 0; i < nonEmptyParty.length; i += 1) { + for (i = 0; i < nonEmptyParty.length; i = i + 1) { base = base.withFriend({ "name": nonEmptyParty[i] }); diff --git a/Task/Scripts/run.js b/Task/Scripts/run.js index 4464a21..6d9bac3 100644 --- a/Task/Scripts/run.js +++ b/Task/Scripts/run.js @@ -8,7 +8,7 @@ */ function setInt(){ var calendary = new Calendary(); - calendary.UpdateShowList(); + calendary.UpdateShowList(); calendary.EventFactory.timer.addEventListener('blur', function() { calendary.errorManager.changeTime(this); }, true); @@ -32,7 +32,7 @@ function setInt(){ calendary.addFriend(calendary.EventFactory.parties); }, false); var filterRadios =document.querySelectorAll("#FilterEventList input[type = radio]"); - for(var i = 0; i < filterRadios.length; i += 1) { + for(var i = 0; i < filterRadios.length; i = i + 1) { filterRadios[i].addEventListener('click', function() { calendary.updateFilter(); calendary.UpdateShowList(); From 305d88f5f85ebc443a18b0b47806cfb99d093d27 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 18:25:03 +0600 Subject: [PATCH 06/11] JSDoc fix --- Task/Scripts/BaseEvent.js | 60 ++++++++++++++++++--------- Task/Scripts/CalendaryErrorManager.js | 29 ++++++++----- Task/Scripts/Collection.js | 38 ++++++++++------- Task/Scripts/DOMErrorManager.js | 43 ++++++++++--------- Task/Scripts/DOMValidator.js | 14 +++---- Task/Scripts/Event.js | 47 ++++++++++++--------- Task/Scripts/Model.js | 20 +++++---- Task/Scripts/calendary.js | 58 +++++++++++++------------- 8 files changed, 180 insertions(+), 129 deletions(-) diff --git a/Task/Scripts/BaseEvent.js b/Task/Scripts/BaseEvent.js index 19dcf06..6c33ba0 100644 --- a/Task/Scripts/BaseEvent.js +++ b/Task/Scripts/BaseEvent.js @@ -1,9 +1,10 @@ /*global Collection: true*/ /** - * Создает оболочку над массивом событий, предоставляющую "sql" подобные операции - * @class Оболочка над массивом событий. - * @augments Collection + * Создает оболочку над массивом событий, предоставляющую "sql" подобные операции + * + * @class Оболочка над массивом событий. + * @augments Collection */ function BaseEvent(events) { "use strict"; @@ -18,13 +19,15 @@ BaseEvent.prototype = Object.create(Collection.prototype, { } }); /** - *@field {BaseEvent} - ссылка на "родной" конструктор + * + *@field {BaseEvent} - ссылка на "родной" конструктор */ BaseEvent.prototype.constructor = BaseEvent; /** - *@function Возвращает новую оболочку, но уже только с прошедшими событиями - *@return {BaseEvent} + *@function Возвращает новую оболочку, но уже только с прошедшими событиями + * + *@return {BaseEvent} */ BaseEvent.prototype.pastEventBase = function () { "use strict"; @@ -34,7 +37,9 @@ BaseEvent.prototype.pastEventBase = function () { }); }; /** - *@function Возвращает новую оболочку, но уже только с ненаступившими событиями + * @function Возвращает новую оболочку, но уже только с ненаступившими событиями + * + * @return {BaseEvent} */ BaseEvent.prototype.nextEventBase = function () { "use strict"; @@ -44,7 +49,9 @@ BaseEvent.prototype.nextEventBase = function () { }); }; /** - *@function Возвращает новую оболочку, но уже с событиями, которые идут в данный момент + * @function Возвращает новую оболочку, но уже с событиями, которые идут в данный момент + * + * @return */ BaseEvent.prototype.nowEventBase = function () { "use strict"; @@ -55,8 +62,10 @@ BaseEvent.prototype.nowEventBase = function () { }; /** - *@function Возвращает новую оболочку, но уже с событиями, в которых участвует определенный человек -*/ + * @function Возвращает новую оболочку, но уже с событиями, в которых участвует определенный человек + * + * @return + */ BaseEvent.prototype.withFriend = function (myFriend) { "use strict"; return this.filter(function (event) { @@ -66,7 +75,9 @@ BaseEvent.prototype.withFriend = function (myFriend) { }); }; /** - *@function Возвращает новую оболочку, но уже с событиями, которые будут через неделю + * @function Возвращает новую оболочку, но уже с событиями, которые будут через неделю + * + * @return {BaseEvent} */ BaseEvent.prototype.getEventAfterWeek = function () { "use strict"; @@ -76,7 +87,9 @@ BaseEvent.prototype.getEventAfterWeek = function () { }); }; /** - *@function Возвращает новую оболочку, но уже с событиями, которые будут через день + * @function Возвращает новую оболочку, но уже с событиями, которые будут через день + * + * @return {BaseEvent} */ BaseEvent.prototype.getEventAfterDay = function () { "use strict"; @@ -86,7 +99,9 @@ BaseEvent.prototype.getEventAfterDay = function () { }); }; /** - *@function Возвращает новую оболочку, но уже с событиями, которые будут через месяц + * @function Возвращает новую оболочку, но уже с событиями, которые будут через месяц + * + * @return {BaseEvent} */ BaseEvent.prototype.getEventAfterMonth = function () { "use strict"; @@ -101,9 +116,12 @@ BaseEvent.prototype.getEventAfterMonth = function () { }); }; /** - *@function Возвращает новую оболочку, но уже с событиями, которые будут в определенный период - *@param {Date} fromDate - начала периода - *@param {Date} toDate - конец периода + * @function Возвращает новую оболочку, но уже с событиями, которые будут в определенный период + * + * @param {Date} fromDate - начала периода + * @param {Date} toDate - конец периода + * + * @return */ BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) { "use strict"; @@ -112,7 +130,9 @@ BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) { }); }; /** - *@function Возвращает новую оболочку c теми же событиями, но отсортированными по уменьшению количества звезд + * @function Возвращает новую оболочку c теми же событиями, но отсортированными по уменьшению количества звезд + * + * @return {BaseEvent} */ BaseEvent.prototype.sortByStars = function (ascending) { "use strict"; @@ -128,8 +148,10 @@ BaseEvent.prototype.sortByStars = function (ascending) { return this.sortBy(comparer, ascending); }; /** - *@function Возвращает новую оболочку c теми же событиями, но отсортированными по дате -*/ + * @function Возвращает новую оболочку c теми же событиями, но отсортированными по дате + * + * @return {BaseEvent} + */ BaseEvent.prototype.sortByDate = function (ascending) { "use strict"; var comparer = function compare(a, b) { diff --git a/Task/Scripts/CalendaryErrorManager.js b/Task/Scripts/CalendaryErrorManager.js index e863ff7..b4083f4 100644 --- a/Task/Scripts/CalendaryErrorManager.js +++ b/Task/Scripts/CalendaryErrorManager.js @@ -1,6 +1,6 @@ /** - * @class Класс содержит обработчики ошибок при изменении элементов DOM связанных с календорем - * @augments DOMErrorManager + * @class Класс содержит обработчики ошибок при изменении элементов DOM связанных с календорем + * @augments DOMErrorManager */ var CalendaryErrorManager = function (errorClassName) { @@ -15,37 +15,46 @@ CalendaryErrorManager.prototype = Object.create(DOMErrorManager.prototype, { } }); /** - * @function Обработчик ошибок объекта, содержащий начальное и конечное время - * @param {DOMdivElement} хранилище, содержащее таймер. + * @function Обработчик ошибок объекта, содержащий начальное и конечное время + * + * @param {DOMdivElement} хранилище, содержащее таймер. */ CalendaryErrorManager.prototype.changeTime = function (timer) { var textError = DOMValidator.isTimeInterval(timer); this.changeTextError(timer, textError); } /** - * @function Обработчик ошибок объекта, содержащий координаты - * @param {DOMdivElement} хранилище, содержащее координаты. + * @function Обработчик ошибок объекта, содержащий координаты + * + * @param {DOMdivElement} хранилище, содержащее координаты. */ CalendaryErrorManager.prototype.changeCoordinate = function (coordinates) { var textError = DOMValidator.isCoordinate(coordinates); this.changeTextError(coordinates, textError); } /** - * @function Обработчик ошибок объекта, содержащий важныее данные - * @param {DOMdivElement} хранилище, содержащее важное поле. + * @function Обработчик ошибок объекта, содержащий важныее данные + * + * @param {DOMdivElement} хранилище, содержащее важное поле. */ CalendaryErrorManager.prototype.changeImportantStringField = function (importantStringField) { var textError = DOMValidator.isImportantStringField(importantStringField, 5, 20); this.changeTextError(importantStringField, textError); } /** - * @function Обработчик ошибок объекта, содержащий поле с положительным числом - * @param {DOMdivElement} хранилище, содержащее поле с положительным числом. + * @function Обработчик ошибок объекта, содержащий поле с положительным числом + * + * @param {DOMdivElement} хранилище, содержащее поле с положительным числом. */ CalendaryErrorManager.prototype.changePositiveNumber = function (positiveNumber) { var textError = DOMValidator.isPositiveNumber(positiveNumber); this.changeTextError(positiveNumber, textError); } +/** + * @function Обработчик ошибок объекта, содержащий поле с рейтингом + * + * @param {DOMdivElement} хранилище, содержащее поле с положительным числом. + */ CalendaryErrorManager.prototype.changeStars = function (stars) { var textError = DOMValidator.isStars(stars); this.changeTextError(stars, textError); diff --git a/Task/Scripts/Collection.js b/Task/Scripts/Collection.js index 77907da..6894f4c 100644 --- a/Task/Scripts/Collection.js +++ b/Task/Scripts/Collection.js @@ -1,9 +1,10 @@ /*global Collection: true*/ /** - * Создает оболочка для хранения массива объектов с операциями по извлечению более конкретных элементов - * @class Оболочка для храения массива объектов - * @param {Array} элементы коллекции + * Создает оболочка для хранения массива объектов с операциями по извлечению более конкретных элементов + * @class Оболочка для храения массива объектов + * + * @param {Array} элементы коллекции */ var Collection = function (otherItems) { "use strict"; @@ -16,22 +17,25 @@ var Collection = function (otherItems) { } }; /** - * @field {Collection} хранит ссылку на родной конструктор - */ + * @field {Collection} хранит ссылку на родной конструктор +*/ Collection.prototype.constructor = Collection /** - * @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj - * @return {instanceof this.constructor} - */ + * @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj + * + * @return {instanceof this.constructor} +*/ Collection.prototype.add = function (obj) { "use strict"; var newEvents = this.items.concat([obj]); return new this.constructor(newEvents); }; /** - * @function создает новую коллекцию элементов с отфильтрованными элементами - * @param {Function} - делегат - * @return {instanceof this.constructor} + * @function создает новую коллекцию элементов с отфильтрованными элементами + * + * @param {Function} - делегат + * + * @return {instanceof this.constructor} */ Collection.prototype.filter = function (selector) { "use strict"; @@ -39,11 +43,13 @@ Collection.prototype.filter = function (selector) { return new this.constructor(newItems); }; /** - * @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj - * @param {Function} - компаратор - * @param {Function} - инвертировать, ли результат - * @return {instanceof this.constructor} - */ +* @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj + * + * @param {Function} - компаратор + * @param {Function} - инвертировать, ли результат + * + * @return {instanceof this.constructor} +*/ Collection.prototype.sortBy = function (comparator, isInvert) { "use strict"; var newItems = [].concat(this.items); diff --git a/Task/Scripts/DOMErrorManager.js b/Task/Scripts/DOMErrorManager.js index b0928e3..01287f6 100644 --- a/Task/Scripts/DOMErrorManager.js +++ b/Task/Scripts/DOMErrorManager.js @@ -1,23 +1,23 @@ /** - - * @class * Класс содержит обработчики ошибок при изменении элементов DOM - */ + * @class * Класс содержит обработчики ошибок при изменении элементов DOM +*/ var DOMErrorManager = function (errorClassName) { this.errorClassName = errorClassName; } /** - * @function Обработчик ошибок объекта, содержащий начальное и конечное время - * @param {DOMdivElement} хранилище, содержащее таймер. - */ + * @function Обработчик ошибок объекта, содержащий начальное и конечное время + * @param {DOMdivElement} хранилище, содержащее таймер. +*/ DOMErrorManager.prototype.isFieldWithError = function (element) { var lastElement = element.querySelector("."+this.errorClassName); return !!lastElement; } /** - * @function Устанавливает в передаваемый элемент ошибку - * @param {DOMdivElement} element на что устанавливаем ошибку. - * @param {String} text текст ошибки. - */ + * @function Устанавливает в передаваемый элемент ошибку + * + * @param {DOMdivElement} element на что устанавливаем ошибку. + * @param {String} text текст ошибки. +*/ DOMErrorManager.prototype.setTextError = function (element, text) { var newError = document.createElement("span"), newTextError = document.createTextNode(text); @@ -26,18 +26,20 @@ DOMErrorManager.prototype.setTextError = function (element, text) { element.appendChild(newError); } /** - * @function Стереть ошибку - * @param {DOMdivElement} element на что устанавливаем ошибку. - */ + * @function Стереть ошибку + * + * @param {DOMdivElement} element на что устанавливаем ошибку. +*/ DOMErrorManager.prototype.removeTextError = function (element) { var error = element.querySelector("."+this.errorClassName); element.removeChild(error); } /** - * @function Изменить или стереть ошибку в зависимости от того есть она или нет - * @param {DOMdivElement} element хранилище элемента - * @param {DOMdivElement} element текст сообщения с ошибкой - */ +* @function Изменить или стереть ошибку в зависимости от того есть она или нет +* +* @param {DOMdivElement} element хранилище элемента +* @param {DOMdivElement} element текст сообщения с ошибкой +*/ DOMErrorManager.prototype.changeTextError = function (element, errorText) { var currentErrorState = this.isFieldWithError(element); if (errorText === "") { @@ -54,9 +56,10 @@ DOMErrorManager.prototype.changeTextError = function (element, errorText) { } } /** - * @function Удалить всех детей элемента - * @param {DOMdivElement} хранилище детей - */ +* @function Удалить всех детей элемента +* +* @param {DOMdivElement} хранилище детей +*/ DOMErrorManager.prototype.removeAllChildren = function(element) { var children = element.childNodes; while(children.length) { diff --git a/Task/Scripts/DOMValidator.js b/Task/Scripts/DOMValidator.js index eb9d540..0a32526 100644 --- a/Task/Scripts/DOMValidator.js +++ b/Task/Scripts/DOMValidator.js @@ -1,11 +1,11 @@ /** - * - * @namespace Пространство имен для DOM обработчиков ошибок - * @field {Function} isTimeInterval - проверяет валидно ли поле содержащее промежуток времени - * @field {Function} isCoordinate - проверяет валидно ли поле содержащая координаты двух мерного пространства - * @field {Function} isImportantStringField - проверяет валидно ли поле содержащая строку определенных размеров - * @field {Function} isStars - проверяет валидно ли поле содержащее рейтинг - * @field {Function} isPositiveNumber - проверяет валидно ли поле содержащее целое положительное число +* @namespace Пространство имен для DOM обработчиков ошибок +* +* @field {Function} isTimeInterval - проверяет валидно ли поле содержащее промежуток времени +* @field {Function} isCoordinate - проверяет валидно ли поле содержащая координаты двух мерного пространства +* @field {Function} isImportantStringField - проверяет валидно ли поле содержащая строку определенных размеров +* @field {Function} isStars - проверяет валидно ли поле содержащее рейтинг +* @field {Function} isPositiveNumber - проверяет валидно ли поле содержащее целое положительное число */ var DOMValidator = { "isTimeInterval" : function (divWithTimeInterval) { diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index 6c661f6..be64910 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -1,12 +1,13 @@ /*global Model: true*/ /** - * Создает новое событие в календаре - * @class Событие в календаре - * @field {Number} - id Индификационный номер объекта по идее тут должен быть GUID - * @field {Object} - location объект содержащий локационные данные о событии + название события - * @field {Number} - реитинг - * @field {Number} - Цена посещения - * @augments Model + * Создает новое событие в календаре + * @class Событие в календаре + * @augments Model + * + * @field {Number} - id Индификационный номер объекта по идее тут должен быть GUID + * @field {Object} - location объект содержащий локационные данные о событии + название события + * @field {Number} - реитинг + * @field {Number} - Цена посещения */ function Event(data) { "use strict"; @@ -32,8 +33,9 @@ Event.prototype = Object.create(Model.prototype, { } }); /** - * @function Функция, проверяющая корректность даты - * @return {bool} + * @function Функция, проверяющая корректность даты + * + * @return {bool} */ Event.prototype.dateValidator = function (date) { "use strict"; @@ -45,9 +47,10 @@ Event.prototype.dateValidator = function (date) { return false; }; /** - * @function set-ер установления локации события - * @field gps координаты в дву мерном пространстве - * @field название события + * @function set-ер установления локации события + * + * @field gps координаты в дву мерном пространстве + * @field название события */ Event.prototype.setLocation = function (gps, name) { "use strict"; @@ -62,8 +65,9 @@ Event.prototype.setLocation = function (gps, name) { } }; /** - * @function Коррекция значения рейтинга - * @return {Number} 0,1,2,3,4,5 + * @function Коррекция значения рейтинга + * + * @return {Number} 0,1,2,3,4,5 */ Event.prototype.leaveMark = function (stars) { "use strict"; @@ -77,8 +81,9 @@ Event.prototype.leaveMark = function (stars) { return stars; }; /** - * @function Проверяет объект на корректность - * @field {Event} event - то что проверяем + * @function Проверяет объект на корректность + * + * @field {Event} event - то что проверяем */ Event.prototype.validate = function (event) { "use strict"; @@ -99,15 +104,17 @@ Event.prototype.validate = function (event) { } }; /** - * @function Функция, печатающие значение локационных данных объекта - * @return {String} [location], (x, y) + * @function Функция, печатающие значение локационных данных объекта + * + * @return {String} [location], (x, y) */ Event.prototype.locationToString = function() { return this.location.nameLocation + ", (" + this.location.gps.x + ";" + this.location.gps.y + ")"; } /** - * @function Функция, печатающие значение рейтинга в звездочках - * @return {String} ,*,**,***,****,***** + * @function Функция, печатающие значение рейтинга в звездочках + * + * @return {String} ,*,**,***,****,***** */ Event.prototype.starsToString= function() { var res = ""; diff --git a/Task/Scripts/Model.js b/Task/Scripts/Model.js index 306a366..1bee4b1 100644 --- a/Task/Scripts/Model.js +++ b/Task/Scripts/Model.js @@ -1,7 +1,8 @@  /** - * @class Абстрактный класс объектов ООП - * @param {data} - копируемый объект + * @class Абстрактный класс объектов ООП + * + * @param {data} - копируемый объект */ var Model = function (data) { "use strict"; @@ -11,8 +12,9 @@ var Model = function (data) { } }; /** - * @function setter - * @param {Object} - присваиваемый объект + * @function setter + * + * @param {Object} - присваиваемый объект */ Model.prototype.set = function (attributes) { "use strict"; @@ -26,9 +28,11 @@ Model.prototype.set = function (attributes) { } }; /** - * @function getter - * @param {String} имя поля - * @return {Object} + * @function getter + * + * @param {String} имя поля + * + * @return {Object} */ Model.prototype.get = function (attribute) { "use strict"; @@ -38,7 +42,7 @@ Model.prototype.get = function (attribute) { return this[attribute]; }; /** - * @function Проверяющая коррекцию объекта + * @function Проверяющая коррекцию объекта */ Model.prototype.validate = function () { "use strict"; diff --git a/Task/Scripts/calendary.js b/Task/Scripts/calendary.js index d229e55..e7fb78f 100644 --- a/Task/Scripts/calendary.js +++ b/Task/Scripts/calendary.js @@ -2,13 +2,13 @@ /*global initTestBase: true*/ /*global CalendaryErrorManager: true*/ /** - * - * @namespace Пространство имен для календаря - * @field {EventFactory} объект, хранящий ссылки на inputы необходимые для создания нового события - * @field eventList ссылка на дом объект, хранящий список событий - * @field eventBase все события пользователя - * @field errorManager объект хранящий функции для валидации полей в дом и хранящий в себе некоторые тривиальные операции - * @field currentFilters фильтры наложенные на текущие события + * @namespace Пространство имен для календаря + * + * @field {EventFactory} объект, хранящий ссылки на inputы необходимые для создания нового события + * @field eventList ссылка на дом объект, хранящий список событий + * @field eventBase все события пользователя + * @field errorManager объект хранящий функции для валидации полей в дом и хранящий в себе некоторые тривиальные операции + * @field currentFilters фильтры наложенные на текущие события */ function Calendary() { "use strict"; @@ -27,9 +27,11 @@ function Calendary() { this.currentFilters = []; } /** - * @function - функция, возвращающая текущую базу событий, но с наложенными фильтрами - * @param {[Function]} фильтры в виде функции - * @return {BaseEvent} + * @function - функция, возвращающая текущую базу событий, но с наложенными фильтрами + * + * @param {[Function]} фильтры в виде функции + * + * @return {BaseEvent} */ Calendary.prototype.ApplyFilter = function (filters) { "use strict"; @@ -41,9 +43,8 @@ Calendary.prototype.ApplyFilter = function (filters) { return base; } /** - * @function - функция пытается создать событие из данных с формы + * @function - функция пытается создать событие из данных с формы */ - Calendary.prototype.CreateEvent = function () { "use strict"; var parties = [], @@ -87,14 +88,14 @@ Calendary.prototype.CreateEvent = function () { "end": new Date(this.EventFactory.timer.querySelector(".FinishDate").value), "parties" : parties } - if (Validator.isCoordinate(this.EventFactory.coordinate)) { + if (DOMValidator.isCoordinate(this.EventFactory.coordinate)) { eventDate.location.gps.x = 0; eventDate.location.gps.y = 0; } - if (Validator.isStars(this.EventFactory.stars)) { + if (DOMValidator.isStars(this.EventFactory.stars)) { eventDate.stars = 0; } - if (Validator.isPositiveNumber(this.EventFactory.cost)) { + if (DOMValidator.isPositiveNumber(this.EventFactory.cost)) { eventDate.cost = 0; } this.eventBase = this.eventBase.add(new Event(eventDate)); @@ -120,8 +121,7 @@ Calendary.prototype.CreateEvent = function () { this.EventFactory.parties.appendChild(docfrag); } /** - * @private - * @function - функция обновляет отфильтрованный список со всеми наложенными фильтрами + * @function - функция обновляет отфильтрованный список со всеми наложенными фильтрами */ Calendary.prototype.UpdateShowList = function () { "use strict"; @@ -170,7 +170,7 @@ Calendary.prototype.UpdateShowList = function () { this.eventList.appendChild(newEventList); } /** - * @function функция вызывает обработчики ошибок необходимых полей + * @function функция вызывает обработчики ошибок необходимых полей */ Calendary.prototype.changeNeed = function () { "use strict"; @@ -178,7 +178,7 @@ Calendary.prototype.changeNeed = function () { this.errorManager.changeImportantStringField(this.EventFactory.nameLocation); } /** - * @function функция вызывает обработчики ошибок необязательных полей + * @function функция вызывает обработчики ошибок необязательных полей */ Calendary.prototype.changeAddition = function () { "use strict"; @@ -187,25 +187,25 @@ Calendary.prototype.changeAddition = function () { this.errorManager.changeStars(this.EventFactory.stars); } /** - * @function функция проверяет корректность необходимых полей + * @function функция проверяет корректность необходимых полей */ Calendary.prototype.isCorrecteNeedFields = function () { "use strict"; - return Validator.isTimeInterval(this.EventFactory.timer) === "" && - Validator.isImportantStringField(this.EventFactory.nameLocation) === ""; + return DOMValidator.isTimeInterval(this.EventFactory.timer) === "" && + DOMValidator.isImportantStringField(this.EventFactory.nameLocation) === ""; } /** - * @function функция проверяет корректность дополнительных полей + * @function функция проверяет корректность дополнительных полей */ Calendary.prototype.isCorrecteAdditionFields = function () { "use strict"; - return Validator.isCoordinate(this.EventFactory.coordinate) === "" && - Validator.isStars(this.EventFactory.stars) === "" && - Validator.isPositiveNumber(this.EventFactory.cost) === ""; + return DOMValidator.isCoordinate(this.EventFactory.coordinate) === "" && + DOMValidator.isStars(this.EventFactory.stars) === "" && + DOMValidator.isPositiveNumber(this.EventFactory.cost) === ""; } /** - * @function функция добавляет дополнительное поле в коллекцию друзей - * @param {DIVdomElement} хранилище коллекции друзей + * @function функция добавляет дополнительное поле в коллекцию друзей + * @param {DIVdomElement} хранилище коллекции друзей */ Calendary.prototype.addFriend = function (li) { "use strict"; @@ -216,7 +216,7 @@ Calendary.prototype.addFriend = function (li) { li.appendChild(newParty); } /** - * @function функция, обновляющая данные фильтра из DOM + * @function функция, обновляющая данные фильтра из DOM */ Calendary.prototype.updateFilter = function () { "use strict"; From b423fe558fad7b65409a9282ddc792adf43c25bd Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 18:32:14 +0600 Subject: [PATCH 07/11] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=82=D0=BE=D0=BF=D0=BE=D0=B3=D1=80=D0=B0=D1=84?= =?UTF-8?q?=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8=D0=B5=20=D0=BE=D0=BF=D0=BB?= =?UTF-8?q?=D0=BE=D1=88=D0=BD=D0=BE=D1=81=D1=82=D0=B8=20=D1=81=20if=20=20?= =?UTF-8?q?=D0=B8=20=D0=BE=D0=B4=D0=B8=D0=BD=20=D1=84=D0=B0=D0=B9=D0=BB?= =?UTF-8?q?=D0=B8=D0=BA=20=D0=BE=D1=82=20jsLint-=D0=B5=D0=BB=20(=D0=92?= =?UTF-8?q?=D0=B8=D0=B4=D0=B8=D0=BC=D0=BE=20=D0=B7=D0=B0=D0=B1=D1=8B=D0=BB?= =?UTF-8?q?=20=D0=BF=D1=80=D0=BE=20=D0=BD=D0=B5=D0=B3=D0=BE)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/DOMValidator.js | 20 +++++++++----------- Task/Scripts/Event.js | 9 +++++++-- Task/Scripts/calendary.js | 6 ++++-- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/Task/Scripts/DOMValidator.js b/Task/Scripts/DOMValidator.js index 0a32526..0cfb679 100644 --- a/Task/Scripts/DOMValidator.js +++ b/Task/Scripts/DOMValidator.js @@ -8,7 +8,7 @@ * @field {Function} isPositiveNumber - проверяет валидно ли поле содержащее целое положительное число */ var DOMValidator = { - "isTimeInterval" : function (divWithTimeInterval) { + "isTimeInterval": function (divWithTimeInterval) { var startDate = new Date(divWithTimeInterval.querySelector(".StartDate").value); var finishDate = new Date(divWithTimeInterval.querySelector(".FinishDate").value); var isDate = function (element) { @@ -25,7 +25,7 @@ var DOMValidator = { } return ""; }, - "isCoordinate" : function (divWithCoordinates) { + "isCoordinate": function (divWithCoordinates) { var xCoordinate = divWithCoordinates.querySelector(".XCoordinate").value; var yCoordinate = divWithCoordinates.querySelector(".YCoordinate").value; var isNumeric = function(element) { @@ -42,30 +42,29 @@ var DOMValidator = { } return ""; }, - - "isImportantStringField" : function (divWithImportantStringField, minSize, maxSize) { + "isImportantStringField": function (divWithImportantStringField, minSize, maxSize) { minSize = minSize || 0; maxSize = maxSize || -1; if (minSize < 0) { minSize = 0; } - if (minSize> maxSize) { + if (minSize > maxSize) { maxSize = -1; } var importantStringField = divWithImportantStringField.querySelector(".ImportantStringField").value; if (maxSize != -1) { if (minSize > importantStringField.length || maxSize < importantStringField.length) { - return "Поле должно содержать от " + minSize + " до "+ maxSize + "символов"; + return "Поле должно содержать от " + minSize + " до " + maxSize + "символов"; } } else { if (minSize > importantStringField.length) { - return "Поле должно содержать как минимум "+minSize+" символов"; + return "Поле должно содержать как минимум " + minSize + " символов"; } } return ""; }, - "isStars" : function (divWithStarField) { + "isStars": function (divWithStarField) { var starsField = parseFloat(divWithStarField.querySelector(".StarsField").value); var isNumeric = function(element) { return !isNaN(parseFloat(element.value)); @@ -73,7 +72,7 @@ var DOMValidator = { if (isNaN(starsField)) { return "В поле введено не число"; } - if (starsField < 0 || starsField>5) { + if (starsField < 0 || starsField > 5) { return "Количество звезд 0-5"; } if (parseInt(starsField) !== starsField) { @@ -81,8 +80,7 @@ var DOMValidator = { } return ""; }, - - "isPositiveNumber" : function (divWithPositiveNumberField) { + "isPositiveNumber": function (divWithPositiveNumberField) { var positiveNumberField = divWithPositiveNumberField.querySelector(" .PositiveNumber").value; var isNumeric = function(element) { return !isNaN(parseFloat(element)); diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index be64910..23d0383 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -54,7 +54,10 @@ Event.prototype.dateValidator = function (date) { */ Event.prototype.setLocation = function (gps, name) { "use strict"; - if (typeof gps !== "undefined" && typeof gps.x !== "undefined" && typeof gps.y !== "undefined" && typeof name === "string") { + if (typeof gps !== "undefined" && + typeof gps.x !== "undefined" && + typeof gps.y !== "undefined" && + typeof name === "string") { this.location.gps = gps; this.location.nameLocation = name; } else { @@ -71,7 +74,9 @@ Event.prototype.setLocation = function (gps, name) { */ Event.prototype.leaveMark = function (stars) { "use strict"; - if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) { + if (isNaN(parseFloat(stars)) || + !isFinite(stars) || + stars < 0) { stars = 0; } if (stars > 5) { diff --git a/Task/Scripts/calendary.js b/Task/Scripts/calendary.js index e7fb78f..b68df43 100644 --- a/Task/Scripts/calendary.js +++ b/Task/Scripts/calendary.js @@ -230,8 +230,10 @@ Calendary.prototype.updateFilter = function () { partyFilter; for (i = 0; i < filterRadios.length; i = i + 1) { radioButton = filterRadios[i]; - if (radioButton.checked && radioButton.checked === true && radioButton.value != "None") { - var nameFunc = radioButton.value.toString(); + if (radioButton.checked && + radioButton.checked === true && + radioButton.value != "None") { + var nameFunc = radioButton.value.toString(); newFilters.push(function() { return this[nameFunc](); }); From ad04ba0e9398968edf46469faf36ed23ecc23a22 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 18:36:14 +0600 Subject: [PATCH 08/11] =?UTF-8?q?=D0=92=D0=BE=D1=81=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D0=BB=D1=81=D1=8F=20=D0=BC=D0=BE?= =?UTF-8?q?=D1=89=D1=8C=D1=8E=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=B0=20Mat?= =?UTF-8?q?h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/Event.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index 23d0383..936fa3d 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -82,7 +82,7 @@ Event.prototype.leaveMark = function (stars) { if (stars > 5) { stars = 5; } - stars = (stars - (stars % 1)); //обрезаем дробную часть + stars = Math.floor(stars); return stars; }; /** From 2624b5d9719eda532355ce05248ed7cf5efe55d6 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 18:44:56 +0600 Subject: [PATCH 09/11] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=83=D0=B6=D0=B0=D1=81=D0=BD=D1=8B=D0=B9=20if?= =?UTF-8?q?=20:(?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/Event.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index 936fa3d..8e149af 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -98,10 +98,10 @@ Event.prototype.validate = function (event) { if (!Array.isArray(event.parties)) { throw new Error("Участники - это массив"); } - if (event.parties.some(function (party) { - return !party.name; - }) - ) { + var existsSomePartyWithoutNameField = event.parties.some(function (party) { + return !party.name; + }); + if (existsSomePartyWithoutNameField) { throw new Error("У одного из участников нет поля <ИМЯ>"); } if (event.end < event.start) { From 639008692fe762f7882fc7dac1d74bf3f51a450e Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 18:47:29 +0600 Subject: [PATCH 10/11] =?UTF-8?q?=D0=92=D0=BE=D1=81=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D0=BB=D1=81=D1=8F=20=D1=85=D0=B0?= =?UTF-8?q?=D0=BA=D0=BE=D0=BC=20=D1=81=20=D0=BC=D0=B0=D1=81=D1=81=D0=B8?= =?UTF-8?q?=D0=B2=D0=BE=D0=BC=20^^?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/Event.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index 8e149af..2e838cd 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -122,9 +122,5 @@ Event.prototype.locationToString = function() { * @return {String} ,*,**,***,****,***** */ Event.prototype.starsToString= function() { - var res = ""; - for(var i = 0; i < this.stars; i++) { - res += "*"; - } - return res; + return return new Array(this.stars + 1).join('*');; } \ No newline at end of file From a1aaa20ee0f97dfff4e3d2062dd579aa6ad0480a Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 13 Nov 2012 21:13:19 +0600 Subject: [PATCH 11/11] =?UTF-8?q?=D0=AF=20=D0=BF=D0=BE=D0=B7=D0=BD=D0=B0?= =?UTF-8?q?=D0=BB=20=D1=81=D0=B8=D0=BB=D1=83=20IEE=20+=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20if?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Scripts/BaseEvent.js | 257 ++++++++++------- Task/Scripts/CalendaryErrorManager.js | 78 ++--- Task/Scripts/Collection.js | 76 ++--- Task/Scripts/DOMErrorManager.js | 76 ++--- Task/Scripts/DOMValidator.js | 220 ++++++++------ Task/Scripts/Event.js | 180 ++++++------ Task/Scripts/Model.js | 59 ++-- Task/Scripts/calendary.js | 396 +++++++++++++------------- Task/Scripts/run.js | 9 +- Task/Scripts/testData.js | 177 ++++++------ Task/index.html | 2 +- 11 files changed, 829 insertions(+), 701 deletions(-) diff --git a/Task/Scripts/BaseEvent.js b/Task/Scripts/BaseEvent.js index 6c33ba0..4c1e784 100644 --- a/Task/Scripts/BaseEvent.js +++ b/Task/Scripts/BaseEvent.js @@ -1,120 +1,155 @@ /*global Collection: true*/ - +(function (toExport) { + "use strict"; /** * Создает оболочку над массивом событий, предоставляющую "sql" подобные операции * * @class Оболочка над массивом событий. * @augments Collection */ -function BaseEvent(events) { - "use strict"; - Collection.call(this, events); -} -BaseEvent.prototype = Object.create(Collection.prototype, { - constructor: { - value: BaseEvent, - enumerable: false, - writable: true, - configurable: true + var BaseEvent = function BaseEvent(events) { + "use strict"; + Collection.call(this, events); } -}); + + toExport.BaseEvent = BaseEvent; + + BaseEvent.prototype = Object.create(Collection.prototype, { + constructor: { + value: BaseEvent, + enumerable: false, + writable: true, + configurable: true + } + }); /** * *@field {BaseEvent} - ссылка на "родной" конструктор */ -BaseEvent.prototype.constructor = BaseEvent; - + BaseEvent.prototype.constructor = BaseEvent; /** *@function Возвращает новую оболочку, но уже только с прошедшими событиями * *@return {BaseEvent} */ -BaseEvent.prototype.pastEventBase = function () { - "use strict"; - var currentDate = new Date(); - return this.filter(function (event) { - return event.end.getTime() < currentDate.getTime(); - }); -}; + BaseEvent.prototype.pastEventBase = function () { + var currentDate = new Date(); + return this.filter(function (event) { + return event.end.getTime() < currentDate.getTime(); + }); + }; /** * @function Возвращает новую оболочку, но уже только с ненаступившими событиями * * @return {BaseEvent} */ -BaseEvent.prototype.nextEventBase = function () { - "use strict"; - var currentDate = new Date(); - return this.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); -}; + BaseEvent.prototype.nextEventBase = function () { + var currentDate = new Date(); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + }; /** * @function Возвращает новую оболочку, но уже с событиями, которые идут в данный момент * * @return */ -BaseEvent.prototype.nowEventBase = function () { - "use strict"; - var currentDate = new Date(); - return this.filter(function (event) { - return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime()); - }); -}; + BaseEvent.prototype.nowEventBase = function () { + var currentDate = new Date(); + return this.filter(function (event) { + return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime()); + }); + }; /** * @function Возвращает новую оболочку, но уже с событиями, в которых участвует определенный человек * * @return */ -BaseEvent.prototype.withFriend = function (myFriend) { - "use strict"; - return this.filter(function (event) { - return event.parties.some(function (party) { - return party.name === myFriend.name; + BaseEvent.prototype.withFriend = function (myFriend) { + return this.filter(function (event) { + return event.parties.some(function (party) { + return party.name === myFriend.name; + }); }); - }); -}; + }; /** - * @function Возвращает новую оболочку, но уже с событиями, которые будут через неделю + * @function Увеличивает дату на день + * @private + * + * @field {Date} currentDate дата, которую будем увеличивать + * + * @return {Date} + */ + var addDay = function (currentDate) { + return new Date(new Date().getTime() + 24 * 60 * 60 * 1000); + } + +/** + * @function Возвращает новую оболочку, но уже с событиями, которые будут через день * * @return {BaseEvent} */ -BaseEvent.prototype.getEventAfterWeek = function () { - "use strict"; - var currentDate = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000); - return this.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); -}; + BaseEvent.prototype.getEventAfterDay = function () { + var currentDate = addDay(new Date()); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + }; + /** - * @function Возвращает новую оболочку, но уже с событиями, которые будут через день + * @function Увеличивает дату на неделю + * @private + * + * @field {Date} currentDate дата, которую будем увеличивать + * + * @return {Date} + */ + var addWeek = function (currentDate) { + return new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000); + } + +/** + * @function Возвращает новую оболочку, но уже с событиями, которые будут через неделю * * @return {BaseEvent} */ -BaseEvent.prototype.getEventAfterDay = function () { - "use strict"; - var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000); - return this.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); -}; + BaseEvent.prototype.getEventAfterWeek = function () { + var currentDate = addWeek(new Date()); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + }; + +/** + * @function Увеличивает дату на месяц + * @private + * + * @field {Date} currentDate дата, которую будем увеличивать + * + * @return {Date} + */ + var addMonth = function (currentDate) { + if (currentDate.getMonth() === 11) { + currentDate = new Date(currentDate.getFullYear() + 1, 0, currentDate.getDay()); + } else { + currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDay()); + } + return currentDate; + } + /** * @function Возвращает новую оболочку, но уже с событиями, которые будут через месяц * * @return {BaseEvent} */ -BaseEvent.prototype.getEventAfterMonth = function () { - "use strict"; - var currentDate = new Date(); - if (currentDate.getMonth() === 11) { - currentDate = new Date(currentDate.getFullYear() + 1, 0, currentDate.getDay()); - } else { - currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDay()); - } - return this.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); -}; + BaseEvent.prototype.getEventAfterMonth = function () { + var currentDate = addMonth(new Date()); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + }; + /** * @function Возвращает новую оболочку, но уже с событиями, которые будут в определенный период * @@ -123,45 +158,67 @@ BaseEvent.prototype.getEventAfterMonth = function () { * * @return */ -BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) { - "use strict"; - return this.filter(function (event) { - return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime()); - }); -}; + BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) { + return this.filter(function (event) { + return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime()); + }); + }; + +/** + * @function Компаратор рейтинга по убыванию + * @private + * + * @field {Date} a + * @field {Date} b + * + * @return {Numeric} + */ + var starsComparer = function compare(a, b) { + if (a.stars > b.stars) { + return -1; + } + if (a.stars < b.stars) { + return 1; + } + return 0; + }; + /** * @function Возвращает новую оболочку c теми же событиями, но отсортированными по уменьшению количества звезд * * @return {BaseEvent} */ -BaseEvent.prototype.sortByStars = function (ascending) { - "use strict"; - var comparer = function compare(a, b) { - if (a.stars > b.stars) { - return -1; - } - if (a.stars < b.stars) { - return 1; - } - return 0; + BaseEvent.prototype.sortByStars = function (ascending) { + + return this.sortBy(starsComparer, ascending); }; - return this.sortBy(comparer, ascending); -}; + +/** + * @function Компаратор дат по возрастанию + * @private + * + * @field {Date} a + * @field {Date} b + * + * @return {Numeric} + */ + var dateComparer = function (a, b) { + if (a.start.getTime() < b.start.getTime()) { + return -1; + } + if (a.start.getTime() > b.start.getTime()) { + return 1; + } + return 0; + }; + /** * @function Возвращает новую оболочку c теми же событиями, но отсортированными по дате * * @return {BaseEvent} */ -BaseEvent.prototype.sortByDate = function (ascending) { - "use strict"; - var comparer = function compare(a, b) { - if (a.start.getTime() < b.start.getTime()) { - return -1; - } - if (a.start.getTime() > b.start.getTime()) { - return 1; - } - return 0; + BaseEvent.prototype.sortByDate = function (ascending) { + + return this.sortBy(dateComparer, ascending); }; - return this.sortBy(comparer, ascending); -}; \ No newline at end of file +}(window)); \ No newline at end of file diff --git a/Task/Scripts/CalendaryErrorManager.js b/Task/Scripts/CalendaryErrorManager.js index b4083f4..6c9ee6d 100644 --- a/Task/Scripts/CalendaryErrorManager.js +++ b/Task/Scripts/CalendaryErrorManager.js @@ -1,61 +1,71 @@ -/** +(function (toExport) { +/** * @class Класс содержит обработчики ошибок при изменении элементов DOM связанных с календорем * @augments DOMErrorManager */ -var CalendaryErrorManager = function (errorClassName) { - DOMErrorManager.call(this, errorClassName); -} -CalendaryErrorManager.prototype = Object.create(DOMErrorManager.prototype, { - constructor: { - value: Event, - enumerable: false, - writable: true, - configurable: true + var CalendaryErrorManager = function (errorClassName) { + DOMErrorManager.call(this, errorClassName); } -}); + + toExport.CalendaryErrorManager = CalendaryErrorManager; + + CalendaryErrorManager.prototype = Object.create(DOMErrorManager.prototype, { + constructor: { + value: Event, + enumerable: false, + writable: true, + configurable: true + } + }); + /** * @function Обработчик ошибок объекта, содержащий начальное и конечное время * * @param {DOMdivElement} хранилище, содержащее таймер. */ -CalendaryErrorManager.prototype.changeTime = function (timer) { - var textError = DOMValidator.isTimeInterval(timer); - this.changeTextError(timer, textError); -} + CalendaryErrorManager.prototype.changeTime = function (timer) { + var textError = DOMValidator.isTimeInterval(timer); + this.changeTextError(timer, textError); + } + /** * @function Обработчик ошибок объекта, содержащий координаты * * @param {DOMdivElement} хранилище, содержащее координаты. */ -CalendaryErrorManager.prototype.changeCoordinate = function (coordinates) { - var textError = DOMValidator.isCoordinate(coordinates); - this.changeTextError(coordinates, textError); -} + CalendaryErrorManager.prototype.changeCoordinate = function (coordinates) { + var textError = DOMValidator.isCoordinate(coordinates); + this.changeTextError(coordinates, textError); + } + /** * @function Обработчик ошибок объекта, содержащий важныее данные * * @param {DOMdivElement} хранилище, содержащее важное поле. - */ -CalendaryErrorManager.prototype.changeImportantStringField = function (importantStringField) { - var textError = DOMValidator.isImportantStringField(importantStringField, 5, 20); - this.changeTextError(importantStringField, textError); -} +*/ + CalendaryErrorManager.prototype.changeImportantStringField = function (importantStringField) { + var textError = DOMValidator.isImportantStringField(importantStringField, 5, 20); + this.changeTextError(importantStringField, textError); + } + /** * @function Обработчик ошибок объекта, содержащий поле с положительным числом * * @param {DOMdivElement} хранилище, содержащее поле с положительным числом. - */ -CalendaryErrorManager.prototype.changePositiveNumber = function (positiveNumber) { - var textError = DOMValidator.isPositiveNumber(positiveNumber); - this.changeTextError(positiveNumber, textError); -} +*/ + CalendaryErrorManager.prototype.changePositiveNumber = function (positiveNumber) { + var textError = DOMValidator.isPositiveNumber(positiveNumber); + this.changeTextError(positiveNumber, textError); + } + /** * @function Обработчик ошибок объекта, содержащий поле с рейтингом * * @param {DOMdivElement} хранилище, содержащее поле с положительным числом. - */ -CalendaryErrorManager.prototype.changeStars = function (stars) { - var textError = DOMValidator.isStars(stars); - this.changeTextError(stars, textError); -} \ No newline at end of file +*/ + CalendaryErrorManager.prototype.changeStars = function (stars) { + var textError = DOMValidator.isStars(stars); + this.changeTextError(stars, textError); + } +}(window)); \ No newline at end of file diff --git a/Task/Scripts/Collection.js b/Task/Scripts/Collection.js index 6894f4c..aed5a7c 100644 --- a/Task/Scripts/Collection.js +++ b/Task/Scripts/Collection.js @@ -1,35 +1,36 @@ /*global Collection: true*/ - +(function(toExport) { + "use strict"; /** * Создает оболочка для хранения массива объектов с операциями по извлечению более конкретных элементов * @class Оболочка для храения массива объектов * * @param {Array} элементы коллекции */ -var Collection = function (otherItems) { - "use strict"; - var item; - this.items = []; - for (item in otherItems) { - if (otherItems.hasOwnProperty(item)) { - this.items.push(otherItems[item]); + var Collection = function (otherItems) { + "use strict"; + var item; + this.items = []; + for (item in otherItems) { + if (otherItems.hasOwnProperty(item)) { + this.items.push(otherItems[item]); + } } - } -}; + }; + toExport.Collection = Collection; /** * @field {Collection} хранит ссылку на родной конструктор */ -Collection.prototype.constructor = Collection + Collection.prototype.constructor = Collection /** * @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj * * @return {instanceof this.constructor} */ -Collection.prototype.add = function (obj) { - "use strict"; - var newEvents = this.items.concat([obj]); - return new this.constructor(newEvents); -}; + Collection.prototype.add = function (obj) { + var newEvents = this.items.concat([obj]); + return new this.constructor(newEvents); + }; /** * @function создает новую коллекцию элементов с отфильтрованными элементами * @@ -37,11 +38,10 @@ Collection.prototype.add = function (obj) { * * @return {instanceof this.constructor} */ -Collection.prototype.filter = function (selector) { - "use strict"; - var newItems = this.items.filter(selector); - return new this.constructor(newItems); -}; + Collection.prototype.filter = function (selector) { + var newItems = this.items.filter(selector); + return new this.constructor(newItems); + }; /** * @function создает новую коллекцию элементов с теме же элементами + с новым элементом obj * @@ -50,22 +50,22 @@ Collection.prototype.filter = function (selector) { * * @return {instanceof this.constructor} */ -Collection.prototype.sortBy = function (comparator, isInvert) { - "use strict"; - var newItems = [].concat(this.items); - if (newItems.length === 0) { - return []; - } - if (comparator) { - if (isInvert) { - newItems.sort(function (a, b) { - return -1 * comparator(a, b); - }); + Collection.prototype.sortBy = function (comparator, isInvert) { + var newItems = [].concat(this.items); + if (newItems.length === 0) { + return []; + } + if (comparator) { + if (isInvert) { + newItems.sort(function (a, b) { + return -1 * comparator(a, b); + }); + } else { + newItems.sort(comparator); + } } else { - newItems.sort(comparator); + newItems.sort(); } - } else { - newItems.sort(); - } - return new this.constructor(newItems); -}; \ No newline at end of file + return new this.constructor(newItems); + }; +}(window)); \ No newline at end of file diff --git a/Task/Scripts/DOMErrorManager.js b/Task/Scripts/DOMErrorManager.js index 01287f6..b06d7bd 100644 --- a/Task/Scripts/DOMErrorManager.js +++ b/Task/Scripts/DOMErrorManager.js @@ -1,68 +1,72 @@ -/** +(function (toExport) { + "use strict"; +/** * @class * Класс содержит обработчики ошибок при изменении элементов DOM */ -var DOMErrorManager = function (errorClassName) { - this.errorClassName = errorClassName; -} + var DOMErrorManager = function (errorClassName) { + this.errorClassName = errorClassName; + } + toExport.DOMErrorManager = DOMErrorManager; /** * @function Обработчик ошибок объекта, содержащий начальное и конечное время * @param {DOMdivElement} хранилище, содержащее таймер. */ -DOMErrorManager.prototype.isFieldWithError = function (element) { - var lastElement = element.querySelector("."+this.errorClassName); - return !!lastElement; -} + DOMErrorManager.prototype.isFieldWithError = function (element) { + var lastElement = element.querySelector("."+this.errorClassName); + return !!lastElement; + } /** * @function Устанавливает в передаваемый элемент ошибку * * @param {DOMdivElement} element на что устанавливаем ошибку. * @param {String} text текст ошибки. */ -DOMErrorManager.prototype.setTextError = function (element, text) { - var newError = document.createElement("span"), - newTextError = document.createTextNode(text); - newError.className = this.errorClassName; - newError.appendChild(newTextError); - element.appendChild(newError); -} + DOMErrorManager.prototype.setTextError = function (element, text) { + var newError = document.createElement("span"), + newTextError = document.createTextNode(text); + newError.className = this.errorClassName; + newError.appendChild(newTextError); + element.appendChild(newError); + } /** * @function Стереть ошибку * * @param {DOMdivElement} element на что устанавливаем ошибку. */ -DOMErrorManager.prototype.removeTextError = function (element) { - var error = element.querySelector("."+this.errorClassName); - element.removeChild(error); -} + DOMErrorManager.prototype.removeTextError = function (element) { + var error = element.querySelector("."+this.errorClassName); + element.removeChild(error); + } /** * @function Изменить или стереть ошибку в зависимости от того есть она или нет * * @param {DOMdivElement} element хранилище элемента * @param {DOMdivElement} element текст сообщения с ошибкой */ -DOMErrorManager.prototype.changeTextError = function (element, errorText) { - var currentErrorState = this.isFieldWithError(element); - if (errorText === "") { - if (currentErrorState) { - this.removeTextError(element); + DOMErrorManager.prototype.changeTextError = function (element, errorText) { + var currentErrorState = this.isFieldWithError(element); + if (errorText === "") { + if (currentErrorState) { + this.removeTextError(element); + } } - } - else - { - if (currentErrorState) { - this.removeTextError(element); + else + { + if (currentErrorState) { + this.removeTextError(element); + } + this.setTextError(element, errorText); } - this.setTextError(element, errorText); } -} /** * @function Удалить всех детей элемента * * @param {DOMdivElement} хранилище детей */ -DOMErrorManager.prototype.removeAllChildren = function(element) { - var children = element.childNodes; - while(children.length) { - element.removeChild(children[0]) + DOMErrorManager.prototype.removeAllChildren = function(element) { + var children = element.childNodes; + while(children.length) { + element.removeChild(children[0]) + } } -} \ No newline at end of file +}(window)); \ No newline at end of file diff --git a/Task/Scripts/DOMValidator.js b/Task/Scripts/DOMValidator.js index 0cfb679..7d42bbe 100644 --- a/Task/Scripts/DOMValidator.js +++ b/Task/Scripts/DOMValidator.js @@ -1,95 +1,139 @@ -/** -* @namespace Пространство имен для DOM обработчиков ошибок +(function (toExport) { + "use strict"; +/** +* @function - проверяет является ли передаваемый объект Датой +* @private +* +* @param {Object} element - проверяемый объект +* +* @return {Boolean} +*/ + var isDate = function (element) { + return Event.prototype.dateValidator(element); + }; + +/** +* @function - проверяет является ли передаваемый объект числом +* @private +* +* @param {Object} element - проверяемый объект +* +* @return {Boolean} +*/ + var isNumeric = function(element) { + return !isNaN(parseFloat(element)); + }; + +/** +* @function - проверяет является ли передаваемый объект числом +* @private +* +* @param {Object} element - проверяемый объект * +* @return {Boolean} +*/ + var isNumeric = function(element) { + return !isNaN(parseFloat(element)); + }; + +/** +* @namespace Пространство имен для DOM обработчиков ошибок +*/ + var DOMValidator = {}; + toExport.DOMValidator = DOMValidator; + +/** * @field {Function} isTimeInterval - проверяет валидно ли поле содержащее промежуток времени -* @field {Function} isCoordinate - проверяет валидно ли поле содержащая координаты двух мерного пространства -* @field {Function} isImportantStringField - проверяет валидно ли поле содержащая строку определенных размеров -* @field {Function} isStars - проверяет валидно ли поле содержащее рейтинг -* @field {Function} isPositiveNumber - проверяет валидно ли поле содержащее целое положительное число - */ -var DOMValidator = { - "isTimeInterval": function (divWithTimeInterval) { - var startDate = new Date(divWithTimeInterval.querySelector(".StartDate").value); - var finishDate = new Date(divWithTimeInterval.querySelector(".FinishDate").value); - var isDate = function (element) { - return Event.prototype.dateValidator(element); - } - if (!isDate(startDate) && !isDate(finishDate)) - return "Обе даты некорректны"; - if (!isDate(startDate)) - return "Дата начала события некорректна"; - if (!isDate(finishDate)) - return "Дата конца события некорректна"; - if (startDate.getTime()> finishDate.getTime()) { - return "Даты перепутаны местами"; - } - return ""; - }, - "isCoordinate": function (divWithCoordinates) { - var xCoordinate = divWithCoordinates.querySelector(".XCoordinate").value; - var yCoordinate = divWithCoordinates.querySelector(".YCoordinate").value; - var isNumeric = function(element) { - return !isNaN(parseFloat(element)); +*/ + DOMValidator.isTimeInterval = function (divWithTimeInterval) { + var startDate = new Date(divWithTimeInterval.querySelector(".StartDate").value); + var finishDate = new Date(divWithTimeInterval.querySelector(".FinishDate").value); + + if (!isDate(startDate) && !isDate(finishDate)) + return "Обе даты некорректны"; + if (!isDate(startDate)) + return "Дата начала события некорректна"; + if (!isDate(finishDate)) + return "Дата конца события некорректна"; + if (startDate.getTime()> finishDate.getTime()) { + return "Даты перепутаны местами"; + } + return ""; + }; + +/** +@field {Function} isCoordinate - проверяет валидно ли поле содержащая координаты двух мерного пространства +*/ + DOMValidator.isCoordinate = function (divWithCoordinates) { + var xCoordinate = divWithCoordinates.querySelector(".XCoordinate").value; + var yCoordinate = divWithCoordinates.querySelector(".YCoordinate").value; + + if (!isNumeric(xCoordinate) && !isNumeric(yCoordinate)) { + return "Обе координаты некорректны"; + } + if (!isNumeric(xCoordinate)) { + return "Координата X - некорректна"; + } + if (!isNumeric(yCoordinate)) { + return "Координата Y - некорректна"; + } + return ""; }; - if (!isNumeric(xCoordinate) && !isNumeric(yCoordinate)) { - return "Обе координаты некорректны"; - } - if (!isNumeric(xCoordinate)) { - return "Координата X - некорректна"; - } - if (!isNumeric(yCoordinate)) { - return "Координата Y - некорректна"; - } - return ""; - }, - "isImportantStringField": function (divWithImportantStringField, minSize, maxSize) { - minSize = minSize || 0; - maxSize = maxSize || -1; - if (minSize < 0) { - minSize = 0; - } - if (minSize > maxSize) { - maxSize = -1; - } - var importantStringField = divWithImportantStringField.querySelector(".ImportantStringField").value; - if (maxSize != -1) { - if (minSize > importantStringField.length || maxSize < importantStringField.length) { - return "Поле должно содержать от " + minSize + " до " + maxSize + "символов"; + +/** +* @field {Function} isTimeInterval - проверяет валидно ли поле содержащее промежуток времени +*/ + DOMValidator.isImportantStringField = function (divWithImportantStringField, minSize, maxSize) { + minSize = minSize || 0; + maxSize = maxSize || -1; + if (minSize < 0) { + minSize = 0; } - } - else { - if (minSize > importantStringField.length) { - return "Поле должно содержать как минимум " + minSize + " символов"; + if (minSize > maxSize) { + maxSize = -1; } - } - return ""; - }, - "isStars": function (divWithStarField) { - var starsField = parseFloat(divWithStarField.querySelector(".StarsField").value); - var isNumeric = function(element) { - return !isNaN(parseFloat(element.value)); + var importantStringField = divWithImportantStringField.querySelector(".ImportantStringField").value; + if (maxSize != -1) { + if (minSize > importantStringField.length || maxSize < importantStringField.length) { + return "Поле должно содержать от " + minSize + " до " + maxSize + "символов"; + } + } + else { + if (minSize > importantStringField.length) { + return "Поле должно содержать как минимум " + minSize + " символов"; + } + } + return ""; }; - if (isNaN(starsField)) { - return "В поле введено не число"; - } - if (starsField < 0 || starsField > 5) { - return "Количество звезд 0-5"; - } - if (parseInt(starsField) !== starsField) { - return "Количество звезд целое число"; - } - return ""; - }, - "isPositiveNumber": function (divWithPositiveNumberField) { - var positiveNumberField = divWithPositiveNumberField.querySelector(" .PositiveNumber").value; - var isNumeric = function(element) { - return !isNaN(parseFloat(element)); + +/** +* @field {Function} isStars - проверяет валидно ли поле содержащее рейтинг +*/ + DOMValidator.isStars = function (divWithStarField) { + var starsField = parseFloat(divWithStarField.querySelector(".StarsField").value); + if (isNaN(starsField)) { + return "В поле введено не число"; + } + if (starsField < 0 || starsField > 5) { + return "Количество звезд 0-5"; + } + if (parseInt(starsField) !== starsField) { + return "Количество звезд целое число"; + } + return ""; }; - if (!isNumeric(positiveNumberField)) { - return "В поле введено не число"; - } - if (parseFloat(positiveNumberField) < 0) { - return "В поле введено отрицательное число"; - } - return ""; -}} \ No newline at end of file + +/** +* @field {Function} isPositiveNumber - проверяет валидно ли поле содержащее целое положительное число +*/ + DOMValidator.isPositiveNumber = function (divWithPositiveNumberField) { + var positiveNumberField = divWithPositiveNumberField.querySelector(" .PositiveNumber").value; + if (!isNumeric(positiveNumberField)) { + return "В поле введено не число"; + } + if (parseFloat(positiveNumberField) < 0) { + return "В поле введено отрицательное число"; + } + return ""; + }; +}(window)); \ No newline at end of file diff --git a/Task/Scripts/Event.js b/Task/Scripts/Event.js index 2e838cd..d5d10b7 100644 --- a/Task/Scripts/Event.js +++ b/Task/Scripts/Event.js @@ -1,4 +1,6 @@ /*global Model: true*/ +(function (toExport) { + "use strict"; /** * Создает новое событие в календаре * @class Событие в календаре @@ -9,118 +11,132 @@ * @field {Number} - реитинг * @field {Number} - Цена посещения */ -function Event(data) { - "use strict"; - this.id = Math.random(); - this.location = { - "gps": {x: 0, y: 0}, - "nameLocation": "Earth" - }; - this.stars = 0; - this.cost = 0; - this.parties = []; - Model.call(this, data); - this.validate(this); - this.setLocation(this.location.gps, this.location.nameLocation); - this.stars = this.leaveMark(this.stars); -} -Event.prototype = Object.create(Model.prototype, { - constructor: { - value: Event, - enumerable: false, - writable: true, - configurable: true + var Event = function Event(data) { + "use strict"; + this.id = Math.random(); + this.location = { + "gps": {x: 0, y: 0}, + "nameLocation": "Earth" + }; + this.stars = 0; + this.cost = 0; + this.parties = []; + Model.call(this, data); + this.validate(this); + this.setLocation(this.location.gps, this.location.nameLocation); + this.stars = this.leaveMark(this.stars); } -}); + toExport.Event = Event; + Event.prototype = Object.create(Model.prototype, { + constructor: { + value: Event, + enumerable: false, + writable: true, + configurable: true + } + }); /** * @function Функция, проверяющая корректность даты * * @return {bool} */ -Event.prototype.dateValidator = function (date) { - "use strict"; - if (Object.prototype.toString.call(date) === "[object Date]") { - if (!isNaN(date.getTime())) { - return true; + Event.prototype.dateValidator = function (date) { + "use strict"; + if (Object.prototype.toString.call(date) === "[object Date]") { + if (!isNaN(date.getTime())) { + return true; + } + } + return false; + }; +/** + * @function Проверяет на корректность координаты + * @private + * + * @field coordinate координаты в дву мерном пространстве + * @field name название события + * @filed {Boolean} +*/ + var isCorrectedCoordinate = function (coordinate, name) { + var isType = typeof coordinate !== "undefined" && typeof name === "string"; + if (!isType) { + return false; + } + var isX = typeof coordinate.x === "number"; + var isY = typeof coordinate.y === "number"; + return isX && isY; } - } - return false; -}; /** * @function set-ер установления локации события * * @field gps координаты в дву мерном пространстве * @field название события */ -Event.prototype.setLocation = function (gps, name) { - "use strict"; - if (typeof gps !== "undefined" && - typeof gps.x !== "undefined" && - typeof gps.y !== "undefined" && - typeof name === "string") { - this.location.gps = gps; - this.location.nameLocation = name; - } else { - this.location = { - "gps" : {"x" : 0, "y" : 0}, - "nameLocation" : "Earth" - }; - } -}; + Event.prototype.setLocation = function (gps, name) { + + if (isCorrectedCoordinate(gps, name)) { + this.location.gps = gps; + this.location.nameLocation = name; + } else { + this.location = { + "gps" : {"x" : 0, "y" : 0}, + "nameLocation" : "Earth" + }; + } + }; /** * @function Коррекция значения рейтинга * * @return {Number} 0,1,2,3,4,5 */ -Event.prototype.leaveMark = function (stars) { - "use strict"; - if (isNaN(parseFloat(stars)) || - !isFinite(stars) || - stars < 0) { - stars = 0; - } - if (stars > 5) { - stars = 5; - } - stars = Math.floor(stars); - return stars; -}; + Event.prototype.leaveMark = function (stars) { + if (isNaN(parseFloat(stars)) || + !isFinite(stars) || + stars < 0) { + stars = 0; + } + if (stars > 5) { + stars = 5; + } + stars = Math.floor(stars); + return stars; + }; /** * @function Проверяет объект на корректность * * @field {Event} event - то что проверяем */ -Event.prototype.validate = function (event) { - "use strict"; - if (event.cost < 0) { - throw new Error("Цена за вход не может быть отрицательной"); - } - if (!Array.isArray(event.parties)) { - throw new Error("Участники - это массив"); - } - var existsSomePartyWithoutNameField = event.parties.some(function (party) { - return !party.name; - }); - if (existsSomePartyWithoutNameField) { - throw new Error("У одного из участников нет поля <ИМЯ>"); - } - if (event.end < event.start) { - throw new Error("Даты начала и конца перепутаны"); - } -}; + Event.prototype.validate = function (event) { + if (event.cost < 0) { + throw new Error("Цена за вход не может быть отрицательной"); + } + if (!Array.isArray(event.parties)) { + throw new Error("Участники - это массив"); + } + var existsSomePartyWithoutNameField = event.parties.some(function (party) { + return !party.name; + }); + if (existsSomePartyWithoutNameField) { + throw new Error("У одного из участников нет поля <ИМЯ>"); + } + if (event.end < event.start) { + throw new Error("Даты начала и конца перепутаны"); + } + }; /** * @function Функция, печатающие значение локационных данных объекта * * @return {String} [location], (x, y) */ -Event.prototype.locationToString = function() { - return this.location.nameLocation + ", (" + this.location.gps.x + ";" + this.location.gps.y + ")"; -} + Event.prototype.locationToString = function() { + return this.location.nameLocation + ", (" + this.location.gps.x + ";" + this.location.gps.y + ")"; + } /** * @function Функция, печатающие значение рейтинга в звездочках * * @return {String} ,*,**,***,****,***** */ -Event.prototype.starsToString= function() { - return return new Array(this.stars + 1).join('*');; -} \ No newline at end of file + Event.prototype.starsToString= function() { + return new Array(this.stars + 1).join('*');; + } +}(window)); \ No newline at end of file diff --git a/Task/Scripts/Model.js b/Task/Scripts/Model.js index 1bee4b1..4a8f174 100644 --- a/Task/Scripts/Model.js +++ b/Task/Scripts/Model.js @@ -1,32 +1,34 @@ - +(function (toExport) { + "use strict"; /** * @class Абстрактный класс объектов ООП * * @param {data} - копируемый объект */ -var Model = function (data) { - "use strict"; - var nameField; - for (nameField in data) { - this[nameField] = data[nameField]; - } -}; + var Model = function (data) { + var nameField; + for (nameField in data) { + this[nameField] = data[nameField]; + } + }; + toExport.Model = Model; + /** * @function setter * * @param {Object} - присваиваемый объект */ -Model.prototype.set = function (attributes) { - "use strict"; - var nameAttr; - for (nameAttr in attributes) { - if (attributes.hasOwnProperty(nameAttr)) { - if (typeof this[nameAttr] !== "undefined") { - this[nameAttr] = attributes[nameAttr]; + Model.prototype.set = function (attributes) { + var nameAttr; + for (nameAttr in attributes) { + if (attributes.hasOwnProperty(nameAttr)) { + if (typeof this[nameAttr] !== "undefined") { + this[nameAttr] = attributes[nameAttr]; + } } } - } -}; + }; + /** * @function getter * @@ -34,17 +36,18 @@ Model.prototype.set = function (attributes) { * * @return {Object} */ -Model.prototype.get = function (attribute) { - "use strict"; - if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") { - return; //return undefined; - } - return this[attribute]; -}; + Model.prototype.get = function (attribute) { + if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") { + return; + } + return this[attribute]; + }; + /** * @function Проверяющая коррекцию объекта */ -Model.prototype.validate = function () { - "use strict"; - throw new Error('this is Abstract method'); -}; + Model.prototype.validate = function () { + "use strict"; + throw new Error('this is Abstract method'); + }; +}(window)); \ No newline at end of file diff --git a/Task/Scripts/calendary.js b/Task/Scripts/calendary.js index b68df43..1e7e1af 100644 --- a/Task/Scripts/calendary.js +++ b/Task/Scripts/calendary.js @@ -1,6 +1,8 @@ /*global document: true*/ /*global initTestBase: true*/ /*global CalendaryErrorManager: true*/ +(function (toExport) { + "use strict"; /** * @namespace Пространство имен для календаря * @@ -10,22 +12,22 @@ * @field errorManager объект хранящий функции для валидации полей в дом и хранящий в себе некоторые тривиальные операции * @field currentFilters фильтры наложенные на текущие события */ -function Calendary() { - "use strict"; - this.whois = "Alex.Mangin"; - this.EventFactory = { - "timer" : document.getElementById("NewEventTimeInterval"), - "nameLocation" : document.getElementById("NewEventNameLocation"), - "coordinate" : document.getElementById("NewEventCoordinate"), - "stars" : document.getElementById("NewEventStars"), - "cost" : document.getElementById("NewEventCost"), - "parties" : document.querySelector("#NewEventPartiesList ol") - }; - this.eventList = document.getElementById("eventList"); - this.eventBase = initTestBase(); - this.errorManager = new CalendaryErrorManager("Error"); - this.currentFilters = []; -} + var Calendary = function () { + this.whois = "Alex.Mangin"; + this.EventFactory = { + "timer" : document.getElementById("NewEventTimeInterval"), + "nameLocation" : document.getElementById("NewEventNameLocation"), + "coordinate" : document.getElementById("NewEventCoordinate"), + "stars" : document.getElementById("NewEventStars"), + "cost" : document.getElementById("NewEventCost"), + "parties" : document.querySelector("#NewEventPartiesList ol") + }; + this.eventList = document.getElementById("eventList"); + this.eventBase = initTestBase(); + this.errorManager = new CalendaryErrorManager("Error"); + this.currentFilters = []; + } + toExport.Calendary = Calendary; /** * @function - функция, возвращающая текущую базу событий, но с наложенными фильтрами * @@ -33,228 +35,220 @@ function Calendary() { * * @return {BaseEvent} */ -Calendary.prototype.ApplyFilter = function (filters) { - "use strict"; - var base = this.eventBase, - i; - for (i = 0; i < filters.length; i = i + 1) { - base = filters[i].call(base); + Calendary.prototype.ApplyFilter = function (filters) { + var base = this.eventBase, + i; + for (i = 0; i < filters.length; i = i + 1) { + base = filters[i].call(base); + } + return base; } - return base; -} /** * @function - функция пытается создать событие из данных с формы */ -Calendary.prototype.CreateEvent = function () { - "use strict"; - var parties = [], - partyList, - i, - eventDate, - inputs, - errors, - docfrag, - io, - input; - if (!this.isCorrecteNeedFields()) { - this.changeNeed(); - this.changeAddition(); - return - } - if (!this.isCorrecteAdditionFields()) { - if (!confirm('Некоторые незначительные поля некорректны, продолжить?')) { + Calendary.prototype.CreateEvent = function () { + var parties = [], + partyList, + i, + eventDate, + inputs, + errors, + docfrag, + io, + input; + if (!this.isCorrecteNeedFields()) { + this.changeNeed(); this.changeAddition(); - return; + return } - } - partyList = this.EventFactory.parties.querySelectorAll(" input"); - for ( i = 0; i < partyList.length; i = i + 1) { - if (partyList[i].value && partyList[i].value !== "") { - parties.push({"name" : partyList[i].value}); + if (!this.isCorrecteAdditionFields()) { + if (!confirm('Некоторые незначительные поля некорректны, продолжить?')) { + this.changeAddition(); + return; + } } - } - eventDate = { - "id" : Math.random(), - "location" : { - "gps": { - "x": parseFloat(this.EventFactory.coordinate.querySelector(" .XCoordinate").value), - "y": parseFloat(this.EventFactory.coordinate.querySelector(" .YCoordinate").value) + partyList = this.EventFactory.parties.querySelectorAll(" input"); + for ( i = 0; i < partyList.length; i = i + 1) { + if (partyList[i].value && partyList[i].value !== "") { + parties.push({"name" : partyList[i].value}); + } + } + eventDate = { + "id" : Math.random(), + "location" : { + "gps": { + "x": parseFloat(this.EventFactory.coordinate.querySelector(" .XCoordinate").value), + "y": parseFloat(this.EventFactory.coordinate.querySelector(" .YCoordinate").value) + }, + "nameLocation": this.EventFactory.nameLocation.querySelector("input").value, }, - "nameLocation": this.EventFactory.nameLocation.querySelector("input").value, - }, - "stars" : parseFloat(this.EventFactory.stars.querySelector("input").value), - "cost" : parseFloat(this.EventFactory.cost.querySelector("input").value), - "start": new Date(this.EventFactory.timer.querySelector(".StartDate").value), - "end": new Date(this.EventFactory.timer.querySelector(".FinishDate").value), - "parties" : parties - } - if (DOMValidator.isCoordinate(this.EventFactory.coordinate)) { - eventDate.location.gps.x = 0; - eventDate.location.gps.y = 0; - } - if (DOMValidator.isStars(this.EventFactory.stars)) { - eventDate.stars = 0; - } - if (DOMValidator.isPositiveNumber(this.EventFactory.cost)) { - eventDate.cost = 0; - } - this.eventBase = this.eventBase.add(new Event(eventDate)); - inputs = document.querySelectorAll('#eventFactory input'); - for (i = 0; i < inputs.length; i = i + 1) { - if (inputs[i].type === "text" || inputs[i].type === "date") { - inputs[i].value = ""; + "stars" : parseFloat(this.EventFactory.stars.querySelector("input").value), + "cost" : parseFloat(this.EventFactory.cost.querySelector("input").value), + "start": new Date(this.EventFactory.timer.querySelector(".StartDate").value), + "end": new Date(this.EventFactory.timer.querySelector(".FinishDate").value), + "parties" : parties } + if (DOMValidator.isCoordinate(this.EventFactory.coordinate)) { + eventDate.location.gps.x = 0; + eventDate.location.gps.y = 0; + } + if (DOMValidator.isStars(this.EventFactory.stars)) { + eventDate.stars = 0; + } + if (DOMValidator.isPositiveNumber(this.EventFactory.cost)) { + eventDate.cost = 0; + } + this.eventBase = this.eventBase.add(new Event(eventDate)); + inputs = document.querySelectorAll('#eventFactory input'); + for (i = 0; i < inputs.length; i = i + 1) { + if (inputs[i].type === "text" || inputs[i].type === "date") { + inputs[i].value = ""; + } + } + errors = document.querySelectorAll('#eventFactory .Error'); + for (i = 0; i < errors.length; i = i + 1) { + errors[i].parentElement.removeChild(errors[i]); + } + this.errorManager.removeAllChildren(this.EventFactory.parties); + docfrag = document.createDocumentFragment() + io = document.createElement("li"); + input = document.createElement("input"); + input.type = "text"; + io.appendChild(input); + for (i = 0; i < 3; i = i + 1) { + docfrag.appendChild(io.cloneNode(true)); + } + this.EventFactory.parties.appendChild(docfrag); } - errors = document.querySelectorAll('#eventFactory .Error'); - for (i = 0; i < errors.length; i = i + 1) { - document.remove(errors); - } - this.errorManager.removeAllChildren(this.EventFactory.parties); - docfrag = document.createDocumentFragment() - io = document.createElement("li"); - input = document.createElement("input"); - input.type = "text"; - io.appendChild(input); - for (i = 0; i < 3; i = i + 1) { - docfrag.appendChild(io.cloneNode(true)); - } - this.EventFactory.parties.appendChild(docfrag); -} /** * @function - функция обновляет отфильтрованный список со всеми наложенными фильтрами */ -Calendary.prototype.UpdateShowList = function () { - "use strict"; - var createEventRow = function (number, event) { - var row = (function createRow() { - var rowTable = document.createElement("tr"), - cellTable = document.createElement("td"), + Calendary.prototype.UpdateShowList = function () { + var createEventRow = function (number, event) { + var row = (function createRow() { + var rowTable = document.createElement("tr"), + cellTable = document.createElement("td"), + i; + for (i = 0; i < 7; i = i + 1) { + rowTable.appendChild(cellTable.cloneNode(false)); + } + return rowTable; + }()), + listParty, + n, + aDOMParty, i; - for (i = 0; i < 7; i = i + 1) { - rowTable.appendChild(cellTable.cloneNode(false)); + row.children[0].appendChild(document.createTextNode(number)); + row.children[1].appendChild(document.createTextNode(event.locationToString())); + row.children[2].appendChild(document.createTextNode(event.starsToString())); + row.children[3].appendChild(document.createTextNode(event.start.toDateString())); + row.children[4].appendChild(document.createTextNode(event.end.toDateString())); + row.children[5].appendChild(document.createTextNode(event.cost + " $")); + listParty = document.createElement("select"); + for (i = 0; i < event.parties.length; i += 1) { + aDOMParty = document.createElement("option"); + aDOMParty.appendChild(document.createTextNode(event.parties[i].name)); + listParty.appendChild(aDOMParty); } - return rowTable; - }()), - listParty, - n, - aDOMParty, - i; - row.children[0].appendChild(document.createTextNode(number)); - row.children[1].appendChild(document.createTextNode(event.locationToString())); - row.children[2].appendChild(document.createTextNode(event.starsToString())); - row.children[3].appendChild(document.createTextNode(event.start.toDateString())); - row.children[4].appendChild(document.createTextNode(event.end.toDateString())); - row.children[5].appendChild(document.createTextNode(event.cost + " $")); - listParty = document.createElement("select"); - for (i = 0; i < event.parties.length; i += 1) { - aDOMParty = document.createElement("option"); - aDOMParty.appendChild(document.createTextNode(event.parties[i].name)); - listParty.appendChild(aDOMParty); - } - if (event.parties.length) { - row.children[6].appendChild(listParty); + if (event.parties.length) { + row.children[6].appendChild(listParty); + } + return row; + }, + newEventList, + currentBase, + i, + event; + this.errorManager.removeAllChildren(this.eventList); + newEventList = document.createDocumentFragment(); + currentBase = this.ApplyFilter(this.currentFilters); + for (i = 0; i < currentBase.items.length; i = i + 1) { + event = currentBase.items[i]; + newEventList.appendChild(createEventRow(i + 1, event)); } - return row; - }, - newEventList, - currentBase, - i, - event; - this.errorManager.removeAllChildren(this.eventList); - newEventList = document.createDocumentFragment(); - currentBase = this.ApplyFilter(this.currentFilters); - for (i = 0; i < currentBase.items.length; i = i + 1) { - event = currentBase.items[i]; - newEventList.appendChild(createEventRow(i + 1, event)); + this.eventList.appendChild(newEventList); } - this.eventList.appendChild(newEventList); -} /** * @function функция вызывает обработчики ошибок необходимых полей */ -Calendary.prototype.changeNeed = function () { - "use strict"; - this.errorManager.changeTime(this.EventFactory.timer); - this.errorManager.changeImportantStringField(this.EventFactory.nameLocation); -} + Calendary.prototype.changeNeed = function () { + this.errorManager.changeTime(this.EventFactory.timer); + this.errorManager.changeImportantStringField(this.EventFactory.nameLocation); + } /** * @function функция вызывает обработчики ошибок необязательных полей */ -Calendary.prototype.changeAddition = function () { - "use strict"; - this.errorManager.changeCoordinate(this.EventFactory.coordinate); - this.errorManager.changePositiveNumber(this.EventFactory.cost); - this.errorManager.changeStars(this.EventFactory.stars); -} + Calendary.prototype.changeAddition = function () { + this.errorManager.changeCoordinate(this.EventFactory.coordinate); + this.errorManager.changePositiveNumber(this.EventFactory.cost); + this.errorManager.changeStars(this.EventFactory.stars); + } /** * @function функция проверяет корректность необходимых полей */ -Calendary.prototype.isCorrecteNeedFields = function () { - "use strict"; - return DOMValidator.isTimeInterval(this.EventFactory.timer) === "" && - DOMValidator.isImportantStringField(this.EventFactory.nameLocation) === ""; -} + Calendary.prototype.isCorrecteNeedFields = function () { + return DOMValidator.isTimeInterval(this.EventFactory.timer) === "" && + DOMValidator.isImportantStringField(this.EventFactory.nameLocation) === ""; + } /** * @function функция проверяет корректность дополнительных полей */ -Calendary.prototype.isCorrecteAdditionFields = function () { - "use strict"; - return DOMValidator.isCoordinate(this.EventFactory.coordinate) === "" && - DOMValidator.isStars(this.EventFactory.stars) === "" && - DOMValidator.isPositiveNumber(this.EventFactory.cost) === ""; -} + Calendary.prototype.isCorrecteAdditionFields = function () { + return DOMValidator.isCoordinate(this.EventFactory.coordinate) === "" && + DOMValidator.isStars(this.EventFactory.stars) === "" && + DOMValidator.isPositiveNumber(this.EventFactory.cost) === ""; + } /** * @function функция добавляет дополнительное поле в коллекцию друзей * @param {DIVdomElement} хранилище коллекции друзей */ -Calendary.prototype.addFriend = function (li) { - "use strict"; - var newParty = document.createElement("li"), - input = document.createElement("input"); - input.type = "text"; - newParty.appendChild(input); - li.appendChild(newParty); -} + Calendary.prototype.addFriend = function (li) { + var newParty = document.createElement("li"), + input = document.createElement("input"); + input.type = "text"; + newParty.appendChild(input); + li.appendChild(newParty); + } /** * @function функция, обновляющая данные фильтра из DOM */ -Calendary.prototype.updateFilter = function () { - "use strict"; - var filterRadios = document.querySelectorAll("#FilterEventList input[type = radio]"), - oldFilters = this.currentFilters, - newFilters = [], - i, - radioButton, - partys, - nonEmptyParty, - partyFilter; - for (i = 0; i < filterRadios.length; i = i + 1) { - radioButton = filterRadios[i]; - if (radioButton.checked && - radioButton.checked === true && - radioButton.value != "None") { - var nameFunc = radioButton.value.toString(); - newFilters.push(function() { - return this[nameFunc](); - }); + Calendary.prototype.updateFilter = function () { + var filterRadios = document.querySelectorAll("#FilterEventList input[type = radio]"), + oldFilters = this.currentFilters, + newFilters = [], + i, + radioButton, + partys, + nonEmptyParty, + partyFilter; + for (i = 0; i < filterRadios.length; i = i + 1) { + radioButton = filterRadios[i]; + if (radioButton.checked && + radioButton.checked === true && + radioButton.value != "None") { + var nameFunc = radioButton.value.toString(); + newFilters.push(function() { + return this[nameFunc](); + }); + } } - } - partys = document.querySelectorAll("#FilterFriens input"); - nonEmptyParty = []; - for (i = 0; i < partys.length; i = i + 1) { - if (partys[i].value != "") { - nonEmptyParty.push(partys[i].value); + partys = document.querySelectorAll("#FilterFriens input"); + nonEmptyParty = []; + for (i = 0; i < partys.length; i = i + 1) { + if (partys[i].value != "") { + nonEmptyParty.push(partys[i].value); + } } - } - partyFilter = function() { - var base = this, i - for (i = 0; i < nonEmptyParty.length; i = i + 1) { - base = base.withFriend({ - "name": nonEmptyParty[i] - }); + partyFilter = function() { + var base = this, i + for (i = 0; i < nonEmptyParty.length; i = i + 1) { + base = base.withFriend({ + "name": nonEmptyParty[i] + }); + } + return base; } - return base; + newFilters.push(partyFilter); + this.currentFilters = newFilters; } - newFilters.push(partyFilter); - this.currentFilters = newFilters; -} \ No newline at end of file +}(window)); \ No newline at end of file diff --git a/Task/Scripts/run.js b/Task/Scripts/run.js index 6d9bac3..b5b85c7 100644 --- a/Task/Scripts/run.js +++ b/Task/Scripts/run.js @@ -1,12 +1,9 @@ - /** - * Creates an instance of Event. + * * * @author Alex.Mangin - * - * @function This is the main function */ -function setInt(){ +(function (){ var calendary = new Calendary(); calendary.UpdateShowList(); calendary.EventFactory.timer.addEventListener('blur', function() { @@ -42,4 +39,4 @@ function setInt(){ calendary.updateFilter(); calendary.UpdateShowList(); }, true); -} \ No newline at end of file +}()); \ No newline at end of file diff --git a/Task/Scripts/testData.js b/Task/Scripts/testData.js index 7ac2d6c..69f33a5 100644 --- a/Task/Scripts/testData.js +++ b/Task/Scripts/testData.js @@ -1,101 +1,104 @@ //Это "мясо" T_T -function initTestBase() { +(function (toExport) { "use strict"; - var bestOfSweetsDateStart = new Date("December 10, 2012 00:00:00"), - bestOfSweetsDateFinish = new Date("December 14, 2012 23:59:59"), - bestOfSweets = new Event({"start": bestOfSweetsDateStart, "end": bestOfSweetsDateFinish, "name": "BestOfSweets", "id": 1}), - сirioDeNazareDateStart = new Date("December 8, 2012 00:00:00"), - сirioDeNazareDateFinish = new Date("December 15, 2012 23:59:59"), - сirioDeNazare = new Event({"start": сirioDeNazareDateStart, "end": сirioDeNazareDateFinish, "name": "Cirio De Nazare", "id": 2}), - vinesDayDateStart = new Date("November 10, 2012 00:00:00"), - vinesDayDateFinish = new Date("November 15, 2012 23:59:59"), - vinesDay = new Event({"start": vinesDayDateStart, "end": vinesDayDateFinish, "name": "День вина", "id": 3}), - theBlackCountryDateStart = new Date("November 15, 2012 00:00:00"), - theBlackCountryDateFinish = new Date("December 1, 2012 23:59:59"), - theBlackCountry = new Event({"start": theBlackCountryDateStart, "end": theBlackCountryDateFinish, "name": 'Вкус "Черной страны"', "id": 4}), - oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), - oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), - oktoberFest = new Event({"start": oktoberFestDateStart, "end": oktoberFestDateFinish, "name": 'OktoberFest', "id": 5}), - francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), - francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), - francfurtBook = new Event({"start": francfurtBookDateStart, "end": francfurtBookDateFinish, "name": 'Франкфуртская международная книжная ярмарка', "id": 6}), - aidaDateStart = new Date("October 12, 2012 00:00:00"), - aidaDateFinish = new Date("October 27, 2012 23:59:59"), - aida = new Event({"start": aidaDateStart, "end": aidaDateFinish, "name": '"Аида" у великих пирамид, Гиза', "id": 7}), - paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), - paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), - paradeOfLove = new Event({"start": paradeOfLoveDateStart, "end": paradeOfLoveDateFinish, "name": 'Парад любви', "id": 8}), - sukkotDateStart = new Date("October 3, 2012 00:00:00"), - sukkotDateFinish = new Date("October 3, 2012 23:59:59"), - sukkot = new Event({"start": sukkotDateStart, "end": sukkotDateFinish, "name": 'Парад любви', "id": 9}), - fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), - fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), - fishFestival = new Event({"start": fishFestivalDateStart, "end": fishFestivalDateFinish, "name": 'Фестиваль рыбы', "id": 10}), - chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), - chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), - chocolateFestival = new Event({"start": chocolateFestivalDateStart, "end": chocolateFestivalDateFinish, "name": 'Фестиваль "Еврошоколад"', "id": 11}), - digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), - digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), - digitalArtFestival = new Event({"start": digitalArtFestivalDateStart, "end": digitalArtFestivalDateFinish, "name": 'Фестиваль цифрового исскуства', "id": 12}), - fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), - fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), - fatherDays = new Event({"start": fatherDaysDateStart, "end": fatherDaysDateFinish, "name": 'Дни наследия', "id": 13}), - bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), - bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), - bearWeekend = new Event({"start": bearWeekendDateStart, "end": bearWeekendDateFinish, "name": 'Bear Weekends', "id": 14}), - teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), - teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), - teaFestival = new Event({"start": teaFestivalDateStart, "end": teaFestivalDateFinish, "name": 'Фестиваль Чая', "id": 15}), - programmerDayDateStart = new Date("September 13, 2012 00:00:00"), - programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), - programmerDay = new Event({"start": programmerDayDateStart, "end": programmerDayDateFinish, "name": 'День программмиста', "id": 16}), - knowDayDateStart = new Date("September 1, 2012 00:00:01"), - knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), - knowDayDate = new Event({"start": knowDayDateStart, "end": knowDayDateDateFinish, "name": 'День знаний', "id": 17, "stars": 1}), - teacherDayDateStart = new Date("October 5, 2012 00:00:00"), - teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), - teacherDay = new Event({"start": teacherDayDateStart, "end": teacherDayDateFinish, "name": 'День учителя', "id": 18, "stars": 5}), - securiteDayDateStart = new Date("November 5, 2012 00:00:00"), - securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), - securiteDay = new Event({"start": securiteDayDateStart, "end": securiteDayDateFinish, "name": 'День защиты информации', "id": 19, "stars": 3}), - nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), - nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), - nationUnition = new Event({"start": nationUnitionDateStart, "end": nationUnitionDateDateFinish, "name": 'День нароного единства', "id": 20}); - bestOfSweets.setLocation({"x": 15, "y": 189}, "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"); + var initTestBase = function () { + var bestOfSweetsDateStart = new Date("December 10, 2012 00:00:00"), + bestOfSweetsDateFinish = new Date("December 14, 2012 23:59:59"), + bestOfSweets = new Event({"start": bestOfSweetsDateStart, "end": bestOfSweetsDateFinish, "name": "BestOfSweets", "id": 1}), + сirioDeNazareDateStart = new Date("December 8, 2012 00:00:00"), + сirioDeNazareDateFinish = new Date("December 15, 2012 23:59:59"), + сirioDeNazare = new Event({"start": сirioDeNazareDateStart, "end": сirioDeNazareDateFinish, "name": "Cirio De Nazare", "id": 2}), + vinesDayDateStart = new Date("November 10, 2012 00:00:00"), + vinesDayDateFinish = new Date("November 15, 2012 23:59:59"), + vinesDay = new Event({"start": vinesDayDateStart, "end": vinesDayDateFinish, "name": "День вина", "id": 3}), + theBlackCountryDateStart = new Date("November 15, 2012 00:00:00"), + theBlackCountryDateFinish = new Date("December 1, 2012 23:59:59"), + theBlackCountry = new Event({"start": theBlackCountryDateStart, "end": theBlackCountryDateFinish, "name": 'Вкус "Черной страны"', "id": 4}), + oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), + oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), + oktoberFest = new Event({"start": oktoberFestDateStart, "end": oktoberFestDateFinish, "name": 'OktoberFest', "id": 5}), + francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), + francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), + francfurtBook = new Event({"start": francfurtBookDateStart, "end": francfurtBookDateFinish, "name": 'Франкфуртская международная книжная ярмарка', "id": 6}), + aidaDateStart = new Date("October 12, 2012 00:00:00"), + aidaDateFinish = new Date("October 27, 2012 23:59:59"), + aida = new Event({"start": aidaDateStart, "end": aidaDateFinish, "name": '"Аида" у великих пирамид, Гиза', "id": 7}), + paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), + paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), + paradeOfLove = new Event({"start": paradeOfLoveDateStart, "end": paradeOfLoveDateFinish, "name": 'Парад любви', "id": 8}), + sukkotDateStart = new Date("October 3, 2012 00:00:00"), + sukkotDateFinish = new Date("October 3, 2012 23:59:59"), + sukkot = new Event({"start": sukkotDateStart, "end": sukkotDateFinish, "name": 'Парад любви', "id": 9}), + fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), + fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), + fishFestival = new Event({"start": fishFestivalDateStart, "end": fishFestivalDateFinish, "name": 'Фестиваль рыбы', "id": 10}), + chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), + chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), + chocolateFestival = new Event({"start": chocolateFestivalDateStart, "end": chocolateFestivalDateFinish, "name": 'Фестиваль "Еврошоколад"', "id": 11}), + digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), + digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), + digitalArtFestival = new Event({"start": digitalArtFestivalDateStart, "end": digitalArtFestivalDateFinish, "name": 'Фестиваль цифрового исскуства', "id": 12}), + fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), + fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), + fatherDays = new Event({"start": fatherDaysDateStart, "end": fatherDaysDateFinish, "name": 'Дни наследия', "id": 13}), + bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), + bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), + bearWeekend = new Event({"start": bearWeekendDateStart, "end": bearWeekendDateFinish, "name": 'Bear Weekends', "id": 14}), + teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), + teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), + teaFestival = new Event({"start": teaFestivalDateStart, "end": teaFestivalDateFinish, "name": 'Фестиваль Чая', "id": 15}), + programmerDayDateStart = new Date("September 13, 2012 00:00:00"), + programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), + programmerDay = new Event({"start": programmerDayDateStart, "end": programmerDayDateFinish, "name": 'День программмиста', "id": 16}), + knowDayDateStart = new Date("September 1, 2012 00:00:01"), + knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), + knowDayDate = new Event({"start": knowDayDateStart, "end": knowDayDateDateFinish, "name": 'День знаний', "id": 17, "stars": 1}), + teacherDayDateStart = new Date("October 5, 2012 00:00:00"), + teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), + teacherDay = new Event({"start": teacherDayDateStart, "end": teacherDayDateFinish, "name": 'День учителя', "id": 18, "stars": 5}), + securiteDayDateStart = new Date("November 5, 2012 00:00:00"), + securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), + securiteDay = new Event({"start": securiteDayDateStart, "end": securiteDayDateFinish, "name": 'День защиты информации', "id": 19, "stars": 3}), + nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), + nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), + nationUnition = new Event({"start": nationUnitionDateStart, "end": nationUnitionDateDateFinish, "name": 'День нароного единства', "id": 20}); + bestOfSweets.setLocation({"x": 15, "y": 189}, "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"); - сirioDeNazare.setLocation({"x": 45, "y": 133}, "Бразилия, Белен, Фестиваль Cirio De Nazare"); + сirioDeNazare.setLocation({"x": 45, "y": 133}, "Бразилия, Белен, Фестиваль Cirio De Nazare"); - vinesDay.setLocation({"x": 45, "y": 133}, "Венгрия, Мор, День вина"); + vinesDay.setLocation({"x": 45, "y": 133}, "Венгрия, Мор, День вина"); - theBlackCountry.setLocation({"x": 45, "y": 133}, "Великобритания, Дадли, Вкус 'Черной страны'"); + theBlackCountry.setLocation({"x": 45, "y": 133}, "Великобритания, Дадли, Вкус 'Черной страны'"); - oktoberFest.setLocation({"x": 45, "y": 133}, "Германия, Мюнхен, OktoberFest"); + oktoberFest.setLocation({"x": 45, "y": 133}, "Германия, Мюнхен, OktoberFest"); - programmerDay.parties = [{"name": "Pupkin"}, {"name": "Alex.IDontKnow"}]; - francfurtBook.setLocation({x : 45, y : 133}, "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"); - aida.setLocation({"x": 45, "y": 133}, "Египет, ?, Аида у великих пирамид, Гиза"); - paradeOfLove.setLocation({"x": 45, "y": 133}, "Израль, Тель-Авиве, Парад любви"); + programmerDay.parties = [{"name": "Pupkin"}, {"name": "Alex.IDontKnow"}]; + francfurtBook.setLocation({x : 45, y : 133}, "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"); + aida.setLocation({"x": 45, "y": 133}, "Египет, ?, Аида у великих пирамид, Гиза"); + paradeOfLove.setLocation({"x": 45, "y": 133}, "Израль, Тель-Авиве, Парад любви"); - sukkot.setLocation({"x": 45, y : 133}, "Израль, Иерусалиме, праздник Суккот"); + sukkot.setLocation({"x": 45, y : 133}, "Израль, Иерусалиме, праздник Суккот"); - fishFestival.setLocation({"x": 45, "y": 133}, "Испания, О Грове, Фестиваль рыбы"); + fishFestival.setLocation({"x": 45, "y": 133}, "Испания, О Грове, Фестиваль рыбы"); - chocolateFestival.setLocation({"x": 45, "y": 133}, 'Италия, Перуджа, Фестиваль "Еврошоколад"'); + chocolateFestival.setLocation({"x": 45, "y": 133}, 'Италия, Перуджа, Фестиваль "Еврошоколад"'); - digitalArtFestival.setLocation({"x": 45, "y": 133}, "Австрия, Линц, Фестиваль Цифрового Исскуства"); + digitalArtFestival.setLocation({"x": 45, "y": 133}, "Австрия, Линц, Фестиваль Цифрового Исскуства"); - fatherDays.setLocation({"x": 45, "y": 133}, "Бельгия, Антверпене, Дни наследия"); + fatherDays.setLocation({"x": 45, "y": 133}, "Бельгия, Антверпене, Дни наследия"); - bearWeekend.setLocation({"x": 45, "y": 133}, "Бельгия, Брюссель, Bear Weekends"); + bearWeekend.setLocation({"x": 45, "y": 133}, "Бельгия, Брюссель, Bear Weekends"); - teaFestival.setLocation({"x": 45, "y": 133}, "Россия, Москва, Фестиваль чая"); - programmerDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День программиста"); - programmerDay.parties = [{"name": "Alexander.Mangin"}, {"name": "Alex.IDontKnow"}]; - knowDayDate.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День знаний"); - teacherDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День учителя"); - securiteDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День защиты информации"); - nationUnition.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День народного единства"); -return new BaseEvent([bestOfSweets, сirioDeNazare, vinesDay, theBlackCountry, oktoberFest, francfurtBook - , aida, paradeOfLove, sukkot, fishFestival, chocolateFestival, digitalArtFestival, fatherDays, - bearWeekend, teaFestival, programmerDay, knowDayDate, teacherDay, securiteDay, nationUnition]); -} \ No newline at end of file + teaFestival.setLocation({"x": 45, "y": 133}, "Россия, Москва, Фестиваль чая"); + programmerDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День программиста"); + programmerDay.parties = [{"name": "Alexander.Mangin"}, {"name": "Alex.IDontKnow"}]; + knowDayDate.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День знаний"); + teacherDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День учителя"); + securiteDay.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День защиты информации"); + nationUnition.setLocation({"x": 45, "y": 133}, "Вселенная, Земля, День народного единства"); + return new BaseEvent([bestOfSweets, сirioDeNazare, vinesDay, theBlackCountry, oktoberFest, francfurtBook + , aida, paradeOfLove, sukkot, fishFestival, chocolateFestival, digitalArtFestival, fatherDays, + bearWeekend, teaFestival, programmerDay, knowDayDate, teacherDay, securiteDay, nationUnition]); + } + toExport.initTestBase = initTestBase; +}(window)); \ No newline at end of file diff --git a/Task/index.html b/Task/index.html index 7862ef2..9fb1361 100644 --- a/Task/index.html +++ b/Task/index.html @@ -2,7 +2,7 @@ - +