From 39e32743e13180c839d829bce65fab1745105580 Mon Sep 17 00:00:00 2001 From: Daniel James Date: Tue, 19 Jun 2012 16:23:09 +0100 Subject: [PATCH 001/157] Fixed typos in changelog --- changelog | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/changelog b/changelog index 087af1103..ebe61ddda 100644 --- a/changelog +++ b/changelog @@ -19,7 +19,7 @@ * Removing a watched directory and adding it again preserves playlists & shows with those files. * An icon in the playlist shows whether a file is missing on disk, warning the user that the playlist will not go according to plan. * Media monitor detects add and removal of watched temporary local storage (USB disks for example) and network drives. - * Broadcast Log - export play count of tracks within a given time range.  Useful for royalty reporting purposes. + * Broadcast Log - export play count of tracks within a given time range. Useful for royalty reporting purposes. * Minor Improvements: * Ability to turn off the broadcast. * Editing metadata in the library will update the metadata on disk. @@ -30,7 +30,7 @@ * Repeating shows default to "No End" * Ability to "View on Soundcloud" for recorded shows in the calendar * "Listen" preview player no longer falls behind the broadcast (you can only mute the stream now, not stop it) - * Tracks that cannot be played will be rejected on upload and put in to the directory "/srv/airtime/store/problem_files" (but currently it will not tell you that it rejected them - sorry\!) + * Tracks that cannot be played will be rejected on upload and put in to the directory "/srv/airtime/stor/problem_files" (but currently it will not tell you that it rejected them - sorry\!) * Library is automatically refreshed when media import is finished * Show "Disk Full" message when trying to upload a file that wont fit on the disk * Reduced CPU utilization for OGG streams From 1e8c8f81572a28974f04a09f7fe1fa9805890a27 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Mon, 9 Jul 2012 11:21:12 -0400 Subject: [PATCH 002/157] add a few try catch blocks --- .../airtimefilemonitor/airtimemetadata.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/python_apps/media-monitor/airtimefilemonitor/airtimemetadata.py b/python_apps/media-monitor/airtimefilemonitor/airtimemetadata.py index e7b6ad01d..cea950cba 100644 --- a/python_apps/media-monitor/airtimefilemonitor/airtimemetadata.py +++ b/python_apps/media-monitor/airtimefilemonitor/airtimemetadata.py @@ -221,9 +221,20 @@ class AirtimeMetadata: md['MDATA_KEY_COPYRIGHT'] = self.truncate_to_length(md['MDATA_KEY_COPYRIGHT'], 512) #end of db truncation checks. - md['MDATA_KEY_BITRATE'] = getattr(file_info.info, "bitrate", None) - md['MDATA_KEY_SAMPLERATE'] = getattr(file_info.info, "sample_rate", None) - self.logger.info( "Bitrate: %s , Samplerate: %s", md['MDATA_KEY_BITRATE'], md['MDATA_KEY_SAMPLERATE'] ) + try: + md['MDATA_KEY_BITRATE'] = getattr(file_info.info, "bitrate", "0") + except Exception as e: + self.logger.warn("Could not get Bitrate") + md['MDATA_KEY_BITRATE'] = "0" + + try: + md['MDATA_KEY_SAMPLERATE'] = getattr(file_info.info, "sample_rate", "0") + except Exception as e: + self.logger.warn("Could not get Samplerate") + md['MDATA_KEY_SAMPLERATE'] = "0" + + self.logger.info("Bitrate: %s , Samplerate: %s", md['MDATA_KEY_BITRATE'], md['MDATA_KEY_SAMPLERATE']) + try: md['MDATA_KEY_DURATION'] = self.format_length(file_info.info.length) except Exception as e: self.logger.warn("File: '%s' raises: %s", filepath, str(e)) From 6ce52f081a0075fba226ba63cef981aaf5a26e9d Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Mon, 9 Jul 2012 12:20:41 -0400 Subject: [PATCH 003/157] CC-4091: More comprehensive error message for installs on systems with incorrect locale -done --- install_minimal/airtime-install | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/install_minimal/airtime-install b/install_minimal/airtime-install index 86691c427..8c4541685 100755 --- a/install_minimal/airtime-install +++ b/install_minimal/airtime-install @@ -107,11 +107,28 @@ echo "* Making sure /etc/default/locale is set properly" set +e update-locale cat /etc/default/locale | grep -i "LANG=.*UTF-\?8" -set -e if [ "$?" != "0" ]; then - echo "non UTF-8 default locale found in /etc/default/locale." + echo -e " * Fail\n" + echo "A non UTF-8 default locale found in /etc/default/locale. Airtime requires +a UTF-8 locale to run. To fix this please do the following: + +Ubuntu: +Put line 'en_US.UTF-8 UTF-8' (or similar) without quotes to '/var/lib/locales/supported.d/local', +replacing any existing lines. +A list of supported locales is available in '/usr/share/i18n/SUPPORTED' +Then run 'sudo dpkg-reconfigure locales' + +Debian: +Run 'sudo dpkg-reconfigure locales' and use the interface to select 'en_US.UTF-8 UTF-8' (or similar). +On the second page select this new locale as the default. + +After these changes have been made simply run install again. + +Now exiting install... +" exit 1 fi +set -e # Check if airtime exists already From 67ac4340c4e7963253ba1dc7199b35ddc53d32bd Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 18 Oct 2012 14:47:19 -0400 Subject: [PATCH 004/157] CC-4596: Too many ajax calls in Calendar page -fixed --- .../public/js/airtime/schedule/full-calendar-functions.js | 1 - 1 file changed, 1 deletion(-) diff --git a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js index f583f4df7..a9cd82be3 100644 --- a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js +++ b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js @@ -206,7 +206,6 @@ function viewDisplay( view ) { } function eventRender(event, element, view) { - getCurrentShow(); $(element).data("event", event); From 6727bce3281ec0e3e11d5f0f47466105f413144f Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 18 Oct 2012 15:03:59 -0400 Subject: [PATCH 005/157] CC-4598: Smart block: cannot save dynamic block with 0.5 hours -fixed --- airtime_mvc/application/models/Block.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/airtime_mvc/application/models/Block.php b/airtime_mvc/application/models/Block.php index 4d62b8329..eb1aab691 100644 --- a/airtime_mvc/application/models/Block.php +++ b/airtime_mvc/application/models/Block.php @@ -319,12 +319,12 @@ SQL; if ($mins >59) { $hour = intval($mins/60); $hour = str_pad($hour, 2, "0", STR_PAD_LEFT); - $value = $mins%60; + $mins = $mins%60; } } $hour = str_pad($hour, 2, "0", STR_PAD_LEFT); - $value = str_pad($value, 2, "0", STR_PAD_LEFT); - $length = $hour.":".$value.":00"; + $mins = str_pad($mins, 2, "0", STR_PAD_LEFT); + $length = $hour.":".$mins.":00"; } return $length; From e9815b617b66aa657e929d3b8f5f89382cc60b54 Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 18 Oct 2012 15:21:38 -0400 Subject: [PATCH 006/157] - added comment --- .../public/js/airtime/schedule/full-calendar-functions.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js index a9cd82be3..ac57d6afb 100644 --- a/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js +++ b/airtime_mvc/public/js/airtime/schedule/full-calendar-functions.js @@ -370,7 +370,9 @@ function checkSCUploadStatus(){ }); }); } - +/** This function adds and removes the current + * show icon + */ function getCurrentShow(){ var url = '/Schedule/get-current-show/format/json', id, From d838d8ae30b77704e51b167e28de32aade57bc21 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Thu, 18 Oct 2012 17:34:37 -0400 Subject: [PATCH 007/157] update version number in VERSION --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 682777c6f..c7aac0e6d 100644 --- a/VERSION +++ b/VERSION @@ -1,2 +1,2 @@ PRODUCT_ID=Airtime -PRODUCT_RELEASE=2.1.3 +PRODUCT_RELEASE=2.2.0 From 58d00cb9b90aacbbde00d0b89e9f58df0dcde3ca Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 19 Oct 2012 11:05:12 -0400 Subject: [PATCH 008/157] Formatting sql --- .../application/models/ShowInstance.php | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index 6a513aac4..3dfd8756f 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -670,15 +670,15 @@ SELECT * FROM ( (SELECT s.starts, 0::INTEGER as type , - f.id AS item_id, + f.id AS item_id, f.track_title, - f.album_title AS album, - f.genre AS genre, - f.length AS length, - f.artist_name AS creator, - f.file_exists AS EXISTS, - f.filepath AS filepath, - f.mime AS mime + f.album_title AS album, + f.genre AS genre, + f.length AS length, + f.artist_name AS creator, + f.file_exists AS EXISTS, + f.filepath AS filepath, + f.mime AS mime FROM cc_schedule AS s LEFT JOIN cc_files AS f ON f.id = s.file_id WHERE s.instance_id = :instance_id1 @@ -689,12 +689,12 @@ FROM ( 1::INTEGER as type, ws.id AS item_id, (ws.name || ': ' || ws.url) AS title, - null AS album, - null AS genre, - ws.length AS length, - sub.login AS creator, - 't'::boolean AS EXISTS, - ws.url AS filepath, + null AS album, + null AS genre, + ws.length AS length, + sub.login AS creator, + 't'::boolean AS EXISTS, + ws.url AS filepath, ws.mime as mime FROM cc_schedule AS s LEFT JOIN cc_webstream AS ws ON ws.id = s.stream_id From ffca5b42a89e7ffbf4725cdf0494c2847feffe2b Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 11:07:37 -0400 Subject: [PATCH 009/157] CC-4605: Some AJAX calls are cached --- airtime_mvc/public/js/airtime/dashboard/dashboard.js | 2 +- airtime_mvc/public/js/airtime/library/library.js | 3 +++ airtime_mvc/public/js/airtime/nowplaying/register.js | 2 ++ .../public/js/airtime/playouthistory/historytable.js | 3 ++- airtime_mvc/public/js/airtime/schedule/schedule.js | 5 ++++- airtime_mvc/public/js/airtime/showbuilder/builder.js | 4 ++++ .../public/js/airtime/showbuilder/main_builder.js | 3 +++ airtime_mvc/public/js/airtime/user/user.js | 11 +++++++++-- 8 files changed, 28 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/public/js/airtime/dashboard/dashboard.js b/airtime_mvc/public/js/airtime/dashboard/dashboard.js index 98a167238..741c5b4fa 100644 --- a/airtime_mvc/public/js/airtime/dashboard/dashboard.js +++ b/airtime_mvc/public/js/airtime/dashboard/dashboard.js @@ -360,7 +360,7 @@ function controlSwitchLight(){ } function getScheduleFromServer(){ - $.ajax({ url: "/Schedule/get-current-playlist/format/json", dataType:"json", success:function(data){ + $.ajax({ cache: false, url: "/Schedule/get-current-playlist/format/json", dataType:"json", success:function(data){ parseItems(data.entries); parseSourceStatus(data.source_status); parseSwitchStatus(data.switch_status); diff --git a/airtime_mvc/public/js/airtime/library/library.js b/airtime_mvc/public/js/airtime/library/library.js index a832134c1..cfab12c6b 100644 --- a/airtime_mvc/public/js/airtime/library/library.js +++ b/airtime_mvc/public/js/airtime/library/library.js @@ -479,6 +479,7 @@ var AIRTIME = (function(AIRTIME) { "fnStateSave": function (oSettings, oData) { localStorage.setItem('datatables-library', JSON.stringify(oData)); $.ajax({ + cache: false, url: "/usersettings/set-library-datatable", type: "POST", data: {settings : oData, format: "json"}, @@ -542,6 +543,7 @@ var AIRTIME = (function(AIRTIME) { aoData.push( { name: "type", value: type} ); $.ajax( { + "cache": false, "dataType": 'json', "type": "POST", "url": sSource, @@ -883,6 +885,7 @@ var AIRTIME = (function(AIRTIME) { } request = $.ajax({ + cache: false, url: "/library/context-menu", type: "GET", data: {id : data.id, type: data.ftype, format: "json", "screen": screen}, diff --git a/airtime_mvc/public/js/airtime/nowplaying/register.js b/airtime_mvc/public/js/airtime/nowplaying/register.js index 0b5b04249..068f0d11a 100644 --- a/airtime_mvc/public/js/airtime/nowplaying/register.js +++ b/airtime_mvc/public/js/airtime/nowplaying/register.js @@ -21,6 +21,7 @@ $(document).ready(function(){ click: function() { var url = '/Usersettings/remindme'; $.ajax({ + cache: false, url: url, data: {format:"json"} }); @@ -34,6 +35,7 @@ $(document).ready(function(){ click: function() { var url ='/Usersettings/remindme-never'; $.ajax({ + cache: false, url: url, data: {format:"json"} }); diff --git a/airtime_mvc/public/js/airtime/playouthistory/historytable.js b/airtime_mvc/public/js/airtime/playouthistory/historytable.js index 9a0db2680..0371fada5 100644 --- a/airtime_mvc/public/js/airtime/playouthistory/historytable.js +++ b/airtime_mvc/public/js/airtime/playouthistory/historytable.js @@ -54,6 +54,7 @@ var AIRTIME = (function(AIRTIME) { aoData.push( { name: "format", value: "json"} ); $.ajax( { + "cache": false, "dataType": 'json', "type": "GET", "url": sSource, @@ -183,4 +184,4 @@ $(document).ready(function(){ oTable.fnDraw(); }); -}); \ No newline at end of file +}); diff --git a/airtime_mvc/public/js/airtime/schedule/schedule.js b/airtime_mvc/public/js/airtime/schedule/schedule.js index 5a43f1eb2..3bddc60f5 100644 --- a/airtime_mvc/public/js/airtime/schedule/schedule.js +++ b/airtime_mvc/public/js/airtime/schedule/schedule.js @@ -36,6 +36,7 @@ function confirmCancelShow(show_instance_id){ if (confirm('Cancel Current Show?')) { var url = "/Schedule/cancel-current-show"; $.ajax({ + cache: false, url: url, data: {format: "json", id: show_instance_id}, success: function(data){ @@ -50,6 +51,7 @@ function confirmCancelRecordedShow(show_instance_id){ var url = "/Schedule/cancel-current-show"; $.ajax({ url: url, + cache: false, data: {format: "json", id: show_instance_id}, success: function(data){ scheduleRefetchEvents(data); @@ -289,7 +291,7 @@ function alertShowErrorAndReload(){ } $(document).ready(function() { - $.ajax({ url: "/Api/calendar-init/format/json", dataType:"json", success:createFullCalendar + $.ajax({ cache: false, url: "/Api/calendar-init/format/json", dataType:"json", success:createFullCalendar , error:function(jqXHR, textStatus, errorThrown){}}); setInterval(checkCalendarSCUploadStatus, 5000); @@ -459,6 +461,7 @@ $(document).ready(function() { } $.ajax({ + cache: false, url: "/schedule/make-context-menu", type: "GET", data: {id : data.id, format: "json"}, diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index 9839df06c..8bcfbdc4a 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -326,6 +326,7 @@ var AIRTIME = (function(AIRTIME){ } $.ajax({ + "cache": false, "dataType": "json", "type": "POST", "url": sSource, @@ -379,6 +380,7 @@ var AIRTIME = (function(AIRTIME){ localStorage.setItem('datatables-timeline', JSON.stringify(oData)); $.ajax({ + cache: false, url: "/usersettings/set-timeline-datatable", type: "POST", data: {settings : oData, format: "json"}, @@ -1003,6 +1005,7 @@ var AIRTIME = (function(AIRTIME){ if (confirm(msg)) { var url = "/Schedule/cancel-current-show"; $.ajax({ + cache: false, url: url, data: {format: "json", id: data.instance}, success: function(data){ @@ -1181,6 +1184,7 @@ var AIRTIME = (function(AIRTIME){ } request = $.ajax({ + cache: false, url: "/showbuilder/context-menu", type: "GET", data: {id : data.id, format: "json"}, diff --git a/airtime_mvc/public/js/airtime/showbuilder/main_builder.js b/airtime_mvc/public/js/airtime/showbuilder/main_builder.js index b640a2882..60a224838 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/main_builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/main_builder.js @@ -168,6 +168,7 @@ AIRTIME = (function(AIRTIME) { schedTable.fnDraw(); $.ajax({ + cache: false, url: "/usersettings/set-now-playing-screen-settings", type: "POST", data: {settings : {library : true}, format: "json"}, @@ -192,6 +193,7 @@ AIRTIME = (function(AIRTIME) { schedTable.fnDraw(); $.ajax({ + cache: false, url: "/usersettings/set-now-playing-screen-settings", type: "POST", data: {settings : {library : false}, format: "json"}, @@ -257,6 +259,7 @@ AIRTIME = (function(AIRTIME) { } $.ajax( { + "cache": false, "dataType": "json", "type": "GET", "url": "/showbuilder/check-builder-feed", diff --git a/airtime_mvc/public/js/airtime/user/user.js b/airtime_mvc/public/js/airtime/user/user.js index 5c8278914..a6ae9b3f8 100644 --- a/airtime_mvc/public/js/airtime/user/user.js +++ b/airtime_mvc/public/js/airtime/user/user.js @@ -24,13 +24,19 @@ function populateForm(entries){ } function rowClickCallback(row_id){ - $.ajax({ url: '/User/get-user-data/id/'+ row_id +'/format/json', dataType:"json", success:function(data){ + $.ajax({ cache: false, + url: '/User/get-user-data/id/'+ row_id +'/format/json', + dataType:"json", + success:function(data){ populateForm(data.entries); }}); } function removeUserCallback(row_id, nRow){ - $.ajax({ url: '/User/remove-user/id/'+ row_id +'/format/json', dataType:"text", success:function(data){ + $.ajax({ cache: false, + url: '/User/remove-user/id/'+ row_id +'/format/json', + dataType:"text", + success:function(data){ var o = $('#users_datatable').dataTable().fnDeleteRow(nRow); }}); } @@ -67,6 +73,7 @@ $(document).ready(function() { "sAjaxSource": "/User/get-user-data-table-info/format/json", "fnServerData": function ( sSource, aoData, fnCallback ) { $.ajax( { + "cache": false, "dataType": 'json', "type": "POST", "url": sSource, From d5c2c37a3eb26be60852833a1150122df1c0b6be Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 11:16:42 -0400 Subject: [PATCH 010/157] Revert "CC-4605: Some AJAX calls are cached" This reverts commit ffca5b42a89e7ffbf4725cdf0494c2847feffe2b. --- airtime_mvc/public/js/airtime/dashboard/dashboard.js | 2 +- airtime_mvc/public/js/airtime/library/library.js | 3 --- airtime_mvc/public/js/airtime/nowplaying/register.js | 2 -- .../public/js/airtime/playouthistory/historytable.js | 3 +-- airtime_mvc/public/js/airtime/schedule/schedule.js | 5 +---- airtime_mvc/public/js/airtime/showbuilder/builder.js | 4 ---- .../public/js/airtime/showbuilder/main_builder.js | 3 --- airtime_mvc/public/js/airtime/user/user.js | 11 ++--------- 8 files changed, 5 insertions(+), 28 deletions(-) diff --git a/airtime_mvc/public/js/airtime/dashboard/dashboard.js b/airtime_mvc/public/js/airtime/dashboard/dashboard.js index 741c5b4fa..98a167238 100644 --- a/airtime_mvc/public/js/airtime/dashboard/dashboard.js +++ b/airtime_mvc/public/js/airtime/dashboard/dashboard.js @@ -360,7 +360,7 @@ function controlSwitchLight(){ } function getScheduleFromServer(){ - $.ajax({ cache: false, url: "/Schedule/get-current-playlist/format/json", dataType:"json", success:function(data){ + $.ajax({ url: "/Schedule/get-current-playlist/format/json", dataType:"json", success:function(data){ parseItems(data.entries); parseSourceStatus(data.source_status); parseSwitchStatus(data.switch_status); diff --git a/airtime_mvc/public/js/airtime/library/library.js b/airtime_mvc/public/js/airtime/library/library.js index cfab12c6b..a832134c1 100644 --- a/airtime_mvc/public/js/airtime/library/library.js +++ b/airtime_mvc/public/js/airtime/library/library.js @@ -479,7 +479,6 @@ var AIRTIME = (function(AIRTIME) { "fnStateSave": function (oSettings, oData) { localStorage.setItem('datatables-library', JSON.stringify(oData)); $.ajax({ - cache: false, url: "/usersettings/set-library-datatable", type: "POST", data: {settings : oData, format: "json"}, @@ -543,7 +542,6 @@ var AIRTIME = (function(AIRTIME) { aoData.push( { name: "type", value: type} ); $.ajax( { - "cache": false, "dataType": 'json', "type": "POST", "url": sSource, @@ -885,7 +883,6 @@ var AIRTIME = (function(AIRTIME) { } request = $.ajax({ - cache: false, url: "/library/context-menu", type: "GET", data: {id : data.id, type: data.ftype, format: "json", "screen": screen}, diff --git a/airtime_mvc/public/js/airtime/nowplaying/register.js b/airtime_mvc/public/js/airtime/nowplaying/register.js index 068f0d11a..0b5b04249 100644 --- a/airtime_mvc/public/js/airtime/nowplaying/register.js +++ b/airtime_mvc/public/js/airtime/nowplaying/register.js @@ -21,7 +21,6 @@ $(document).ready(function(){ click: function() { var url = '/Usersettings/remindme'; $.ajax({ - cache: false, url: url, data: {format:"json"} }); @@ -35,7 +34,6 @@ $(document).ready(function(){ click: function() { var url ='/Usersettings/remindme-never'; $.ajax({ - cache: false, url: url, data: {format:"json"} }); diff --git a/airtime_mvc/public/js/airtime/playouthistory/historytable.js b/airtime_mvc/public/js/airtime/playouthistory/historytable.js index 0371fada5..9a0db2680 100644 --- a/airtime_mvc/public/js/airtime/playouthistory/historytable.js +++ b/airtime_mvc/public/js/airtime/playouthistory/historytable.js @@ -54,7 +54,6 @@ var AIRTIME = (function(AIRTIME) { aoData.push( { name: "format", value: "json"} ); $.ajax( { - "cache": false, "dataType": 'json', "type": "GET", "url": sSource, @@ -184,4 +183,4 @@ $(document).ready(function(){ oTable.fnDraw(); }); -}); +}); \ No newline at end of file diff --git a/airtime_mvc/public/js/airtime/schedule/schedule.js b/airtime_mvc/public/js/airtime/schedule/schedule.js index 3bddc60f5..5a43f1eb2 100644 --- a/airtime_mvc/public/js/airtime/schedule/schedule.js +++ b/airtime_mvc/public/js/airtime/schedule/schedule.js @@ -36,7 +36,6 @@ function confirmCancelShow(show_instance_id){ if (confirm('Cancel Current Show?')) { var url = "/Schedule/cancel-current-show"; $.ajax({ - cache: false, url: url, data: {format: "json", id: show_instance_id}, success: function(data){ @@ -51,7 +50,6 @@ function confirmCancelRecordedShow(show_instance_id){ var url = "/Schedule/cancel-current-show"; $.ajax({ url: url, - cache: false, data: {format: "json", id: show_instance_id}, success: function(data){ scheduleRefetchEvents(data); @@ -291,7 +289,7 @@ function alertShowErrorAndReload(){ } $(document).ready(function() { - $.ajax({ cache: false, url: "/Api/calendar-init/format/json", dataType:"json", success:createFullCalendar + $.ajax({ url: "/Api/calendar-init/format/json", dataType:"json", success:createFullCalendar , error:function(jqXHR, textStatus, errorThrown){}}); setInterval(checkCalendarSCUploadStatus, 5000); @@ -461,7 +459,6 @@ $(document).ready(function() { } $.ajax({ - cache: false, url: "/schedule/make-context-menu", type: "GET", data: {id : data.id, format: "json"}, diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index 8bcfbdc4a..9839df06c 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -326,7 +326,6 @@ var AIRTIME = (function(AIRTIME){ } $.ajax({ - "cache": false, "dataType": "json", "type": "POST", "url": sSource, @@ -380,7 +379,6 @@ var AIRTIME = (function(AIRTIME){ localStorage.setItem('datatables-timeline', JSON.stringify(oData)); $.ajax({ - cache: false, url: "/usersettings/set-timeline-datatable", type: "POST", data: {settings : oData, format: "json"}, @@ -1005,7 +1003,6 @@ var AIRTIME = (function(AIRTIME){ if (confirm(msg)) { var url = "/Schedule/cancel-current-show"; $.ajax({ - cache: false, url: url, data: {format: "json", id: data.instance}, success: function(data){ @@ -1184,7 +1181,6 @@ var AIRTIME = (function(AIRTIME){ } request = $.ajax({ - cache: false, url: "/showbuilder/context-menu", type: "GET", data: {id : data.id, format: "json"}, diff --git a/airtime_mvc/public/js/airtime/showbuilder/main_builder.js b/airtime_mvc/public/js/airtime/showbuilder/main_builder.js index 60a224838..b640a2882 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/main_builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/main_builder.js @@ -168,7 +168,6 @@ AIRTIME = (function(AIRTIME) { schedTable.fnDraw(); $.ajax({ - cache: false, url: "/usersettings/set-now-playing-screen-settings", type: "POST", data: {settings : {library : true}, format: "json"}, @@ -193,7 +192,6 @@ AIRTIME = (function(AIRTIME) { schedTable.fnDraw(); $.ajax({ - cache: false, url: "/usersettings/set-now-playing-screen-settings", type: "POST", data: {settings : {library : false}, format: "json"}, @@ -259,7 +257,6 @@ AIRTIME = (function(AIRTIME) { } $.ajax( { - "cache": false, "dataType": "json", "type": "GET", "url": "/showbuilder/check-builder-feed", diff --git a/airtime_mvc/public/js/airtime/user/user.js b/airtime_mvc/public/js/airtime/user/user.js index a6ae9b3f8..5c8278914 100644 --- a/airtime_mvc/public/js/airtime/user/user.js +++ b/airtime_mvc/public/js/airtime/user/user.js @@ -24,19 +24,13 @@ function populateForm(entries){ } function rowClickCallback(row_id){ - $.ajax({ cache: false, - url: '/User/get-user-data/id/'+ row_id +'/format/json', - dataType:"json", - success:function(data){ + $.ajax({ url: '/User/get-user-data/id/'+ row_id +'/format/json', dataType:"json", success:function(data){ populateForm(data.entries); }}); } function removeUserCallback(row_id, nRow){ - $.ajax({ cache: false, - url: '/User/remove-user/id/'+ row_id +'/format/json', - dataType:"text", - success:function(data){ + $.ajax({ url: '/User/remove-user/id/'+ row_id +'/format/json', dataType:"text", success:function(data){ var o = $('#users_datatable').dataTable().fnDeleteRow(nRow); }}); } @@ -73,7 +67,6 @@ $(document).ready(function() { "sAjaxSource": "/User/get-user-data-table-info/format/json", "fnServerData": function ( sSource, aoData, fnCallback ) { $.ajax( { - "cache": false, "dataType": 'json', "type": "POST", "url": sSource, From f5051cff3a31540f6e28aa9c33890505738ff73b Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 11:22:44 -0400 Subject: [PATCH 011/157] CC-4605: Some AJAX calls are cached -fixed --- airtime_mvc/application/Bootstrap.php | 3 +-- airtime_mvc/public/js/airtime/airtime_bootstrap.js | 5 +++++ 2 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 airtime_mvc/public/js/airtime/airtime_bootstrap.js diff --git a/airtime_mvc/application/Bootstrap.php b/airtime_mvc/application/Bootstrap.php index c4c53ffa5..cb35a8a9c 100644 --- a/airtime_mvc/application/Bootstrap.php +++ b/airtime_mvc/application/Bootstrap.php @@ -75,6 +75,7 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap $view->headScript()->appendScript("var baseUrl='$baseUrl/'"); //scripts for now playing bar + $view->headScript()->appendFile($baseUrl.'/js/airtime/airtime_bootstrap.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/helperfunctions.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/dashboard.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); $view->headScript()->appendFile($baseUrl.'/js/airtime/dashboard/versiontooltip.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); @@ -91,8 +92,6 @@ class Bootstrap extends Zend_Application_Bootstrap_Bootstrap } $view->headScript()->appendScript("var userType = '$userType';"); - - if (isset($CC_CONFIG['demo']) && $CC_CONFIG['demo'] == 1) { $view->headScript()->appendFile($baseUrl.'/js/libs/google-analytics.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); } diff --git a/airtime_mvc/public/js/airtime/airtime_bootstrap.js b/airtime_mvc/public/js/airtime/airtime_bootstrap.js new file mode 100644 index 000000000..632d61627 --- /dev/null +++ b/airtime_mvc/public/js/airtime/airtime_bootstrap.js @@ -0,0 +1,5 @@ +$(document).ready(function() { + $.ajaxSetup({ + cache: false + }); +}); From 8d56c03fe3e198f944513069c80bd7a399675156 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 19 Oct 2012 11:32:35 -0400 Subject: [PATCH 012/157] deep voodoo magic to optimize schedule --- airtime_mvc/application/models/Show.php | 4 ++-- .../application/models/ShowInstance.php | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index bb58409fd..5da348b52 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1789,9 +1789,9 @@ SQL; $showInstance = new Application_Model_ShowInstance( $show["instance_id"]); - $showContent = $showInstance->getShowListContent(); + //$showContent = $showInstance->getShowListContent(); - $options["show_empty"] = empty($showContent) ? 1 : 0; + $options["show_empty"] = ($showInstance->showEmpty()) ? 1 : 0; $events[] = &self::makeFullCalendarEvent($show, $options, $startsDT, $endsDT, $startsEpochStr, $endsEpochStr); diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index 3dfd8756f..e657494f9 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -661,6 +661,28 @@ SQL; return $returnStr; } + + public function showEmpty() + { + $sql = <<= 0 + AND ((s.stream_id IS NOT NULL) + OR (s.file_id IS NOT NULL)) LIMIT 1 +SQL; + # TODO : use prepareAndExecute properly + $res = Application_Common_Database::prepareAndExecute($sql, + array( ':instance_id' => $this->_instanceId ), 'all' ); + # TODO : A bit retarded. fix this later + foreach ($res as $r) { + return false; + } + return true; + + } + public function getShowListContent() { $con = Propel::getConnection(); From ee89ac660375481bfca7ba99b49406d6e822e591 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 12:16:04 -0400 Subject: [PATCH 013/157] CC-4589: Small inconsistency in config files after upgrade --- .../upgrades/airtime-2.2.0/common/UpgradeCommon.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/install_minimal/upgrades/airtime-2.2.0/common/UpgradeCommon.php b/install_minimal/upgrades/airtime-2.2.0/common/UpgradeCommon.php index 77c297a65..496a576a2 100644 --- a/install_minimal/upgrades/airtime-2.2.0/common/UpgradeCommon.php +++ b/install_minimal/upgrades/airtime-2.2.0/common/UpgradeCommon.php @@ -111,6 +111,10 @@ class UpgradeCommon{ $old = "list_all_db_files = 'list-all-files/format/json/api_key/%%api_key%%/dir_id/%%dir_id%%'"; $new = "list_all_db_files = 'list-all-files/format/json/api_key/%%api_key%%/dir_id/%%dir_id%%/all/%%all%%'"; exec("sed -i \"s#$old#$new#g\" /etc/airtime/api_client.cfg"); + + $old = "update_start_playing_url = 'notify-media-item-start-play/api_key/%%api_key%%/media_id/%%media_id%%/schedule_id/%%schedule_id%%'"; + $new = "update_start_playing_url = 'notify-media-item-start-play/api_key/%%api_key%%/media_id/%%media_id%%/'"; + exec("sed -i \"s#$old#$new#g\" /etc/airtime/api_client.cfg"); } /** From a51c3174e0f18f844b312d4c1ea401f2098d74d8 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 19 Oct 2012 12:33:12 -0400 Subject: [PATCH 014/157] SAAS-282: Overlap detection prevents creation of a repeating show -fixed --- airtime_mvc/application/forms/AddShowWhen.php | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/airtime_mvc/application/forms/AddShowWhen.php b/airtime_mvc/application/forms/AddShowWhen.php index 1ed9d2619..e6d164022 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -143,10 +143,12 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm * upto this point */ if ($valid) { + $utc = new DateTimeZone('UTC'); + $localTimezone = new DateTimeZone(Application_Model_Preference::GetTimezone()); $show_start = new DateTime($start_time); - $show_start->setTimezone(new DateTimeZone('UTC')); + $show_start->setTimezone($utc); $show_end = new DateTime($end_time); - $show_end->setTimezone(new DateTimeZone('UTC')); + $show_end->setTimezone($utc); if ($formData["add_show_repeats"]) { @@ -155,7 +157,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm $date = Application_Model_Preference::GetShowsPopulatedUntil(); if (is_null($date)) { - $populateUntilDateTime = new DateTime("now", new DateTimeZone('UTC')); + $populateUntilDateTime = new DateTime("now", $utc); Application_Model_Preference::SetShowsPopulatedUntil($populateUntilDateTime); } else { $populateUntilDateTime = clone $date; @@ -164,7 +166,7 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } elseif (!$formData["add_show_no_end"]) { $popUntil = $formData["add_show_end_date"]." ".$formData["add_show_end_time"]; $populateUntilDateTime = new DateTime($popUntil); - $populateUntilDateTime->setTimezone(new DateTimeZone('UTC')); + $populateUntilDateTime->setTimezone($utc); } //get repeat interval @@ -203,8 +205,18 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm else $daysAdd = $day - $startDow; + /* In case we are crossing daylights saving time we need + * to convert show start and show end to local time before + * adding the interval for the next repeating show + */ + + $repeatShowStart->setTimezone($localTimezone); + $repeatShowEnd->setTimezone($localTimezone); $repeatShowStart->add(new DateInterval("P".$daysAdd."D")); $repeatShowEnd->add(new DateInterval("P".$daysAdd."D")); + //set back to UTC + $repeatShowStart->setTimezone($utc); + $repeatShowEnd->setTimezone($utc); } /* Here we are checking each repeating show by * the show day. @@ -238,8 +250,12 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm $this->getElement('add_show_duration')->setErrors(array('Cannot schedule overlapping shows')); break 1; } else { + $repeatShowStart->setTimezone($localTimezone); + $repeatShowEnd->setTimezone($localTimezone); $repeatShowStart->add(new DateInterval($interval)); $repeatShowEnd->add(new DateInterval($interval)); + $repeatShowStart->setTimezone($utc); + $repeatShowEnd->setTimezone($utc); } } } From a1e653b41f0657ca8d366897e0c824cd993fe7a5 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 19 Oct 2012 13:22:00 -0400 Subject: [PATCH 015/157] Deep optimization --- airtime_mvc/application/models/Show.php | 7 ++++--- .../application/models/ShowInstance.php | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 5da348b52..0006057f7 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1743,7 +1743,8 @@ SQL; $days = $interval->format('%a'); $shows = Application_Model_Show::getShows($p_start, $p_end); $nowEpoch = time(); - + $content_count = Application_Model_ShowInstance::getContentCount( + $p_start, $p_end); $timezone = date_default_timezone_get(); foreach ($shows as $show) { @@ -1789,9 +1790,9 @@ SQL; $showInstance = new Application_Model_ShowInstance( $show["instance_id"]); - //$showContent = $showInstance->getShowListContent(); - $options["show_empty"] = ($showInstance->showEmpty()) ? 1 : 0; + $options["show_empty"] = (array_key_exists($show['instance_id'], + $content_count)) ? 1 : 0; $events[] = &self::makeFullCalendarEvent($show, $options, $startsDT, $endsDT, $startsEpochStr, $endsEpochStr); diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index e657494f9..8854f3896 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -662,6 +662,27 @@ SQL; } + + public static function getContentCount($p_start, $p_end) + { + $sql = << :p_start::TIMESTAMP + AND starts < :p_end::TIMESTAMP +GROUP BY instance_id; +SQL; + + $counts = Application_Common_Database::prepareAndExecute( $sql, array( + ':p_start' => $p_start->format("Y-m-d G:i:s"), + ':p_end' => $p_end->format("Y-m-d G:i:s")) + , 'all'); + + return $counts; + + } + public function showEmpty() { $sql = << Date: Fri, 19 Oct 2012 13:24:06 -0400 Subject: [PATCH 016/157] Removed trailing whitespace --- airtime_mvc/application/models/ShowInstance.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index 8854f3896..5b60e1f70 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -671,16 +671,16 @@ SELECT instance_id, FROM cc_schedule WHERE ends > :p_start::TIMESTAMP AND starts < :p_end::TIMESTAMP -GROUP BY instance_id; -SQL; +GROUP BY instance_id +SQL; - $counts = Application_Common_Database::prepareAndExecute( $sql, array( - ':p_start' => $p_start->format("Y-m-d G:i:s"), + $counts = Application_Common_Database::prepareAndExecute( $sql, array( + ':p_start' => $p_start->format("Y-m-d G:i:s"), ':p_end' => $p_end->format("Y-m-d G:i:s")) - , 'all'); - - return $counts; - + , 'all'); + + return $counts; + } public function showEmpty() From 8f998fd2c89edc5334f3ae1d138f04aaee0bc0e2 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 19 Oct 2012 13:42:24 -0400 Subject: [PATCH 017/157] CC-4595: Fade in/out setting doesn't work -fixed --- airtime_mvc/application/models/airtime/CcSchedule.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/airtime_mvc/application/models/airtime/CcSchedule.php b/airtime_mvc/application/models/airtime/CcSchedule.php index e051df6c3..db7fb19a7 100644 --- a/airtime_mvc/application/models/airtime/CcSchedule.php +++ b/airtime_mvc/application/models/airtime/CcSchedule.php @@ -127,9 +127,9 @@ class CcSchedule extends BaseCcSchedule { } if ($microsecond == 0) { - $this->fadein = $dt->format('H:i:s.u'); + $this->fade_in = $dt->format('H:i:s.u'); } else { - $this->fadein = $dt->format('H:i:s').".".$microsecond; + $this->fade_in = $dt->format('H:i:s').".".$microsecond; } $this->modifiedColumns[] = CcSchedulePeer::FADE_IN; @@ -164,9 +164,9 @@ class CcSchedule extends BaseCcSchedule { } if ($microsecond == 0) { - $this->fadeout = $dt->format('H:i:s.u'); + $this->fade_out = $dt->format('H:i:s.u'); } else { - $this->fadeout = $dt->format('H:i:s').".".$microsecond; + $this->fade_out = $dt->format('H:i:s').".".$microsecond; } $this->modifiedColumns[] = CcSchedulePeer::FADE_OUT; From 96ff4404350360af4c51b2b6b33298d3cd8fca84 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 19 Oct 2012 14:18:34 -0400 Subject: [PATCH 018/157] Removed space --- airtime_mvc/application/models/ShowInstance.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index 5b60e1f70..a73d1f7f0 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -674,7 +674,7 @@ WHERE ends > :p_start::TIMESTAMP GROUP BY instance_id SQL; - $counts = Application_Common_Database::prepareAndExecute( $sql, array( + $counts = Application_Common_Database::prepareAndExecute($sql, array( ':p_start' => $p_start->format("Y-m-d G:i:s"), ':p_end' => $p_end->format("Y-m-d G:i:s")) , 'all'); From 1146e1f269fb60b1c4112460213fc73c3b8d89e0 Mon Sep 17 00:00:00 2001 From: James Date: Fri, 19 Oct 2012 14:27:57 -0400 Subject: [PATCH 019/157] CC-4215: Smart Playlist: Exception happens when generate with criteria Length is 2012-08-10 14:00:00 - fixed --- airtime_mvc/application/forms/SmartBlockCriteria.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airtime_mvc/application/forms/SmartBlockCriteria.php b/airtime_mvc/application/forms/SmartBlockCriteria.php index 59c375bf7..55a28c79a 100644 --- a/airtime_mvc/application/forms/SmartBlockCriteria.php +++ b/airtime_mvc/application/forms/SmartBlockCriteria.php @@ -454,7 +454,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm $column = CcFilesPeer::getTableMap()->getColumnByPhpName($criteria2PeerMap[$d['sp_criteria_field']]); // validation on type of column if ($d['sp_criteria_field'] == 'length') { - if (!preg_match("/(\d{2}):(\d{2}):(\d{2})/", $d['sp_criteria_value'])) { + if (!preg_match("/^(\d{2}):(\d{2}):(\d{2})/", $d['sp_criteria_value'])) { $element->addError("'Length' should be in '00:00:00' format"); $isValid = false; } From 77b430ce01e35ffc3d72fd639651e7613123d650 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 15:14:52 -0400 Subject: [PATCH 020/157] CC-4564: Webstream Book same webstream twice in Scheduler, the 2nd one doesn't get played -fixed --- .../pypo/liquidsoap_scripts/ls_lib.liq | 113 +++++++++--------- .../pypo/liquidsoap_scripts/ls_script.liq | 8 +- 2 files changed, 61 insertions(+), 60 deletions(-) diff --git a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq index 4e9167638..16d688a4f 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq @@ -413,7 +413,7 @@ def create_dynamic_source(uri) = # We register both source and output # in the list of sources dyn_sources := - list.append([(uri,s),(uri,active_dyn_out)], !dyn_sources) + list.append([(current_dyn_id, s),(current_dyn_id, active_dyn_out)], !dyn_sources) notify([("schedule_table_id", !current_dyn_id)]) "Done!" @@ -421,7 +421,62 @@ end # A function to destroy a dynamic source -def destroy_dynamic_source_all(uri) = +def destroy_dynamic_source(id) = + # We need to find the source in the list, + # remove it and destroy it. Currently, the language + # lacks some nice operators for that so we do it + # the functional way + + # This function is executed on every item in the list + # of dynamic sources + def parse_list(ret, current_element) = + # ret is of the form: (matching_sources, remaining_sources) + # We extract those two: + matching_sources = fst(ret) + remaining_sources = snd(ret) + + # current_element is of the form: ("uri", source) so + # we check the first element + current_id = fst(current_element) + if current_id == id then + # In this case, we add the source to the list of + # matched sources + (list.append( [snd(current_element)], + matching_sources), + remaining_sources) + else + # In this case, we put the element in the list of remaining + # sources + (matching_sources, + list.append([current_element], + remaining_sources)) + end + end + + # Now we execute the function: + result = list.fold(parse_list, ([], []), !dyn_sources) + matching_sources = fst(result) + remaining_sources = snd(result) + + # We store the remaining sources in dyn_sources + dyn_sources := remaining_sources + + # If no source matched, we return an error + if list.length(matching_sources) == 0 then + "Error: no matching sources!" + else + # We stop all sources + list.iter(source.shutdown, matching_sources) + # And return + "Done!" + end +end + + + + +# A function to destroy a dynamic source +def destroy_dynamic_source_all() = # We need to find the source in the list, # remove it and destroy it. Currently, the language # lacks some nice operators for that so we do it @@ -466,57 +521,3 @@ end - -# A function to destroy a dynamic source -def destroy_dynamic_source(uri) = - # We need to find the source in the list, - # remove it and destroy it. Currently, the language - # lacks some nice operators for that so we do it - # the functional way - - # This function is executed on every item in the list - # of dynamic sources - def parse_list(ret, current_element) = - # ret is of the form: (matching_sources, remaining_sources) - # We extract those two: - matching_sources = fst(ret) - remaining_sources = snd(ret) - - # current_element is of the form: ("uri", source) so - # we check the first element - current_uri = fst(current_element) - if current_uri == uri then - # In this case, we add the source to the list of - # matched sources - (list.append( [snd(current_element)], - matching_sources), - remaining_sources) - else - # In this case, we put the element in the list of remaining - # sources - (matching_sources, - list.append([current_element], - remaining_sources)) - end - end - - # Now we execute the function: - result = list.fold(parse_list, ([], []), !dyn_sources) - matching_sources = fst(result) - remaining_sources = snd(result) - - # We store the remaining sources in dyn_sources - dyn_sources := remaining_sources - - # If no source matched, we return an error - if list.length(matching_sources) == 0 then - "Error: no matching sources!" - else - # We stop all sources - list.iter(source.shutdown, matching_sources) - # And return - "Done!" - end -end - - diff --git a/python_apps/pypo/liquidsoap_scripts/ls_script.liq b/python_apps/pypo/liquidsoap_scripts/ls_script.liq index fbb8e9870..0d60cd9c3 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_script.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_script.liq @@ -99,17 +99,17 @@ server.register(namespace="dynamic_source", description="Start a new dynamic source.", usage="start ", "read_start", - fun (s) -> begin log("dynamic_source.read_start") create_dynamic_source(s) end) + fun (uri) -> begin log("dynamic_source.read_start") create_dynamic_source(uri) end) server.register(namespace="dynamic_source", description="Stop a dynamic source.", - usage="stop ", + usage="stop ", "read_stop", fun (s) -> begin log("dynamic_source.read_stop") destroy_dynamic_source(s) end) server.register(namespace="dynamic_source", description="Stop a dynamic source.", - usage="stop ", + usage="stop ", "read_stop_all", - fun (s) -> begin log("dynamic_source.read_stop") destroy_dynamic_source_all(s) end) + fun (s) -> begin log("dynamic_source.read_stop") destroy_dynamic_source_all() end) default = amplify(id="silence_src", 0.00001, noise()) default = rewrite_metadata([("artist","Airtime"), ("title", "offline")], default) From 1d4b9055722e3a94efa417b354670567d967fc4d Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 15:18:48 -0400 Subject: [PATCH 021/157] CC-4564: Webstream Book same webstream twice in Scheduler, the 2nd one doesn't get played -small syntax error in last commit --- python_apps/pypo/liquidsoap_scripts/ls_lib.liq | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq index 16d688a4f..9d48eebbb 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq @@ -413,7 +413,7 @@ def create_dynamic_source(uri) = # We register both source and output # in the list of sources dyn_sources := - list.append([(current_dyn_id, s),(current_dyn_id, active_dyn_out)], !dyn_sources) + list.append([(!current_dyn_id, s),(!current_dyn_id, active_dyn_out)], !dyn_sources) notify([("schedule_table_id", !current_dyn_id)]) "Done!" From 9dfee6aa688098f5c102f11c5b1a6979bb45f3dc Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 15:39:45 -0400 Subject: [PATCH 022/157] CC-4564: Webstream: Book same webstream twice in Scheduler, the 2nd one doesn't get played -fixed --- airtime_mvc/application/models/Schedule.php | 1 + python_apps/pypo/pypopush.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 1102efaff..5a18d7b79 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -713,6 +713,7 @@ SQL; 'end' => $stream_end, 'uri' => $uri, 'type' => 'stream_buffer_end', + 'row_id' => $item["id"], 'independent_event' => true ); self::appendScheduleItem($data, $stream_end, $schedule_item); diff --git a/python_apps/pypo/pypopush.py b/python_apps/pypo/pypopush.py index 87e1704bf..ad28abef9 100644 --- a/python_apps/pypo/pypopush.py +++ b/python_apps/pypo/pypopush.py @@ -455,6 +455,7 @@ class PypoPush(Thread): tn = telnetlib.Telnet(LS_HOST, LS_PORT) msg = 'dynamic_source.id %s\n' % media_item['row_id'] + self.logger.debug(msg) tn.write(msg) #example: dynamic_source.read_start http://87.230.101.24:80/top100station.mp3 @@ -523,7 +524,7 @@ class PypoPush(Thread): tn = telnetlib.Telnet(LS_HOST, LS_PORT) #dynamic_source.stop http://87.230.101.24:80/top100station.mp3 - msg = 'dynamic_source.read_stop %s\n' % media_item['uri'].encode('latin-1') + msg = 'dynamic_source.read_stop %s\n' % media_item['row_id'] self.logger.debug(msg) tn.write(msg) From f30d636b17d960601f3bdec2df73a2108e1dc410 Mon Sep 17 00:00:00 2001 From: denise Date: Fri, 19 Oct 2012 16:19:32 -0400 Subject: [PATCH 023/157] CC-4581: Confirmation dialog for removing an item from a show refers to deletion --- airtime_mvc/public/js/airtime/showbuilder/builder.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index 9839df06c..fc8463481 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -283,7 +283,7 @@ var AIRTIME = (function(AIRTIME){ mod.fnRemove = function(aItems) { mod.disableUI(); - if (confirm("Delete selected item(s)?")) { + if (confirm("Remove selected scheduled item(s)?")) { $.post( "/showbuilder/schedule-remove", {"items": aItems, "format": "json"}, mod.fnItemCallback From bd5fef0bcd0e86e140660a474fd15ff755ea842e Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 16:29:31 -0400 Subject: [PATCH 024/157] CC-4487: Webstream could not be heard unless you restart playout as well -fixed --- .../pypo/liquidsoap_scripts/ls_lib.liq | 5 +++ .../pypo/liquidsoap_scripts/ls_script.liq | 9 +++- python_apps/pypo/pypopush.py | 43 +++++++++++++++---- 3 files changed, 47 insertions(+), 10 deletions(-) diff --git a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq index 9d48eebbb..9e7903751 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq @@ -402,6 +402,11 @@ def set_dynamic_source_id(id) = string_of(!current_dyn_id) end +def get_dynamic_source_id() = + string_of(!current_dyn_id) +end + + # Function to create a playlist source and output it. def create_dynamic_source(uri) = # The playlist source diff --git a/python_apps/pypo/liquidsoap_scripts/ls_script.liq b/python_apps/pypo/liquidsoap_scripts/ls_script.liq index 0d60cd9c3..7a6d8c61d 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_script.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_script.liq @@ -19,7 +19,7 @@ queue = amplify(1., override="replay_gain", queue) #live stream setup set("harbor.bind_addr", "0.0.0.0") -current_dyn_id = ref '' +current_dyn_id = ref '-1' pypo_data = ref '0' stream_metadata_type = ref 0 @@ -95,6 +95,13 @@ server.register(namespace="dynamic_source", usage="id ", "id", fun (s) -> begin log("dynamic_source.id") set_dynamic_source_id(s) end) + +server.register(namespace="dynamic_source", + description="Get the cc_schedule row id", + usage="get_id", + "get_id", + fun (s) -> begin log("dynamic_source.get_id") get_dynamic_source_id() end) + server.register(namespace="dynamic_source", description="Start a new dynamic source.", usage="start ", diff --git a/python_apps/pypo/pypopush.py b/python_apps/pypo/pypopush.py index ad28abef9..82d7593f0 100644 --- a/python_apps/pypo/pypopush.py +++ b/python_apps/pypo/pypopush.py @@ -78,6 +78,7 @@ class PypoPush(Thread): #We get to the following lines only if a schedule was received. liquidsoap_queue_approx = self.get_queue_items_from_liquidsoap() + liquidsoap_stream_id = self.get_current_stream_id_from_liquidsoap() tnow = datetime.utcnow() current_event_chain, original_chain = self.get_current_chain(chains, tnow) @@ -92,7 +93,7 @@ class PypoPush(Thread): #is scheduled. We need to verify whether the schedule we just received matches #what Liquidsoap is playing, and if not, correct it. - self.handle_new_schedule(media_schedule, liquidsoap_queue_approx, current_event_chain) + self.handle_new_schedule(media_schedule, liquidsoap_queue_approx, liquidsoap_stream_id, current_event_chain) #At this point everything in the present has been taken care of and Liquidsoap @@ -134,6 +135,25 @@ class PypoPush(Thread): loops = 0 loops += 1 + def get_current_stream_id_from_liquidsoap(self): + response = "-1" + try: + self.telnet_lock.acquire() + tn = telnetlib.Telnet(LS_HOST, LS_PORT) + + msg = 'dynamic_source.get_id\n' + tn.write(msg) + response = tn.read_until("\r\n").strip(" \r\n") + tn.write('exit\n') + tn.read_all() + except Exception, e: + self.logger.error("Error connecting to Liquidsoap: %s", e) + response = [] + finally: + self.telnet_lock.release() + + return response + def get_queue_items_from_liquidsoap(self): """ This function connects to Liquidsoap to find what media items are in its queue. @@ -175,7 +195,7 @@ class PypoPush(Thread): return liquidsoap_queue_approx - def is_correct_current_item(self, media_item, liquidsoap_queue_approx): + def is_correct_current_item(self, media_item, liquidsoap_queue_approx, liquidsoap_stream_id): correct = False if media_item is None: correct = (len(liquidsoap_queue_approx) == 0 and self.current_stream_info is None) @@ -188,10 +208,7 @@ class PypoPush(Thread): liquidsoap_queue_approx[0]['row_id'] == media_item['row_id'] and \ liquidsoap_queue_approx[0]['end'] == media_item['end'] elif is_stream(media_item): - if self.current_stream_info is None: - correct = False - else: - correct = self.current_stream_info['row_id'] == media_item['row_id'] + correct = liquidsoap_stream_id == str(media_item['row_id']) self.logger.debug("Is current item correct?: %s", str(correct)) return correct @@ -202,7 +219,7 @@ class PypoPush(Thread): self.remove_from_liquidsoap_queue(0, None) self.stop_web_stream_all() - def handle_new_schedule(self, media_schedule, liquidsoap_queue_approx, current_event_chain): + def handle_new_schedule(self, media_schedule, liquidsoap_queue_approx, liquidsoap_stream_id, current_event_chain): """ This function's purpose is to gracefully handle situations where Liquidsoap already has a track in its queue, but the schedule @@ -220,7 +237,7 @@ class PypoPush(Thread): if len(current_event_chain) > 0: current_item = current_event_chain[0] - if not self.is_correct_current_item(current_item, liquidsoap_queue_approx): + if not self.is_correct_current_item(current_item, liquidsoap_queue_approx, liquidsoap_stream_id): self.clear_all_liquidsoap_items() if is_stream(current_item): if current_item['row_id'] != self.current_prebuffering_stream_id: @@ -234,7 +251,7 @@ class PypoPush(Thread): #we've changed the queue, so let's refetch it liquidsoap_queue_approx = self.get_queue_items_from_liquidsoap() - elif not self.is_correct_current_item(None, liquidsoap_queue_approx): + elif not self.is_correct_current_item(None, liquidsoap_queue_approx, liquidsoap_stream_id): #Liquidsoap is playing something even though it shouldn't be self.clear_all_liquidsoap_items() @@ -509,6 +526,10 @@ class PypoPush(Thread): self.logger.debug(msg) tn.write(msg) + msg = 'dynamic_source.id -1\n' + self.logger.debug(msg) + tn.write(msg) + tn.write("exit\n") self.logger.debug(tn.read_all()) @@ -528,6 +549,10 @@ class PypoPush(Thread): self.logger.debug(msg) tn.write(msg) + msg = 'dynamic_source.id -1\n' + self.logger.debug(msg) + tn.write(msg) + tn.write("exit\n") self.logger.debug(tn.read_all()) From 58535bef88aea186a6b07337614096791e9421eb Mon Sep 17 00:00:00 2001 From: James Date: Fri, 19 Oct 2012 16:40:32 -0400 Subject: [PATCH 025/157] CC-4580: No contents in rebroadcast show - fixed --- airtime_mvc/application/controllers/ApiController.php | 5 ++++- python_apps/media-monitor2/media/monitor/events.py | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/application/controllers/ApiController.php b/airtime_mvc/application/controllers/ApiController.php index 6572774cc..1a1876ce9 100644 --- a/airtime_mvc/application/controllers/ApiController.php +++ b/airtime_mvc/application/controllers/ApiController.php @@ -490,6 +490,10 @@ class ApiController extends Zend_Controller_Action $file->setFileExistsFlag(true); $file->setMetadata($md); } + if ($md['is_record'] != 0) { + $this->uploadRecordedActionParam($md['MDATA_KEY_TRACKNUMBER'], $file->getId()); + } + } elseif ($mode == "modify") { $filepath = $md['MDATA_KEY_FILEPATH']; $file = Application_Model_StoredFile::RecallByFilepath($filepath); @@ -562,7 +566,6 @@ class ApiController extends Zend_Controller_Action // least 1 digit if ( !preg_match('/^md\d+$/', $k) ) { continue; } $info_json = json_decode($raw_json, $assoc = true); - unset( $info_json["is_record"] ); // Log invalid requests if ( !array_key_exists('mode', $info_json) ) { Logging::info("Received bad request(key=$k), no 'mode' parameter. Bad request is:"); diff --git a/python_apps/media-monitor2/media/monitor/events.py b/python_apps/media-monitor2/media/monitor/events.py index a8ccc3b54..0b2a92e14 100644 --- a/python_apps/media-monitor2/media/monitor/events.py +++ b/python_apps/media-monitor2/media/monitor/events.py @@ -199,6 +199,7 @@ class NewFile(BaseEvent, HasMetaData): """ req_dict = self.metadata.extract() req_dict['mode'] = u'create' + req_dict['is_record'] = self.metadata.is_recorded() self.assign_owner(req_dict) req_dict['MDATA_KEY_FILEPATH'] = unicode( self.path ) return [req_dict] From ef78cefcd96b1e9472cb5ea0af0b0a726dde2c1a Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 19 Oct 2012 16:49:01 -0400 Subject: [PATCH 026/157] CC-4487: Webstream could not be heard unless you restart playout as well -cleanup of unused variables --- python_apps/pypo/pypopush.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/python_apps/pypo/pypopush.py b/python_apps/pypo/pypopush.py index 82d7593f0..5bcce21b6 100644 --- a/python_apps/pypo/pypopush.py +++ b/python_apps/pypo/pypopush.py @@ -55,7 +55,6 @@ class PypoPush(Thread): self.pushed_objects = {} self.logger = logging.getLogger('push') - self.current_stream_info = None self.current_prebuffering_stream_id = None def main(self): @@ -198,7 +197,7 @@ class PypoPush(Thread): def is_correct_current_item(self, media_item, liquidsoap_queue_approx, liquidsoap_stream_id): correct = False if media_item is None: - correct = (len(liquidsoap_queue_approx) == 0 and self.current_stream_info is None) + correct = (len(liquidsoap_queue_approx) == 0 and liquidsoap_stream_id == "-1") else: if is_file(media_item): if len(liquidsoap_queue_approx) == 0: @@ -230,7 +229,6 @@ class PypoPush(Thread): file_chain = filter(lambda item: (item["type"] == "file"), current_event_chain) stream_chain = filter(lambda item: (item["type"] == "stream_output_start"), current_event_chain) - self.logger.debug(self.current_stream_info) self.logger.debug(current_event_chain) #Take care of the case where the current playing may be incorrect @@ -507,7 +505,6 @@ class PypoPush(Thread): self.logger.debug(tn.read_all()) self.current_prebuffering_stream_id = None - self.current_stream_info = media_item except Exception, e: self.logger.error(str(e)) finally: @@ -533,7 +530,6 @@ class PypoPush(Thread): tn.write("exit\n") self.logger.debug(tn.read_all()) - self.current_stream_info = None except Exception, e: self.logger.error(str(e)) finally: @@ -556,7 +552,6 @@ class PypoPush(Thread): tn.write("exit\n") self.logger.debug(tn.read_all()) - self.current_stream_info = None except Exception, e: self.logger.error(str(e)) finally: @@ -575,7 +570,6 @@ class PypoPush(Thread): tn.write("exit\n") self.logger.debug(tn.read_all()) - self.current_stream_info = None except Exception, e: self.logger.error(str(e)) finally: From a9df8cd7f21525747fb2a9297cbf66ff8a88dd08 Mon Sep 17 00:00:00 2001 From: James Date: Fri, 19 Oct 2012 17:30:54 -0400 Subject: [PATCH 027/157] CC-4610: Creating recording show will generate lots of exception in zendphp.log - fixed --- airtime_mvc/application/models/Schedule.php | 1 - airtime_mvc/application/models/ShowBuilder.php | 8 +++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 5a18d7b79..1f2e98810 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -1128,7 +1128,6 @@ SQL; } } else { if ($isAdminOrPM) { - Logging::info( $data ); Application_Model_Show::create($data); } diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php index e1e2382aa..90a67a1d6 100644 --- a/airtime_mvc/application/models/ShowBuilder.php +++ b/airtime_mvc/application/models/ShowBuilder.php @@ -198,7 +198,9 @@ class Application_Model_ShowBuilder } elseif (intval($p_item["si_record"]) === 1) { $row["record"] = true; - if (Application_Model_Preference::GetUploadToSoundcloudOption()) { + // at the time of creating on show, the recorded file is not in the DB yet. + // therefore, 'si_file_id' is null. So we need to check it. + if (Application_Model_Preference::GetUploadToSoundcloudOption() && isset($p_item['si_file_id'])) { $file = Application_Model_StoredFile::Recall( $p_item['si_file_id']); if (isset($file)) { @@ -398,7 +400,7 @@ class Application_Model_ShowBuilder //see if the displayed show instances have changed. (deleted, //empty schedule etc) - if ($outdated === false && count($instances) + if ($outdated === false && count($instances) !== count($currentInstances)) { Logging::debug("show instances have changed."); $outdated = true; @@ -459,7 +461,7 @@ class Application_Model_ShowBuilder $display_items[] = $row; } - if ($current_id !== -1 && + if ($current_id !== -1 && !in_array($current_id, $this->showInstances)) { $this->showInstances[] = $current_id; } From e0402c88cf8bc9d24460af93d4a32299e693c7ab Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Mon, 22 Oct 2012 15:20:03 -0400 Subject: [PATCH 028/157] cc-4613: fixed --- airtime_mvc/application/models/Show.php | 2 +- airtime_mvc/application/models/ShowInstance.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 0006057f7..41ffbeefd 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1792,7 +1792,7 @@ SQL; $show["instance_id"]); $options["show_empty"] = (array_key_exists($show['instance_id'], - $content_count)) ? 1 : 0; + $content_count)) ? 0 : 1; $events[] = &self::makeFullCalendarEvent($show, $options, $startsDT, $endsDT, $startsEpochStr, $endsEpochStr); diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index a73d1f7f0..3d1d1d055 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -681,7 +681,7 @@ SQL; return $counts; - } + } public function showEmpty() { From feac48a0035326ce1b8c0d8a8ed415b980e89043 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Mon, 22 Oct 2012 15:34:33 -0400 Subject: [PATCH 029/157] cc-4613: fixed --- airtime_mvc/application/models/Show.php | 2 ++ airtime_mvc/application/models/ShowInstance.php | 7 ++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 41ffbeefd..5fce268c6 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1747,6 +1747,8 @@ SQL; $p_start, $p_end); $timezone = date_default_timezone_get(); + Logging::info( $content_count ); + foreach ($shows as $show) { $options = array(); diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index 3d1d1d055..b6930766d 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -679,7 +679,12 @@ SQL; ':p_end' => $p_end->format("Y-m-d G:i:s")) , 'all'); - return $counts; + + $real_counts = array(); + foreach ($counts as $c) { + $real_counts[$c['instance_id']] = $c['instance_count']; + } + return $real_counts; } From b7b849a48f71848c6c7ea447cfbb60d89d0b3162 Mon Sep 17 00:00:00 2001 From: James Date: Mon, 22 Oct 2012 15:35:01 -0400 Subject: [PATCH 030/157] CC-4612: Create index for cc_schedule during upgrade to improve the performance when cc_schedule's getting bigger - fixed --- install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql b/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql index 36b4f5734..771c3b13c 100644 --- a/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql +++ b/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql @@ -140,6 +140,12 @@ ALTER TABLE cc_playlistcontents ALTER TABLE cc_schedule ADD COLUMN stream_id integer; +CREATE INDEX cc_schedule_instance_id_idx + ON cc_schedule + USING btree + (instance_id); + + ALTER TABLE cc_subjs ADD COLUMN cell_phone character varying(255); From abf4319d67bc49eaf5fc9f20edc4fc19bbc0a9ec Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Mon, 22 Oct 2012 15:55:24 -0400 Subject: [PATCH 031/157] Removed logging --- airtime_mvc/application/models/Show.php | 2 -- airtime_mvc/application/models/ShowInstance.php | 1 - 2 files changed, 3 deletions(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 5fce268c6..41ffbeefd 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1747,8 +1747,6 @@ SQL; $p_start, $p_end); $timezone = date_default_timezone_get(); - Logging::info( $content_count ); - foreach ($shows as $show) { $options = array(); diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index b6930766d..533118c29 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -679,7 +679,6 @@ SQL; ':p_end' => $p_end->format("Y-m-d G:i:s")) , 'all'); - $real_counts = array(); foreach ($counts as $c) { $real_counts[$c['instance_id']] = $c['instance_count']; From 780a05c2aa4121b2c5e2beb49ad50e1184c29949 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Mon, 22 Oct 2012 16:23:33 -0400 Subject: [PATCH 032/157] CC-2236: Overbooked shows do not respect default fade time -once a release we manage to break fades :) fixed. --- python_apps/pypo/liquidsoap_scripts/ls_lib.liq | 2 +- python_apps/pypo/liquidsoap_scripts/ls_script.liq | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq index 9e7903751..5c5919e2e 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_lib.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_lib.liq @@ -27,7 +27,7 @@ def append_title(m) = end end -def crossfade(s) +def crossfade_airtime(s) #duration is automatically overwritten by metadata fields passed in #with audio s = fade.in(type="log", duration=0., s) diff --git a/python_apps/pypo/liquidsoap_scripts/ls_script.liq b/python_apps/pypo/liquidsoap_scripts/ls_script.liq index 7a6d8c61d..2c1ef9dee 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_script.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_script.liq @@ -44,9 +44,9 @@ web_stream = on_metadata(notify_stream, web_stream) output.dummy(fallible=true, web_stream) queue = on_metadata(notify, queue) -queue = map_metadata(update=false, append_title, queue) +queue = map_metadata(update=true, append_title, queue) # the crossfade function controls fade in/out -queue = crossfade(queue) +queue = crossfade_airtime(queue) output.dummy(fallible=true, queue) From 795ffbbf631443b315819a8ec4968f3f6ad772e2 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Mon, 22 Oct 2012 16:36:57 -0400 Subject: [PATCH 033/157] CC-2236: Overbooked shows do not respect default fade time -move map_metadata after crossfade function --- python_apps/pypo/liquidsoap_scripts/ls_script.liq | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python_apps/pypo/liquidsoap_scripts/ls_script.liq b/python_apps/pypo/liquidsoap_scripts/ls_script.liq index 2c1ef9dee..1f476b919 100644 --- a/python_apps/pypo/liquidsoap_scripts/ls_script.liq +++ b/python_apps/pypo/liquidsoap_scripts/ls_script.liq @@ -43,10 +43,11 @@ web_stream = input.harbor("test-harbor", port=8999, password=stream_harbor_pass) web_stream = on_metadata(notify_stream, web_stream) output.dummy(fallible=true, web_stream) -queue = on_metadata(notify, queue) -queue = map_metadata(update=true, append_title, queue) + # the crossfade function controls fade in/out queue = crossfade_airtime(queue) +queue = on_metadata(notify, queue) +queue = map_metadata(update=false, append_title, queue) output.dummy(fallible=true, queue) From c51fb8a04030035cdde8ed2fe70aad83aee871b9 Mon Sep 17 00:00:00 2001 From: denise Date: Mon, 22 Oct 2012 16:37:06 -0400 Subject: [PATCH 034/157] CC-4549: Tooltip for source username cannot be shared between input and output settings -fixed --- .../scripts/form/preferences_livestream.phtml | 2 +- airtime_mvc/public/css/styles.css | 3 ++- .../js/airtime/preferences/streamsetting.js | 21 +++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml b/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml index 00221bf4e..e2dd5d7dc 100644 --- a/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml +++ b/airtime_mvc/application/views/scripts/form/preferences_livestream.phtml @@ -49,7 +49,7 @@
diff --git a/airtime_mvc/public/css/styles.css b/airtime_mvc/public/css/styles.css index 29d694d28..b14b77251 100644 --- a/airtime_mvc/public/css/styles.css +++ b/airtime_mvc/public/css/styles.css @@ -104,7 +104,8 @@ select { line-height:16px !important; } -.airtime_auth_help_icon, .custom_auth_help_icon, .stream_username_help_icon, .playlist_type_help_icon { +.airtime_auth_help_icon, .custom_auth_help_icon, .stream_username_help_icon, +.playlist_type_help_icon, .master_username_help_icon { cursor: help; position: relative; display:inline-block; zoom:1; diff --git a/airtime_mvc/public/js/airtime/preferences/streamsetting.js b/airtime_mvc/public/js/airtime/preferences/streamsetting.js index 35f7b373e..b25e2d157 100644 --- a/airtime_mvc/public/js/airtime/preferences/streamsetting.js +++ b/airtime_mvc/public/js/airtime/preferences/streamsetting.js @@ -333,6 +333,27 @@ $(document).ready(function() { }) $(".stream_username_help_icon").qtip({ + content: { + text: "If your Icecast server expects a username of 'source', this field can be left blank." + }, + hide: { + delay: 500, + fixed: true + }, + style: { + border: { + width: 0, + radius: 4 + }, + classes: "ui-tooltip-dark ui-tooltip-rounded" + }, + position: { + my: "left bottom", + at: "right center" + }, + }) + + $(".master_username_help_icon").qtip({ content: { text: "If your live streaming client does not ask for a username, this field should be 'source'." }, From 8b9b005708021cd1bd618c6ddbe0a7506b5c49fa Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Mon, 22 Oct 2012 17:29:26 -0400 Subject: [PATCH 035/157] CC-4612: Create index for cc_schedule during upgrade to improve the performance when cc_schedule's getting bigger - also create one during fresh install --- airtime_mvc/build/schema.xml | 5 +++++ airtime_mvc/build/sql/schema.sql | 2 ++ 2 files changed, 7 insertions(+) diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index d56927199..3d0957a50 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -91,6 +91,8 @@ + @@ -332,6 +334,9 @@ + + + diff --git a/airtime_mvc/build/sql/schema.sql b/airtime_mvc/build/sql/schema.sql index 332715b22..597ebf417 100644 --- a/airtime_mvc/build/sql/schema.sql +++ b/airtime_mvc/build/sql/schema.sql @@ -429,6 +429,8 @@ COMMENT ON TABLE "cc_schedule" IS ''; SET search_path TO public; +CREATE INDEX "cc_schedule_instance_id_idx" ON "cc_schedule" ("instance_id"); + ----------------------------------------------------------------------------- -- cc_sess ----------------------------------------------------------------------------- From 50d09d09d39dbe7f4d09bc6d17c459507c563882 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 23 Oct 2012 12:08:01 -0400 Subject: [PATCH 036/157] cc-4304: fixed ticket by deleting playlists when user is deleted. also removed useless index on file_exists --- airtime_mvc/build/schema.xml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index 3d0957a50..fc3e6a51f 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -91,11 +91,6 @@ - - - -
@@ -208,7 +203,7 @@ - +
From 5024a3083c056d207fe1559e4e4687c40bf2e349 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 23 Oct 2012 12:18:52 -0400 Subject: [PATCH 037/157] cc-4487: keep playing webstream on liquidsoap restart --- install_minimal/upgrades/airtime-2.2.0/etc/api_client.cfg.220 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/install_minimal/upgrades/airtime-2.2.0/etc/api_client.cfg.220 b/install_minimal/upgrades/airtime-2.2.0/etc/api_client.cfg.220 index 2e0e938e8..06e92edb2 100644 --- a/install_minimal/upgrades/airtime-2.2.0/etc/api_client.cfg.220 +++ b/install_minimal/upgrades/airtime-2.2.0/etc/api_client.cfg.220 @@ -117,3 +117,5 @@ get_files_without_replay_gain = 'get-files-without-replay-gain/api_key/%%api_key update_replay_gain_value = 'update-replay-gain-value/api_key/%%api_key%%' notify_webstream_data = 'notify-webstream-data/api_key/%%api_key%%/media_id/%%media_id%%/format/json' + +notify_liquidsoap_started = 'rabbitmq-do-push/api_key/%%api_key%%/format/json' From dff5bb4e2be704de6edb2d63bf8f5bdad3072c70 Mon Sep 17 00:00:00 2001 From: james Date: Tue, 23 Oct 2012 12:24:38 -0400 Subject: [PATCH 038/157] CC-4620: Now Playing page loading is very slow because 1M records in cc_schedule table - fixed --- airtime_mvc/application/models/Schedule.php | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 1f2e98810..233128433 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -287,7 +287,14 @@ SQL; SQL; $filesJoin = <<= '{$p_start}' + AND sched.starts < '{$p_end}') + OR (sched.ends > '{$p_start}' + AND sched.ends <= '{$p_end}') + OR (sched.starts <= '{$p_start}' + AND sched.ends >= '{$p_end}')) + ) SQL; @@ -307,7 +314,14 @@ SQL; SQL; $streamJoin = <<= '{$p_start}' + AND sched.starts < '{$p_end}') + OR (sched.ends > '{$p_start}' + AND sched.ends <= '{$p_end}') + OR (sched.starts <= '{$p_start}' + AND sched.ends >= '{$p_end}')) + ) LEFT JOIN cc_subjs AS sub ON (ws.creator_id = sub.id) SQL; From 2d6be404d491bb6b3cf4c32760093ce8fba82d97 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 23 Oct 2012 13:45:15 -0400 Subject: [PATCH 039/157] cc-4304: fixed ticket by deleting playlists when user is deleted. also removed useless index on file_exists -regen propel files --- .../application/models/airtime/map/CcPlaylistTableMap.php | 2 +- .../application/models/airtime/map/CcSubjsTableMap.php | 2 +- airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php | 3 +++ airtime_mvc/build/sql/schema.sql | 4 +--- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php b/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php index 3162280d0..8dba50bbd 100644 --- a/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcPlaylistTableMap.php @@ -53,7 +53,7 @@ class CcPlaylistTableMap extends TableMap { */ public function buildRelations() { - $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), null, null); + $this->addRelation('CcSubjs', 'CcSubjs', RelationMap::MANY_TO_ONE, array('creator_id' => 'id', ), 'CASCADE', null); $this->addRelation('CcPlaylistcontents', 'CcPlaylistcontents', RelationMap::ONE_TO_MANY, array('id' => 'playlist_id', ), 'CASCADE', null); } // buildRelations() diff --git a/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php b/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php index 7ed8469d8..ffbe8cded 100644 --- a/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcSubjsTableMap.php @@ -63,7 +63,7 @@ class CcSubjsTableMap extends TableMap { $this->addRelation('CcFilesRelatedByDbEditedby', 'CcFiles', RelationMap::ONE_TO_MANY, array('id' => 'editedby', ), null, null); $this->addRelation('CcPerms', 'CcPerms', RelationMap::ONE_TO_MANY, array('id' => 'subj', ), 'CASCADE', null); $this->addRelation('CcShowHosts', 'CcShowHosts', RelationMap::ONE_TO_MANY, array('id' => 'subjs_id', ), 'CASCADE', null); - $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), null, null); + $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), 'CASCADE', null); $this->addRelation('CcBlock', 'CcBlock', RelationMap::ONE_TO_MANY, array('id' => 'creator_id', ), null, null); $this->addRelation('CcPref', 'CcPref', RelationMap::ONE_TO_MANY, array('id' => 'subjid', ), 'CASCADE', null); $this->addRelation('CcSess', 'CcSess', RelationMap::ONE_TO_MANY, array('id' => 'userid', ), 'CASCADE', null); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php index 68403579f..dbd9978d7 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSubjsPeer.php @@ -404,6 +404,9 @@ abstract class BaseCcSubjsPeer { // Invalidate objects in CcShowHostsPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcShowHostsPeer::clearInstancePool(); + // Invalidate objects in CcPlaylistPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcPlaylistPeer::clearInstancePool(); // Invalidate objects in CcPrefPeer instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. CcPrefPeer::clearInstancePool(); diff --git a/airtime_mvc/build/sql/schema.sql b/airtime_mvc/build/sql/schema.sql index 597ebf417..d7e1107a4 100644 --- a/airtime_mvc/build/sql/schema.sql +++ b/airtime_mvc/build/sql/schema.sql @@ -105,8 +105,6 @@ CREATE INDEX "cc_files_md5_idx" ON "cc_files" ("md5"); CREATE INDEX "cc_files_name_idx" ON "cc_files" ("name"); -CREATE INDEX "cc_files_file_exists_idx" ON "cc_files" ("file_exists"); - ----------------------------------------------------------------------------- -- cc_perms ----------------------------------------------------------------------------- @@ -691,7 +689,7 @@ ALTER TABLE "cc_show_hosts" ADD CONSTRAINT "cc_perm_show_fkey" FOREIGN KEY ("sho ALTER TABLE "cc_show_hosts" ADD CONSTRAINT "cc_perm_host_fkey" FOREIGN KEY ("subjs_id") REFERENCES "cc_subjs" ("id") ON DELETE CASCADE; -ALTER TABLE "cc_playlist" ADD CONSTRAINT "cc_playlist_createdby_fkey" FOREIGN KEY ("creator_id") REFERENCES "cc_subjs" ("id"); +ALTER TABLE "cc_playlist" ADD CONSTRAINT "cc_playlist_createdby_fkey" FOREIGN KEY ("creator_id") REFERENCES "cc_subjs" ("id") ON DELETE CASCADE; ALTER TABLE "cc_playlistcontents" ADD CONSTRAINT "cc_playlistcontents_file_id_fkey" FOREIGN KEY ("file_id") REFERENCES "cc_files" ("id") ON DELETE CASCADE; From 943d5f2a72e0256abc24d29a5fd1d9a9120cef0d Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 23 Oct 2012 13:52:11 -0400 Subject: [PATCH 040/157] cc-4304: fixed ticket by deleting playlists when user is deleted. also removed useless index on file_exists -add database modifications to upgrade.sql script --- .../upgrades/airtime-2.2.0/data/upgrade.sql | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql b/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql index 771c3b13c..9f524fa39 100644 --- a/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql +++ b/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql @@ -14,6 +14,13 @@ INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s2_channels', 'ste INSERT INTO cc_stream_setting (keyname, value, type) VALUES ('s3_channels', 'stereo', 'string'); +CREATE FUNCTION airtime_to_int(chartoconvert character varying) RETURNS integer + AS + 'SELECT CASE WHEN trim($1) SIMILAR TO ''[0-9]+'' THEN CAST(trim($1) AS integer) ELSE NULL END;' + LANGUAGE SQL + IMMUTABLE + RETURNS NULL ON NULL INPUT; + --clean up database of scheduled items that weren't properly deleted in 2.1.x --due to a bug DELETE @@ -27,14 +34,9 @@ WHERE id IN ALTER TABLE cc_files DROP CONSTRAINT cc_files_gunid_idx; -DROP TABLE cc_access; +DROP INDEX cc_files_file_exists_idx; -CREATE FUNCTION airtime_to_int(chartoconvert character varying) RETURNS integer - AS - 'SELECT CASE WHEN trim($1) SIMILAR TO ''[0-9]+'' THEN CAST(trim($1) AS integer) ELSE NULL END;' - LANGUAGE SQL - IMMUTABLE - RETURNS NULL ON NULL INPUT; +DROP TABLE cc_access; CREATE SEQUENCE cc_block_id_seq START WITH 1 @@ -176,6 +178,9 @@ ALTER TABLE cc_blockcontents ALTER TABLE cc_blockcriteria ADD CONSTRAINT cc_blockcontents_block_id_fkey FOREIGN KEY (block_id) REFERENCES cc_block(id) ON DELETE CASCADE; +ALTER TABLE cc_playlist + ADD CONSTRAINT cc_playlist_createdby_fkey FOREIGN KEY (creator_id) REFERENCES cc_subjs(id) ON DELETE CASCADE; + ALTER TABLE cc_playlistcontents ADD CONSTRAINT cc_playlistcontents_block_id_fkey FOREIGN KEY (block_id) REFERENCES cc_block(id) ON DELETE CASCADE; From a73aef6cd89a1ad06fcd08433a41b299daab4c98 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 23 Oct 2012 14:20:41 -0400 Subject: [PATCH 041/157] cc-4304: fixed ticket by deleting playlists when user is deleted. also removed useless index on file_exists -add database modifications to upgrade.sql script --- .../upgrades/airtime-2.2.0/data/upgrade.sql | 30 +++++++++++++++++-- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql b/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql index 9f524fa39..95e621874 100644 --- a/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql +++ b/install_minimal/upgrades/airtime-2.2.0/data/upgrade.sql @@ -178,9 +178,6 @@ ALTER TABLE cc_blockcontents ALTER TABLE cc_blockcriteria ADD CONSTRAINT cc_blockcontents_block_id_fkey FOREIGN KEY (block_id) REFERENCES cc_block(id) ON DELETE CASCADE; -ALTER TABLE cc_playlist - ADD CONSTRAINT cc_playlist_createdby_fkey FOREIGN KEY (creator_id) REFERENCES cc_subjs(id) ON DELETE CASCADE; - ALTER TABLE cc_playlistcontents ADD CONSTRAINT cc_playlistcontents_block_id_fkey FOREIGN KEY (block_id) REFERENCES cc_block(id) ON DELETE CASCADE; @@ -190,6 +187,33 @@ ALTER TABLE cc_schedule ALTER TABLE cc_webstream_metadata ADD CONSTRAINT cc_schedule_inst_fkey FOREIGN KEY (instance_id) REFERENCES cc_schedule(id) ON DELETE CASCADE; + + + +ALTER TABLE cc_playlist + DROP CONSTRAINT cc_playlist_createdby_fkey; + +ALTER SEQUENCE cc_block_id_seq + OWNED BY cc_block.id; + +ALTER SEQUENCE cc_blockcontents_id_seq + OWNED BY cc_blockcontents.id; + +ALTER SEQUENCE cc_blockcriteria_id_seq + OWNED BY cc_blockcriteria.id; + +ALTER SEQUENCE cc_webstream_id_seq + OWNED BY cc_webstream.id; + +ALTER SEQUENCE cc_webstream_metadata_id_seq + OWNED BY cc_webstream_metadata.id; + +ALTER TABLE cc_playlist + ADD CONSTRAINT cc_playlist_createdby_fkey FOREIGN KEY (creator_id) REFERENCES cc_subjs(id) ON DELETE CASCADE; + + + + DROP FUNCTION airtime_to_int(chartoconvert character varying); UPDATE cc_files From 4daaa776e27d820a8665e3d9669e1eaefd2ec8cf Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 23 Oct 2012 17:45:55 -0400 Subject: [PATCH 042/157] CC-4620: Now Playing page loading is very slow because 1M records in cc_schedule table -fixed --- airtime_mvc/application/models/Schedule.php | 45 +++++++++++-------- .../application/models/ShowBuilder.php | 3 +- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 233128433..b668f13e5 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -263,6 +263,15 @@ SQL; global $CC_CONFIG; $con = Propel::getConnection(); + $p_start_str = $p_start->format("Y-m-d H:i:s"); + $p_end_str = $p_end->format("Y-m-d H:i:s"); + + + //We need to search 24 hours before and after the show times so that that we + //capture all of the show's contents. + $p_track_start= $p_start->sub(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); + $p_track_end = $p_end->add(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); + $templateSql = <<= '{$p_start}' - AND sched.starts < '{$p_end}') - OR (sched.ends > '{$p_start}' - AND sched.ends <= '{$p_end}') - OR (sched.starts <= '{$p_start}' - AND sched.ends >= '{$p_end}')) + AND ((sched.starts >= '{$p_track_start}' + AND sched.starts < '{$p_track_end}') + OR (sched.ends > '{$p_track_start}' + AND sched.ends <= '{$p_track_end}') + OR (sched.starts <= '{$p_track_start}' + AND sched.ends >= '{$p_track_end}')) ) SQL; @@ -315,12 +324,12 @@ SQL; $streamJoin = <<= '{$p_start}' - AND sched.starts < '{$p_end}') - OR (sched.ends > '{$p_start}' - AND sched.ends <= '{$p_end}') - OR (sched.starts <= '{$p_start}' - AND sched.ends >= '{$p_end}')) + AND ((sched.starts >= '{$p_track_start}' + AND sched.starts < '{$p_track_end}') + OR (sched.ends > '{$p_track_start}' + AND sched.ends <= '{$p_track_end}') + OR (sched.starts <= '{$p_track_start}' + AND sched.ends >= '{$p_track_end}')) ) LEFT JOIN cc_subjs AS sub ON (ws.creator_id = sub.id) SQL; @@ -358,12 +367,12 @@ SELECT showt.name AS show_name, JOIN cc_show AS showt ON (showt.id = si.show_id) WHERE si.modified_instance = FALSE $showPredicate - AND ((si.starts >= '{$p_start}' - AND si.starts < '{$p_end}') - OR (si.ends > '{$p_start}' - AND si.ends <= '{$p_end}') - OR (si.starts <= '{$p_start}' - AND si.ends >= '{$p_end}')) + AND ((si.starts >= '{$p_start_str}' + AND si.starts < '{$p_end_str}') + OR (si.ends > '{$p_start_str}' + AND si.ends <= '{$p_end_str}') + OR (si.starts <= '{$p_start_str}' + AND si.ends >= '{$p_end_str}')) ORDER BY si_starts, sched_starts; SQL; diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php index 90a67a1d6..8436c3011 100644 --- a/airtime_mvc/application/models/ShowBuilder.php +++ b/airtime_mvc/application/models/ShowBuilder.php @@ -423,8 +423,7 @@ class Application_Model_ShowBuilder } $scheduled_items = Application_Model_Schedule::GetScheduleDetailItems( - $this->startDT->format("Y-m-d H:i:s"), $this->endDT->format( - "Y-m-d H:i:s"), $shows); + $this->startDT, $this->endDT, $shows); for ($i = 0, $rows = count($scheduled_items); $i < $rows; $i++) { From f9f3f9527ead8c5c76e57b7af87e463422157c95 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Thu, 25 Oct 2012 12:25:02 -0400 Subject: [PATCH 043/157] CC-4624: phone_home_stat is broken in Ubuntu 12.10, with php 5.4 -fixed --- utils/airtime-check-system.php | 2 ++ utils/airtime-log.php | 2 ++ utils/phone_home_stat.php | 2 ++ utils/soundcloud-uploader.php | 2 ++ 4 files changed, 8 insertions(+) diff --git a/utils/airtime-check-system.php b/utils/airtime-check-system.php index 91fe19c5e..39d9b19b7 100644 --- a/utils/airtime-check-system.php +++ b/utils/airtime-check-system.php @@ -2,6 +2,8 @@ AirtimeCheck::ExitIfNotRoot(); +date_default_timezone_set("UTC"); + $sapi_type = php_sapi_name(); $showColor = !in_array("--no-color", $argv); diff --git a/utils/airtime-log.php b/utils/airtime-log.php index b98cc34c0..7a1050e72 100644 --- a/utils/airtime-log.php +++ b/utils/airtime-log.php @@ -2,6 +2,8 @@ exitIfNotRoot(); +date_default_timezone_set("UTC"); + $airtimeIni = getAirtimeConf(); $airtime_base_dir = $airtimeIni['general']['airtime_dir']; diff --git a/utils/phone_home_stat.php b/utils/phone_home_stat.php index 47929f5f7..d25c546f7 100644 --- a/utils/phone_home_stat.php +++ b/utils/phone_home_stat.php @@ -2,6 +2,8 @@ exitIfNotRoot(); +date_default_timezone_set("UTC"); + $values = parse_ini_file('/etc/airtime/airtime.conf', true); // Name of the web server user diff --git a/utils/soundcloud-uploader.php b/utils/soundcloud-uploader.php index 2660d32e2..2b4615a8c 100644 --- a/utils/soundcloud-uploader.php +++ b/utils/soundcloud-uploader.php @@ -1,4 +1,6 @@ Date: Thu, 25 Oct 2012 16:04:12 -0400 Subject: [PATCH 044/157] added throttling --- python_apps/media-monitor2/media/monitor/organizer.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/media/monitor/organizer.py b/python_apps/media-monitor2/media/monitor/organizer.py index 713bd2156..0532b79b0 100644 --- a/python_apps/media-monitor2/media/monitor/organizer.py +++ b/python_apps/media-monitor2/media/monitor/organizer.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- - +import time import media.monitor.pure as mmp import media.monitor.owners as owners from media.monitor.handler import ReportHandler @@ -72,6 +72,8 @@ class Organizer(ReportHandler,Loggable): directory=d) return cb + time.sleep(0.1) + mmp.magic_move(event.path, new_path, after_dir_make=new_dir_watch(dirname(new_path))) From 9811c670195b6321d5ba01d2df24680fd0cfb912 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 16:10:33 -0400 Subject: [PATCH 045/157] more throttling --- python_apps/media-monitor2/media/monitor/organizer.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python_apps/media-monitor2/media/monitor/organizer.py b/python_apps/media-monitor2/media/monitor/organizer.py index 0532b79b0..176a4f2a4 100644 --- a/python_apps/media-monitor2/media/monitor/organizer.py +++ b/python_apps/media-monitor2/media/monitor/organizer.py @@ -77,6 +77,8 @@ class Organizer(ReportHandler,Loggable): mmp.magic_move(event.path, new_path, after_dir_make=new_dir_watch(dirname(new_path))) + time.sleep(0.1) + # The reason we need to go around saving the owner in this ass # backwards way is bewcause we are unable to encode the owner id # into the file itself so that the StoreWatchListener listener can From b89862f304e15c9a1086aea3ee988a3104a6e1ea Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 16:34:00 -0400 Subject: [PATCH 046/157] tweaked throttling --- python_apps/media-monitor2/media/monitor/organizer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/organizer.py b/python_apps/media-monitor2/media/monitor/organizer.py index 176a4f2a4..bb3c0cb02 100644 --- a/python_apps/media-monitor2/media/monitor/organizer.py +++ b/python_apps/media-monitor2/media/monitor/organizer.py @@ -72,12 +72,12 @@ class Organizer(ReportHandler,Loggable): directory=d) return cb - time.sleep(0.1) + time.sleep(0.05) mmp.magic_move(event.path, new_path, after_dir_make=new_dir_watch(dirname(new_path))) - time.sleep(0.1) + time.sleep(0.05) # The reason we need to go around saving the owner in this ass # backwards way is bewcause we are unable to encode the owner id From 5579a99d2bb8051604d649811622edb475b34f47 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Thu, 25 Oct 2012 16:57:02 -0400 Subject: [PATCH 047/157] added changelog for 2.2.0 --- changelog | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/changelog b/changelog index 96eb74af9..115265768 100644 --- a/changelog +++ b/changelog @@ -1,3 +1,14 @@ +2.2.0 - October 25th, 2012 + * New features + * Smart Playlists + * Webstream rebroadcasts + * Replaygain support + * FLAC + WAV support (AAC if you compile your own Liquidsoap) + * Huge performance increase on library import + * User ownership of files + * Stereo/mono streams + * Rescan watched folders button (useful for network drives where keeping in sync is more difficult) + 2.1.3 - July 4th, 2012 * Changes * Clarify inputs and output labels under stream settings From 5b051aae32c5c8179ac9ab1aeb73543cb1256060 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 17:20:02 -0400 Subject: [PATCH 048/157] changed throttling --- python_apps/media-monitor2/media/monitor/listeners.py | 6 ++++-- python_apps/media-monitor2/media/monitor/manager.py | 2 +- python_apps/media-monitor2/media/monitor/organizer.py | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/listeners.py b/python_apps/media-monitor2/media/monitor/listeners.py index 72b8ca8aa..d30a65147 100644 --- a/python_apps/media-monitor2/media/monitor/listeners.py +++ b/python_apps/media-monitor2/media/monitor/listeners.py @@ -48,11 +48,13 @@ class BaseListener(object): class OrganizeListener(BaseListener, pyinotify.ProcessEvent, Loggable): def process_IN_CLOSE_WRITE(self, event): #self.logger.info("===> handling: '%s'" % str(event)) - self.process_to_organize(event) + #self.process_to_organize(event) + pass # got cookie def process_IN_MOVED_TO(self, event): #self.logger.info("===> handling: '%s'" % str(event)) - self.process_to_organize(event) + #self.process_to_organize(event) + pass def process_default(self, event): pass diff --git a/python_apps/media-monitor2/media/monitor/manager.py b/python_apps/media-monitor2/media/monitor/manager.py index 77bcf10ec..ec705d5af 100644 --- a/python_apps/media-monitor2/media/monitor/manager.py +++ b/python_apps/media-monitor2/media/monitor/manager.py @@ -18,7 +18,7 @@ class ManagerTimeout(threading.Thread,Loggable): secnods. This used to be just a work around for cc-4235 but recently became a permanent solution because it's "cheap" and reliable """ - def __init__(self, manager, interval=3): + def __init__(self, manager, interval=1.5): # TODO : interval should be read from config and passed here instead # of just using the hard coded value threading.Thread.__init__(self) diff --git a/python_apps/media-monitor2/media/monitor/organizer.py b/python_apps/media-monitor2/media/monitor/organizer.py index bb3c0cb02..c6bda1cfa 100644 --- a/python_apps/media-monitor2/media/monitor/organizer.py +++ b/python_apps/media-monitor2/media/monitor/organizer.py @@ -72,12 +72,12 @@ class Organizer(ReportHandler,Loggable): directory=d) return cb - time.sleep(0.05) + time.sleep(0.02) mmp.magic_move(event.path, new_path, after_dir_make=new_dir_watch(dirname(new_path))) - time.sleep(0.05) + time.sleep(0.02) # The reason we need to go around saving the owner in this ass # backwards way is bewcause we are unable to encode the owner id From 3dd5b2869db158a3e77f238f883550ac67f343fa Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 18:38:15 -0400 Subject: [PATCH 049/157] Added lsof to check if file is locked --- .../media-monitor2/media/monitor/listeners.py | 17 ++++++----------- .../media-monitor2/media/monitor/manager.py | 4 ++-- .../media-monitor2/media/monitor/organizer.py | 5 ----- .../media-monitor2/media/monitor/pure.py | 7 +++++++ 4 files changed, 15 insertions(+), 18 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/listeners.py b/python_apps/media-monitor2/media/monitor/listeners.py index d30a65147..4c860a97e 100644 --- a/python_apps/media-monitor2/media/monitor/listeners.py +++ b/python_apps/media-monitor2/media/monitor/listeners.py @@ -48,17 +48,11 @@ class BaseListener(object): class OrganizeListener(BaseListener, pyinotify.ProcessEvent, Loggable): def process_IN_CLOSE_WRITE(self, event): #self.logger.info("===> handling: '%s'" % str(event)) - #self.process_to_organize(event) - pass - # got cookie + self.process_to_organize(event) + def process_IN_MOVED_TO(self, event): #self.logger.info("===> handling: '%s'" % str(event)) - #self.process_to_organize(event) - pass - - def process_default(self, event): - pass - #self.logger.info("===> Not handling: '%s'" % str(event)) + self.process_to_organize(event) def flush_events(self, path): """ @@ -69,8 +63,9 @@ class OrganizeListener(BaseListener, pyinotify.ProcessEvent, Loggable): for f in mmp.walk_supported(path, clean_empties=True): self.logger.info("Bootstrapping: File in 'organize' directory: \ '%s'" % f) - dispatcher.send(signal=self.signal, sender=self, - event=OrganizeFile(f)) + if not mmp.file_locked(f): + dispatcher.send(signal=self.signal, sender=self, + event=OrganizeFile(f)) flushed += 1 #self.logger.info("Flushed organized directory with %d files" % flushed) diff --git a/python_apps/media-monitor2/media/monitor/manager.py b/python_apps/media-monitor2/media/monitor/manager.py index ec705d5af..33dc90468 100644 --- a/python_apps/media-monitor2/media/monitor/manager.py +++ b/python_apps/media-monitor2/media/monitor/manager.py @@ -26,7 +26,7 @@ class ManagerTimeout(threading.Thread,Loggable): self.interval = interval def run(self): while True: - time.sleep(self.interval) # every 3 seconds + time.sleep(self.interval) self.manager.flush_organize() class Manager(Loggable): @@ -178,7 +178,7 @@ class Manager(Loggable): # the OrganizeListener instance will walk path and dispatch an organize # event for every file in that directory self.organize['organize_listener'].flush_events(new_path) - self.__add_watch(new_path, self.organize['organize_listener']) + #self.__add_watch(new_path, self.organize['organize_listener']) def flush_organize(self): path = self.organize['organize_path'] diff --git a/python_apps/media-monitor2/media/monitor/organizer.py b/python_apps/media-monitor2/media/monitor/organizer.py index c6bda1cfa..ea6851356 100644 --- a/python_apps/media-monitor2/media/monitor/organizer.py +++ b/python_apps/media-monitor2/media/monitor/organizer.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -import time import media.monitor.pure as mmp import media.monitor.owners as owners from media.monitor.handler import ReportHandler @@ -72,13 +71,9 @@ class Organizer(ReportHandler,Loggable): directory=d) return cb - time.sleep(0.02) - mmp.magic_move(event.path, new_path, after_dir_make=new_dir_watch(dirname(new_path))) - time.sleep(0.02) - # The reason we need to go around saving the owner in this ass # backwards way is bewcause we are unable to encode the owner id # into the file itself so that the StoreWatchListener listener can diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index ec8f1695a..877cbdc72 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import copy +from subprocess import Popen, PIPE import subprocess import os import math @@ -165,6 +166,12 @@ def walk_supported(directory, clean_empties=False): for fp in full_paths: yield fp if clean_empties: clean_empty_dirs(directory) + +def file_locked(path): + cmd = "lsof %s" % path + f = Popen(cmd, shell=True, stdout=PIPE).stdout + return bool(f.readlines()) + def magic_move(old, new, after_dir_make=lambda : None): """ Moves path old to new and constructs the necessary to directories for new From 4cb4b2d3d5b0af5df461dbe0da84b27fb95d7904 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Oct 2012 00:04:38 -0400 Subject: [PATCH 050/157] updated credits file for 2.2.0 --- CREDITS | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/CREDITS b/CREDITS index d303519ef..2594f4dc5 100644 --- a/CREDITS +++ b/CREDITS @@ -1,3 +1,32 @@ +======= +CREDITS +======= +Version 2.2.0 +------------- +Martin Konecny (martin.konecny@sourcefabric.org) + Role: Developer Team Lead + +Naomi Aro (naomi.aro@sourcefabric.org) + Role: Software Developer + +James Moon (james.moon@sourcefabric.org) + Role: Software Developer + +Denise Rigato (denise.rigato@sourcefabric.org) + Role: Software Developer + +Rudi Grinberg (rudi.grinberg@sourcefabric.org) + Role: Software Developer + +Cliff Wang (cliff.wang@sourcefabric.org) + Role: QA + +Mikayel Karapetian (michael.karapetian@sourcefabric.org) + Role: QA + +Daniel James (daniel.james@sourcefabric.org) + Role: Documentor & QA + ======= CREDITS ======= From e5bbed378213581cb1a0cdba5228e9638f7e8ba7 Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Oct 2012 00:35:44 -0400 Subject: [PATCH 051/157] remove CR line endings --- widgets/sample_page.html | 114 +++++++++++++++++++-------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/widgets/sample_page.html b/widgets/sample_page.html index 94cc51396..cba9c37ed 100644 --- a/widgets/sample_page.html +++ b/widgets/sample_page.html @@ -1,57 +1,57 @@ - - - - -Airtime widgets - - - - - - - -

"Now Playing" Widget

-This widget displays what is currently playing: -
-
-
-
-
-

"Today's Program" Widget

-This widget displays what is being played today: -
-
-
-
-
-

"Weekly Program" Widget

-This widget displays all the shows for the entire week: -
-
-
- - - + + + + +Airtime widgets + + + + + + + +

"Now Playing" Widget

+This widget displays what is currently playing: +
+
+
+
+
+

"Today's Program" Widget

+This widget displays what is being played today: +
+
+
+
+
+

"Weekly Program" Widget

+This widget displays all the shows for the entire week: +
+
+
+ + + From e285bcfba1e64266c3f53577cbcab2a85e29142f Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 26 Oct 2012 12:54:10 -0400 Subject: [PATCH 052/157] update liquidsoap library scripts -git commit hash f776e7f4c5d3729cbcf863381f3cadd96c578a5b --- .../library/external-todo.liq | 314 ------------------ .../liquidsoap_scripts/library/externals.liq | 1 + .../pypo/liquidsoap_scripts/library/http.liq | 16 +- .../liquidsoap_scripts/library/pervasives.liq | 3 +- .../pypo/liquidsoap_scripts/library/utils.liq | 59 ++-- .../liquidsoap_scripts/library/video_text.liq | 2 + 6 files changed, 46 insertions(+), 349 deletions(-) delete mode 100644 python_apps/pypo/liquidsoap_scripts/library/external-todo.liq diff --git a/python_apps/pypo/liquidsoap_scripts/library/external-todo.liq b/python_apps/pypo/liquidsoap_scripts/library/external-todo.liq deleted file mode 100644 index 24ae18cdc..000000000 --- a/python_apps/pypo/liquidsoap_scripts/library/external-todo.liq +++ /dev/null @@ -1,314 +0,0 @@ -# These operators need to be updated.. - - -# Stream data from mplayer -# @category Source / Input -# @param s data URI. -# @param ~restart restart on exit. -# @param ~restart_on_error restart on exit with error. -# @param ~buffer Duration of the pre-buffered data. -# @param ~max Maximum duration of the buffered data. -def input.mplayer(~id="input.mplayer", - ~restart=true,~restart_on_error=false, - ~buffer=0.2,~max=10.,s) = - input.external(id=id,restart=restart, - restart_on_error=restart_on_error, - buffer=buffer,max=max, - "mplayer -really-quiet -ao pcm:file=/dev/stdout \ - -vc null -vo null #{quote(s)} 2>/dev/null") -end - - -# Output the stream using aplay. -# Using this turns "root.sync" to false -# since aplay will do the synchronisation -# @category Source / Output -# @param ~id Output's ID -# @param ~device Alsa pcm device name -# @param ~restart_on_crash Restart external process on crash. If false, liquidsoap will stop. -# @param ~fallible Allow the child source to fail, in which case the output will be (temporarily) stopped. -# @param ~on_start Callback executed when outputting starts. -# @param ~on_stop Callback executed when outputting stops. -# @param s Source to play -def output.aplay(~id="output.aplay",~device="default", - ~fallible=false,~on_start={()},~on_stop={()}, - ~restart_on_crash=false,s) - def aplay_p(m) = - "aplay -D #{device}" - end - log(label=id,level=3,"Setting root.sync to false") - set("root.sync",false) - output.pipe.external(id=id, - fallible=fallible,on_start=on_start,on_stop=on_stop, - restart_on_crash=restart_on_crash, - restart_on_new_track=false, - process=aplay_p,s) -end - -%ifdef output.icecast.external -# Output to icecast using the lame command line encoder. -# @category Source / Output -# @param ~id Output's ID -# @param ~start Start output threads on operator initialization. -# @param ~restart Restart output after a failure. By default, liquidsoap will stop if the output failed. -# @param ~restart_delay Delay, in seconds, before attempting new connection, if restart is enabled. -# @param ~restart_on_crash Restart external process on crash. If false, liquidsoap will stop. -# @param ~restart_on_new_track Restart encoder upon new track. -# @param ~restart_encoder_delay Restart the encoder after this delay, in seconds. -# @param ~user User for shout source connection. Useful only in special cases, like with per-mountpoint users. -# @param ~lame The lame binary -# @param ~bitrate Encoder bitrate -# @param ~swap Swap audio samples. Depends on local machine's endianess and lame's version. Test this parameter if you experience garbaged mp3 audio data. On intel 32 and 64 architectures, the parameter should be "true" for lame version >= 3.98. -# @param ~dumpfile Dump stream to file, for debugging purpose. Disabled if empty. -# @param ~protocol Protocol of the streaming server: 'http' for Icecast, 'icy' for Shoutcast. -# @param ~fallible Allow the child source to fail, in which case the output will be (temporarily) stopped. -# @param ~on_start Callback executed when outputting starts. -# @param ~on_stop Callback executed when outputting stops. -# @param s The source to output -def output.icecast.lame( - ~id="output.icecast.lame",~start=true, - ~restart=false,~restart_delay=3, - ~host="localhost",~port=8000, - ~user="source",~password="hackme", - ~genre="Misc",~url="http://savonet.sf.net/", - ~description="Liquidsoap Radio!",~public=true, - ~dumpfile="",~mount="Use [name]", - ~name="Use [mount]",~protocol="http", - ~lame="lame",~bitrate=128,~swap=false, - ~fallible=false,~on_start={()},~on_stop={()}, - ~restart_on_crash=false,~restart_on_new_track=false, - ~restart_encoder_delay=3600,~headers=[],s) - samplerate = get(default=44100,"frame.samplerate") - samplerate = float_of_int(samplerate) / 1000. - channels = get(default=2,"frame.channels") - swap = if swap then "-x" else "" end - mode = - if channels == 2 then - "j" # Encoding in joint stereo.. - else - "m" - end - # Metadata update is set by ICY with icecast - def lame_p(m) - "#{lame} -b #{bitrate} -r --bitwidth 16 -s #{samplerate} \ - --signed -m #{mode} --nores #{swap} -t - -" - end - output.icecast.external(id=id, - process=lame_p,bitrate=bitrate,start=start, - restart=restart,restart_delay=restart_delay, - host=host,port=port,user=user,password=password, - genre=genre,url=url,description=description, - public=public,dumpfile=dumpfile,restart_encoder_delay=restart_encoder_delay, - name=name,mount=mount,protocol=protocol, - header=false,restart_on_crash=restart_on_crash, - restart_on_new_track=restart_on_new_track,headers=headers, - fallible=fallible,on_start=on_start,on_stop=on_stop, - s) -end - -# Output to shoutcast using the lame encoder. -# @category Source / Output -# @param ~id Output's ID -# @param ~start Start output threads on operator initialization. -# @param ~restart Restart output after a failure. By default, liquidsoap will stop if the output failed. -# @param ~restart_delay Delay, in seconds, before attempting new connection, if restart is enabled. -# @param ~restart_on_crash Restart external process on crash. If false, liquidsoap will stop. -# @param ~restart_on_new_track Restart encoder upon new track. -# @param ~restart_encoder_delay Restart the encoder after this delay, in seconds. -# @param ~user User for shout source connection. Useful only in special cases, like with per-mountpoint users. -# @param ~lame The lame binary -# @param ~bitrate Encoder bitrate -# @param ~icy_reset Reset shoutcast source buffer upon connecting (necessary for NSV). -# @param ~dumpfile Dump stream to file, for debugging purpose. Disabled if empty. -# @param ~fallible Allow the child source to fail, in which case the output will be (temporarily) stopped. -# @param ~on_start Callback executed when outputting starts. -# @param ~on_stop Callback executed when outputting stops. -# @param s The source to output -def output.shoutcast.lame( - ~id="output.shoutcast.mp3",~start=true, - ~restart=false,~restart_delay=3, - ~host="localhost",~port=8000, - ~user="source",~password="hackme", - ~genre="Misc",~url="http://savonet.sf.net/", - ~description="Liquidsoap Radio!",~public=true, - ~dumpfile="",~name="Use [mount]",~icy_reset=true, - ~lame="lame",~aim="",~icq="",~irc="", - ~fallible=false,~on_start={()},~on_stop={()}, - ~restart_on_crash=false,~restart_on_new_track=false, - ~restart_encoder_delay=3600,~bitrate=128,s) = - icy_reset = if icy_reset then "1" else "0" end - headers = [("icy-aim",aim),("icy-irc",irc), - ("icy-icq",icq),("icy-reset",icy_reset)] - output.icecast.lame( - id=id, headers=headers, lame=lame, - bitrate=bitrate, start=start, - restart=restart, restart_encoder_delay=restart_encoder_delay, - host=host, port=port, user=user, password=password, - genre=genre, url=url, description=description, - public=public, dumpfile=dumpfile, - restart_on_crash=restart_on_crash, - restart_on_new_track=restart_on_new_track, - name=name, mount="/", protocol="icy", - fallible=fallible,on_start=on_start,on_stop=on_stop, - s) -end - -# Output to icecast using the flac command line encoder. -# @category Source / Output -# @param ~id Output's ID -# @param ~start Start output threads on operator initialization. -# @param ~restart Restart output after a failure. By default, liquidsoap will stop if the output failed. -# @param ~restart_delay Delay, in seconds, before attempting new connection, if restart is enabled. -# @param ~restart_on_crash Restart external process on crash. If false, liquidsoap will stop. -# @param ~restart_on_new_track Restart encoder upon new track. If false, the resulting stream will have a single track. -# @param ~restart_encoder_delay Restart the encoder after this delay, in seconds. -# @param ~user User for shout source connection. Useful only in special cases, like with per-mountpoint users. -# @param ~flac The flac binary -# @param ~quality Encoder quality (0..8) -# @param ~dumpfile Dump stream to file, for debugging purpose. Disabled if empty. -# @param ~protocol Protocol of the streaming server: 'http' for Icecast, 'icy' for Shoutcast. -# @param ~fallible Allow the child source to fail, in which case the output will be (temporarily) stopped. -# @param ~on_start Callback executed when outputting starts. -# @param ~on_stop Callback executed when outputting stops. -# @param s The source to output -def output.icecast.flac( - ~id="output.icecast.flac",~start=true, - ~restart=false,~restart_delay=3, - ~host="localhost",~port=8000, - ~user="source",~password="hackme", - ~genre="Misc",~url="http://savonet.sf.net/", - ~description="Liquidsoap Radio!",~public=true, - ~dumpfile="",~mount="Use [name]", - ~name="Use [mount]",~protocol="http", - ~flac="flac",~quality=6, - ~restart_on_crash=false, - ~restart_on_new_track=true, - ~restart_encoder_delay=(-1), - ~fallible=false,~on_start={()},~on_stop={()}, - s) - # We will use raw format, to - # bypass input length value in WAV - # header (input length is not known) - channels = get(default=2,"frame.channels") - samplerate = get(default=44100,"frame.samplerate") - def flac_p(m)= - def option(x) = - "-T #{quote(fst(x))}=#{quote(snd(x))}" - end - m = list.map(option,m) - m = string.concat(separator=" ",m) - "#{flac} --force-raw-format --endian=little --channels=#{channels} \ - --bps=16 --sample-rate=#{samplerate} --sign=signed #{m} \ - -#{quality} --ogg -c -" - end - output.icecast.external(id=id, - process=flac_p,bitrate=(-1),start=start, - restart=restart,restart_delay=restart_delay, - host=host,port=port,user=user,password=password, - genre=genre,url=url,description=description, - public=public,dumpfile=dumpfile, - name=name,mount=mount,protocol=protocol, - fallible=fallible,on_start=on_start,on_stop=on_stop, - restart_on_new_track=restart_on_new_track, - format="ogg",header=false,icy_metadata=false, - restart_on_crash=restart_on_crash, - restart_encoder_delay=restart_encoder_delay, - s) -end - -# Output to icecast using the aacplusenc command line encoder. -# @category Source / Output -# @param ~id Output's ID -# @param ~start Start output threads on operator initialization. -# @param ~restart Restart output after a failure. By default, liquidsoap will stop if the output failed. -# @param ~restart_delay Delay, in seconds, before attempting new connection, if restart is enabled. -# @param ~restart_on_crash Restart external process on crash. If false, liquidsoap will stop. -# @param ~restart_on_new_track Restart encoder upon new track. -# @param ~restart_encoder_delay Restart the encoder after this delay, in seconds. -# @param ~user User for shout source connection. Useful only in special cases, like with per-mountpoint users. -# @param ~aacplusenc The aacplusenc binary -# @param ~bitrate Encoder bitrate -# @param ~dumpfile Dump stream to file, for debugging purpose. Disabled if empty. -# @param ~protocol Protocol of the streaming server: 'http' for Icecast, 'icy' for Shoutcast. -# @param ~fallible Allow the child source to fail, in which case the output will be (temporarily) stopped. -# @param ~on_start Callback executed when outputting starts. -# @param ~on_stop Callback executed when outputting stops. -# @param s The source to output -def output.icecast.aacplusenc( - ~id="output.icecast.aacplusenc",~start=true, - ~restart=false,~restart_delay=3, - ~host="localhost",~port=8000, - ~user="source",~password="hackme", - ~genre="Misc",~url="http://savonet.sf.net/", - ~description="Liquidsoap Radio!",~public=true, - ~dumpfile="",~mount="Use [name]", - ~name="Use [mount]",~protocol="http", - ~aacplusenc="aacplusenc",~bitrate=64, - ~fallible=false,~on_start={()},~on_stop={()}, - ~restart_on_crash=false,~restart_on_new_track=false, - ~restart_encoder_delay=3600,~headers=[],s) - # Metadata update is set by ICY with icecast - def aacplusenc_p(m) - "#{aacplusenc} - - #{bitrate}" - end - output.icecast.external(id=id, - process=aacplusenc_p,bitrate=bitrate,start=start, - restart=restart,restart_delay=restart_delay, - host=host,port=port,user=user,password=password, - genre=genre,url=url,description=description, - public=public,dumpfile=dumpfile, - name=name,mount=mount,protocol=protocol, - fallible=fallible,on_start=on_start,on_stop=on_stop, - header=true,restart_on_crash=restart_on_crash, - restart_on_new_track=restart_on_new_track,headers=headers, - restart_encoder_delay=restart_encoder_delay,format="audio/aacp",s) -end - -# Output to shoutcast using the aacplusenc encoder. -# @category Source / Output -# @param ~id Output's ID -# @param ~start Start output threads on operator initialization. -# @param ~restart Restart output after a failure. By default, liquidsoap will stop if the output failed. -# @param ~restart_delay Delay, in seconds, before attempting new connection, if restart is enabled. -# @param ~restart_on_crash Restart external process on crash. If false, liquidsoap will stop. -# @param ~restart_on_new_track Restart encoder upon new track. -# @param ~restart_encoder_delay Restart the encoder after this delay, in seconds. -# @param ~user User for shout source connection. Useful only in special cases, like with per-mountpoint users. -# @param ~aacplusenc The aacplusenc binary -# @param ~bitrate Encoder bitrate -# @param ~icy_reset Reset shoutcast source buffer upon connecting (necessary for NSV). -# @param ~dumpfile Dump stream to file, for debugging purpose. Disabled if empty. -# @param ~fallible Allow the child source to fail, in which case the output will be (temporarily) stopped. -# @param ~on_start Callback executed when outputting starts. -# @param ~on_stop Callback executed when outputting stops. -# @param s The source to output -def output.shoutcast.aacplusenc( - ~id="output.shoutcast.aacplusenc",~start=true, - ~restart=false,~restart_delay=3, - ~host="localhost",~port=8000, - ~user="source",~password="hackme", - ~genre="Misc",~url="http://savonet.sf.net/", - ~description="Liquidsoap Radio!",~public=true, - ~fallible=false,~on_start={()},~on_stop={()}, - ~dumpfile="",~name="Use [mount]",~icy_reset=true, - ~aim="",~icq="",~irc="",~aacplusenc="aacplusenc", - ~restart_on_crash=false,~restart_on_new_track=false, - ~restart_encoder_delay=3600,~bitrate=64,s) = - icy_reset = if icy_reset then "1" else "0" end - headers = [("icy-aim",aim),("icy-irc",irc), - ("icy-icq",icq),("icy-reset",icy_reset)] - output.icecast.aacplusenc( - id=id, headers=headers, aacplusenc=aacplusenc, - bitrate=bitrate, start=start, - restart=restart, restart_delay=restart_delay, - host=host, port=port, user=user, password=password, - genre=genre, url=url, description=description, - public=public, dumpfile=dumpfile, - fallible=fallible,on_start=on_start,on_stop=on_stop, - restart_on_crash=restart_on_crash, restart_encoder_delay=restart_encoder_delay, - restart_on_new_track=restart_on_new_track, - name=name, mount="/", protocol="icy", - s) -end -%endif - diff --git a/python_apps/pypo/liquidsoap_scripts/library/externals.liq b/python_apps/pypo/liquidsoap_scripts/library/externals.liq index 6e1b98a60..b56f13d0c 100644 --- a/python_apps/pypo/liquidsoap_scripts/library/externals.liq +++ b/python_apps/pypo/liquidsoap_scripts/library/externals.liq @@ -4,6 +4,7 @@ # Enable external Musepack decoder. Requires the # mpcdec binary in the path. Does not work on # Win32. +# @category Liquidsoap def enable_external_mpc_decoder() = # A list of know extensions and content-type for Musepack. # Values from http://en.wikipedia.org/wiki/Musepack diff --git a/python_apps/pypo/liquidsoap_scripts/library/http.liq b/python_apps/pypo/liquidsoap_scripts/library/http.liq index 109baf41e..53644ce38 100644 --- a/python_apps/pypo/liquidsoap_scripts/library/http.liq +++ b/python_apps/pypo/liquidsoap_scripts/library/http.liq @@ -13,18 +13,12 @@ def http_response(~protocol="HTTP/1.1", ~headers=[], ~data="") = status = http_codes[string_of(code)] - # Set content-length if needed and not set by the - # user. + # Set content-length and connection: close headers = - if data != "" and - not list.mem_assoc("Content-Length",headers) - then - list.append([("Content-Length", - "#{string.length(data)}")], - headers) - else - headers - end + list.append(headers, + [("Content-Length", "#{string.length(data)}"), + ("Connection", "close")]) + headers = list.map(fun (x) -> "#{fst(x)}: #{snd(x)}",headers) headers = string.concat(separator="\r\n",headers) # If no headers are provided, we should avoid diff --git a/python_apps/pypo/liquidsoap_scripts/library/pervasives.liq b/python_apps/pypo/liquidsoap_scripts/library/pervasives.liq index bd894766b..722138018 100644 --- a/python_apps/pypo/liquidsoap_scripts/library/pervasives.liq +++ b/python_apps/pypo/liquidsoap_scripts/library/pervasives.liq @@ -4,4 +4,5 @@ %include "lastfm.liq" %include "flows.liq" %include "http.liq" -%include "video_text.liq" \ No newline at end of file +%include "video_text.liq" +%include "gstreamer.liq" diff --git a/python_apps/pypo/liquidsoap_scripts/library/utils.liq b/python_apps/pypo/liquidsoap_scripts/library/utils.liq index 3d82d8997..a35af94f3 100644 --- a/python_apps/pypo/liquidsoap_scripts/library/utils.liq +++ b/python_apps/pypo/liquidsoap_scripts/library/utils.liq @@ -21,10 +21,14 @@ end # @param a Key to look for # @param l List of pairs (key,value) def list.mem_assoc(a,l) - v = list.assoc(a,l) - # We check for existence, since "" may indicate - # either a binding (a,"") or no binding.. - list.mem((a,v),l) + def f(cur, el) = + if not cur then + fst(el) == a + else + cur + end + end + list.fold(f, false, l) end # Remove a pair from an associative list @@ -164,8 +168,7 @@ def out(s) output.prefered(mksafe(s)) end -# Special track insensitive fallback that -# always skip current song before switching. +# Special track insensitive fallback that always skips current song before switching. # @category Source / Track Processing # @param ~input The input source # @param f The fallback source @@ -212,14 +215,17 @@ end # Simple crossfade. # @category Source / Track Processing # @param ~start_next Duration in seconds of the crossed end of track. -# @param ~fade_in Duration of the fade in for next track -# @param ~fade_out Duration of the fade out for previous track -# @param s The source to use -def crossfade(~id="",~start_next,~fade_in,~fade_out,s) +# @param ~fade_in Duration of the fade in for next track. +# @param ~fade_out Duration of the fade out for previous track. +# @param ~conservative Always prepare for a premature end-of-track. +# @param s The source to use. +def crossfade(~id="",~conservative=true, + ~start_next=5.,~fade_in=3.,~fade_out=3., + s) s = fade.in(duration=fade_in,s) s = fade.out(duration=fade_out,s) fader = fun (a,b) -> add(normalize=false,[b,a]) - cross(id=id,conservative=true,duration=start_next,fader,s) + cross(id=id,conservative=conservative,duration=start_next,fader,s) end # Append speech-synthesized tracks reading the metadata. @@ -242,8 +248,7 @@ def helium(s) end %endif -# Return true if process exited with 0 code. -# Command should return quickly. +# Return true if process exited with 0 code. Command should return quickly. # @category System # @param command Command to test def test_process(command) @@ -277,12 +282,9 @@ def url.split(uri) = end end -# Register a server/telnet command to -# update a source's metadata. Returns -# a new source, which will receive the -# updated metadata. It behaves just like -# the pre-1.0 insert_metadata() operator, -# i.e. insert key1="val1",key2="val2",... +# Register a server/telnet command to update a source's metadata. Returns +# a new source, which will receive the updated metadata. The command has +# the following format: insert key1="val1",key2="val2",... # @category Source / Track Processing # @param ~id Force the value of the source ID. def server.insert_metadata(~id="",s) = @@ -424,15 +426,15 @@ end # @param ~conservative Always prepare for a premature end-of-track. # @param ~default Transition used when no rule applies \ # (default: sequence). -# @param ~high Value, in dB, for loud sound level -# @param ~medium Value, in dB, for medium sound level +# @param ~high Value, in dB, for loud sound level. +# @param ~medium Value, in dB, for medium sound level. # @param ~margin Margin to detect sources that have too different \ # sound level for crossing. # @param s The input source. def smart_crossfade (~start_next=5.,~fade_in=3.,~fade_out=3., ~default=(fun (a,b) -> sequence([a, b])), ~high=-15., ~medium=-32., ~margin=4., - ~width=2.,~conservative=false,s) + ~width=2.,~conservative=true,s) fade.out = fade.out(type="sin",duration=fade_out) fade.in = fade.in(type="sin",duration=fade_in) add = fun (a,b) -> add(normalize=false,[b, a]) @@ -549,7 +551,18 @@ def playlist.reloadable(~id="",~random=false,~on_done={()},uri) if request.resolve(playlist) then playlist = request.filename(playlist) files = playlist.parse(playlist) - list.map(snd,files) + def file_request(el) = + meta = fst(el) + file = snd(el) + s = list.fold(fun (cur, el) -> + "#{cur},#{fst(el)}=#{string.escape(snd(el))}", "", meta) + if s == "" then + file + else + "annotate:#{s}:#{file}" + end + end + list.map(file_request,files) else log(label=id,"Couldn't read playlist: request resolution failed.") [] diff --git a/python_apps/pypo/liquidsoap_scripts/library/video_text.liq b/python_apps/pypo/liquidsoap_scripts/library/video_text.liq index b372a1f7b..8c017a93d 100644 --- a/python_apps/pypo/liquidsoap_scripts/library/video_text.liq +++ b/python_apps/pypo/liquidsoap_scripts/library/video_text.liq @@ -1,5 +1,6 @@ %ifdef video.add_text.gd # Add a scrolling line of text on video frames. +# @category Source / Video Processing # @param ~id Force the value of the source ID. # @param ~color Text color (in 0xRRGGBB format). # @param ~cycle Cycle text. @@ -22,6 +23,7 @@ end %ifdef video.add_text.sdl # Add a scrolling line of text on video frames. +# @category Source / Video Processing # @param ~id Force the value of the source ID. # @param ~color Text color (in 0xRRGGBB format). # @param ~cycle Cycle text. From cad6a7e7b0783e24cddbb12db40cff9fa0c07efb Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 9 Oct 2012 12:25:40 -0400 Subject: [PATCH 053/157] added perliminary stuff for emf --- python_apps/media-monitor2/media/monitor/metadata.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index bd42e434c..7b7d6d184 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -185,6 +185,15 @@ class Metadata(Loggable): # TODO : Simplify the way all of these rules are handled right now it's # extremely unclear and needs to be refactored. #if full_mutagen is None: raise BadSongFile(fpath) + try: # emf stuff for testing: + import media.metadata.process as md + import pprint.pformat as pf + if full_mutagen: + normalized = md.global_reader.read('fpath', full_mutagen) + self.logger.info(pf(normalized)) + except Exception as e: + self.logger.unexpected_exception(e) + if full_mutagen is None: full_mutagen = FakeMutagen(fpath) self.__metadata = Metadata.airtime_dict(full_mutagen) # Now we extra the special values that are calculated from the mutagen @@ -209,6 +218,7 @@ class Metadata(Loggable): # from the file? self.__metadata['MDATA_KEY_MD5'] = mmp.file_md5(fpath,max_length=100) + def is_recorded(self): """ returns true if the file has been created by airtime through recording From a88b7255ff9ec2d223bacc3cfaa380471e8db26b Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 9 Oct 2012 12:36:52 -0400 Subject: [PATCH 054/157] removed automatic loading of emf definitions --- .../media/metadata/definitions.py | 171 +++++++++--------- .../media-monitor2/media/monitor/metadata.py | 12 +- 2 files changed, 97 insertions(+), 86 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index 51ef6fd14..cfeb0d2fb 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -3,109 +3,116 @@ import media.monitor.process as md from os.path import normpath from media.monitor.pure import format_length, file_md5 -with md.metadata('MDATA_KEY_DURATION') as t: - t.default(u'0.0') - t.depends('length') - t.translate(lambda k: format_length(k['length'])) +defs_loaded = False -with md.metadata('MDATA_KEY_MIME') as t: - t.default(u'') - t.depends('mime') - t.translate(lambda k: k['mime'].replace('-','/')) +def is_defs_loaded(): + global defs_loaded + return defs_loaded -with md.metadata('MDATA_KEY_BITRATE') as t: - t.default(u'') - t.depends('bitrate') - t.translate(lambda k: k['bitrate']) +def load_definitions(): + with md.metadata('MDATA_KEY_DURATION') as t: + t.default(u'0.0') + t.depends('length') + t.translate(lambda k: format_length(k['length'])) -with md.metadata('MDATA_KEY_SAMPLERATE') as t: - t.default(u'0') - t.depends('sample_rate') - t.translate(lambda k: k['sample_rate']) + with md.metadata('MDATA_KEY_MIME') as t: + t.default(u'') + t.depends('mime') + t.translate(lambda k: k['mime'].replace('-','/')) -with md.metadata('MDATA_KEY_FTYPE'): - t.depends('ftype') # i don't think this field even exists - t.default(u'audioclip') - t.translate(lambda k: k['ftype']) # but just in case + with md.metadata('MDATA_KEY_BITRATE') as t: + t.default(u'') + t.depends('bitrate') + t.translate(lambda k: k['bitrate']) -with md.metadata("MDATA_KEY_CREATOR") as t: - t.depends("artist") - # A little kludge to make sure that we have some value for when we parse - # MDATA_KEY_TITLE - t.default(u"") - t.max_length(512) + with md.metadata('MDATA_KEY_SAMPLERATE') as t: + t.default(u'0') + t.depends('sample_rate') + t.translate(lambda k: k['sample_rate']) -with md.metadata("MDATA_KEY_SOURCE") as t: - t.depends("album") - t.max_length(512) + with md.metadata('MDATA_KEY_FTYPE'): + t.depends('ftype') # i don't think this field even exists + t.default(u'audioclip') + t.translate(lambda k: k['ftype']) # but just in case -with md.metadata("MDATA_KEY_GENRE") as t: - t.depends("genre") - t.max_length(64) + with md.metadata("MDATA_KEY_CREATOR") as t: + t.depends("artist") + # A little kludge to make sure that we have some value for when we parse + # MDATA_KEY_TITLE + t.default(u"") + t.max_length(512) -with md.metadata("MDATA_KEY_MOOD") as t: - t.depends("mood") - t.max_length(64) + with md.metadata("MDATA_KEY_SOURCE") as t: + t.depends("album") + t.max_length(512) -with md.metadata("MDATA_KEY_TRACKNUMBER") as t: - t.depends("tracknumber") + with md.metadata("MDATA_KEY_GENRE") as t: + t.depends("genre") + t.max_length(64) -with md.metadata("MDATA_KEY_BPM") as t: - t.depends("bpm") - t.max_length(8) + with md.metadata("MDATA_KEY_MOOD") as t: + t.depends("mood") + t.max_length(64) -with md.metadata("MDATA_KEY_LABEL") as t: - t.depends("organization") - t.max_length(512) + with md.metadata("MDATA_KEY_TRACKNUMBER") as t: + t.depends("tracknumber") -with md.metadata("MDATA_KEY_COMPOSER") as t: - t.depends("composer") - t.max_length(512) + with md.metadata("MDATA_KEY_BPM") as t: + t.depends("bpm") + t.max_length(8) -with md.metadata("MDATA_KEY_ENCODER") as t: - t.depends("encodedby") - t.max_length(512) + with md.metadata("MDATA_KEY_LABEL") as t: + t.depends("organization") + t.max_length(512) -with md.metadata("MDATA_KEY_CONDUCTOR") as t: - t.depends("conductor") - t.max_length(512) + with md.metadata("MDATA_KEY_COMPOSER") as t: + t.depends("composer") + t.max_length(512) -with md.metadata("MDATA_KEY_YEAR") as t: - t.depends("date") - t.max_length(16) + with md.metadata("MDATA_KEY_ENCODER") as t: + t.depends("encodedby") + t.max_length(512) -with md.metadata("MDATA_KEY_URL") as t: - t.depends("website") + with md.metadata("MDATA_KEY_CONDUCTOR") as t: + t.depends("conductor") + t.max_length(512) -with md.metadata("MDATA_KEY_ISRC") as t: - t.depends("isrc") - t.max_length(512) + with md.metadata("MDATA_KEY_YEAR") as t: + t.depends("date") + t.max_length(16) -with md.metadata("MDATA_KEY_COPYRIGHT") as t: - t.depends("copyright") - t.max_length(512) + with md.metadata("MDATA_KEY_URL") as t: + t.depends("website") -with md.metadata("MDATA_KEY_FILEPATH") as t: - t.depends('path') - t.translate(lambda k: normpath(k['path'])) + with md.metadata("MDATA_KEY_ISRC") as t: + t.depends("isrc") + t.max_length(512) -with md.metadata("MDATA_KEY_MD5") as t: - t.depends('path') - t.optional(False) - t.translate(lambda k: file_md5(k['path'], max_length=100)) + with md.metadata("MDATA_KEY_COPYRIGHT") as t: + t.depends("copyright") + t.max_length(512) -# owner is handled differently by (by events.py) + with md.metadata("MDATA_KEY_FILEPATH") as t: + t.depends('path') + t.translate(lambda k: normpath(k['path'])) -with md.metadata('MDATA_KEY_ORIGINAL_PATH') as t: - t.depends('original_path') + with md.metadata("MDATA_KEY_MD5") as t: + t.depends('path') + t.optional(False) + t.translate(lambda k: file_md5(k['path'], max_length=100)) -# MDATA_KEY_TITLE is the annoying special case -with md.metadata('MDATA_KEY_TITLE') as t: - # Need to know MDATA_KEY_CREATOR to know if show was recorded. Value is - # defaulted to "" from definitions above - t.depends('title','MDATA_KEY_CREATOR') - t.max_length(512) + # owner is handled differently by (by events.py) -with md.metadata('MDATA_KEY_LABEL') as t: - t.depends('label') - t.max_length(512) + with md.metadata('MDATA_KEY_ORIGINAL_PATH') as t: + t.depends('original_path') + + # MDATA_KEY_TITLE is the annoying special case + with md.metadata('MDATA_KEY_TITLE') as t: + # Need to know MDATA_KEY_CREATOR to know if show was recorded. Value is + # defaulted to "" from definitions above + t.depends('title','MDATA_KEY_CREATOR') + t.max_length(512) + + with md.metadata('MDATA_KEY_LABEL') as t: + t.depends('label') + t.max_length(512) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 7b7d6d184..3e7fa893d 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -11,6 +11,12 @@ from media.monitor.log import Loggable from media.monitor.pure import format_length, truncate_to_length import media.monitor.pure as mmp +# emf related stuff +from media.metadata.process import global_reader +import media.metadata.definitions as defs +from pprint import pformat +defs.load_definitions() + """ list of supported easy tags in mutagen version 1.20 ['albumartistsort', 'musicbrainz_albumstatus', 'lyricist', 'releasecountry', @@ -186,11 +192,9 @@ class Metadata(Loggable): # extremely unclear and needs to be refactored. #if full_mutagen is None: raise BadSongFile(fpath) try: # emf stuff for testing: - import media.metadata.process as md - import pprint.pformat as pf if full_mutagen: - normalized = md.global_reader.read('fpath', full_mutagen) - self.logger.info(pf(normalized)) + normalized = global_reader.read('fpath', full_mutagen) + self.logger.info(pformat(normalized)) except Exception as e: self.logger.unexpected_exception(e) From 10c4a71866bbb0e9c0992f93b79515077a3dcb0e Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 9 Oct 2012 14:46:01 -0400 Subject: [PATCH 055/157] Added default translator for mdata elements that don't specify it --- .../media/metadata/definitions.py | 2 +- .../media-monitor2/media/metadata/process.py | 19 ++++++++++++++++++- .../media-monitor2/media/monitor/metadata.py | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index cfeb0d2fb..68ada6034 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -import media.monitor.process as md +import media.metadata.process as md from os.path import normpath from media.monitor.pure import format_length, file_md5 diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index a4c361468..6cebc0269 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from contextlib import contextmanager from media.monitor.pure import truncate_to_length, toposort +from media.monitor.log import Loggable import mutagen @@ -8,7 +9,12 @@ class MetadataAbsent(Exception): def __init__(self, name): self.name = name def __str__(self): return "Could not obtain element '%s'" % self.name -class MetadataElement(object): +class MetadataElement(Loggable): + + def __default_translator(k): + e = [ x for x in self.dependencies() ][0] + return k[e] + def __init__(self,name): self.name = name # "Sane" defaults @@ -19,6 +25,8 @@ class MetadataElement(object): self.__is_normalized = lambda _ : True self.__max_length = -1 + + def max_length(self,l): self.__max_length = l @@ -82,6 +90,15 @@ class MetadataElement(object): if self.has_default(): return self.get_default() else: raise MetadataAbsent(self.name) # We have all dependencies. Now for actual for parsing + + # Only case where we can select a default translator + if not self.__translator: + if len(self.dependencies()) == 1: + self.translate(MetadataElement.__default_translator) + else: + self.logger.info("Could not set more than 1 translator with \ + more than 1 dependancies") + r = self.__normalizer( self.__translator(full_deps) ) if self.__max_length != -1: r = truncate_to_length(r, self.__max_length) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 3e7fa893d..6cce20e34 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -196,7 +196,7 @@ class Metadata(Loggable): normalized = global_reader.read('fpath', full_mutagen) self.logger.info(pformat(normalized)) except Exception as e: - self.logger.unexpected_exception(e) + self.unexpected_exception(e) if full_mutagen is None: full_mutagen = FakeMutagen(fpath) self.__metadata = Metadata.airtime_dict(full_mutagen) From b7b11feae00dd1ef6b12a8fcf6bfe3d79e7f882e Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 9 Oct 2012 18:02:03 -0400 Subject: [PATCH 056/157] emf improvements --- .../media/metadata/definitions.py | 11 +++---- .../media-monitor2/media/metadata/process.py | 30 +++++++++++-------- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index 68ada6034..f3399e24c 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -96,17 +96,18 @@ def load_definitions(): t.depends('path') t.translate(lambda k: normpath(k['path'])) - with md.metadata("MDATA_KEY_MD5") as t: - t.depends('path') - t.optional(False) - t.translate(lambda k: file_md5(k['path'], max_length=100)) + #with md.metadata("MDATA_KEY_MD5") as t: + #t.depends('path') + #t.optional(False) + #t.translate(lambda k: file_md5(k['path'], max_length=100)) # owner is handled differently by (by events.py) with md.metadata('MDATA_KEY_ORIGINAL_PATH') as t: t.depends('original_path') - # MDATA_KEY_TITLE is the annoying special case + # MDATA_KEY_TITLE is the annoying special case b/c we sometimes read it + # from file name with md.metadata('MDATA_KEY_TITLE') as t: # Need to know MDATA_KEY_CREATOR to know if show was recorded. Value is # defaulted to "" from definitions above diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index 6cebc0269..88a8b5cc6 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -11,10 +11,6 @@ class MetadataAbsent(Exception): class MetadataElement(Loggable): - def __default_translator(k): - e = [ x for x in self.dependencies() ][0] - return k[e] - def __init__(self,name): self.name = name # "Sane" defaults @@ -24,8 +20,7 @@ class MetadataElement(Loggable): self.__default = None self.__is_normalized = lambda _ : True self.__max_length = -1 - - + self.__translator = None def max_length(self,l): self.__max_length = l @@ -71,6 +66,7 @@ class MetadataElement(Loggable): return "%s(%s)" % (self.name, ' '.join(list(self.__deps))) def read_value(self, path, original, running={}): + self.logger.info("Trying to read: %s" % str(original)) # If value is present and normalized then we don't touch it if self.name in original: v = original[self.name] @@ -83,21 +79,29 @@ class MetadataElement(Loggable): full_deps = dict( dep_slice_orig.items() + dep_slice_running.items() ) + full_deps['path'] = path + # check if any dependencies are absent - if len(full_deps) != len(self.__deps) or len(self.__deps) == 0: + if len(full_deps) < len(self.__deps) or len(self.__deps) == 0: # If we have a default value then use that. Otherwise throw an # exception if self.has_default(): return self.get_default() else: raise MetadataAbsent(self.name) # We have all dependencies. Now for actual for parsing + def def_translate(dep): + def wrap(k): + e = [ x for x in dep ][0] + return k[e] + return wrap + # Only case where we can select a default translator - if not self.__translator: - if len(self.dependencies()) == 1: - self.translate(MetadataElement.__default_translator) - else: - self.logger.info("Could not set more than 1 translator with \ - more than 1 dependancies") + if self.__translator is None: + self.translate(def_translate(self.dependencies())) + if len(self.dependencies()) > 2: # dependencies include themselves + self.logger.info("Ignoring some dependencies in translate %s" + % self.name) + self.logger.info(self.dependencies()) r = self.__normalizer( self.__translator(full_deps) ) if self.__max_length != -1: From 55567d1de03d7f993b33b93794a4fb4d93356a4a Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Wed, 10 Oct 2012 14:40:46 -0400 Subject: [PATCH 057/157] Aded diff_dict function to help locate differences between emf and old metadata parsing. --- .../media-monitor2/media/monitor/pure.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index 877cbdc72..81b9cba49 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -68,6 +68,23 @@ class IncludeOnly(object): return _wrap + +def diff_dict(d1, d2, width=30): + """ + returns a formatted diff of 2 dictionaries + """ + out = "" + all_keys = d1.keys() + d2.keys() + for k in all_keys: + v1, v2 = d1.get(k), d2.get(k) + + # default values + if v1 is None: v1 = "N/A" + if v2 is None: v2 = "N/A" + + if d1[k] != d2[k]: + out += "%s%s%s" % (k, d1[k], d2[k]) + def partition(f, alist): """ Partition is very similar to filter except that it also returns the From 31b2a29392120de85fab4d05f3e1aaa7e76c838c Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Wed, 10 Oct 2012 14:41:12 -0400 Subject: [PATCH 058/157] Added docstirng for __slice_deps --- .../media-monitor2/media/metadata/process.py | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index 88a8b5cc6..d8be46bdf 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -60,35 +60,49 @@ class MetadataElement(Loggable): return self.__path def __slice_deps(self, d): + """ + returns a dictionary of all the key value pairs in d that are also + present in self.__deps + """ return dict( (k,v) for k,v in d.iteritems() if k in self.__deps) def __str__(self): return "%s(%s)" % (self.name, ' '.join(list(self.__deps))) def read_value(self, path, original, running={}): - self.logger.info("Trying to read: %s" % str(original)) - # If value is present and normalized then we don't touch it + + # If value is present and normalized then we only check if it's + # normalized or not. We normalize if it's not normalized already + if self.name in original: v = original[self.name] if self.__is_normalized(v): return v else: return self.__normalizer(v) - # A dictionary slice with all the dependencies and their values + # We slice out only the dependencies that are required for the metadata + # element. dep_slice_orig = self.__slice_deps(original) dep_slice_running = self.__slice_deps(running) + # TODO : remove this later + dep_slice_special = self.__slice_deps({'path' : path}) + # We combine all required dependencies into a single dictionary + # that we will pass to the translator full_deps = dict( dep_slice_orig.items() - + dep_slice_running.items() ) - - full_deps['path'] = path + + dep_slice_running.items() + + dep_slice_special.items()) # check if any dependencies are absent - if len(full_deps) < len(self.__deps) or len(self.__deps) == 0: + # note: there is no point checking the case that len(full_deps) > + # len(self.__deps) because we make sure to "slice out" any supefluous + # dependencies above. + if len(full_deps) != len(self.dependencies()) or \ + len(self.dependencies()) == 0: # If we have a default value then use that. Otherwise throw an # exception if self.has_default(): return self.get_default() else: raise MetadataAbsent(self.name) - # We have all dependencies. Now for actual for parsing + # We have all dependencies. Now for actual for parsing def def_translate(dep): def wrap(k): e = [ x for x in dep ][0] From 4bbc1fa95bf9afe8a47d2eaec2b68b88567d4c67 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Wed, 10 Oct 2012 14:41:39 -0400 Subject: [PATCH 059/157] Added comparison for emf and non emf metadata values. --- .../media-monitor2/media/monitor/metadata.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 6cce20e34..2b6c07a83 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -191,12 +191,6 @@ class Metadata(Loggable): # TODO : Simplify the way all of these rules are handled right now it's # extremely unclear and needs to be refactored. #if full_mutagen is None: raise BadSongFile(fpath) - try: # emf stuff for testing: - if full_mutagen: - normalized = global_reader.read('fpath', full_mutagen) - self.logger.info(pformat(normalized)) - except Exception as e: - self.unexpected_exception(e) if full_mutagen is None: full_mutagen = FakeMutagen(fpath) self.__metadata = Metadata.airtime_dict(full_mutagen) @@ -222,6 +216,17 @@ class Metadata(Loggable): # from the file? self.__metadata['MDATA_KEY_MD5'] = mmp.file_md5(fpath,max_length=100) + try: # emf stuff for testing: + if full_mutagen: + normalized = global_reader.read_mutagen(fpath) + self.logger.info("EMF--------------------") + self.logger.info(pformat(normalized)) + self.logger.info("OLD--------------------") + self.logger.info(pformat(self.__metadata)) + self.logger.info("-----------------------") + + except Exception as e: + self.unexpected_exception(e) def is_recorded(self): """ From a2792b01acd7e13720b7c4674543585f67f94db5 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Wed, 10 Oct 2012 14:42:07 -0400 Subject: [PATCH 060/157] Got rid of emf bug where a list of 0 elements might be accessed. --- python_apps/media-monitor2/media/metadata/process.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index d8be46bdf..51a3c732d 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -130,10 +130,11 @@ def normalize_mutagen(path): m = mutagen.File(path, easy=True) md = {} for k,v in m.iteritems(): - if type(v) is list: md[k] = v[0] + if type(v) is list: + if len(v) > 0: md[k] = v[0] else: md[k] = v # populate special metadata values - md['length'] = getattr(m.info, u'length', 0.0) + md['length'] = getattr(m.info, 'length', 0.0) md['bitrate'] = getattr(m.info, 'bitrate', u'') md['sample_rate'] = getattr(m.info, 'sample_rate', 0) md['mime'] = m.mime[0] if len(m.mime) > 0 else u'' From 445ec23b8e0efe4fcfdce0834ceaaaf8ddfad006 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Wed, 10 Oct 2012 14:42:22 -0400 Subject: [PATCH 061/157] Added utility method for reading mutagen info through emf. --- python_apps/media-monitor2/media/metadata/process.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index 51a3c732d..1b62646a4 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -167,6 +167,9 @@ class MetadataReader(object): if not mdata.is_optional(): raise return normalized_metadata + def read_mutagen(self, path): + return self.read(path, normalize_mutagen(path)) + global_reader = MetadataReader() @contextmanager From 4242ed38be7c5a002f5f2f5af93bb269da9a3b5d Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 11:14:53 -0400 Subject: [PATCH 062/157] Added more testing for emf --- python_apps/media-monitor2/tests/test_emf.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 python_apps/media-monitor2/tests/test_emf.py diff --git a/python_apps/media-monitor2/tests/test_emf.py b/python_apps/media-monitor2/tests/test_emf.py new file mode 100644 index 000000000..69fc566db --- /dev/null +++ b/python_apps/media-monitor2/tests/test_emf.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +import unittest + +from media.metadata.process import global_reader +import media.metadata.definitions as defs +defs.load_definitions() + +class TestMMP(unittest.TestCase): + def test_sanity(self): + m = global_reader.read_mutagen("/home/rudi/music/Nightingale.mp3") + self.assertTrue( len(m) > 0 ) From 09a8dfefc1d5f88ec4a4edfd50a458e1040ef6a4 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 13:55:03 -0400 Subject: [PATCH 063/157] Fixed metadata definitions in emf --- .../media-monitor2/media/metadata/definitions.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index f3399e24c..f0288bc61 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -30,7 +30,7 @@ def load_definitions(): t.depends('sample_rate') t.translate(lambda k: k['sample_rate']) - with md.metadata('MDATA_KEY_FTYPE'): + with md.metadata('MDATA_KEY_FTYPE') as t: t.depends('ftype') # i don't think this field even exists t.default(u'audioclip') t.translate(lambda k: k['ftype']) # but just in case @@ -92,9 +92,9 @@ def load_definitions(): t.depends("copyright") t.max_length(512) - with md.metadata("MDATA_KEY_FILEPATH") as t: + with md.metadata("MDATA_KEY_ORIGINAL_PATH") as t: t.depends('path') - t.translate(lambda k: normpath(k['path'])) + t.translate(lambda k: unicode(normpath(k['path']))) #with md.metadata("MDATA_KEY_MD5") as t: #t.depends('path') @@ -103,15 +103,13 @@ def load_definitions(): # owner is handled differently by (by events.py) - with md.metadata('MDATA_KEY_ORIGINAL_PATH') as t: - t.depends('original_path') - # MDATA_KEY_TITLE is the annoying special case b/c we sometimes read it # from file name with md.metadata('MDATA_KEY_TITLE') as t: # Need to know MDATA_KEY_CREATOR to know if show was recorded. Value is # defaulted to "" from definitions above t.depends('title','MDATA_KEY_CREATOR') + t.translate(lambda k: k['title']) t.max_length(512) with md.metadata('MDATA_KEY_LABEL') as t: From 027153b88224376fddfc2a665f067dc249309baa Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 13:56:54 -0400 Subject: [PATCH 064/157] Fixed emf handling of bad definitions --- python_apps/media-monitor2/media/metadata/process.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index 1b62646a4..ca24feeb0 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -74,6 +74,7 @@ class MetadataElement(Loggable): # If value is present and normalized then we only check if it's # normalized or not. We normalize if it's not normalized already + if self.name in original: v = original[self.name] if self.__is_normalized(v): return v @@ -141,11 +142,18 @@ def normalize_mutagen(path): md['path'] = path return md + +class OverwriteMetadataElement(Exception): + def __init__(self, m): self.m = m + def __str__(self): return "Trying to overwrite: %s" % self.m + class MetadataReader(object): def __init__(self): self.clear() def register_metadata(self,m): + if m in self.__mdata_name_map: + raise OverwriteMetadataElement(m) self.__mdata_name_map[m.name] = m d = dict( (name,m.dependencies()) for name,m in self.__mdata_name_map.iteritems() ) From 591d2d741f814ed63cc4d7ce89bebf73fb23ce17 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 13:57:37 -0400 Subject: [PATCH 065/157] Added original path element in metadata --- python_apps/media-monitor2/media/monitor/pure.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index 81b9cba49..1bb4231ae 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -312,6 +312,7 @@ def normalized_metadata(md, original_path): # TODO : wtf is this for again? new_md['MDATA_KEY_TITLE'] = re.sub(r'-?%s-?' % unicode_unknown, u'', new_md['MDATA_KEY_TITLE']) + new_md['MDATA_KEY_ORIGINAL_PATH'] = original_path return new_md def organized_path(old_path, root_path, orig_md): From 7db61cc4b4b1089f8de5746e8d63b360540cec78 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 13:58:05 -0400 Subject: [PATCH 066/157] fixed tests --- .../media-monitor2/media/monitor/metadata.py | 20 +++++++++---------- python_apps/media-monitor2/tests/test_emf.py | 14 ++++++++++++- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 2b6c07a83..30511c50d 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -216,17 +216,17 @@ class Metadata(Loggable): # from the file? self.__metadata['MDATA_KEY_MD5'] = mmp.file_md5(fpath,max_length=100) - try: # emf stuff for testing: - if full_mutagen: - normalized = global_reader.read_mutagen(fpath) - self.logger.info("EMF--------------------") - self.logger.info(pformat(normalized)) - self.logger.info("OLD--------------------") - self.logger.info(pformat(self.__metadata)) - self.logger.info("-----------------------") + #try: # emf stuff for testing: + #if full_mutagen: + #normalized = global_reader.read_mutagen(fpath) + #self.logger.info("EMF--------------------") + #self.logger.info(pformat(normalized)) + #self.logger.info("OLD--------------------") + #self.logger.info(pformat(self.__metadata)) + #self.logger.info("-----------------------") - except Exception as e: - self.unexpected_exception(e) + #except Exception as e: + #self.unexpected_exception(e) def is_recorded(self): """ diff --git a/python_apps/media-monitor2/tests/test_emf.py b/python_apps/media-monitor2/tests/test_emf.py index 69fc566db..355f93dd9 100644 --- a/python_apps/media-monitor2/tests/test_emf.py +++ b/python_apps/media-monitor2/tests/test_emf.py @@ -1,11 +1,23 @@ # -*- coding: utf-8 -*- import unittest +from pprint import pprint as pp from media.metadata.process import global_reader +from media.monitor.metadata import Metadata + import media.metadata.definitions as defs defs.load_definitions() class TestMMP(unittest.TestCase): def test_sanity(self): - m = global_reader.read_mutagen("/home/rudi/music/Nightingale.mp3") + path = "/home/rudi/music/Nightingale.mp3" + m = global_reader.read_mutagen(path) self.assertTrue( len(m) > 0 ) + n = Metadata(path) + self.assertEqual(n.extract(), m) + pp(n.extract()) + print("--------------") + pp(m) + + +if __name__ == '__main__': unittest.main() From 482e2475ca6d49ca042921b06698e7259b164f7b Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 14:24:33 -0400 Subject: [PATCH 067/157] cleaned up test --- python_apps/media-monitor2/media/metadata/definitions.py | 8 ++++---- python_apps/media-monitor2/tests/test_emf.py | 3 --- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index f0288bc61..97b3f6841 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -96,10 +96,10 @@ def load_definitions(): t.depends('path') t.translate(lambda k: unicode(normpath(k['path']))) - #with md.metadata("MDATA_KEY_MD5") as t: - #t.depends('path') - #t.optional(False) - #t.translate(lambda k: file_md5(k['path'], max_length=100)) + with md.metadata("MDATA_KEY_MD5") as t: + t.depends('path') + t.optional(False) + t.translate(lambda k: file_md5(k['path'], max_length=100)) # owner is handled differently by (by events.py) diff --git a/python_apps/media-monitor2/tests/test_emf.py b/python_apps/media-monitor2/tests/test_emf.py index 355f93dd9..b4f9ef03b 100644 --- a/python_apps/media-monitor2/tests/test_emf.py +++ b/python_apps/media-monitor2/tests/test_emf.py @@ -15,9 +15,6 @@ class TestMMP(unittest.TestCase): self.assertTrue( len(m) > 0 ) n = Metadata(path) self.assertEqual(n.extract(), m) - pp(n.extract()) - print("--------------") - pp(m) if __name__ == '__main__': unittest.main() From d00c74fdbe8f6779553f66ecbdb4c44279a52f36 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 14:32:56 -0400 Subject: [PATCH 068/157] Renamed test --- python_apps/media-monitor2/tests/test_emf.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/tests/test_emf.py b/python_apps/media-monitor2/tests/test_emf.py index b4f9ef03b..545c059fd 100644 --- a/python_apps/media-monitor2/tests/test_emf.py +++ b/python_apps/media-monitor2/tests/test_emf.py @@ -9,12 +9,11 @@ import media.metadata.definitions as defs defs.load_definitions() class TestMMP(unittest.TestCase): - def test_sanity(self): + def test_old_metadata(self): path = "/home/rudi/music/Nightingale.mp3" m = global_reader.read_mutagen(path) self.assertTrue( len(m) > 0 ) n = Metadata(path) self.assertEqual(n.extract(), m) - if __name__ == '__main__': unittest.main() From cefc5c99d93dd23fbdd3f0301e3573ea866db20e Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 15:39:35 -0400 Subject: [PATCH 069/157] Added special handling for title in emf --- .../media/metadata/definitions.py | 29 +++++++++++++++++-- .../media-monitor2/media/metadata/process.py | 1 + python_apps/media-monitor2/tests/test_emf.py | 6 ++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index 97b3f6841..a4f93848e 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -1,7 +1,9 @@ # -*- coding: utf-8 -*- import media.metadata.process as md +import re from os.path import normpath -from media.monitor.pure import format_length, file_md5 +from media.monitor.pure import format_length, file_md5, is_airtime_recorded, \ + no_extension_basename defs_loaded = False @@ -105,11 +107,32 @@ def load_definitions(): # MDATA_KEY_TITLE is the annoying special case b/c we sometimes read it # from file name + + + # must handle 3 cases: + # 1. regular case (not recorded + title is present) + # 2. title is absent (read from file) + # 3. recorded file + def tr_title(k): + unicode_unknown = u"unknown" + new_title = u"" + if is_airtime_recorded(k) or k['title'] != u"": + new_title = k['title'] + else: + default_title = no_extension_basename(k['path']) + default_title = re.sub(r'__\d+\.',u'.', default_title) + if re.match(".+-%s-.+$" % unicode_unknown, default_title): + default_title = u'' + new_title = default_title + new_title = re.sub(r'-\d+kbps$', u'', new_title) + return new_title + with md.metadata('MDATA_KEY_TITLE') as t: # Need to know MDATA_KEY_CREATOR to know if show was recorded. Value is # defaulted to "" from definitions above - t.depends('title','MDATA_KEY_CREATOR') - t.translate(lambda k: k['title']) + t.depends('title','MDATA_KEY_CREATOR','path') + t.optional(False) + t.translate(tr_title) t.max_length(512) with md.metadata('MDATA_KEY_LABEL') as t: diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index ca24feeb0..cde28cfaa 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -140,6 +140,7 @@ def normalize_mutagen(path): md['sample_rate'] = getattr(m.info, 'sample_rate', 0) md['mime'] = m.mime[0] if len(m.mime) > 0 else u'' md['path'] = path + if 'title' not in md: md['title'] = u'' return md diff --git a/python_apps/media-monitor2/tests/test_emf.py b/python_apps/media-monitor2/tests/test_emf.py index 545c059fd..3114e2f41 100644 --- a/python_apps/media-monitor2/tests/test_emf.py +++ b/python_apps/media-monitor2/tests/test_emf.py @@ -16,4 +16,10 @@ class TestMMP(unittest.TestCase): n = Metadata(path) self.assertEqual(n.extract(), m) + def test_recorded(self): + recorded_file = "./15:15:00-Untitled Show-256kbps.ogg" + m = global_reader.read_mutagen(recorded_file) + pp(m) + + if __name__ == '__main__': unittest.main() From ff8969efb997c7aefbbcd06593587ce7e3b03073 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 12 Oct 2012 15:54:38 -0400 Subject: [PATCH 070/157] Improved handling for paths and added tests for it --- .../media-monitor2/media/metadata/definitions.py | 3 ++- .../media-monitor2/media/metadata/process.py | 3 ++- python_apps/media-monitor2/media/monitor/pure.py | 2 +- python_apps/media-monitor2/tests/test_emf.py | 13 ++++++++++--- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index a4f93848e..ee4175033 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -20,7 +20,8 @@ def load_definitions(): with md.metadata('MDATA_KEY_MIME') as t: t.default(u'') t.depends('mime') - t.translate(lambda k: k['mime'].replace('-','/')) + # Is this necessary? + t.translate(lambda k: k['mime'].replace('audio/vorbis','audio/ogg')) with md.metadata('MDATA_KEY_BITRATE') as t: t.default(u'') diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index cde28cfaa..85a462919 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from contextlib import contextmanager from media.monitor.pure import truncate_to_length, toposort +from os.path import normpath from media.monitor.log import Loggable import mutagen @@ -139,7 +140,7 @@ def normalize_mutagen(path): md['bitrate'] = getattr(m.info, 'bitrate', u'') md['sample_rate'] = getattr(m.info, 'sample_rate', 0) md['mime'] = m.mime[0] if len(m.mime) > 0 else u'' - md['path'] = path + md['path'] = normpath(path) if 'title' not in md: md['title'] = u'' return md diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index 1bb4231ae..fd1c55a13 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -312,7 +312,7 @@ def normalized_metadata(md, original_path): # TODO : wtf is this for again? new_md['MDATA_KEY_TITLE'] = re.sub(r'-?%s-?' % unicode_unknown, u'', new_md['MDATA_KEY_TITLE']) - new_md['MDATA_KEY_ORIGINAL_PATH'] = original_path + new_md['MDATA_KEY_ORIGINAL_PATH'] = normpath(original_path) return new_md def organized_path(old_path, root_path, orig_md): diff --git a/python_apps/media-monitor2/tests/test_emf.py b/python_apps/media-monitor2/tests/test_emf.py index 3114e2f41..0213fa918 100644 --- a/python_apps/media-monitor2/tests/test_emf.py +++ b/python_apps/media-monitor2/tests/test_emf.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import unittest -from pprint import pprint as pp +#from pprint import pprint as pp from media.metadata.process import global_reader from media.monitor.metadata import Metadata @@ -9,6 +9,13 @@ import media.metadata.definitions as defs defs.load_definitions() class TestMMP(unittest.TestCase): + + def setUp(self): + self.maxDiff = None + + def metadatas(self,f): + return global_reader.read_mutagen(f), Metadata(f).extract() + def test_old_metadata(self): path = "/home/rudi/music/Nightingale.mp3" m = global_reader.read_mutagen(path) @@ -18,8 +25,8 @@ class TestMMP(unittest.TestCase): def test_recorded(self): recorded_file = "./15:15:00-Untitled Show-256kbps.ogg" - m = global_reader.read_mutagen(recorded_file) - pp(m) + emf, old = self.metadatas(recorded_file) + self.assertEqual(emf, old) if __name__ == '__main__': unittest.main() From 5a593112b38209dc44c3cd43629eb5c0bdcf132b Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 16 Oct 2012 12:20:08 -0400 Subject: [PATCH 071/157] Use emf instead of omf --- python_apps/media-monitor2/media/monitor/metadata.py | 4 +++- python_apps/media-monitor2/tests/test_emf.py | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 30511c50d..2bd059323 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -14,7 +14,6 @@ import media.monitor.pure as mmp # emf related stuff from media.metadata.process import global_reader import media.metadata.definitions as defs -from pprint import pformat defs.load_definitions() """ @@ -173,6 +172,9 @@ class Metadata(Loggable): for e in exceptions: raise e def __init__(self, fpath): + self.__metadata = global_reader.read_mutagen(fpath) + + def __init__2(self, fpath): # Forcing the unicode through try : fpath = fpath.decode("utf-8") except : pass diff --git a/python_apps/media-monitor2/tests/test_emf.py b/python_apps/media-monitor2/tests/test_emf.py index 0213fa918..140c0aa8b 100644 --- a/python_apps/media-monitor2/tests/test_emf.py +++ b/python_apps/media-monitor2/tests/test_emf.py @@ -28,5 +28,4 @@ class TestMMP(unittest.TestCase): emf, old = self.metadatas(recorded_file) self.assertEqual(emf, old) - if __name__ == '__main__': unittest.main() From 7255241e6cbe293445d5ca098c557efd1aff3b1b Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 16 Oct 2012 12:27:58 -0400 Subject: [PATCH 072/157] Removed old commented code --- python_apps/media-monitor2/media/monitor/metadata.py | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 2bd059323..199bd7420 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -218,18 +218,6 @@ class Metadata(Loggable): # from the file? self.__metadata['MDATA_KEY_MD5'] = mmp.file_md5(fpath,max_length=100) - #try: # emf stuff for testing: - #if full_mutagen: - #normalized = global_reader.read_mutagen(fpath) - #self.logger.info("EMF--------------------") - #self.logger.info(pformat(normalized)) - #self.logger.info("OLD--------------------") - #self.logger.info(pformat(self.__metadata)) - #self.logger.info("-----------------------") - - #except Exception as e: - #self.unexpected_exception(e) - def is_recorded(self): """ returns true if the file has been created by airtime through recording From 0638d2147365e394a342f7daed475f134ee0cd03 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 16 Oct 2012 14:48:16 -0400 Subject: [PATCH 073/157] Refactored code --- .../media-monitor2/media/metadata/process.py | 28 ++++++++++++++++++- .../media-monitor2/media/monitor/metadata.py | 5 ++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/media/metadata/process.py b/python_apps/media-monitor2/media/metadata/process.py index 85a462919..b500d029d 100644 --- a/python_apps/media-monitor2/media/metadata/process.py +++ b/python_apps/media-monitor2/media/metadata/process.py @@ -2,9 +2,28 @@ from contextlib import contextmanager from media.monitor.pure import truncate_to_length, toposort from os.path import normpath +from media.monitor.exceptions import BadSongFile from media.monitor.log import Loggable +import media.monitor.pure as mmp +from collections import namedtuple import mutagen +class FakeMutagen(dict): + """ + Need this fake mutagen object so that airtime_special functions + return a proper default value instead of throwing an exceptions for + files that mutagen doesn't recognize + """ + FakeInfo = namedtuple('FakeInfo','length bitrate') + def __init__(self,path): + self.path = path + self.mime = ['audio/wav'] + self.info = FakeMutagen.FakeInfo(0.0, '') + dict.__init__(self) + def set_length(self,l): + old_bitrate = self.info.bitrate + self.info = FakeMutagen.FakeInfo(l, old_bitrate) + class MetadataAbsent(Exception): def __init__(self, name): self.name = name @@ -129,7 +148,14 @@ def normalize_mutagen(path): Consumes a path and reads the metadata using mutagen. normalizes some of the metadata that isn't read through the mutagen hash """ - m = mutagen.File(path, easy=True) + if not mmp.file_playable(path): raise BadSongFile(path) + try : m = mutagen.File(path, easy=True) + except Exception : raise BadSongFile(path) + if m is None: m = FakeMutagen(path) + try: + if mmp.extension(path) == 'wav': + m.set_length(mmp.read_wave_duration(path)) + except Exception: raise BadSongFile(path) md = {} for k,v in m.iteritems(): if type(v) is list: diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 199bd7420..a496af61a 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -48,6 +48,8 @@ airtime2mutagen = { "MDATA_KEY_COPYRIGHT" : "copyright", } + +# TODO :Remove FakeMutagen class. Moved to media.metadata.process class FakeMutagen(dict): """ Need this fake mutagen object so that airtime_special functions @@ -172,6 +174,9 @@ class Metadata(Loggable): for e in exceptions: raise e def __init__(self, fpath): + # Forcing the unicode through + try : fpath = fpath.decode("utf-8") + except : pass self.__metadata = global_reader.read_mutagen(fpath) def __init__2(self, fpath): From 9a1948707c8ea2d0c0aa769ae0f5d048bff32032 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 16 Oct 2012 14:51:51 -0400 Subject: [PATCH 074/157] Removed duplicate code --- .../media-monitor2/media/monitor/metadata.py | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index a496af61a..30bab7419 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -49,23 +49,6 @@ airtime2mutagen = { } -# TODO :Remove FakeMutagen class. Moved to media.metadata.process -class FakeMutagen(dict): - """ - Need this fake mutagen object so that airtime_special functions - return a proper default value instead of throwing an exceptions for - files that mutagen doesn't recognize - """ - FakeInfo = namedtuple('FakeInfo','length bitrate') - def __init__(self,path): - self.path = path - self.mime = ['audio/wav'] - self.info = FakeMutagen.FakeInfo(0.0, '') - dict.__init__(self) - def set_length(self,l): - old_bitrate = self.info.bitrate - self.info = FakeMutagen.FakeInfo(l, old_bitrate) - # Some airtime attributes are special because they must use the mutagen object # itself to calculate the value that they need. The lambda associated with each # key should attempt to extract the corresponding value from the mutagen object From 6a8d902a61e9dacea8ccecef1bbe74eb46c5448d Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 16 Oct 2012 14:52:38 -0400 Subject: [PATCH 075/157] Removed omf --- .../media-monitor2/media/monitor/metadata.py | 45 ------------------- 1 file changed, 45 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 30bab7419..9754c1b0e 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -2,7 +2,6 @@ import mutagen import os import copy -from collections import namedtuple from mutagen.easymp4 import EasyMP4KeyError from mutagen.easyid3 import EasyID3KeyError @@ -162,50 +161,6 @@ class Metadata(Loggable): except : pass self.__metadata = global_reader.read_mutagen(fpath) - def __init__2(self, fpath): - # Forcing the unicode through - try : fpath = fpath.decode("utf-8") - except : pass - - if not mmp.file_playable(fpath): raise BadSongFile(fpath) - - try : full_mutagen = mutagen.File(fpath, easy=True) - except Exception : raise BadSongFile(fpath) - - self.path = fpath - if not os.path.exists(self.path): - self.logger.info("Attempting to read metadata of file \ - that does not exist. Setting metadata to {}") - self.__metadata = {} - return - # TODO : Simplify the way all of these rules are handled right now it's - # extremely unclear and needs to be refactored. - #if full_mutagen is None: raise BadSongFile(fpath) - - if full_mutagen is None: full_mutagen = FakeMutagen(fpath) - self.__metadata = Metadata.airtime_dict(full_mutagen) - # Now we extra the special values that are calculated from the mutagen - # object itself: - - if mmp.extension(fpath) == 'wav': - full_mutagen.set_length(mmp.read_wave_duration(fpath)) - - for special_key,f in airtime_special.iteritems(): - try: - new_val = f(full_mutagen) - if new_val is not None: - self.__metadata[special_key] = new_val - except Exception as e: - self.logger.info("Could not get special key %s for %s" % - (special_key, fpath)) - self.logger.info(str(e)) - # Finally, we "normalize" all the metadata here: - self.__metadata = mmp.normalized_metadata(self.__metadata, fpath) - # Now we must load the md5: - # TODO : perhaps we shouldn't hard code how many bytes we're reading - # from the file? - self.__metadata['MDATA_KEY_MD5'] = mmp.file_md5(fpath,max_length=100) - def is_recorded(self): """ returns true if the file has been created by airtime through recording From 66b5bf304f0c692d3d59955162c6ccc3152db6ed Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 16 Oct 2012 14:58:03 -0400 Subject: [PATCH 076/157] changed test strings --- python_apps/media-monitor2/tests/test_api_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/tests/test_api_client.py b/python_apps/media-monitor2/tests/test_api_client.py index 26f1a25ef..18595f860 100644 --- a/python_apps/media-monitor2/tests/test_api_client.py +++ b/python_apps/media-monitor2/tests/test_api_client.py @@ -19,8 +19,8 @@ class TestApiClient(unittest.TestCase): self.apc.register_component("api-client-tester") # All of the following requests should error out in some way self.bad_requests = [ - { 'mode' : 'dang it', 'is_record' : 0 }, - { 'mode' : 'damn frank', 'is_record' : 1 }, + { 'mode' : 'foo', 'is_record' : 0 }, + { 'mode' : 'bar', 'is_record' : 1 }, { 'no_mode' : 'at_all' }, ] def test_bad_requests(self): From dc361c11367f5bc5ab4f4d42107f9ce41a29124b Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 16 Oct 2012 14:59:06 -0400 Subject: [PATCH 077/157] Aligned constants --- airtime_mvc/application/configs/constants.php | 70 +++++++++---------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/airtime_mvc/application/configs/constants.php b/airtime_mvc/application/configs/constants.php index 1d1ed55e4..eb5cb3989 100644 --- a/airtime_mvc/application/configs/constants.php +++ b/airtime_mvc/application/configs/constants.php @@ -1,40 +1,40 @@ Date: Tue, 23 Oct 2012 12:06:30 -0400 Subject: [PATCH 078/157] Removed unused method --- .../media-monitor2/media/monitor/metadata.py | 36 ++----------------- 1 file changed, 2 insertions(+), 34 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 9754c1b0e..5bbbafaeb 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -7,7 +7,7 @@ from mutagen.easyid3 import EasyID3KeyError from media.monitor.exceptions import BadSongFile, InvalidMetadataElement from media.monitor.log import Loggable -from media.monitor.pure import format_length, truncate_to_length +from media.monitor.pure import format_length import media.monitor.pure as mmp # emf related stuff @@ -89,6 +89,7 @@ class Metadata(Loggable): # little bit messy. Some of the handling is in m.m.pure while the rest is # here. Also interface is not very consistent + # TODO : what is this shit? maybe get rid of it? @staticmethod def fix_title(path): # If we have no title in path we will format it @@ -99,39 +100,6 @@ class Metadata(Loggable): m[u'title'] = new_title m.save() - @staticmethod - def airtime_dict(d): - """ - Converts mutagen dictionary 'd' into airtime dictionary - """ - temp_dict = {} - for m_key, m_val in d.iteritems(): - # TODO : some files have multiple fields for the same metadata. - # genre is one example. In that case mutagen will return a list - # of values - - if isinstance(m_val, list): - # TODO : does it make more sense to just skip the element in - # this case? - if len(m_val) == 0: assign_val = '' - else: assign_val = m_val[0] - else: assign_val = m_val - - temp_dict[ m_key ] = assign_val - airtime_dictionary = {} - for muta_k, muta_v in temp_dict.iteritems(): - # We must check if we can actually translate the mutagen key into - # an airtime key before doing the conversion - if muta_k in mutagen2airtime: - airtime_key = mutagen2airtime[muta_k] - # Apply truncation in the case where airtime_key is in our - # truncation table - muta_v = \ - truncate_to_length(muta_v, truncate_table[airtime_key])\ - if airtime_key in truncate_table else muta_v - airtime_dictionary[ airtime_key ] = muta_v - return airtime_dictionary - @staticmethod def write_unsafe(path,md): """ From 54e6bec16af71eb9ba26832e2acd1144a20d1f59 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 23 Oct 2012 15:00:09 -0400 Subject: [PATCH 079/157] Reshuffled/removed some unit tests to get rid of omf --- .../media-monitor2/tests/test_metadata.py | 6 -- python_apps/media-monitor2/tests/test_pure.py | 70 ++----------------- 2 files changed, 7 insertions(+), 69 deletions(-) diff --git a/python_apps/media-monitor2/tests/test_metadata.py b/python_apps/media-monitor2/tests/test_metadata.py index 6f24240b0..4b05a9fce 100644 --- a/python_apps/media-monitor2/tests/test_metadata.py +++ b/python_apps/media-monitor2/tests/test_metadata.py @@ -42,10 +42,4 @@ class TestMetadata(unittest.TestCase): x1 = 123456 print("Formatting '%s' to '%s'" % (x1, mmm.format_length(x1))) - def test_truncate_to_length(self): - s1 = "testing with non string literal" - s2 = u"testing with unicode literal" - self.assertEqual( len(mmm.truncate_to_length(s1, 5)), 5) - self.assertEqual( len(mmm.truncate_to_length(s2, 8)), 8) - if __name__ == '__main__': unittest.main() diff --git a/python_apps/media-monitor2/tests/test_pure.py b/python_apps/media-monitor2/tests/test_pure.py index 64d09dc62..6bc5d4906 100644 --- a/python_apps/media-monitor2/tests/test_pure.py +++ b/python_apps/media-monitor2/tests/test_pure.py @@ -2,7 +2,6 @@ import unittest import os import media.monitor.pure as mmp -from media.monitor.metadata import Metadata class TestMMP(unittest.TestCase): def setUp(self): @@ -34,68 +33,6 @@ class TestMMP(unittest.TestCase): sd = mmp.default_to(dictionary=sd, keys=def_keys, default='DEF') for k in def_keys: self.assertEqual( sd[k], 'DEF' ) - def test_normalized_metadata(self): - #Recorded show test first - orig = Metadata.airtime_dict({ - 'date' : [u'2012-08-21'], - 'tracknumber' : [u'2'], - 'title' : [u'record-2012-08-21-11:29:00'], - 'artist' : [u'Airtime Show Recorder'] - }) - orga = Metadata.airtime_dict({ - 'date' : [u'2012-08-21'], - 'tracknumber' : [u'2'], - 'artist' : [u'Airtime Show Recorder'], - 'title' : [u'record-2012-08-21-11:29:00'] - }) - orga['MDATA_KEY_FTYPE'] = u'audioclip' - orig['MDATA_KEY_BITRATE'] = u'256000' - orga['MDATA_KEY_BITRATE'] = u'256000' - old_path = "/home/rudi/recorded/2012-08-21-11:29:00.ogg" - normalized = mmp.normalized_metadata(orig, old_path) - normalized['MDATA_KEY_BITRATE'] = u'256000' - - self.assertEqual( orga, normalized ) - - organized_base_name = "11:29:00-record-256kbps.ogg" - base = "/srv/airtime/stor/" - organized_path = mmp.organized_path(old_path,base, normalized) - self.assertEqual(os.path.basename(organized_path), organized_base_name) - - def test_normalized_metadata2(self): - """ - cc-4305 - """ - orig = Metadata.airtime_dict({ - 'date' : [u'2012-08-27'], - 'tracknumber' : [u'3'], - 'title' : [u'18-11-00-Untitled Show'], - 'artist' : [u'Airtime Show Recorder'] - }) - old_path = "/home/rudi/recorded/doesnt_really_matter.ogg" - normalized = mmp.normalized_metadata(orig, old_path) - normalized['MDATA_KEY_BITRATE'] = u'256000' - opath = mmp.organized_path(old_path, "/srv/airtime/stor/", - normalized) - # TODO : add a better test than this... - self.assertTrue( len(opath) > 0 ) - - def test_normalized_metadata3(self): - """ - Test the case where the metadata is empty - """ - orig = Metadata.airtime_dict({}) - paths_unknown_title = [ - ("/testin/unknown-unknown-unknown.mp3",""), - ("/testin/01-unknown-123kbps.mp3",""), - ("/testin/02-unknown-140kbps.mp3",""), - ("/testin/unknown-unknown-123kbps.mp3",""), - ("/testin/unknown-bibimbop-unknown.mp3","bibimbop"), - ] - for p,res in paths_unknown_title: - normalized = mmp.normalized_metadata(orig, p) - self.assertEqual( normalized['MDATA_KEY_TITLE'], res) - def test_file_md5(self): p = os.path.realpath(__file__) m1 = mmp.file_md5(p) @@ -116,6 +53,13 @@ class TestMMP(unittest.TestCase): self.assertEqual( mmp.parse_int("123asf"), "123" ) self.assertEqual( mmp.parse_int("asdf"), None ) + def test_truncate_to_length(self): + s1 = "testing with non string literal" + s2 = u"testing with unicode literal" + self.assertEqual( len(mmp.truncate_to_length(s1, 5)), 5) + self.assertEqual( len(mmp.truncate_to_length(s2, 8)), 8) + + def test_owner_id(self): start_path = "testing.mp3" id_path = "testing.mp3.identifier" From 1359bb402e2af565bc94a9c83a443c291ac02fc5 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 23 Oct 2012 15:03:37 -0400 Subject: [PATCH 080/157] Removed useless comment --- python_apps/media-monitor2/media/monitor/pure.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index fd1c55a13..fa14089d7 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -22,7 +22,6 @@ from configobj import ConfigObj from media.monitor.exceptions import FailedToSetLocale, FailedToCreateDir -#supported_extensions = [u"mp3", u"ogg", u"oga"] supported_extensions = [u"mp3", u"ogg", u"oga", u"flac", u"wav", u'm4a', u'mp4'] From 29c96d2efe9f29c799d5f38eb7224beeb7e500b3 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 23 Oct 2012 15:24:27 -0400 Subject: [PATCH 081/157] Removed md5 related test --- python_apps/media-monitor2/tests/test_metadata.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python_apps/media-monitor2/tests/test_metadata.py b/python_apps/media-monitor2/tests/test_metadata.py index 4b05a9fce..7a32b61a8 100644 --- a/python_apps/media-monitor2/tests/test_metadata.py +++ b/python_apps/media-monitor2/tests/test_metadata.py @@ -26,7 +26,6 @@ class TestMetadata(unittest.TestCase): i += 1 print("Sample metadata: '%s'" % md) self.assertTrue( len( md.keys() ) > 0 ) - self.assertTrue( 'MDATA_KEY_MD5' in md ) utf8 = md_full.utf8() for k,v in md.iteritems(): if hasattr(utf8[k], 'decode'): From 9169893e4d0deaebb19d5790d068367dcb4a683a Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 23 Oct 2012 16:44:11 -0400 Subject: [PATCH 082/157] Alignment of method definitions --- python_apps/media-monitor2/media/monitor/syncdb.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/syncdb.py b/python_apps/media-monitor2/media/monitor/syncdb.py index 0c14fb038..cc8abc294 100644 --- a/python_apps/media-monitor2/media/monitor/syncdb.py +++ b/python_apps/media-monitor2/media/monitor/syncdb.py @@ -53,11 +53,11 @@ class AirtimeDB(Loggable): """ return self.id_to_dir[ dir_id ] - def storage_path(self): return self.base_storage - def organize_path(self): return self.storage_paths['organize'] - def problem_path(self): return self.storage_paths['problem_files'] - def import_path(self): return self.storage_paths['imported'] - def recorded_path(self): return self.storage_paths['recorded'] + def storage_path(self) : return self.base_storage + def organize_path(self) : return self.storage_paths['organize'] + def problem_path(self) : return self.storage_paths['problem_files'] + def import_path(self) : return self.storage_paths['imported'] + def recorded_path(self) : return self.storage_paths['recorded'] def list_watched(self): """ From f718070d3cda1165f338888216ec76617e06364a Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Tue, 23 Oct 2012 17:00:22 -0400 Subject: [PATCH 083/157] Uncoupled the api_client instance from the RequestSync object --- .../media-monitor2/media/monitor/watchersyncer.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/watchersyncer.py b/python_apps/media-monitor2/media/monitor/watchersyncer.py index e7a2cf9c0..191a0f8a1 100644 --- a/python_apps/media-monitor2/media/monitor/watchersyncer.py +++ b/python_apps/media-monitor2/media/monitor/watchersyncer.py @@ -18,10 +18,18 @@ class RequestSync(threading.Thread,Loggable): to airtime. In the process it packs the requests and retries for some number of times """ - def __init__(self, watcher, requests): + + @classmethod + def create_with_api_client(cls, watcher, requests): + apiclient = ac.AirtimeApiClient.create_right_config() + self = cls(watcher, requests, apiclient) + return self + + def __init__(self, watcher, requests, apiclient): threading.Thread.__init__(self) self.watcher = watcher self.requests = requests + self.apiclient = apiclient self.retries = 1 self.request_wait = 0.3 @@ -209,7 +217,8 @@ class WatchSyncer(ReportHandler,Loggable): requests = copy.copy(self.__queue) def launch_request(): # Need shallow copy here - t = RequestSync(watcher=self, requests=requests) + t = RequestSync.create_with_api_client(watcher=self, + requests=requests) t.start() self.__current_thread = t self.__requests.append(launch_request) From 86b262ed8f89b0fd0b07b4140a1803457bdecc5c Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 11:08:21 -0400 Subject: [PATCH 084/157] uncoupled threading from making a request --- .../media/monitor/watchersyncer.py | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/watchersyncer.py b/python_apps/media-monitor2/media/monitor/watchersyncer.py index 191a0f8a1..6ed9ba594 100644 --- a/python_apps/media-monitor2/media/monitor/watchersyncer.py +++ b/python_apps/media-monitor2/media/monitor/watchersyncer.py @@ -6,13 +6,23 @@ import copy from media.monitor.handler import ReportHandler from media.monitor.log import Loggable from media.monitor.exceptions import BadSongFile -from media.monitor.pure import LazyProperty from media.monitor.eventcontractor import EventContractor from media.monitor.events import EventProxy import api_clients.api_client as ac -class RequestSync(threading.Thread,Loggable): + +class ThreadedRequestSync(threading.Thread, Loggable): + def __init__(self, rs): + threading.Thread.__init__(self) + self.rs = rs + self.daemon = True + self.start() + + def run(self): + self.rs.run_request() + +class RequestSync(Loggable): """ This class is responsible for making the api call to send a request to airtime. In the process it packs the requests and retries for @@ -26,18 +36,13 @@ class RequestSync(threading.Thread,Loggable): return self def __init__(self, watcher, requests, apiclient): - threading.Thread.__init__(self) self.watcher = watcher self.requests = requests self.apiclient = apiclient self.retries = 1 self.request_wait = 0.3 - @LazyProperty - def apiclient(self): - return ac.AirtimeApiClient.create_right_config() - - def run(self): + def run_request(self): self.logger.info("Attempting request with %d items." % len(self.requests)) # Note that we must attach the appropriate mode to every @@ -59,6 +64,8 @@ class RequestSync(threading.Thread,Loggable): request_event.path) def make_req(): self.apiclient.send_media_monitor_requests( packed_requests ) + # TODO : none of the shit below is necessary. get rid of it + # eventually for try_index in range(0,self.retries): try: make_req() # most likely we did not get json response as we expected @@ -76,7 +83,7 @@ class RequestSync(threading.Thread,Loggable): break else: self.logger.info("Failed to send request after '%d' tries..." % self.retries) - self.watcher.flag_done() + self.watcher.flag_done() # poor man's condition variable class TimeoutWatcher(threading.Thread,Loggable): """ @@ -217,9 +224,8 @@ class WatchSyncer(ReportHandler,Loggable): requests = copy.copy(self.__queue) def launch_request(): # Need shallow copy here - t = RequestSync.create_with_api_client(watcher=self, - requests=requests) - t.start() + t = ThreadedRequestSync( RequestSync.create_with_api_client( + watcher=self, requests=requests) ) self.__current_thread = t self.__requests.append(launch_request) self.__reset_queue() From 289d5575ece18521d4a21747a1634860a0d5e03e Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 11:18:41 -0400 Subject: [PATCH 085/157] Cleaned the shit out of RequestSync. Removed old comments and useless code --- .../media/monitor/watchersyncer.py | 40 +++++-------------- 1 file changed, 11 insertions(+), 29 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/watchersyncer.py b/python_apps/media-monitor2/media/monitor/watchersyncer.py index 6ed9ba594..6ab6509bf 100644 --- a/python_apps/media-monitor2/media/monitor/watchersyncer.py +++ b/python_apps/media-monitor2/media/monitor/watchersyncer.py @@ -28,7 +28,6 @@ class RequestSync(Loggable): to airtime. In the process it packs the requests and retries for some number of times """ - @classmethod def create_with_api_client(cls, watcher, requests): apiclient = ac.AirtimeApiClient.create_right_config() @@ -39,17 +38,10 @@ class RequestSync(Loggable): self.watcher = watcher self.requests = requests self.apiclient = apiclient - self.retries = 1 - self.request_wait = 0.3 def run_request(self): self.logger.info("Attempting request with %d items." % len(self.requests)) - # Note that we must attach the appropriate mode to every - # response. Also Not forget to attach the 'is_record' to any - # requests that are related to recorded shows - # TODO : recorded shows aren't flagged right - # Is this retry shit even necessary? Consider getting rid of this. packed_requests = [] for request_event in self.requests: try: @@ -62,27 +54,17 @@ class RequestSync(Loggable): if hasattr(request_event, 'path'): self.logger.info("Possibly related to path: '%s'" % request_event.path) - def make_req(): - self.apiclient.send_media_monitor_requests( packed_requests ) - # TODO : none of the shit below is necessary. get rid of it - # eventually - for try_index in range(0,self.retries): - try: make_req() - # most likely we did not get json response as we expected - except ValueError: - self.logger.info("ApiController.php probably crashed, we \ - diagnose this from the fact that it did not return \ - valid json") - self.logger.info("Trying again after %f seconds" % - self.request_wait) - time.sleep( self.request_wait ) - except Exception as e: self.unexpected_exception(e) - else: - self.logger.info("Request worked on the '%d' try" % - (try_index + 1)) - break - else: self.logger.info("Failed to send request after '%d' tries..." % - self.retries) + try: self.apiclient.send_media_monitor_requests( packed_requests ) + # most likely we did not get json response as we expected + except ValueError: + self.logger.info("ApiController.php probably crashed, we \ + diagnose this from the fact that it did not return \ + valid json") + self.logger.info("Trying again after %f seconds" % + self.request_wait) + except Exception as e: self.unexpected_exception(e) + else: + self.logger.info("Request was successful") self.watcher.flag_done() # poor man's condition variable class TimeoutWatcher(threading.Thread,Loggable): From a6ab91333f278375286e3be0bb635565b781970e Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 11:24:23 -0400 Subject: [PATCH 086/157] formatting --- python_apps/media-monitor2/media/monitor/watchersyncer.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/watchersyncer.py b/python_apps/media-monitor2/media/monitor/watchersyncer.py index 6ab6509bf..d7567a535 100644 --- a/python_apps/media-monitor2/media/monitor/watchersyncer.py +++ b/python_apps/media-monitor2/media/monitor/watchersyncer.py @@ -63,8 +63,7 @@ class RequestSync(Loggable): self.logger.info("Trying again after %f seconds" % self.request_wait) except Exception as e: self.unexpected_exception(e) - else: - self.logger.info("Request was successful") + else: self.logger.info("Request was successful") self.watcher.flag_done() # poor man's condition variable class TimeoutWatcher(threading.Thread,Loggable): From 38cbd7d7e42ac7020954e9b36223a4c4cc4b11bd Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 11:52:47 -0400 Subject: [PATCH 087/157] added emf unit tests --- .../media-monitor2/tests/test_metadata_def.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 python_apps/media-monitor2/tests/test_metadata_def.py diff --git a/python_apps/media-monitor2/tests/test_metadata_def.py b/python_apps/media-monitor2/tests/test_metadata_def.py new file mode 100644 index 000000000..e666ef68a --- /dev/null +++ b/python_apps/media-monitor2/tests/test_metadata_def.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +import unittest + +import media.metadata.process as md + +class TestMetadataDef(unittest.TestCase): + def test_simple(self): + + with md.metadata('MDATA_TESTING') as t: + t.optional(True) + t.depends('ONE','TWO') + t.default('unknown') + t.translate(lambda kw: kw['ONE'] + kw['TWO']) + + h = { 'ONE' : "testing", 'TWO' : "123" } + result = md.global_reader.read('test_path',h) + self.assertTrue( 'MDATA_TESTING' in result ) + self.assertEqual( result['MDATA_TESTING'], 'testing123' ) + h1 = { 'ONE' : 'big testing', 'two' : 'nothing' } + result1 = md.global_reader.read('bs path', h1) + self.assertEqual( result1['MDATA_TESTING'], 'unknown' ) + + def test_topo(self): + with md.metadata('MDATA_TESTING') as t: + t.depends('shen','sheni') + t.default('megitzda') + t.translate(lambda kw: kw['shen'] + kw['sheni']) + + with md.metadata('shen') as t: + t.default('vaxo') + + with md.metadata('sheni') as t: + t.default('gio') + + with md.metadata('vaxo') as t: + t.depends('shevetsi') + + v = md.global_reader.read('bs mang', {}) + self.assertEqual(v['MDATA_TESTING'], 'vaxogio') + self.assertTrue( 'vaxo' not in v ) + + md.global_reader.clear() + +if __name__ == '__main__': unittest.main() From 0422127689ef4a073090d766aae66fefea04a434 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 12:54:28 -0400 Subject: [PATCH 088/157] Added unit tests for requestsync --- .../media-monitor2/tests/test_requestsync.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 python_apps/media-monitor2/tests/test_requestsync.py diff --git a/python_apps/media-monitor2/tests/test_requestsync.py b/python_apps/media-monitor2/tests/test_requestsync.py new file mode 100644 index 000000000..a26b86b46 --- /dev/null +++ b/python_apps/media-monitor2/tests/test_requestsync.py @@ -0,0 +1,48 @@ +import unittest +from mock import MagicMock + +from media.monitor.watchersyncer import RequestSync + +class TestRequestSync(unittest.TestCase): + + def apc_mock(self): + fake_apc = MagicMock() + fake_apc.send_media_monitor_requests = MagicMock() + return fake_apc + + def watcher_mock(self): + fake_watcher = MagicMock() + fake_watcher.flag_done = MagicMock() + return fake_watcher + + def request_mock(self): + fake_request = MagicMock() + fake_request.safe_pack = MagicMock(return_value=[]) + return fake_request + + def test_send_media_monitor(self): + fake_apc = self.apc_mock() + fake_requests = [ self.request_mock() for x in range(1,5) ] + fake_watcher = self.watcher_mock() + rs = RequestSync(fake_watcher, fake_requests, fake_apc) + rs.run_request() + self.assertEquals(fake_apc.send_media_monitor_requests.call_count, 1) + + def test_flag_done(self): + fake_apc = self.apc_mock() + fake_requests = [ self.request_mock() for x in range(1,5) ] + fake_watcher = self.watcher_mock() + rs = RequestSync(fake_watcher, fake_requests, fake_apc) + rs.run_request() + self.assertEquals(fake_watcher.flag_done.call_count, 1) + + def test_safe_pack(self): + fake_apc = self.apc_mock() + fake_requests = [ self.request_mock() for x in range(1,5) ] + fake_watcher = self.watcher_mock() + rs = RequestSync(fake_watcher, fake_requests, fake_apc) + rs.run_request() + for req in fake_requests: + self.assertEquals(req.safe_pack.call_count, 1) + +if __name__ == '__main__': unittest.main() From 212e3bd30e614de05adbaa7d6f1b0ce69a8490a0 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:07:51 -0400 Subject: [PATCH 089/157] created a module for requests (refactorings) --- .../media-monitor2/media/monitor/request.py | 62 +++++++++++++++++++ .../media/monitor/watchersyncer.py | 58 +---------------- .../media-monitor2/tests/test_requestsync.py | 2 +- 3 files changed, 64 insertions(+), 58 deletions(-) create mode 100644 python_apps/media-monitor2/media/monitor/request.py diff --git a/python_apps/media-monitor2/media/monitor/request.py b/python_apps/media-monitor2/media/monitor/request.py new file mode 100644 index 000000000..934290a05 --- /dev/null +++ b/python_apps/media-monitor2/media/monitor/request.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- + +import threading + +from media.monitor.exceptions import BadSongFile +from media.monitor.log import Loggable +import api_clients.api_client as ac + +class ThreadedRequestSync(threading.Thread, Loggable): + def __init__(self, rs): + threading.Thread.__init__(self) + self.rs = rs + self.daemon = True + self.start() + + def run(self): + self.rs.run_request() + +class RequestSync(Loggable): + """ + This class is responsible for making the api call to send a request + to airtime. In the process it packs the requests and retries for + some number of times + """ + @classmethod + def create_with_api_client(cls, watcher, requests): + apiclient = ac.AirtimeApiClient.create_right_config() + self = cls(watcher, requests, apiclient) + return self + + def __init__(self, watcher, requests, apiclient): + self.watcher = watcher + self.requests = requests + self.apiclient = apiclient + + def run_request(self): + self.logger.info("Attempting request with %d items." % + len(self.requests)) + packed_requests = [] + for request_event in self.requests: + try: + for request in request_event.safe_pack(): + if isinstance(request, BadSongFile): + self.logger.info("Bad song file: '%s'" % request.path) + else: packed_requests.append(request) + except Exception as e: + self.unexpected_exception( e ) + if hasattr(request_event, 'path'): + self.logger.info("Possibly related to path: '%s'" % + request_event.path) + try: self.apiclient.send_media_monitor_requests( packed_requests ) + # most likely we did not get json response as we expected + except ValueError: + self.logger.info("ApiController.php probably crashed, we \ + diagnose this from the fact that it did not return \ + valid json") + self.logger.info("Trying again after %f seconds" % + self.request_wait) + except Exception as e: self.unexpected_exception(e) + else: self.logger.info("Request was successful") + self.watcher.flag_done() # poor man's condition variable + diff --git a/python_apps/media-monitor2/media/monitor/watchersyncer.py b/python_apps/media-monitor2/media/monitor/watchersyncer.py index d7567a535..9f83c6526 100644 --- a/python_apps/media-monitor2/media/monitor/watchersyncer.py +++ b/python_apps/media-monitor2/media/monitor/watchersyncer.py @@ -8,63 +8,7 @@ from media.monitor.log import Loggable from media.monitor.exceptions import BadSongFile from media.monitor.eventcontractor import EventContractor from media.monitor.events import EventProxy - -import api_clients.api_client as ac - - -class ThreadedRequestSync(threading.Thread, Loggable): - def __init__(self, rs): - threading.Thread.__init__(self) - self.rs = rs - self.daemon = True - self.start() - - def run(self): - self.rs.run_request() - -class RequestSync(Loggable): - """ - This class is responsible for making the api call to send a request - to airtime. In the process it packs the requests and retries for - some number of times - """ - @classmethod - def create_with_api_client(cls, watcher, requests): - apiclient = ac.AirtimeApiClient.create_right_config() - self = cls(watcher, requests, apiclient) - return self - - def __init__(self, watcher, requests, apiclient): - self.watcher = watcher - self.requests = requests - self.apiclient = apiclient - - def run_request(self): - self.logger.info("Attempting request with %d items." % - len(self.requests)) - packed_requests = [] - for request_event in self.requests: - try: - for request in request_event.safe_pack(): - if isinstance(request, BadSongFile): - self.logger.info("Bad song file: '%s'" % request.path) - else: packed_requests.append(request) - except Exception as e: - self.unexpected_exception( e ) - if hasattr(request_event, 'path'): - self.logger.info("Possibly related to path: '%s'" % - request_event.path) - try: self.apiclient.send_media_monitor_requests( packed_requests ) - # most likely we did not get json response as we expected - except ValueError: - self.logger.info("ApiController.php probably crashed, we \ - diagnose this from the fact that it did not return \ - valid json") - self.logger.info("Trying again after %f seconds" % - self.request_wait) - except Exception as e: self.unexpected_exception(e) - else: self.logger.info("Request was successful") - self.watcher.flag_done() # poor man's condition variable +from media.monitor.request import ThreadedRequestSync, RequestSync class TimeoutWatcher(threading.Thread,Loggable): """ diff --git a/python_apps/media-monitor2/tests/test_requestsync.py b/python_apps/media-monitor2/tests/test_requestsync.py index a26b86b46..2570bc34e 100644 --- a/python_apps/media-monitor2/tests/test_requestsync.py +++ b/python_apps/media-monitor2/tests/test_requestsync.py @@ -1,7 +1,7 @@ import unittest from mock import MagicMock -from media.monitor.watchersyncer import RequestSync +from media.monitor.request import RequestSync class TestRequestSync(unittest.TestCase): From fb28c3a6c5c7dc9ad3780d12f219f449c3756cc2 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:32:27 -0400 Subject: [PATCH 090/157] Formatting --- python_apps/media-monitor2/media/monitor/watchersyncer.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/watchersyncer.py b/python_apps/media-monitor2/media/monitor/watchersyncer.py index 9f83c6526..b008b10d0 100644 --- a/python_apps/media-monitor2/media/monitor/watchersyncer.py +++ b/python_apps/media-monitor2/media/monitor/watchersyncer.py @@ -71,8 +71,7 @@ class WatchSyncer(ReportHandler,Loggable): #self.push_queue( event ) except BadSongFile as e: self.fatal_exception("Received bas song file '%s'" % e.path, e) - except Exception as e: - self.unexpected_exception(e) + except Exception as e: self.unexpected_exception(e) else: self.logger.info("Received event that does not implement packing.\ Printing its representation:") From a42210e321f6a3e563ee655d8e6197756c620f38 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:38:11 -0400 Subject: [PATCH 091/157] added comment for destructor --- python_apps/media-monitor2/media/monitor/watchersyncer.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/media/monitor/watchersyncer.py b/python_apps/media-monitor2/media/monitor/watchersyncer.py index b008b10d0..d2df9ed3a 100644 --- a/python_apps/media-monitor2/media/monitor/watchersyncer.py +++ b/python_apps/media-monitor2/media/monitor/watchersyncer.py @@ -157,7 +157,8 @@ class WatchSyncer(ReportHandler,Loggable): def __reset_queue(self): self.__queue = [] def __del__(self): - # Ideally we would like to do a little more to ensure safe shutdown + #this destructor is completely untested and it's unclear whether + #it's even doing anything useful. consider removing it if self.events_in_queue(): self.logger.warn("Terminating with events still in the queue...") if self.requests_in_queue(): From a0f83c4db0600d99890fcf0b81f6d437aec02817 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:40:13 -0400 Subject: [PATCH 092/157] removed big unused method --- .../media-monitor2/media/monitor/pure.py | 48 ------------------- 1 file changed, 48 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index fa14089d7..462daf07a 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -265,54 +265,6 @@ def parse_int(s): try : return str(reduce(op.add, takewhile(lambda x: x.isdigit(), s))) except: return None -def normalized_metadata(md, original_path): - """ - consumes a dictionary of metadata and returns a new dictionary with the - formatted meta data. We also consume original_path because we must set - MDATA_KEY_CREATOR based on in it sometimes - """ - new_md = copy.deepcopy(md) - # replace all slashes with dashes - #for k,v in new_md.iteritems(): new_md[k] = unicode(v).replace('/','-') - # Specific rules that are applied in a per attribute basis - format_rules = { - 'MDATA_KEY_TRACKNUMBER' : parse_int, - 'MDATA_KEY_FILEPATH' : lambda x: os.path.normpath(x), - 'MDATA_KEY_BPM' : lambda x: x[0:8], - 'MDATA_KEY_MIME' : lambda x: x.replace('audio/vorbis','audio/ogg'), - # Whenever 0 is reported we change it to empty - #'MDATA_KEY_BITRATE' : lambda x: '' if str(x) == '0' else x - } - - new_md = remove_whitespace(new_md) # remove whitespace fields - # Format all the fields in format_rules - new_md = apply_rules_dict(new_md, format_rules) - # set filetype to audioclip by default - new_md = default_to(dictionary=new_md, keys=['MDATA_KEY_FTYPE'], - default=u'audioclip') - - # Try to parse bpm but delete the whole key if that fails - if 'MDATA_KEY_BPM' in new_md: - new_md['MDATA_KEY_BPM'] = parse_int(new_md['MDATA_KEY_BPM']) - if new_md['MDATA_KEY_BPM'] is None: - del new_md['MDATA_KEY_BPM'] - - if not is_airtime_recorded(new_md): - # Read title from filename if it does not exist - default_title = no_extension_basename(original_path) - default_title = re.sub(r'__\d+\.',u'.', default_title) - if re.match(".+-%s-.+$" % unicode_unknown, default_title): - default_title = u'' - new_md = default_to(dictionary=new_md, keys=['MDATA_KEY_TITLE'], - default=default_title) - new_md['MDATA_KEY_TITLE'] = re.sub(r'-\d+kbps$', u'', - new_md['MDATA_KEY_TITLE']) - - # TODO : wtf is this for again? - new_md['MDATA_KEY_TITLE'] = re.sub(r'-?%s-?' % unicode_unknown, u'', - new_md['MDATA_KEY_TITLE']) - new_md['MDATA_KEY_ORIGINAL_PATH'] = normpath(original_path) - return new_md def organized_path(old_path, root_path, orig_md): """ From 958b489fca148833214a4e698b434bfba191ebc0 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:43:15 -0400 Subject: [PATCH 093/157] formatted comments and removed unused function --- .../media-monitor2/media/monitor/pure.py | 31 +++---------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index 462daf07a..1c747fdf0 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -66,24 +66,6 @@ class IncludeOnly(object): return func(moi, event, *args, **kwargs) return _wrap - - -def diff_dict(d1, d2, width=30): - """ - returns a formatted diff of 2 dictionaries - """ - out = "" - all_keys = d1.keys() + d2.keys() - for k in all_keys: - v1, v2 = d1.get(k), d2.get(k) - - # default values - if v1 is None: v1 = "N/A" - if v2 is None: v2 = "N/A" - - if d1[k] != d2[k]: - out += "%s%s%s" % (k, d1[k], d2[k]) - def partition(f, alist): """ Partition is very similar to filter except that it also returns the @@ -452,9 +434,8 @@ def owner_id(original_path): return owner_id def file_playable(pathname): - """ - Returns True if 'pathname' is playable by liquidsoap. False otherwise. - """ + """ Returns True if 'pathname' is playable by liquidsoap. False + otherwise. """ # when there is an single apostrophe inside of a string quoted by # apostrophes, we can only escape it by replace that apostrophe with # '\''. This breaks the string into two, and inserts an escaped @@ -490,18 +471,14 @@ def toposort(data): assert not data, "A cyclic dependency exists amongst %r" % data def truncate_to_length(item, length): - """ - Truncates 'item' to 'length' - """ + """ Truncates 'item' to 'length' """ if isinstance(item, int): item = str(item) if isinstance(item, basestring): if len(item) > length: return item[0:length] else: return item def format_length(mutagen_length): - """ - Convert mutagen length to airtime length - """ + """ Convert mutagen length to airtime length """ t = float(mutagen_length) h = int(math.floor(t / 3600)) t = t % 3600 From 5ed86e26665b8f090b22c89f7559ce1704f01147 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:44:51 -0400 Subject: [PATCH 094/157] added docstring for wave duration --- python_apps/media-monitor2/media/monitor/pure.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index 1c747fdf0..1d8abf8f3 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -91,14 +91,13 @@ def is_file_supported(path): # TODO : In the future we would like a better way to find out whether a show # has been recorded def is_airtime_recorded(md): - """ - Takes a metadata dictionary and returns True if it belongs to a file that - was recorded by Airtime. - """ + """ Takes a metadata dictionary and returns True if it belongs to a + file that was recorded by Airtime. """ if not 'MDATA_KEY_CREATOR' in md: return False return md['MDATA_KEY_CREATOR'] == u'Airtime Show Recorder' def read_wave_duration(path): + """ Read the length of .wav file (mutagen does not handle this) """ with contextlib.closing(wave.open(path,'r')) as f: frames = f.getnframes() rate = f.getframerate() @@ -106,9 +105,7 @@ def read_wave_duration(path): return duration def clean_empty_dirs(path): - """ - walks path and deletes every empty directory it finds - """ + """ walks path and deletes every empty directory it finds """ # TODO : test this function if path.endswith('/'): clean_empty_dirs(path[0:-1]) else: From cccbfa2c3465df9b45d260a0863af6be1723e04b Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:47:23 -0400 Subject: [PATCH 095/157] Formatted docstrings --- .../media-monitor2/media/monitor/pure.py | 66 +++++++------------ 1 file changed, 24 insertions(+), 42 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index 1d8abf8f3..ad8ce336b 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -150,11 +150,10 @@ def no_extension_basename(path): else: return '.'.join(base.split(".")[0:-1]) def walk_supported(directory, clean_empties=False): - """ - A small generator wrapper around os.walk to only give us files that support - the extensions we are considering. When clean_empties is True we - recursively delete empty directories left over in directory after the walk. - """ + """ A small generator wrapper around os.walk to only give us files + that support the extensions we are considering. When clean_empties + is True we recursively delete empty directories left over in + directory after the walk. """ for root, dirs, files in os.walk(directory): full_paths = ( os.path.join(root, name) for name in files if is_file_supported(name) ) @@ -168,10 +167,8 @@ def file_locked(path): return bool(f.readlines()) def magic_move(old, new, after_dir_make=lambda : None): - """ - Moves path old to new and constructs the necessary to directories for new - along the way - """ + """ Moves path old to new and constructs the necessary to + directories for new along the way """ new_dir = os.path.dirname(new) if not os.path.exists(new_dir): os.makedirs(new_dir) # We need this crusty hack because anytime a directory is created we must @@ -181,18 +178,15 @@ def magic_move(old, new, after_dir_make=lambda : None): shutil.move(old,new) def move_to_dir(dir_path,file_path): - """ - moves a file at file_path into dir_path/basename(filename) - """ + """ moves a file at file_path into dir_path/basename(filename) """ bs = os.path.basename(file_path) magic_move(file_path, os.path.join(dir_path, bs)) def apply_rules_dict(d, rules): - """ - Consumes a dictionary of rules that maps some keys to lambdas which it - applies to every matching element in d and returns a new dictionary with - the rules applied. If a rule returns none then it's not applied - """ + """ Consumes a dictionary of rules that maps some keys to lambdas + which it applies to every matching element in d and returns a new + dictionary with the rules applied. If a rule returns none then it's + not applied """ new_d = copy.deepcopy(d) for k, rule in rules.iteritems(): if k in d: @@ -207,17 +201,14 @@ def default_to_f(dictionary, keys, default, condition): return new_d def default_to(dictionary, keys, default): - """ - Checks if the list of keys 'keys' exists in 'dictionary'. If not then it - returns a new dictionary with all those missing keys defaults to 'default' - """ + """ Checks if the list of keys 'keys' exists in 'dictionary'. If + not then it returns a new dictionary with all those missing keys + defaults to 'default' """ cnd = lambda dictionary, key: key not in dictionary return default_to_f(dictionary, keys, default, cnd) def remove_whitespace(dictionary): - """ - Remove values that empty whitespace in the dictionary - """ + """ Remove values that empty whitespace in the dictionary """ nd = copy.deepcopy(dictionary) bad_keys = [] for k,v in nd.iteritems(): @@ -303,10 +294,9 @@ def organized_path(old_path, root_path, orig_md): # TODO : Get rid of this function and every one of its uses. We no longer use # the md5 signature of a song for anything def file_md5(path,max_length=100): - """ - Get md5 of file path (if it exists). Use only max_length characters to save - time and memory. Pass max_length=-1 to read the whole file (like in mm1) - """ + """ Get md5 of file path (if it exists). Use only max_length + characters to save time and memory. Pass max_length=-1 to read the + whole file (like in mm1) """ if os.path.exists(path): with open(path, 'rb') as f: m = hashlib.md5() @@ -322,16 +312,12 @@ def encode_to(obj, encoding='utf-8'): return obj def convert_dict_value_to_utf8(md): - """ - formats a dictionary to send as a request to api client - """ + """ formats a dictionary to send as a request to api client """ return dict([(item[0], encode_to(item[1], "utf-8")) for item in md.items()]) def get_system_locale(locale_path='/etc/default/locale'): - """ - Returns the configuration object for the system's default locale. Normally - requires root access. - """ + """ Returns the configuration object for the system's default + locale. Normally requires root access. """ if os.path.exists(locale_path): try: config = ConfigObj(locale_path) @@ -341,9 +327,7 @@ def get_system_locale(locale_path='/etc/default/locale'): permissions issue?" % locale_path) def configure_locale(config): - """ - sets the locale according to the system's locale. - """ + """ sets the locale according to the system's locale. """ current_locale = locale.getlocale() if current_locale[1] is None: default_locale = locale.getdefaultlocale() @@ -360,10 +344,8 @@ def configure_locale(config): def fondle(path,times=None): # TODO : write unit tests for this - """ - touch a file to change the last modified date. Beware of calling this - function on the same file from multiple threads. - """ + """ touch a file to change the last modified date. Beware of calling + this function on the same file from multiple threads. """ with file(path, 'a'): os.utime(path, times) def last_modified(path): From 41b1b357eb8e9fc130a282df2d381d8c9a9fe3b0 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:48:01 -0400 Subject: [PATCH 096/157] formatted more docstrings --- .../media-monitor2/media/monitor/pure.py | 31 +++++++------------ 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index ad8ce336b..45f4cc66e 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -349,20 +349,16 @@ def fondle(path,times=None): with file(path, 'a'): os.utime(path, times) def last_modified(path): - """ - return the time of the last time mm2 was ran. path refers to the index file - whose date modified attribute contains this information. In the case when - the file does not exist we set this time 0 so that any files on the - filesystem were modified after it - """ + """ return the time of the last time mm2 was ran. path refers to the + index file whose date modified attribute contains this information. + In the case when the file does not exist we set this time 0 so that + any files on the filesystem were modified after it """ if os.path.exists(path): return os.path.getmtime(path) else: return 0 def expand_storage(store): - """ - A storage directory usually consists of 4 different subdirectories. This - function returns their paths - """ + """ A storage directory usually consists of 4 different + subdirectories. This function returns their paths """ store = os.path.normpath(store) return { 'organize' : os.path.join(store, 'organize'), @@ -372,10 +368,8 @@ def expand_storage(store): } def create_dir(path): - """ - will try and make sure that path exists at all costs. raises an exception - if it fails at this task. - """ + """ will try and make sure that path exists at all costs. raises an + exception if it fails at this task. """ if not os.path.exists(path): try : os.makedirs(path) except Exception as e : raise FailedToCreateDir(path, e) @@ -393,11 +387,10 @@ def sub_path(directory,f): return common == normalized def owner_id(original_path): - """ - Given 'original_path' return the file name of the of 'identifier' file. - return the id that is contained in it. If no file is found or nothing is - read then -1 is returned. File is deleted after the number has been read - """ + """ Given 'original_path' return the file name of the of + 'identifier' file. return the id that is contained in it. If no file + is found or nothing is read then -1 is returned. File is deleted + after the number has been read """ fname = "%s.identifier" % original_path owner_id = -1 try: From b2650b9a21dc80639915903e3a549e29d746bc0d Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:49:01 -0400 Subject: [PATCH 097/157] Added comment --- python_apps/media-monitor2/media/monitor/pure.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python_apps/media-monitor2/media/monitor/pure.py b/python_apps/media-monitor2/media/monitor/pure.py index 45f4cc66e..a879f449f 100644 --- a/python_apps/media-monitor2/media/monitor/pure.py +++ b/python_apps/media-monitor2/media/monitor/pure.py @@ -220,6 +220,7 @@ def remove_whitespace(dictionary): return nd def parse_int(s): + # TODO : this function isn't used anywhere yet but it may useful for emf """ Tries very hard to get some sort of integer result from s. Defaults to 0 when it fails From 0f1e843017662cc909e1d12d76f27f9d81303b69 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:49:49 -0400 Subject: [PATCH 098/157] Formatted docstring --- python_apps/media-monitor2/media/monitor/log.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/log.py b/python_apps/media-monitor2/media/monitor/log.py index 5d632bbf4..cf4efb79a 100644 --- a/python_apps/media-monitor2/media/monitor/log.py +++ b/python_apps/media-monitor2/media/monitor/log.py @@ -6,23 +6,19 @@ from media.monitor.pure import LazyProperty appname = 'root' def setup_logging(log_path): - """ - Setup logging by writing log to 'log_path' - """ + """ Setup logging by writing log to 'log_path' """ #logger = logging.getLogger(appname) logging.basicConfig(filename=log_path, level=logging.DEBUG) def get_logger(): - """ - in case we want to use the common logger from a procedural interface - """ + """ in case we want to use the common logger from a procedural + interface """ return logging.getLogger() class Loggable(object): - """ - Any class that wants to log can inherit from this class and automatically - get a logger attribute that can be used like: self.logger.info(...) etc. - """ + """ Any class that wants to log can inherit from this class and + automatically get a logger attribute that can be used like: + self.logger.info(...) etc. """ __metaclass__ = abc.ABCMeta @LazyProperty def logger(self): return get_logger() From 2e54fd64d3ab0312a98840ce7cc8fdb134437ac9 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 14:50:08 -0400 Subject: [PATCH 099/157] Formatted more docstrings --- python_apps/media-monitor2/media/monitor/log.py | 9 +++------ python_apps/media-monitor2/media/monitor/request.py | 8 +++----- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/log.py b/python_apps/media-monitor2/media/monitor/log.py index cf4efb79a..7e75c719d 100644 --- a/python_apps/media-monitor2/media/monitor/log.py +++ b/python_apps/media-monitor2/media/monitor/log.py @@ -24,15 +24,12 @@ class Loggable(object): def logger(self): return get_logger() def unexpected_exception(self,e): - """ - Default message for 'unexpected' exceptions - """ + """ Default message for 'unexpected' exceptions """ self.fatal_exception("'Unexpected' exception has occured:", e) def fatal_exception(self, message, e): - """ - Prints an exception 'e' with 'message'. Also outputs the traceback. - """ + """ Prints an exception 'e' with 'message'. Also outputs the + traceback. """ self.logger.error( message ) self.logger.error( str(e) ) self.logger.error( traceback.format_exc() ) diff --git a/python_apps/media-monitor2/media/monitor/request.py b/python_apps/media-monitor2/media/monitor/request.py index 934290a05..a2f3cdc8f 100644 --- a/python_apps/media-monitor2/media/monitor/request.py +++ b/python_apps/media-monitor2/media/monitor/request.py @@ -17,11 +17,9 @@ class ThreadedRequestSync(threading.Thread, Loggable): self.rs.run_request() class RequestSync(Loggable): - """ - This class is responsible for making the api call to send a request - to airtime. In the process it packs the requests and retries for - some number of times - """ + """ This class is responsible for making the api call to send a + request to airtime. In the process it packs the requests and retries + for some number of times """ @classmethod def create_with_api_client(cls, watcher, requests): apiclient = ac.AirtimeApiClient.create_right_config() From 10a6a4d541e47cee48f552e4c04a7586f20cac40 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 15:03:59 -0400 Subject: [PATCH 100/157] formatted docstrings. fixed decorator with functools --- .../media-monitor2/media/monitor/listeners.py | 2 ++ .../media-monitor2/media/monitor/organizer.py | 22 ++++++++----------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/python_apps/media-monitor2/media/monitor/listeners.py b/python_apps/media-monitor2/media/monitor/listeners.py index 4c860a97e..b33a5c1a9 100644 --- a/python_apps/media-monitor2/media/monitor/listeners.py +++ b/python_apps/media-monitor2/media/monitor/listeners.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import pyinotify from pydispatch import dispatcher +from functools import wraps import media.monitor.pure as mmp from media.monitor.pure import IncludeOnly @@ -31,6 +32,7 @@ class FileMediator(object): def unignore(path): FileMediator.ignored_set.remove(path) def mediate_ignored(fn): + @wraps(fn) def wrapped(self, event, *args,**kwargs): event.pathname = unicode(event.pathname, "utf-8") if FileMediator.is_ignored(event.pathname): diff --git a/python_apps/media-monitor2/media/monitor/organizer.py b/python_apps/media-monitor2/media/monitor/organizer.py index ea6851356..ce1849b90 100644 --- a/python_apps/media-monitor2/media/monitor/organizer.py +++ b/python_apps/media-monitor2/media/monitor/organizer.py @@ -10,14 +10,12 @@ from os.path import dirname import os.path class Organizer(ReportHandler,Loggable): - """ - Organizer is responsible to to listening to OrganizeListener events - and committing the appropriate changes to the filesystem. It does - not in any interact with WatchSyncer's even when the the WatchSyncer - is a "storage directory". The "storage" directory picks up all of - its events through pyinotify. (These events are fed to it through - StoreWatchListener) - """ + """ Organizer is responsible to to listening to OrganizeListener + events and committing the appropriate changes to the filesystem. + It does not in any interact with WatchSyncer's even when the the + WatchSyncer is a "storage directory". The "storage" directory picks + up all of its events through pyinotify. (These events are fed to it + through StoreWatchListener) """ # Commented out making this class a singleton because it's just a band aid # for the real issue. The real issue being making multiple Organizer @@ -41,11 +39,9 @@ class Organizer(ReportHandler,Loggable): super(Organizer, self).__init__(signal=self.channel, weak=False) def handle(self, sender, event): - """ - Intercept events where a new file has been added to the organize - directory and place it in the correct path (starting with - self.target_path) - """ + """ Intercept events where a new file has been added to the + organize directory and place it in the correct path (starting + with self.target_path) """ # Only handle this event type assert isinstance(event, OrganizeFile), \ "Organizer can only handle OrganizeFile events.Given '%s'" % event From 0135fbe9dd457c0c6762bec91999e70d6dde5859 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Thu, 25 Oct 2012 16:20:15 -0400 Subject: [PATCH 101/157] Fixed code formatting --- python_apps/media-monitor2/mm2.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/mm2.py b/python_apps/media-monitor2/mm2.py index 17731cad8..ea1178a2f 100644 --- a/python_apps/media-monitor2/mm2.py +++ b/python_apps/media-monitor2/mm2.py @@ -59,7 +59,8 @@ def main(global_config, api_client_config, log_config, try: with open(config['index_path'], 'w') as f: f.write(" ") except Exception as e: - log.info("Failed to create index file with exception: %s" % str(e)) + log.info("Failed to create index file with exception: %s" \ + % str(e)) else: log.info("Created index file, reloading configuration:") main( global_config, api_client_config, log_config, From b8a5c6ce955ffd7339249dad7c8e7f64a92a1c21 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 26 Oct 2012 15:44:58 -0400 Subject: [PATCH 102/157] cc-4634: Fixed --- python_apps/media-monitor2/media/monitor/metadata.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python_apps/media-monitor2/media/monitor/metadata.py b/python_apps/media-monitor2/media/monitor/metadata.py index 5bbbafaeb..d5dba3b51 100644 --- a/python_apps/media-monitor2/media/monitor/metadata.py +++ b/python_apps/media-monitor2/media/monitor/metadata.py @@ -114,6 +114,7 @@ class Metadata(Loggable): if airtime_k in airtime2mutagen: # The unicode cast here is mostly for integers that need to be # strings + if airtime_v is None: continue try: song_file[ airtime2mutagen[airtime_k] ] = unicode(airtime_v) except (EasyMP4KeyError, EasyID3KeyError) as e: From 7c48683492772523cac454aad89f45d148a1bf16 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg Date: Fri, 26 Oct 2012 16:02:32 -0400 Subject: [PATCH 103/157] cc-4635: Fix --- python_apps/media-monitor2/media/metadata/definitions.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index ee4175033..c53d091f3 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -122,8 +122,16 @@ def load_definitions(): else: default_title = no_extension_basename(k['path']) default_title = re.sub(r'__\d+\.',u'.', default_title) + + # format is: track_number-title-123kbps.mp3 + m = re.match(".+-(?P.+)-\d+kbps", default_title) + if m: + if m.group('title') == unicode_unknown: new_title = '' + else: new_title = m.group('title') + if re.match(".+-%s-.+$" % unicode_unknown, default_title): default_title = u'' + new_title = default_title new_title = re.sub(r'-\d+kbps$', u'', new_title) return new_title From 1ee228558ac3dffcf95fb889af65800f776ebe25 Mon Sep 17 00:00:00 2001 From: James <james@sourcefabric-DX4840.(none)> Date: Fri, 26 Oct 2012 16:24:17 -0400 Subject: [PATCH 104/157] CC-4574: Audio preview fails with certain characters in metadata - fixed --- airtime_mvc/public/js/airtime/common/common.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airtime_mvc/public/js/airtime/common/common.js b/airtime_mvc/public/js/airtime/common/common.js index 3125d8d55..19de0d0a9 100644 --- a/airtime_mvc/public/js/airtime/common/common.js +++ b/airtime_mvc/public/js/airtime/common/common.js @@ -54,7 +54,7 @@ function open_audio_preview(type, id, audioFileTitle, audioFileArtist) { audioFileTitle = audioFileTitle.substring(0,index); } - openPreviewWindow('audiopreview/audio-preview/audioFileID/'+id+'/audioFileArtist/'+encodeURIComponent(audioFileArtist)+'/audioFileTitle/'+encodeURIComponent(audioFileTitle)+'/type/'+type); + openPreviewWindow('audiopreview/audio-preview/audioFileID/'+id+'/audioFileArtist/'+encodeURIComponent(encodeURIComponent(audioFileArtist))+'/audioFileTitle/'+encodeURIComponent(encodeURIComponent(audioFileTitle))+'/type/'+type); _preview_window.focus(); } From e667a721adfb8350e092d9dd05b66df9bb72b160 Mon Sep 17 00:00:00 2001 From: James <james@sourcefabric-DX4840.(none)> Date: Fri, 26 Oct 2012 16:26:48 -0400 Subject: [PATCH 105/157] - comment for some code --- airtime_mvc/public/js/airtime/common/common.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/airtime_mvc/public/js/airtime/common/common.js b/airtime_mvc/public/js/airtime/common/common.js index 19de0d0a9..0d9883b66 100644 --- a/airtime_mvc/public/js/airtime/common/common.js +++ b/airtime_mvc/public/js/airtime/common/common.js @@ -54,6 +54,9 @@ function open_audio_preview(type, id, audioFileTitle, audioFileArtist) { audioFileTitle = audioFileTitle.substring(0,index); } + // The reason that we need to encode artist and title string is that + // sometime they contain '/' or '\' and apache reject %2f or %5f + // so the work around is to encode it twice. openPreviewWindow('audiopreview/audio-preview/audioFileID/'+id+'/audioFileArtist/'+encodeURIComponent(encodeURIComponent(audioFileArtist))+'/audioFileTitle/'+encodeURIComponent(encodeURIComponent(audioFileTitle))+'/type/'+type); _preview_window.focus(); From 7cd8541696372bb15e83d64f1c46686d72b7fa80 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Fri, 26 Oct 2012 16:41:29 -0400 Subject: [PATCH 106/157] cc-4635: Fix --- python_apps/media-monitor2/media/metadata/definitions.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index c53d091f3..0e7282b20 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -124,16 +124,12 @@ def load_definitions(): default_title = re.sub(r'__\d+\.',u'.', default_title) # format is: track_number-title-123kbps.mp3 - m = re.match(".+-(?P<title>.+)-\d+kbps", default_title) + m = re.match(".+-(?P<title>.+)-\d+kbps$", default_title) if m: if m.group('title') == unicode_unknown: new_title = '' else: new_title = m.group('title') + else: new_title = re.sub(r'-\d+kbps$', u'', new_title) - if re.match(".+-%s-.+$" % unicode_unknown, default_title): - default_title = u'' - - new_title = default_title - new_title = re.sub(r'-\d+kbps$', u'', new_title) return new_title with md.metadata('MDATA_KEY_TITLE') as t: From e10f81aec85b77a327aa7938fea1c90340103fb8 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Fri, 26 Oct 2012 16:48:03 -0400 Subject: [PATCH 107/157] cc-4635: Fix --- python_apps/media-monitor2/media/metadata/definitions.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index 0e7282b20..a6d8221df 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -115,7 +115,7 @@ def load_definitions(): # 2. title is absent (read from file) # 3. recorded file def tr_title(k): - unicode_unknown = u"unknown" + #unicode_unknown = u"unknown" new_title = u"" if is_airtime_recorded(k) or k['title'] != u"": new_title = k['title'] @@ -125,9 +125,7 @@ def load_definitions(): # format is: track_number-title-123kbps.mp3 m = re.match(".+-(?P<title>.+)-\d+kbps$", default_title) - if m: - if m.group('title') == unicode_unknown: new_title = '' - else: new_title = m.group('title') + if m: new_title = m.group('title') else: new_title = re.sub(r'-\d+kbps$', u'', new_title) return new_title From 72928bb5e65f1a7ab68212a2f71b2cd15b05ca92 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Fri, 26 Oct 2012 16:59:32 -0400 Subject: [PATCH 108/157] cc-4635: Fix --- python_apps/media-monitor2/media/metadata/definitions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index a6d8221df..31d28b563 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -126,7 +126,7 @@ def load_definitions(): # format is: track_number-title-123kbps.mp3 m = re.match(".+-(?P<title>.+)-\d+kbps$", default_title) if m: new_title = m.group('title') - else: new_title = re.sub(r'-\d+kbps$', u'', new_title) + else: new_title = re.sub(r'-\d+kbps$', u'', default_title) return new_title From c4f0491ff643ca8b17038118c41be32123e15255 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Fri, 26 Oct 2012 17:04:42 -0400 Subject: [PATCH 109/157] cc-4635: Fix --- python_apps/media-monitor2/media/metadata/definitions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index 31d28b563..9919eb041 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -124,7 +124,7 @@ def load_definitions(): default_title = re.sub(r'__\d+\.',u'.', default_title) # format is: track_number-title-123kbps.mp3 - m = re.match(".+-(?P<title>.+)-\d+kbps$", default_title) + m = re.match(".+-(?P<title>.+)-(\d+kbps|unknown)$", default_title) if m: new_title = m.group('title') else: new_title = re.sub(r'-\d+kbps$', u'', default_title) From 0a396378e52397c6c9d5ecf8a0c744760d808f27 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Fri, 26 Oct 2012 17:15:28 -0400 Subject: [PATCH 110/157] cc-4635: Fix --- python_apps/media-monitor2/media/metadata/definitions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python_apps/media-monitor2/media/metadata/definitions.py b/python_apps/media-monitor2/media/metadata/definitions.py index 9919eb041..ec3bed48f 100644 --- a/python_apps/media-monitor2/media/metadata/definitions.py +++ b/python_apps/media-monitor2/media/metadata/definitions.py @@ -124,7 +124,7 @@ def load_definitions(): default_title = re.sub(r'__\d+\.',u'.', default_title) # format is: track_number-title-123kbps.mp3 - m = re.match(".+-(?P<title>.+)-(\d+kbps|unknown)$", default_title) + m = re.match(".+?-(?P<title>.+)-(\d+kbps|unknown)$", default_title) if m: new_title = m.group('title') else: new_title = re.sub(r'-\d+kbps$', u'', default_title) From f14320a769c9884bbba1718a769572c1e04573f0 Mon Sep 17 00:00:00 2001 From: James <james@sourcefabric-DX4840.(none)> Date: Fri, 26 Oct 2012 17:15:39 -0400 Subject: [PATCH 111/157] CC-4603: Dynamic Smart Blocks: adding to multiple shows at once generates the same content - fixed --- airtime_mvc/application/models/Scheduler.php | 43 +++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/airtime_mvc/application/models/Scheduler.php b/airtime_mvc/application/models/Scheduler.php index 664c40504..def7fb045 100644 --- a/airtime_mvc/application/models/Scheduler.php +++ b/airtime_mvc/application/models/Scheduler.php @@ -366,12 +366,11 @@ class Application_Model_Scheduler * @param array $fileIds * @param array $playlistIds */ - private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true) + private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true, $mediaItems = null) { try { - $affectedShowInstances = array(); - + //dont want to recalculate times for moved items. $excludeIds = array(); foreach ($schedFiles as $file) { @@ -384,7 +383,17 @@ class Application_Model_Scheduler foreach ($scheduleItems as $schedule) { $id = intval($schedule["id"]); - + + // if mediaItmes is passed in, we want to create contents + // at the time of insert. This is for dyanmic blocks or + // playlist that contains dynamic blocks + if ($mediaItems != null) { + $schedFiles = array(); + foreach ($mediaItems as $media) { + $schedFiles = array_merge($schedFiles, $this->retrieveMediaFiles($media["id"], $media["type"])); + } + } + if ($id !== 0) { $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); $instance = $schedItem->getCcShowInstances($this->con); @@ -527,10 +536,32 @@ class Application_Model_Scheduler $this->validateRequest($scheduleItems); + $requireDynamicContentCreation = false; + foreach ($mediaItems as $media) { - $schedFiles = array_merge($schedFiles, $this->retrieveMediaFiles($media["id"], $media["type"])); + if ($media['type'] == "playlist") { + $pl = new Application_Model_Playlist($media['id']); + if ($pl->hasDynamicBlock()) { + $requireDynamicContentCreation = true; + break; + } + } else if ($media['type'] == "block") { + $bl = new Application_Model_Block($media['id']); + if (!$bl->isStatic()) { + $requireDynamicContentCreation = true; + break; + } + } + } + + if ($requireDynamicContentCreation) { + $this->insertAfter($scheduleItems, $schedFiles, $adjustSched, $mediaItems); + } else { + foreach ($mediaItems as $media) { + $schedFiles = array_merge($schedFiles, $this->retrieveMediaFiles($media["id"], $media["type"])); + } + $this->insertAfter($scheduleItems, $schedFiles, $adjustSched); } - $this->insertAfter($scheduleItems, $schedFiles, $adjustSched); $this->con->commit(); From 3cb2346af95a1b11436e774bf9bd8b595e6a97d8 Mon Sep 17 00:00:00 2001 From: Martin Konecny <martin.konecny@gmail.com> Date: Fri, 26 Oct 2012 18:23:28 -0400 Subject: [PATCH 112/157] add pcre debian package for compiling liquidsoap --- dev_tools/fabric/fab_liquidsoap_compile.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dev_tools/fabric/fab_liquidsoap_compile.py b/dev_tools/fabric/fab_liquidsoap_compile.py index 221aa41c6..98f816e47 100644 --- a/dev_tools/fabric/fab_liquidsoap_compile.py +++ b/dev_tools/fabric/fab_liquidsoap_compile.py @@ -181,7 +181,8 @@ libmad-ocaml-dev libtaglib-ocaml-dev libalsa-ocaml-dev libtaglib-ocaml-dev libvo libspeex-dev libspeexdsp-dev speex libladspa-ocaml-dev festival festival-dev \ libsamplerate-dev libxmlplaylist-ocaml-dev libxmlrpc-light-ocaml-dev libflac-dev \ libxml-dom-perl libxml-dom-xpath-perl patch autoconf libmp3lame-dev \ -libcamomile-ocaml-dev libcamlimages-ocaml-dev libtool libpulse-dev libjack-dev camlidl libfaad-dev''') +libcamomile-ocaml-dev libcamlimages-ocaml-dev libtool libpulse-dev libjack-dev +camlidl libfaad-dev libpcre-ocaml-dev''') root = '/home/martin/src' do_run('mkdir -p %s' % root) From d6a4f2f7136fa6c1f165fe7ef7eedfb67f79b7ba Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Fri, 26 Oct 2012 18:45:27 -0400 Subject: [PATCH 113/157] Cleaned up soundcloud --- airtime_mvc/application/models/Soundcloud.php | 115 +++++++++--------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/airtime_mvc/application/models/Soundcloud.php b/airtime_mvc/application/models/Soundcloud.php index 2b1068e57..70148c05c 100644 --- a/airtime_mvc/application/models/Soundcloud.php +++ b/airtime_mvc/application/models/Soundcloud.php @@ -25,66 +25,67 @@ class Application_Model_Soundcloud public function uploadTrack($filepath, $filename, $description, $tags=array(), $release=null, $genre=null) - { - if ($this->getToken()) { - if (count($tags)) { - $tags = join(" ", $tags); - $tags = $tags." ".Application_Model_Preference::GetSoundCloudTags(); - } else { - $tags = Application_Model_Preference::GetSoundCloudTags(); - } + { - $downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'; - - $track_data = array( - 'track[sharing]' => 'private', - 'track[title]' => $filename, - 'track[asset_data]' => '@' . $filepath, - 'track[tag_list]' => $tags, - 'track[description]' => $description, - 'track[downloadable]' => $downloadable, - - ); - - if (isset($release)) { - $release = str_replace(" ", "-", $release); - $release = str_replace(":", "-", $release); - - //YYYY-MM-DD-HH-mm-SS - $release = explode("-", $release); - $track_data['track[release_year]'] = $release[0]; - $track_data['track[release_month]'] = $release[1]; - $track_data['track[release_day]'] = $release[2]; - } - - if (isset($genre) && $genre != "") { - $track_data['track[genre]'] = $genre; - } else { - $default_genre = Application_Model_Preference::GetSoundCloudGenre(); - if ($default_genre != "") { - $track_data['track[genre]'] = $default_genre; - } - } - - $track_type = Application_Model_Preference::GetSoundCloudTrackType(); - if ($track_type != "") { - $track_data['track[track_type]'] = $track_type; - } - - $license = Application_Model_Preference::GetSoundCloudLicense(); - if ($license != "") { - $track_data['track[license]'] = $license; - } - - $response = json_decode( - $this->_soundcloud->post('tracks', $track_data), - true - ); - - return $response; - } else { + if (!$this->getToken()) { throw new NoSoundCloundToken(); + } + if (count($tags)) { + $tags = join(" ", $tags); + $tags = $tags." ".Application_Model_Preference::GetSoundCloudTags(); + } else { + $tags = Application_Model_Preference::GetSoundCloudTags(); } + + $downloadable = Application_Model_Preference::GetSoundCloudDownloadbleOption() == '1'; + + $track_data = array( + 'track[sharing]' => 'private', + 'track[title]' => $filename, + 'track[asset_data]' => '@' . $filepath, + 'track[tag_list]' => $tags, + 'track[description]' => $description, + 'track[downloadable]' => $downloadable, + + ); + + if (isset($release)) { + $release = str_replace(" ", "-", $release); + $release = str_replace(":", "-", $release); + + //YYYY-MM-DD-HH-mm-SS + $release = explode("-", $release); + $track_data['track[release_year]'] = $release[0]; + $track_data['track[release_month]'] = $release[1]; + $track_data['track[release_day]'] = $release[2]; + } + + if (isset($genre) && $genre != "") { + $track_data['track[genre]'] = $genre; + } else { + $default_genre = Application_Model_Preference::GetSoundCloudGenre(); + if ($default_genre != "") { + $track_data['track[genre]'] = $default_genre; + } + } + + $track_type = Application_Model_Preference::GetSoundCloudTrackType(); + if ($track_type != "") { + $track_data['track[track_type]'] = $track_type; + } + + $license = Application_Model_Preference::GetSoundCloudLicense(); + if ($license != "") { + $track_data['track[license]'] = $license; + } + + $response = json_decode( + $this->_soundcloud->post('tracks', $track_data), + true + ); + + return $response; + } public static function uploadSoundcloud($id) From 3b51c93766383f73b7193368e21ba1c99708014a Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Mon, 29 Oct 2012 11:25:05 -0400 Subject: [PATCH 114/157] Refactored pyponotify. Removed code duplication and made runner reusable by other scripts. --- python_apps/pypo/pyponotify.py | 61 +++++++++++++--------------------- 1 file changed, 24 insertions(+), 37 deletions(-) diff --git a/python_apps/pypo/pyponotify.py b/python_apps/pypo/pyponotify.py index 446da8d49..9c2f1688c 100644 --- a/python_apps/pypo/pyponotify.py +++ b/python_apps/pypo/pyponotify.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +import traceback """ Python part of radio playout (pypo) @@ -102,6 +103,24 @@ class Notify: logger.debug('# Calling server to update webstream data #') logger.debug('#################################################') response = self.api_client.notify_webstream_data(data, media_id) + logger.debug("Response: " + json.dumps(response)) + + def run_with_options(self, options): + if options.error and options.stream_id: + self.notify_liquidsoap_status(options.error, options.stream_id, options.time) + elif options.connect and options.stream_id: + self.notify_liquidsoap_status("OK", options.stream_id, options.time) + elif options.source_name and options.source_status: + self.notify_source_status(options.source_name, options.source_status) + elif options.webstream: + self.notify_webstream_data(options.webstream, options.media_id) + elif options.media_id: + self.notify_media_start_playing(options.media_id) + elif options.liquidsoap_started: + self.notify_liquidsoap_started() + else: + logger.debug("Unrecognized option in options(%s). Doing nothing" \ + % str(options)) if __name__ == '__main__': @@ -112,41 +131,9 @@ if __name__ == '__main__': print '#########################################' # initialize - if options.error and options.stream_id: - try: - n = Notify() - n.notify_liquidsoap_status(options.error, options.stream_id, options.time) - except Exception, e: - print e - elif options.connect and options.stream_id: - try: - n = Notify() - n.notify_liquidsoap_status("OK", options.stream_id, options.time) - except Exception, e: - print e - elif options.source_name and options.source_status: - try: - n = Notify() - n.notify_source_status(options.source_name, options.source_status) - except Exception, e: - print e - elif options.webstream: - try: - n = Notify() - n.notify_webstream_data(options.webstream, options.media_id) - except Exception, e: - print e - elif options.media_id: - - try: - n = Notify() - n.notify_media_start_playing(options.media_id) - except Exception, e: - print e - elif options.liquidsoap_started: - try: - n = Notify() - n.notify_liquidsoap_started() - except Exception, e: - print e + try: + n = Notify() + n.run_with_options(options) + except Exception as e: + print( traceback.format_exc() ) From 35a9e77062c5400039ce224d7d01c928162d5163 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Mon, 29 Oct 2012 11:40:23 -0400 Subject: [PATCH 115/157] Formatted spaces. --- utils/airtime-import/airtime-import.py | 34 +++++++++++++------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/utils/airtime-import/airtime-import.py b/utils/airtime-import/airtime-import.py index 5f1d305ca..408bd91ac 100644 --- a/utils/airtime-import/airtime-import.py +++ b/utils/airtime-import/airtime-import.py @@ -21,7 +21,7 @@ logger.addHandler(ch) if (os.geteuid() != 0): print 'Must be a root user.' sys.exit() - + # loading config file try: config = ConfigObj('/etc/airtime/media-monitor.cfg') @@ -66,12 +66,12 @@ def copy_or_move_files_to(paths, dest, flag): print "Cannot find file or path: %s" % path except Exception as e: print "Error: ", e - + def format_dir_string(path): if(path[-1] != '/'): path = path+'/' return path - + def helper_get_stor_dir(): res = api_client.list_all_watched_dirs() if(res is None): @@ -87,18 +87,18 @@ def checkOtherOption(args): for i in args: if(i[0] == '-'): return True - + def errorIfMultipleOption(args, msg=''): if(checkOtherOption(args)): if(msg != ''): raise OptionValueError(msg) else: raise OptionValueError("This option cannot be combined with other options") - + def printHelp(): storage_dir = helper_get_stor_dir() if(storage_dir is None): - storage_dir = "Unknown" + storage_dir = "Unknown" else: storage_dir += "imported/" print """ @@ -111,15 +111,15 @@ There are two ways to import audio files into Airtime: Copied or moved files will be placed into the folder: %s - + Files will be automatically organized into the structure "Artist/Album/TrackNumber-TrackName-Bitrate.file_extension". 2) Use airtime-import to add a folder to the Airtime library ("watch" a folder). - + All the files in the watched folder will be imported to Airtime and the folder will be monitored to automatically detect any changes. Hence any - changes done in the folder(add, delete, edit a file) will trigger + changes done in the folder(add, delete, edit a file) will trigger updates in Airtime library. """ % storage_dir parser.print_help() @@ -209,7 +209,7 @@ def WatchRemoveAction(option, opt, value, parser): print "Removing the watch folder failed: %s" % res['msg']['error'] else: print "The given path is not a directory: %s" % path - + def StorageSetAction(option, opt, value, parser): bypass = False isF = '-f' in parser.rargs @@ -231,12 +231,12 @@ def StorageSetAction(option, opt, value, parser): confirm = confirm or 'N' if(confirm == 'n' or confirm =='N'): sys.exit(1) - + if(len(parser.rargs) > 1): raise OptionValueError("Too many arguments. This option requires exactly one argument.") elif(len(parser.rargs) == 0 ): raise OptionValueError("No argument found. This option requires exactly one argument.") - + path = parser.rargs[0] if (path[0] == "/" or path[0] == "~"): path = os.path.realpath(path) @@ -254,17 +254,17 @@ def StorageSetAction(option, opt, value, parser): print "Setting storage folder failed: %s" % res['msg']['error'] else: print "The given path is not a directory: %s" % path - + def StorageGetAction(option, opt, value, parser): errorIfMultipleOption(parser.rargs) if(len(parser.rargs) > 0): raise OptionValueError("This option does not take any arguments.") print helper_get_stor_dir() - + class OptionValueError(RuntimeError): def __init__(self, msg): self.msg = msg - + usage = """[-c|--copy FILE/DIR [FILE/DIR...]] [-m|--move FILE/DIR [FILE/DIR...]] [--watch-add DIR] [--watch-list] [--watch-remove DIR] [--storage-dir-set DIR] [--storage-dir-get]""" @@ -293,7 +293,7 @@ if('-h' in sys.argv): if(len(sys.argv) == 1 or '-' not in sys.argv[1]): printHelp() sys.exit() - + try: (option, args) = parser.parse_args() except Exception, e: @@ -306,7 +306,7 @@ except Exception, e: except SystemExit: printHelp() sys.exit() - + if option.help: printHelp() sys.exit() From 31a7b8f94353f4d683276094b3c005eb0003f006 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Mon, 29 Oct 2012 11:40:41 -0400 Subject: [PATCH 116/157] Removed usesless try catch from send_media_monitor_requests. --- python_apps/api_clients/api_client.py | 85 ++++++++++++--------------- 1 file changed, 39 insertions(+), 46 deletions(-) diff --git a/python_apps/api_clients/api_client.py b/python_apps/api_clients/api_client.py index 130724f66..5b855686a 100644 --- a/python_apps/api_clients/api_client.py +++ b/python_apps/api_clients/api_client.py @@ -422,53 +422,46 @@ class AirtimeApiClient(): def send_media_monitor_requests(self, action_list, dry=False): """ - Send a gang of media monitor events at a time. actions_list is a list - of dictionaries where every dictionary is representing an action. Every - action dict must contain a 'mode' key that says what kind of action it - is and an optional 'is_record' key that says whether the show was - recorded or not. The value of this key does not matter, only if it's - present or not. + Send a gang of media monitor events at a time. actions_list is a + list of dictionaries where every dictionary is representing an + action. Every action dict must contain a 'mode' key that says + what kind of action it is and an optional 'is_record' key that + says whether the show was recorded or not. The value of this key + does not matter, only if it's present or not. """ - logger = self.logger - try: - url = self.construct_url('reload_metadata_group') - # We are assuming that action_list is a list of dictionaries such - # that every dictionary represents the metadata of a file along - # with a special mode key that is the action to be executed by the - # controller. - valid_actions = [] - # We could get a list of valid_actions in a much shorter way using - # filter but here we prefer a little more verbosity to help - # debugging - for action in action_list: - if not 'mode' in action: - self.logger.debug("Warning: Trying to send a request element without a 'mode'") - self.logger.debug("Here is the the request: '%s'" % str(action) ) - else: - # We alias the value of is_record to true or false no - # matter what it is based on if it's absent in the action - if 'is_record' not in action: - action['is_record'] = 0 - valid_actions.append(action) - # Note that we must prefix every key with: mdX where x is a number - # Is there a way to format the next line a little better? The - # parenthesis make the code almost unreadable - md_list = dict((("md%d" % i), json.dumps(convert_dict_value_to_utf8(md))) \ - for i,md in enumerate(valid_actions)) - # For testing we add the following "dry" parameter to tell the - # controller not to actually do any changes - if dry: md_list['dry'] = 1 - self.logger.info("Pumping out %d requests..." % len(valid_actions)) - data = urllib.urlencode(md_list) - req = urllib2.Request(url, data) - response = self.get_response_from_server(req) - response = json.loads(response) - return response - except ValueError: raise - except Exception, e: - logger.error('Exception: %s', e) - logger.error("traceback: %s", traceback.format_exc()) - raise + url = self.construct_url('reload_metadata_group') + # We are assuming that action_list is a list of dictionaries such + # that every dictionary represents the metadata of a file along + # with a special mode key that is the action to be executed by the + # controller. + valid_actions = [] + # We could get a list of valid_actions in a much shorter way using + # filter but here we prefer a little more verbosity to help + # debugging + for action in action_list: + if not 'mode' in action: + self.logger.debug("Warning: Trying to send a request element without a 'mode'") + self.logger.debug("Here is the the request: '%s'" % str(action) ) + else: + # We alias the value of is_record to true or false no + # matter what it is based on if it's absent in the action + if 'is_record' not in action: + action['is_record'] = 0 + valid_actions.append(action) + # Note that we must prefix every key with: mdX where x is a number + # Is there a way to format the next line a little better? The + # parenthesis make the code almost unreadable + md_list = dict((("md%d" % i), json.dumps(convert_dict_value_to_utf8(md))) \ + for i,md in enumerate(valid_actions)) + # For testing we add the following "dry" parameter to tell the + # controller not to actually do any changes + if dry: md_list['dry'] = 1 + self.logger.info("Pumping out %d requests..." % len(valid_actions)) + data = urllib.urlencode(md_list) + req = urllib2.Request(url, data) + response = self.get_response_from_server(req) + response = json.loads(response) + return response #returns a list of all db files for a given directory in JSON format: #{"files":["path/to/file1", "path/to/file2"]} From 3cec987d100b14403ff8eb31dfee9946eaa7011d Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Mon, 29 Oct 2012 11:42:24 -0400 Subject: [PATCH 117/157] Added todo --- python_apps/api_clients/api_client.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/python_apps/api_clients/api_client.py b/python_apps/api_clients/api_client.py index 5b855686a..9ef49618d 100644 --- a/python_apps/api_clients/api_client.py +++ b/python_apps/api_clients/api_client.py @@ -20,6 +20,11 @@ import traceback AIRTIME_VERSION = "2.2.0" + +# TODO : Place these functions in some common module. Right now, media +# monitor uses the same functions and it would be better to reuse them +# instead of copy pasting them around + def to_unicode(obj, encoding='utf-8'): if isinstance(obj, basestring): if not isinstance(obj, unicode): From bf5bc3a1166ca19dcc60d35cfe5026851f8209e8 Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@sourcefabric.org> Date: Mon, 29 Oct 2012 11:43:39 -0400 Subject: [PATCH 118/157] Changed APC to new-style classes --- python_apps/api_clients/api_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python_apps/api_clients/api_client.py b/python_apps/api_clients/api_client.py index 9ef49618d..5ca176ec2 100644 --- a/python_apps/api_clients/api_client.py +++ b/python_apps/api_clients/api_client.py @@ -44,7 +44,7 @@ def convert_dict_value_to_utf8(md): # Airtime API Client ################################################################################ -class AirtimeApiClient(): +class AirtimeApiClient(object): # This is a little hacky fix so that I don't have to pass the config object # everywhere where AirtimeApiClient needs to be initialized From 8ac0f419873355c35b7ea27e01d38c48b1c65ce2 Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Mon, 29 Oct 2012 11:57:20 -0400 Subject: [PATCH 119/157] CC-4590: New smart block says 'Empty playlist' -fixed --- .../application/views/scripts/playlist/update.phtml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/application/views/scripts/playlist/update.phtml b/airtime_mvc/application/views/scripts/playlist/update.phtml index 70176ff9e..87cd0662f 100644 --- a/airtime_mvc/application/views/scripts/playlist/update.phtml +++ b/airtime_mvc/application/views/scripts/playlist/update.phtml @@ -92,5 +92,13 @@ if ($item['type'] == 2) { <?php endforeach; ?> <?php else : ?> -<li class="spl_empty">Empty playlist</li> +<li class="spl_empty"> +<?php + if ($this->obj instanceof Application_Model_Block) { + echo 'Empty smart block'; + } else { + echo 'Empty playlist'; + } +?> +</li> <?php endif; ?> From fdd889d7a8e2f661945cd047896f33a36be42719 Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Mon, 29 Oct 2012 12:09:11 -0400 Subject: [PATCH 120/157] - fixed formatting --- .../js/airtime/showbuilder/main_builder.js | 336 +++++++++--------- 1 file changed, 171 insertions(+), 165 deletions(-) diff --git a/airtime_mvc/public/js/airtime/showbuilder/main_builder.js b/airtime_mvc/public/js/airtime/showbuilder/main_builder.js index b640a2882..48e503ac6 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/main_builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/main_builder.js @@ -113,174 +113,180 @@ AIRTIME = (function(AIRTIME) { } mod.onReady = function() { - //define module vars. - $lib = $("#library_content"); - $builder = $("#show_builder"); - $fs = $builder.find('fieldset'); - - /* - * Icon hover states for search. - */ - $builder.on("mouseenter", ".sb-timerange .ui-button", function(ev) { - $(this).addClass("ui-state-hover"); - }); - $builder.on("mouseleave", ".sb-timerange .ui-button", function(ev) { - $(this).removeClass("ui-state-hover"); - }); - - $builder.find(dateStartId).datepicker(oBaseDatePickerSettings); - $builder.find(timeStartId).timepicker(oBaseTimePickerSettings); - $builder.find(dateEndId).datepicker(oBaseDatePickerSettings); - $builder.find(timeEndId).timepicker(oBaseTimePickerSettings); - - oRange = AIRTIME.utilities.fnGetScheduleRange(dateStartId, timeStartId, dateEndId, timeEndId); - AIRTIME.showbuilder.fnServerData.start = oRange.start; - AIRTIME.showbuilder.fnServerData.end = oRange.end; + // define module vars. + $lib = $("#library_content"); + $builder = $("#show_builder"); + $fs = $builder.find('fieldset'); - AIRTIME.library.libraryInit(); - AIRTIME.showbuilder.builderDataTable(); - setWidgetSize(); - - $libWrapper = $lib.find("#library_display_wrapper"); - $libWrapper.prepend($libClose); - - $builder.find('.dataTables_scrolling').css("max-height", widgetHeight - 95); - - $builder.on("click", "#sb_submit", showSearchSubmit); + /* + * Icon hover states for search. + */ + $builder.on("mouseenter", ".sb-timerange .ui-button", function(ev) { + $(this).addClass("ui-state-hover"); + }); + $builder.on("mouseleave", ".sb-timerange .ui-button", function(ev) { + $(this).removeClass("ui-state-hover"); + }); - $builder.on("click","#sb_edit", function (ev){ - var schedTable = $("#show_builder_table").dataTable(); - - //reset timestamp to redraw the cursors. - AIRTIME.showbuilder.resetTimestamp(); - - $lib.show() - .width(Math.floor(screenWidth * 0.48)); - - $builder.width(Math.floor(screenWidth * 0.48)) - .find("#sb_edit") - .remove() - .end() - .find("#sb_date_start") - .css("margin-left", 0) - .end(); - - schedTable.fnDraw(); - - $.ajax({ - url: "/usersettings/set-now-playing-screen-settings", - type: "POST", - data: {settings : {library : true}, format: "json"}, - dataType: "json", - success: function(){} - }); - }); - - $lib.on("click", "#sb_lib_close", function() { - var schedTable = $("#show_builder_table").dataTable(); + $builder.find(dateStartId).datepicker(oBaseDatePickerSettings); + $builder.find(timeStartId).timepicker(oBaseTimePickerSettings); + $builder.find(dateEndId).datepicker(oBaseDatePickerSettings); + $builder.find(timeEndId).timepicker(oBaseTimePickerSettings); + + oRange = AIRTIME.utilities.fnGetScheduleRange(dateStartId, timeStartId, + dateEndId, timeEndId); + AIRTIME.showbuilder.fnServerData.start = oRange.start; + AIRTIME.showbuilder.fnServerData.end = oRange.end; + + AIRTIME.library.libraryInit(); + AIRTIME.showbuilder.builderDataTable(); + setWidgetSize(); + + $libWrapper = $lib.find("#library_display_wrapper"); + $libWrapper.prepend($libClose); + + $builder.find('.dataTables_scrolling').css("max-height", + widgetHeight - 95); + + $builder.on("click", "#sb_submit", showSearchSubmit); + + $builder.on("click", "#sb_edit", function(ev) { + var schedTable = $("#show_builder_table").dataTable(); + + // reset timestamp to redraw the cursors. + AIRTIME.showbuilder.resetTimestamp(); + + $lib.show().width(Math.floor(screenWidth * 0.48)); + + $builder.width(Math.floor(screenWidth * 0.48)).find("#sb_edit") + .remove().end().find("#sb_date_start") + .css("margin-left", 0).end(); + + schedTable.fnDraw(); + + $.ajax( { + url : "/usersettings/set-now-playing-screen-settings", + type : "POST", + data : { + settings : { + library : true + }, + format : "json" + }, + dataType : "json", + success : function() { + } + }); + }); + + $lib.on("click", "#sb_lib_close", function() { + var schedTable = $("#show_builder_table").dataTable(); + + $lib.hide(); + $builder.width(screenWidth).find(".sb-timerange").prepend( + $toggleLib).find("#sb_date_start").css("margin-left", 30) + .end().end(); + + $toggleLib.removeClass("ui-state-hover"); + schedTable.fnDraw(); + + $.ajax( { + url : "/usersettings/set-now-playing-screen-settings", + type : "POST", + data : { + settings : { + library : false + }, + format : "json" + }, + dataType : "json", + success : function() { + } + }); + }); + + $builder.find('legend').click( + function(ev, item) { + + if ($fs.hasClass("closed")) { + + $fs.removeClass("closed"); + $builder.find('.dataTables_scrolling').css( + "max-height", widgetHeight - 150); + } else { + $fs.addClass("closed"); + + // set defaults for the options. + $fs.find('select').val(0); + $fs.find('input[type="checkbox"]').attr("checked", + false); + $builder.find('.dataTables_scrolling').css( + "max-height", widgetHeight - 110); + } + }); + + // set click event for all my shows checkbox. + $builder.on("click", "#sb_my_shows", function(ev) { + + if ($(this).is(':checked')) { + $(ev.delegateTarget).find('#sb_show_filter').val(0); + } + + showSearchSubmit(); + }); + + //set select event for choosing a show. + $builder.on("change", '#sb_show_filter', function(ev) { + + if ($(this).val() !== 0) { + $(ev.delegateTarget).find('#sb_my_shows') + .attr("checked", false); + } + + showSearchSubmit(); + + }); + + function checkScheduleUpdates() { + var data = {}, oTable = $('#show_builder_table').dataTable(), fn = oTable + .fnSettings().fnServerData, start = fn.start, end = fn.end; + + data["format"] = "json"; + data["start"] = start; + data["end"] = end; + data["timestamp"] = AIRTIME.showbuilder.getTimestamp(); + data["instances"] = AIRTIME.showbuilder.getShowInstances(); + + if (fn.hasOwnProperty("ops")) { + data["myShows"] = fn.ops.myShows; + data["showFilter"] = fn.ops.showFilter; + } + + $.ajax( { + "dataType" : "json", + "type" : "GET", + "url" : "/showbuilder/check-builder-feed", + "data" : data, + "success" : function(json) { + if (json.update === true) { + oTable.fnDraw(); + } + } + }); + } + + //check if the timeline view needs updating. + setInterval(checkScheduleUpdates, 5 * 1000); //need refresh in milliseconds + }; + + mod.onResize = function() { + + clearTimeout(resizeTimeout); + resizeTimeout = setTimeout(setWidgetSize, 100); + }; + + return AIRTIME; - $lib.hide(); - $builder.width(screenWidth) - .find(".sb-timerange") - .prepend($toggleLib) - .find("#sb_date_start") - .css("margin-left", 30) - .end() - .end(); - - $toggleLib.removeClass("ui-state-hover"); - schedTable.fnDraw(); - - $.ajax({ - url: "/usersettings/set-now-playing-screen-settings", - type: "POST", - data: {settings : {library : false}, format: "json"}, - dataType: "json", - success: function(){} - }); - }); - - $builder.find('legend').click(function(ev, item){ - - if ($fs.hasClass("closed")) { - - $fs.removeClass("closed"); - $builder.find('.dataTables_scrolling').css("max-height", widgetHeight - 150); - } - else { - $fs.addClass("closed"); - - //set defaults for the options. - $fs.find('select').val(0); - $fs.find('input[type="checkbox"]').attr("checked", false); - $builder.find('.dataTables_scrolling').css("max-height", widgetHeight - 110); - } - }); - - //set click event for all my shows checkbox. - $builder.on("click", "#sb_my_shows", function(ev) { - - if ($(this).is(':checked')) { - $(ev.delegateTarget).find('#sb_show_filter').val(0); - } - - showSearchSubmit(); - }); - - //set select event for choosing a show. - $builder.on("change", '#sb_show_filter', function(ev) { - - if ($(this).val() !== 0) { - $(ev.delegateTarget).find('#sb_my_shows').attr("checked", false); - } - - showSearchSubmit(); - - }); - - function checkScheduleUpdates(){ - var data = {}, - oTable = $('#show_builder_table').dataTable(), - fn = oTable.fnSettings().fnServerData, - start = fn.start, - end = fn.end; - - data["format"] = "json"; - data["start"] = start; - data["end"] = end; - data["timestamp"] = AIRTIME.showbuilder.getTimestamp(); - data["instances"] = AIRTIME.showbuilder.getShowInstances(); - - if (fn.hasOwnProperty("ops")) { - data["myShows"] = fn.ops.myShows; - data["showFilter"] = fn.ops.showFilter; - } - - $.ajax( { - "dataType": "json", - "type": "GET", - "url": "/showbuilder/check-builder-feed", - "data": data, - "success": function(json) { - if (json.update === true) { - oTable.fnDraw(); - } - } - } ); - } - - //check if the timeline view needs updating. - setInterval(checkScheduleUpdates, 5 * 1000); //need refresh in milliseconds - }; - - mod.onResize = function() { - - clearTimeout(resizeTimeout); - resizeTimeout = setTimeout(setWidgetSize, 100); - }; - - return AIRTIME; - } (AIRTIME || {})); $(document).ready(AIRTIME.builderMain.onReady); From 332f9993c0890a52101bf9cecb8c0283b2325021 Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Mon, 29 Oct 2012 15:20:16 -0400 Subject: [PATCH 121/157] CC-4640: Automatically jump to current song when loading the Now Playing page. -done --- .../public/js/airtime/showbuilder/builder.js | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index fc8463481..daf44a510 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -339,11 +339,23 @@ var AIRTIME = (function(AIRTIME){ }); }; + mod.jumpToCurrentTrack = function() { + var $scroll = $sbContent.find(".dataTables_scrolling"); + var scrolled = $scroll.scrollTop(); + var scrollingTop = $scroll.offset().top; + var oTable = $('#show_builder_table').dataTable(); + var current = $sbTable.find("."+NOW_PLAYING_CLASS); + var currentTop = current.offset().top; + + $scroll.scrollTop(currentTop - scrollingTop + scrolled); + } + mod.builderDataTable = function() { $sbContent = $('#show_builder'); $lib = $("#library_content"), $sbTable = $sbContent.find('table'); - + var isInitialized = false; + oSchedTable = $sbTable.dataTable( { "aoColumns": [ /* checkbox */ {"mDataProp": "allowed", "sTitle": "", "sWidth": "15px", "sClass": "sb-checkbox"}, @@ -636,6 +648,11 @@ var AIRTIME = (function(AIRTIME){ $("#draggingContainer").remove(); }, "fnDrawCallback": function fnBuilderDrawCallback(oSettings, json) { + if (!isInitialized) { + mod.jumpToCurrentTrack(); + } + + isInitialized = true; var wrapperDiv, markerDiv, $td, @@ -1021,7 +1038,7 @@ var AIRTIME = (function(AIRTIME){ if (AIRTIME.button.isDisabled('icon-step-forward', true) === true) { return; } - + /* var $scroll = $sbContent.find(".dataTables_scrolling"), scrolled = $scroll.scrollTop(), scrollingTop = $scroll.offset().top, @@ -1029,6 +1046,8 @@ var AIRTIME = (function(AIRTIME){ currentTop = current.offset().top; $scroll.scrollTop(currentTop - scrollingTop + scrolled); + */ + mod.jumpToCurrentTrack(); }); //delete overbooked tracks. @@ -1196,7 +1215,7 @@ var AIRTIME = (function(AIRTIME){ }; } - }); + }); }; return AIRTIME; From d97afabaea958660053db8ff7f2e3a474d4424d3 Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Mon, 29 Oct 2012 15:40:58 -0400 Subject: [PATCH 122/157] CC-4640: Automatically jump to current song when loading the Now Playing page. -added check to see if a show is currently playing --- airtime_mvc/public/js/airtime/showbuilder/builder.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index daf44a510..21d0b5c43 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -649,7 +649,9 @@ var AIRTIME = (function(AIRTIME){ }, "fnDrawCallback": function fnBuilderDrawCallback(oSettings, json) { if (!isInitialized) { - mod.jumpToCurrentTrack(); + if ($(this).find("."+NOW_PLAYING_CLASS).length > 0) { + mod.jumpToCurrentTrack(); + } } isInitialized = true; From 48613978727d2185961f31c09b234da4bc38d17f Mon Sep 17 00:00:00 2001 From: James <james@sourcefabric-DX4840.(none)> Date: Mon, 29 Oct 2012 16:19:23 -0400 Subject: [PATCH 123/157] CC-4644: Exception from zendphp.log - fixed --- airtime_mvc/application/models/Schedule.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index b668f13e5..58f7bbdba 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -268,7 +268,7 @@ SQL; //We need to search 24 hours before and after the show times so that that we - //capture all of the show's contents. + //capture all of the show's contents. $p_track_start= $p_start->sub(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); $p_track_end = $p_end->add(new DateInterval("PT24H"))->format("Y-m-d H:i:s"); @@ -661,6 +661,7 @@ SQL; $data["media"][$switch_start]['start'] = $switch_start; $data["media"][$switch_start]['end'] = $switch_start; $data["media"][$switch_start]['event_type'] = "switch_off"; + $data["media"][$kick_start]['type'] = "event"; $data["media"][$switch_start]['independent_event'] = true; } } From e40d49219bf3a04d68bafc0b2c70772dbb2e0af8 Mon Sep 17 00:00:00 2001 From: Martin Konecny <martin.konecny@gmail.com> Date: Mon, 29 Oct 2012 16:29:10 -0400 Subject: [PATCH 124/157] add missing gstreamer.liq file --- .../liquidsoap_scripts/library/gstreamer.liq | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 python_apps/pypo/liquidsoap_scripts/library/gstreamer.liq diff --git a/python_apps/pypo/liquidsoap_scripts/library/gstreamer.liq b/python_apps/pypo/liquidsoap_scripts/library/gstreamer.liq new file mode 100644 index 000000000..d3a364abd --- /dev/null +++ b/python_apps/pypo/liquidsoap_scripts/library/gstreamer.liq @@ -0,0 +1,34 @@ +%ifdef input.gstreamer.video +# Stream from a video4linux 2 input device, such as a webcam. +# @category Source / Input +# @param ~id Force the value of the source ID. +# @param ~clock_safe Force the use of the dedicated v4l clock. +# @param ~device V4L2 device to use. +def input.v4l2(~id="",~clock_safe=true,~device="/dev/video0") + pipeline = "v4l2src device=#{device}" + input.gstreamer.video(id=id, clock_safe=clock_safe, pipeline=pipeline) +end + +# Stream from a video4linux 2 input device, such as a webcam. +# @category Source / Input +# @param ~id Force the value of the source ID. +# @param ~clock_safe Force the use of the dedicated v4l clock. +# @param ~device V4L2 device to use. +def input.v4l2_with_audio(~id="",~clock_safe=true,~device="/dev/video0") + audio_pipeline = "autoaudiosrc" + video_pipeline = "v4l2src device=#{device}" + input.gstreamer.audio_video(id=id, clock_safe=clock_safe, audio_pipeline=audio_pipeline, video_pipeline=video_pipeline) +end + +def gstreamer.encode_x264_avi(fname, source) + output.gstreamer.video(pipeline="videoconvert ! x264enc ! avimux ! filesink location=\"#{fname}\"", source) +end + +def gstreamer.encode_jpeg_avi(fname, source) + output.gstreamer.video(pipeline="videoconvert ! jpegenc ! avimux ! filesink location=\"#{fname}\"", source) +end + +def gstreamer.encode_mp3(fname, source) + output.gstreamer.audio(pipeline="audioconvert ! lamemp3enc ! filesink location=\"#{fname}\"", source) +end +%endif \ No newline at end of file From 5651dbce5615221b73f5c6de168388b4031adf89 Mon Sep 17 00:00:00 2001 From: James <james@sourcefabric-DX4840.(none)> Date: Mon, 29 Oct 2012 16:37:27 -0400 Subject: [PATCH 125/157] CC-4644: Exception from zendphp.log - fixed --- airtime_mvc/application/models/Schedule.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index 58f7bbdba..c6776a43e 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -661,7 +661,7 @@ SQL; $data["media"][$switch_start]['start'] = $switch_start; $data["media"][$switch_start]['end'] = $switch_start; $data["media"][$switch_start]['event_type'] = "switch_off"; - $data["media"][$kick_start]['type'] = "event"; + $data["media"][$switch_start]['type'] = "event"; $data["media"][$switch_start]['independent_event'] = true; } } From 7276985bb401f8b8aba5482f987ec86b83deaddb Mon Sep 17 00:00:00 2001 From: Rudi Grinberg <rudi.grinberg@gmail.com> Date: Mon, 29 Oct 2012 19:19:48 -0400 Subject: [PATCH 126/157] test commit --- airtime_mvc/tests/phpunit.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/airtime_mvc/tests/phpunit.xml b/airtime_mvc/tests/phpunit.xml index e69de29bb..01ad1609e 100644 --- a/airtime_mvc/tests/phpunit.xml +++ b/airtime_mvc/tests/phpunit.xml @@ -0,0 +1,2 @@ + +<!-- b bs --> From b08f5091b5fc1d871ce8846c71404e377d30c90d Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Tue, 30 Oct 2012 11:18:11 -0400 Subject: [PATCH 127/157] CC-4609: Calendar -> Add/Remove contents: Please remove useless buttons: 'Jump to current playing song' and 'Cancel current show' -done --- airtime_mvc/public/js/airtime/showbuilder/builder.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index 21d0b5c43..c64825393 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -649,6 +649,8 @@ var AIRTIME = (function(AIRTIME){ }, "fnDrawCallback": function fnBuilderDrawCallback(oSettings, json) { if (!isInitialized) { + //when coming to 'Now Playing' page we want the page + //to jump to the current track if ($(this).find("."+NOW_PLAYING_CLASS).length > 0) { mod.jumpToCurrentTrack(); } @@ -985,13 +987,18 @@ var AIRTIME = (function(AIRTIME){ "<i class='icon-white icon-cut'></i></button></div>") .append("<div class='btn-group'>" + "<button title='Remove selected scheduled items' class='ui-state-disabled btn btn-small' disabled='disabled'>" + - "<i class='icon-white icon-trash'></i></button></div>") - .append("<div class='btn-group'>" + + "<i class='icon-white icon-trash'></i></button></div>"); + + //if 'Add/Remove content' was chosen from the context menu + //in the Calendar do not append these buttons + if ($(".ui-dialog-content").length === 0) { + $menu.append("<div class='btn-group'>" + "<button title='Jump to the current playing track' class='ui-state-disabled btn btn-small' disabled='disabled'>" + "<i class='icon-white icon-step-forward'></i></button></div>") .append("<div class='btn-group'>" + "<button title='Cancel current show' class='ui-state-disabled btn btn-small btn-danger' disabled='disabled'>" + "<i class='icon-white icon-ban-circle'></i></button></div>"); + } $toolbar.append($menu); $menu = undefined; From 695c0fa926b73901b04ec8cf7cbf3ded60f2a2ed Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Tue, 30 Oct 2012 11:45:53 -0400 Subject: [PATCH 128/157] CC-4607: Library: Please make the 'Add x items' following mouse's point -fixed --- .../js/airtime/library/events/library_playlistbuilder.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/public/js/airtime/library/events/library_playlistbuilder.js b/airtime_mvc/public/js/airtime/library/events/library_playlistbuilder.js index 4b139f66e..5392cbd49 100644 --- a/airtime_mvc/public/js/airtime/library/events/library_playlistbuilder.js +++ b/airtime_mvc/public/js/airtime/library/events/library_playlistbuilder.js @@ -64,8 +64,9 @@ var AIRTIME = (function(AIRTIME) { helper : function() { var $el = $(this), selected = mod - .getChosenAudioFilesLength(), container, message, li = $("#side_playlist ul[id='spl_sortable'] li:first"), width = li - .width(), height = 55; + .getChosenAudioFilesLength(), container, message, li = $("#side_playlist ul[id='spl_sortable'] li:first"), + width = li.width(), height = 55; + if (width > 798) width = 798; // dragging an element that has an unselected // checkbox. From 71291b14f0b99e0ea832176745f0c3bc92f40818 Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Tue, 30 Oct 2012 11:59:52 -0400 Subject: [PATCH 129/157] CC-4646: Library: Make advanced search options hidden by default -done --- airtime_mvc/application/views/scripts/library/library.phtml | 2 +- .../application/views/scripts/showbuilder/builderDialog.phtml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/application/views/scripts/library/library.phtml b/airtime_mvc/application/views/scripts/library/library.phtml index 0b60020c5..ec96a3a44 100644 --- a/airtime_mvc/application/views/scripts/library/library.phtml +++ b/airtime_mvc/application/views/scripts/library/library.phtml @@ -1,5 +1,5 @@ <div id="import_status" class="library_import" style="display:none">File import in progress... <img src="/css/images/file_import_loader.gif"></img></div> -<fieldset class="toggle" id="filter_options"> +<fieldset class="toggle closed" id="filter_options"> <legend style="cursor: pointer;"><span class="ui-icon ui-icon-triangle-2-n-s"></span>Advanced Search Options</legend> <div id="advanced_search" class="advanced_search form-horizontal"></div> </fieldset> diff --git a/airtime_mvc/application/views/scripts/showbuilder/builderDialog.phtml b/airtime_mvc/application/views/scripts/showbuilder/builderDialog.phtml index 92331d6cc..46ce9488e 100644 --- a/airtime_mvc/application/views/scripts/showbuilder/builderDialog.phtml +++ b/airtime_mvc/application/views/scripts/showbuilder/builderDialog.phtml @@ -1,7 +1,7 @@ <div class="wrapper"> <div id="library_content" class="lib-content tabs ui-widget ui-widget-content block-shadow alpha-block padded"> <div id="import_status" style="display:none">File import in progress...</div> - <fieldset class="toggle" id="filter_options"> + <fieldset class="toggle closed" id="filter_options"> <legend style="cursor: pointer;"><span class="ui-icon ui-icon-triangle-2-n-s"></span>Advanced Search Options</legend> <div id="advanced_search" class="advanced_search form-horizontal"></div> </fieldset> From 5061dfa05d3b6078cf136936cba4d8f14186734e Mon Sep 17 00:00:00 2001 From: James <james@sourcefabric-DX4840.(none)> Date: Tue, 30 Oct 2012 12:36:50 -0400 Subject: [PATCH 130/157] CC-4647: apache error log entries - fixed --- airtime_mvc/application/models/Block.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/application/models/Block.php b/airtime_mvc/application/models/Block.php index eb1aab691..80fae297d 100644 --- a/airtime_mvc/application/models/Block.php +++ b/airtime_mvc/application/models/Block.php @@ -308,10 +308,11 @@ SQL; $length = $value." ".$modifier; } else { $hour = "00"; + $mins = "00"; if ($modifier == "minutes") { if ($value >59) { $hour = intval($value/60); - $value = $value%60; + $mins = $value%60; } } elseif ($modifier == "hours") { From b8039e315a2730e59a36c48a0b6d70a256865356 Mon Sep 17 00:00:00 2001 From: denise <denise@denise-DX4860sourcefabric.org> Date: Tue, 30 Oct 2012 13:02:55 -0400 Subject: [PATCH 131/157] CC-4577: Webstream UI: little improvement about 'SAVE' button and input boxes for URL and length -done --- .../views/scripts/webstream/webstream.phtml | 35 ++++++++++--------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/airtime_mvc/application/views/scripts/webstream/webstream.phtml b/airtime_mvc/application/views/scripts/webstream/webstream.phtml index 1757f9be0..6695c82fc 100644 --- a/airtime_mvc/application/views/scripts/webstream/webstream.phtml +++ b/airtime_mvc/application/views/scripts/webstream/webstream.phtml @@ -9,6 +9,10 @@ <li id='lib-new-ws'><a href="#">New Webstream</a></li> </ul> </div> + + <div class="btn-group pull-right"> + <button class="btn btn-inverse" type="submit" id="webstream_save" name="submit">Save</button> +</div> <?php if (isset($this->obj)) : ?> <div class="btn-group pull-right"> <button id="ws_delete" class="btn" <?php if ($this->action == "new"): ?>style="display:none;"<?php endif; ?>aria-disabled="false">Delete</button> @@ -37,24 +41,23 @@ <dd id="description-element"> <textarea cols="80" rows="24" id="description" name="description"><?php echo $this->obj->getDescription(); ?></textarea> </dd> - <dt id="submit-label" style="display: none;"> </dt> - <div id="url-error" class="errors" style="display:none;"></div> - <dt id="streamurl-label"><label for="streamurl">Stream URL:</label></dt> - <dd id="streamurl-element"> - <input type="text" value="<?php echo $this->obj->getUrl(); ?>" size="40"/> - </dd> - <div id="length-error" class="errors" style="display:none;"></div> - <dt id="streamlength-label"><label for="streamlength">Default Length:</label></dt> - <dd id="streamlength-element"> - <input type="text" value="<?php echo $this->obj->getDefaultLength() ?>"/> - </dd> - <dd id="submit-element" class="buttons"> - <input class="btn btn-inverse" type="submit" value="Save" id="webstream_save" name="submit"> - </dd> + </dl> </fieldset> - - + + <dl class="zend_form"> + <dt id="submit-label" style="display: none;"> </dt> + <div id="url-error" class="errors" style="display:none;"></div> + <dt id="streamurl-label"><label for="streamurl">Stream URL:</label></dt> + <dd id="streamurl-element"> + <input type="text" value="<?php echo $this->obj->getUrl(); ?>" size="40"/> + </dd> + <div id="length-error" class="errors" style="display:none;"></div> + <dt id="streamlength-label"><label for="streamlength">Default Length:</label></dt> + <dd id="streamlength-element"> + <input type="text" value="<?php echo $this->obj->getDefaultLength() ?>"/> + </dd> + </dl> <?php else : ?> <div>No webstream</div> From 3e60ac4393d8bc5f0f18163105f1cd7d09eee580 Mon Sep 17 00:00:00 2001 From: James <james@sourcefabric-DX4840.(none)> Date: Tue, 30 Oct 2012 13:23:09 -0400 Subject: [PATCH 132/157] remove \r line endings --- .../views/scripts/api/status.phtml | 4 +- .../views/scripts/form/register-dialog.phtml | 364 +- .../views/scripts/schedule/show-list.phtml | 2 +- airtime_mvc/public/css/add-show.css | 258 +- .../css/colorpicker/css/colorpicker.css | 324 +- .../public/css/jquery.ui.timepicker.css | 142 +- airtime_mvc/public/css/plupload.queue.css | 352 +- airtime_mvc/public/css/pro_dropdown_3.css | 370 +- .../css/redmond/jquery-ui-1.8.8.custom.css | 3046 +++++++------- .../common/Version20120405114454.php | 16 +- .../common/Version20120410104441.php | 18 +- .../common/Version20120410143340.php | 2 +- .../propel/airtime/CcShowInstances.php | 54 +- .../upgrade-template/UpgradeCommon.php | 40 +- .../icecast2/airtime-icecast-status.xsl | 14 +- widgets/css/airtime-widgets.css | 424 +- widgets/widget_schedule.html | 3646 ++++++++--------- widgets/widgets.html | 102 +- 18 files changed, 4589 insertions(+), 4589 deletions(-) diff --git a/airtime_mvc/application/views/scripts/api/status.phtml b/airtime_mvc/application/views/scripts/api/status.phtml index 1cffa8b84..b597b4b71 100644 --- a/airtime_mvc/application/views/scripts/api/status.phtml +++ b/airtime_mvc/application/views/scripts/api/status.phtml @@ -1,3 +1,3 @@ -<?php - +<?php + echo $status; \ No newline at end of file diff --git a/airtime_mvc/application/views/scripts/form/register-dialog.phtml b/airtime_mvc/application/views/scripts/form/register-dialog.phtml index 68f653d71..b4c9630bb 100644 --- a/airtime_mvc/application/views/scripts/form/register-dialog.phtml +++ b/airtime_mvc/application/views/scripts/form/register-dialog.phtml @@ -1,182 +1,182 @@ -<div id="register_popup" class="dialogPopup register-dialog" title="Register Airtime" style="display: none;"> - <form id="register-form" method="<?php echo $this->element->getMethod() ?>" action="<?php echo $this->element->getAction() ?>" enctype="multipart/form-data"> - <fieldset> - <dl class="zend_form"> - <dt class="block-display info-text"> - Help Airtime improve by letting us know how you are using it. This info - will be collected regularly in order to enhance your user experience. - <br /><br /> - Click "Yes, help Airtime" and we'll make sure the features you use are - constantly improving. - </dt> - <dd id="SupportFeedback-element" class="block-display"> - <label class="optional" for="SupportFeedback"> - <?php echo $this->element->getElement('SupportFeedback') ?> - <strong><?php echo $this->element->getElement('SupportFeedback')->getLabel() ?></strong> - </label> - <?php if($this->element->getElement('SupportFeedback')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('SupportFeedback')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt class="block-display info-text"> - Click the box below to advertise your station on - <a id="link_to_whos_using" href="http://sourcefabric.org/en/airtime/whosusing" onclick="window.open(this.href); return false">Sourcefabric.org</a>. - In order to promote your station, "Send support feedback" must be enabled. This data will be collected in addition to the support feedback. - </dt> - <dd id="publicize-element" class="block-display"> - <label class="optional" for="Publicise"> - <?php echo $this->element->getElement('Publicise') ?> - <strong><?php echo $this->element->getElement('Publicise')->getLabel() ?></strong> - </label> - <?php if($this->element->getElement('Publicise')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('Publicise')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - </dl> - <dl id="public-info" style="display:none;"> - <dt id="stnName-label"> - <label class="optional" for="stnName"><?php echo $this->element->getElement('stnName')->getLabel() ?> - <span class="info-text-small">(Required)</span> : - </label> - </dt> - <dd id="stnName-element"> - <?php echo $this->element->getElement('stnName') ?> - <?php if($this->element->getElement('stnName')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('stnName')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt id="Phone-label"> - <label class="optional" for="Phone"><?php echo $this->element->getElement('Phone')->getLabel() ?></label> - </dt> - <dd id="Phone-element"> - <?php echo $this->element->getElement('Phone') ?> - <span class="info-text-small">(for verification purposes only, will not be published)</span> - <?php if($this->element->getElement('Phone')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('Phone')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt id="Email-label"> - <label class="optional" for="Email"><?php echo $this->element->getElement('Email')->getLabel() ?></label> - </dt> - <dd id="Email-element"> - <?php echo $this->element->getElement('Email') ?> - <span class="info-text-small">(for verification purposes only, will not be published)</span> - <?php if($this->element->getElement('Email')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('Email')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt id="StationWebSite-label"> - <label class="optional" for="StationWebSite"><?php echo $this->element->getElement('StationWebSite')->getLabel() ?></label> - </dt> - <dd id="StationWebSite-element"> - <?php echo $this->element->getElement('StationWebSite') ?> - <?php if($this->element->getElement('StationWebSite')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('StationWebSite')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt id="Country-label"> - <label class="optional" for="Country"><?php echo $this->element->getElement('Country')->getLabel() ?></label> - </dt> - <dd id="Country-element"> - <?php echo $this->element->getElement('Country') ?> - <?php if($this->element->getElement('Country')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('Country')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt id="City-label"> - <label class="optional" for="City"><?php echo $this->element->getElement('City')->getLabel() ?></label> - </dt> - <dd id="City-element"> - <?php echo $this->element->getElement('City') ?> - <?php if($this->element->getElement('City')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('City')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt id="Description-label"> - <label class="optional" for="Description"><?php echo $this->element->getElement('Description')->getLabel() ?></label> - </dt> - <dd id="Description-element"> - <?php echo $this->element->getElement('Description') ?> - <?php if($this->element->getElement('Description')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('Description')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - <dt id="Logo-label" class="block-display"> - <label class="optional" for="Description"><?php echo $this->element->getElement('Logo')->getLabel() ?></label> - </dt> - - <dd id="Logo-element"> - <?php if($this->element->getView()->logoImg){?> - <div id="Logo-img-container"><img id="logo-img" onload='resizeImg(this, 450, 450);' src="data:image/png;base64,<?php echo $this->element->getView()->logoImg ?>" /></div> - <?php }?> - - <?php echo $this->element->getElement('Logo') ?> - <p class="info-text">Note: Anything larger than 600x600 will be resized.</p> - <?php if($this->element->getElement('Logo')->hasErrors()) : ?> - <ul class='errors'> - <?php foreach($this->element->getElement('Logo')->getMessages() as $error): ?> - <li><?php echo $error; ?></li> - <?php endforeach; ?> - </ul> - <?php endif; ?> - </dd> - </dl> - </fieldset> - - <div id="show_what_sending" style="display: block;"> - <fieldset class="display_field toggle closed"> - <legend style="cursor: pointer;"><span class="ui-icon ui-icon-triangle-2-n-s"></span>Show me what I am sending </legend> - <dl> - <?php echo $this->element->getElement('SendInfo') ?> - </dl> - </fieldset> - </div> - <div> - <br> - <?php if(!$this->privacyChecked){?> - <label class="optional" for="Privacy"> - <?php echo $this->element->getElement('Privacy') ?> - <?php echo $this->element->getElement('Privacy')->getLabel() ?> - </label> - <?php }else{?> - <a id="link_to_terms_and_condition" href="http://www.sourcefabric.org/en/about/policy/" onclick="window.open(this.href); return false;">Terms and Conditions</a> - <?php }?> - </div> - </form> -</div> +<div id="register_popup" class="dialogPopup register-dialog" title="Register Airtime" style="display: none;"> + <form id="register-form" method="<?php echo $this->element->getMethod() ?>" action="<?php echo $this->element->getAction() ?>" enctype="multipart/form-data"> + <fieldset> + <dl class="zend_form"> + <dt class="block-display info-text"> + Help Airtime improve by letting us know how you are using it. This info + will be collected regularly in order to enhance your user experience. + <br /><br /> + Click "Yes, help Airtime" and we'll make sure the features you use are + constantly improving. + </dt> + <dd id="SupportFeedback-element" class="block-display"> + <label class="optional" for="SupportFeedback"> + <?php echo $this->element->getElement('SupportFeedback') ?> + <strong><?php echo $this->element->getElement('SupportFeedback')->getLabel() ?></strong> + </label> + <?php if($this->element->getElement('SupportFeedback')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('SupportFeedback')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt class="block-display info-text"> + Click the box below to advertise your station on + <a id="link_to_whos_using" href="http://sourcefabric.org/en/airtime/whosusing" onclick="window.open(this.href); return false">Sourcefabric.org</a>. + In order to promote your station, "Send support feedback" must be enabled. This data will be collected in addition to the support feedback. + </dt> + <dd id="publicize-element" class="block-display"> + <label class="optional" for="Publicise"> + <?php echo $this->element->getElement('Publicise') ?> + <strong><?php echo $this->element->getElement('Publicise')->getLabel() ?></strong> + </label> + <?php if($this->element->getElement('Publicise')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('Publicise')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + </dl> + <dl id="public-info" style="display:none;"> + <dt id="stnName-label"> + <label class="optional" for="stnName"><?php echo $this->element->getElement('stnName')->getLabel() ?> + <span class="info-text-small">(Required)</span> : + </label> + </dt> + <dd id="stnName-element"> + <?php echo $this->element->getElement('stnName') ?> + <?php if($this->element->getElement('stnName')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('stnName')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt id="Phone-label"> + <label class="optional" for="Phone"><?php echo $this->element->getElement('Phone')->getLabel() ?></label> + </dt> + <dd id="Phone-element"> + <?php echo $this->element->getElement('Phone') ?> + <span class="info-text-small">(for verification purposes only, will not be published)</span> + <?php if($this->element->getElement('Phone')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('Phone')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt id="Email-label"> + <label class="optional" for="Email"><?php echo $this->element->getElement('Email')->getLabel() ?></label> + </dt> + <dd id="Email-element"> + <?php echo $this->element->getElement('Email') ?> + <span class="info-text-small">(for verification purposes only, will not be published)</span> + <?php if($this->element->getElement('Email')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('Email')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt id="StationWebSite-label"> + <label class="optional" for="StationWebSite"><?php echo $this->element->getElement('StationWebSite')->getLabel() ?></label> + </dt> + <dd id="StationWebSite-element"> + <?php echo $this->element->getElement('StationWebSite') ?> + <?php if($this->element->getElement('StationWebSite')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('StationWebSite')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt id="Country-label"> + <label class="optional" for="Country"><?php echo $this->element->getElement('Country')->getLabel() ?></label> + </dt> + <dd id="Country-element"> + <?php echo $this->element->getElement('Country') ?> + <?php if($this->element->getElement('Country')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('Country')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt id="City-label"> + <label class="optional" for="City"><?php echo $this->element->getElement('City')->getLabel() ?></label> + </dt> + <dd id="City-element"> + <?php echo $this->element->getElement('City') ?> + <?php if($this->element->getElement('City')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('City')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt id="Description-label"> + <label class="optional" for="Description"><?php echo $this->element->getElement('Description')->getLabel() ?></label> + </dt> + <dd id="Description-element"> + <?php echo $this->element->getElement('Description') ?> + <?php if($this->element->getElement('Description')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('Description')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + <dt id="Logo-label" class="block-display"> + <label class="optional" for="Description"><?php echo $this->element->getElement('Logo')->getLabel() ?></label> + </dt> + + <dd id="Logo-element"> + <?php if($this->element->getView()->logoImg){?> + <div id="Logo-img-container"><img id="logo-img" onload='resizeImg(this, 450, 450);' src="data:image/png;base64,<?php echo $this->element->getView()->logoImg ?>" /></div> + <?php }?> + + <?php echo $this->element->getElement('Logo') ?> + <p class="info-text">Note: Anything larger than 600x600 will be resized.</p> + <?php if($this->element->getElement('Logo')->hasErrors()) : ?> + <ul class='errors'> + <?php foreach($this->element->getElement('Logo')->getMessages() as $error): ?> + <li><?php echo $error; ?></li> + <?php endforeach; ?> + </ul> + <?php endif; ?> + </dd> + </dl> + </fieldset> + + <div id="show_what_sending" style="display: block;"> + <fieldset class="display_field toggle closed"> + <legend style="cursor: pointer;"><span class="ui-icon ui-icon-triangle-2-n-s"></span>Show me what I am sending </legend> + <dl> + <?php echo $this->element->getElement('SendInfo') ?> + </dl> + </fieldset> + </div> + <div> + <br> + <?php if(!$this->privacyChecked){?> + <label class="optional" for="Privacy"> + <?php echo $this->element->getElement('Privacy') ?> + <?php echo $this->element->getElement('Privacy')->getLabel() ?> + </label> + <?php }else{?> + <a id="link_to_terms_and_condition" href="http://www.sourcefabric.org/en/about/policy/" onclick="window.open(this.href); return false;">Terms and Conditions</a> + <?php }?> + </div> + </form> +</div> diff --git a/airtime_mvc/application/views/scripts/schedule/show-list.phtml b/airtime_mvc/application/views/scripts/schedule/show-list.phtml index 992701db3..939ab6afd 100644 --- a/airtime_mvc/application/views/scripts/schedule/show-list.phtml +++ b/airtime_mvc/application/views/scripts/schedule/show-list.phtml @@ -1,2 +1,2 @@ -<div id='json-string'></div> +<div id='json-string'></div> <div id='demo'></div> \ No newline at end of file diff --git a/airtime_mvc/public/css/add-show.css b/airtime_mvc/public/css/add-show.css index 0dd479a3c..4ca5dc469 100644 --- a/airtime_mvc/public/css/add-show.css +++ b/airtime_mvc/public/css/add-show.css @@ -1,129 +1,129 @@ -#schedule-add-show, -#fullcalendar_show_display { - float: left; -} - -#schedule-add-show { - font-size: 12px; - /*width: 25%;*/ - width:310px; -} - -#schedule-add-show textarea { - width: 99%; - height: 80px; -} - -#fullcalendar_show_display { - width: 60%; -} - - - -#schedule-add-show .ui-tabs-panel { - padding-top: 8px; -} -#schedule-add-show fieldset { - padding:8px; - margin-bottom:8px; -} - -#schedule-add-show dl { - padding:8px; - margin-bottom:8px; - margin:0; - padding:0; - width:100%; -} -#schedule-add-show dd { - padding: 4px 0; - float: left; - font-size: 1.2em; - margin: 0; - padding: 4px 0 4px 15px; -} -#schedule-add-show dt, #schedule-add-show dt.big { - clear: left; - color: #666666; - float: left; - font-size: 1.2em; - font-weight: bold; - margin: 0; - padding: 4px 0; - text-align: left; - min-width:103px; - clear:left; -} -#schedule-add-show dt.big { - min-width:130px; -} -#schedule-add-show dt.block-display, #schedule-add-show dd.block-display { - display:block; - float:none; - margin-left:0; - padding-left:0; -} - -#schedule-add-show dt label { - padding-right:0; -} -.wrapp-label { - padding:0; - height:16px; - display:block; - line-height:18px; -} -label.wrapp-label input[type="checkbox"] { - float:left; - margin:-1px 2px 0 0; -} - -#schedule-add-show fieldset:last-child { - margin-bottom:0; -} -#schedule-add-show fieldset dd input[type="checkbox"] { - margin-top:2px; -} -#add_show_day_check-element.block-display { - margin-bottom:15px; - margin-top:7px; -} -#add_show_day_check-element.block-display label.wrapp-label { - font-size:12px; - float:left; - margin-right:10px; -} -#add_show_name-element .input_text { - /*width:99%;*/ -} - -#schedule-add-show-overlap { - border: 1px solid #c83f3f; - background: #c6b4b4; - margin-top:8px; - padding:8px; - color:#902d2d; - display:none; -} - -#add_show_hosts-element { - max-height: 80px; - min-width: 150px; - overflow: auto; -} - -#add_show_start_time, #add_show_end_time { - width: 54px; - margin-left:10px; -} - -#add_show_end_date_no_repeat, #add_show_start_date { - width: 89px; - -} - -#add_show_duration { - background: #AAAAAA; - cursor: default; - width: 65px; -} +#schedule-add-show, +#fullcalendar_show_display { + float: left; +} + +#schedule-add-show { + font-size: 12px; + /*width: 25%;*/ + width:310px; +} + +#schedule-add-show textarea { + width: 99%; + height: 80px; +} + +#fullcalendar_show_display { + width: 60%; +} + + + +#schedule-add-show .ui-tabs-panel { + padding-top: 8px; +} +#schedule-add-show fieldset { + padding:8px; + margin-bottom:8px; +} + +#schedule-add-show dl { + padding:8px; + margin-bottom:8px; + margin:0; + padding:0; + width:100%; +} +#schedule-add-show dd { + padding: 4px 0; + float: left; + font-size: 1.2em; + margin: 0; + padding: 4px 0 4px 15px; +} +#schedule-add-show dt, #schedule-add-show dt.big { + clear: left; + color: #666666; + float: left; + font-size: 1.2em; + font-weight: bold; + margin: 0; + padding: 4px 0; + text-align: left; + min-width:103px; + clear:left; +} +#schedule-add-show dt.big { + min-width:130px; +} +#schedule-add-show dt.block-display, #schedule-add-show dd.block-display { + display:block; + float:none; + margin-left:0; + padding-left:0; +} + +#schedule-add-show dt label { + padding-right:0; +} +.wrapp-label { + padding:0; + height:16px; + display:block; + line-height:18px; +} +label.wrapp-label input[type="checkbox"] { + float:left; + margin:-1px 2px 0 0; +} + +#schedule-add-show fieldset:last-child { + margin-bottom:0; +} +#schedule-add-show fieldset dd input[type="checkbox"] { + margin-top:2px; +} +#add_show_day_check-element.block-display { + margin-bottom:15px; + margin-top:7px; +} +#add_show_day_check-element.block-display label.wrapp-label { + font-size:12px; + float:left; + margin-right:10px; +} +#add_show_name-element .input_text { + /*width:99%;*/ +} + +#schedule-add-show-overlap { + border: 1px solid #c83f3f; + background: #c6b4b4; + margin-top:8px; + padding:8px; + color:#902d2d; + display:none; +} + +#add_show_hosts-element { + max-height: 80px; + min-width: 150px; + overflow: auto; +} + +#add_show_start_time, #add_show_end_time { + width: 54px; + margin-left:10px; +} + +#add_show_end_date_no_repeat, #add_show_start_date { + width: 89px; + +} + +#add_show_duration { + background: #AAAAAA; + cursor: default; + width: 65px; +} diff --git a/airtime_mvc/public/css/colorpicker/css/colorpicker.css b/airtime_mvc/public/css/colorpicker/css/colorpicker.css index d704c4c64..9b449e780 100644 --- a/airtime_mvc/public/css/colorpicker/css/colorpicker.css +++ b/airtime_mvc/public/css/colorpicker/css/colorpicker.css @@ -1,162 +1,162 @@ -.colorpicker { - width: 356px; - height: 176px; - overflow: hidden; - position: absolute; - background: url(../images/colorpicker_background.png); - font-family: Arial, Helvetica, sans-serif; - display: none; - z-index: 1003; /* so it can display above the jQuery dialog*/ -} -.colorpicker_color { - width: 150px; - height: 150px; - left: 14px; - top: 13px; - position: absolute; - background: #f00; - overflow: hidden; - cursor: crosshair; -} -.colorpicker_color div { - position: absolute; - top: 0; - left: 0; - width: 150px; - height: 150px; - background: url(../images/colorpicker_overlay.png); -} -.colorpicker_color div div { - position: absolute; - top: 0; - left: 0; - width: 11px; - height: 11px; - overflow: hidden; - background: url(../images/colorpicker_select.gif); - margin: -5px 0 0 -5px; -} -.colorpicker_hue { - position: absolute; - top: 13px; - left: 171px; - width: 35px; - height: 150px; - cursor: n-resize; -} -.colorpicker_hue div { - position: absolute; - width: 35px; - height: 9px; - overflow: hidden; - background: url(../images/colorpicker_indic.gif) left top; - margin: -4px 0 0 0; - left: 0px; -} -.colorpicker_new_color { - position: absolute; - width: 60px; - height: 30px; - left: 213px; - top: 13px; - background: #f00; -} -.colorpicker_current_color { - position: absolute; - width: 60px; - height: 30px; - left: 283px; - top: 13px; - background: #f00; -} -.colorpicker input { - background-color: transparent; - border: 1px solid transparent; - position: absolute; - font-size: 10px; - font-family: Arial, Helvetica, sans-serif; - color: #898989; - top: 4px; - right: 11px; - text-align: right; - margin: 0; - padding: 0; - height: 11px; -} -.colorpicker_hex { - position: absolute; - width: 72px; - height: 22px; - background: url(../images/colorpicker_hex.png) top; - left: 212px; - top: 142px; -} -.colorpicker_hex input { - right: 6px; -} -.colorpicker_field { - height: 22px; - width: 62px; - background-position: top; - position: absolute; -} -.colorpicker_field span { - position: absolute; - width: 12px; - height: 22px; - overflow: hidden; - top: 0; - right: 0; - cursor: n-resize; -} -.colorpicker_rgb_r { - background-image: url(../images/colorpicker_rgb_r.png); - top: 52px; - left: 212px; -} -.colorpicker_rgb_g { - background-image: url(../images/colorpicker_rgb_g.png); - top: 82px; - left: 212px; -} -.colorpicker_rgb_b { - background-image: url(../images/colorpicker_rgb_b.png); - top: 112px; - left: 212px; -} -.colorpicker_hsb_h { - background-image: url(../images/colorpicker_hsb_h.png); - top: 52px; - left: 282px; -} -.colorpicker_hsb_s { - background-image: url(../images/colorpicker_hsb_s.png); - top: 82px; - left: 282px; -} -.colorpicker_hsb_b { - background-image: url(../images/colorpicker_hsb_b.png); - top: 112px; - left: 282px; -} -.colorpicker_submit { - position: absolute; - width: 22px; - height: 22px; - background: url(../images/colorpicker_submit.png) top; - left: 322px; - top: 142px; - overflow: hidden; -} -.colorpicker_focus { - background-position: center; -} -.colorpicker_hex.colorpicker_focus { - background-position: bottom; -} -.colorpicker_submit.colorpicker_focus { - background-position: bottom; -} -.colorpicker_slider { - background-position: bottom; -} +.colorpicker { + width: 356px; + height: 176px; + overflow: hidden; + position: absolute; + background: url(../images/colorpicker_background.png); + font-family: Arial, Helvetica, sans-serif; + display: none; + z-index: 1003; /* so it can display above the jQuery dialog*/ +} +.colorpicker_color { + width: 150px; + height: 150px; + left: 14px; + top: 13px; + position: absolute; + background: #f00; + overflow: hidden; + cursor: crosshair; +} +.colorpicker_color div { + position: absolute; + top: 0; + left: 0; + width: 150px; + height: 150px; + background: url(../images/colorpicker_overlay.png); +} +.colorpicker_color div div { + position: absolute; + top: 0; + left: 0; + width: 11px; + height: 11px; + overflow: hidden; + background: url(../images/colorpicker_select.gif); + margin: -5px 0 0 -5px; +} +.colorpicker_hue { + position: absolute; + top: 13px; + left: 171px; + width: 35px; + height: 150px; + cursor: n-resize; +} +.colorpicker_hue div { + position: absolute; + width: 35px; + height: 9px; + overflow: hidden; + background: url(../images/colorpicker_indic.gif) left top; + margin: -4px 0 0 0; + left: 0px; +} +.colorpicker_new_color { + position: absolute; + width: 60px; + height: 30px; + left: 213px; + top: 13px; + background: #f00; +} +.colorpicker_current_color { + position: absolute; + width: 60px; + height: 30px; + left: 283px; + top: 13px; + background: #f00; +} +.colorpicker input { + background-color: transparent; + border: 1px solid transparent; + position: absolute; + font-size: 10px; + font-family: Arial, Helvetica, sans-serif; + color: #898989; + top: 4px; + right: 11px; + text-align: right; + margin: 0; + padding: 0; + height: 11px; +} +.colorpicker_hex { + position: absolute; + width: 72px; + height: 22px; + background: url(../images/colorpicker_hex.png) top; + left: 212px; + top: 142px; +} +.colorpicker_hex input { + right: 6px; +} +.colorpicker_field { + height: 22px; + width: 62px; + background-position: top; + position: absolute; +} +.colorpicker_field span { + position: absolute; + width: 12px; + height: 22px; + overflow: hidden; + top: 0; + right: 0; + cursor: n-resize; +} +.colorpicker_rgb_r { + background-image: url(../images/colorpicker_rgb_r.png); + top: 52px; + left: 212px; +} +.colorpicker_rgb_g { + background-image: url(../images/colorpicker_rgb_g.png); + top: 82px; + left: 212px; +} +.colorpicker_rgb_b { + background-image: url(../images/colorpicker_rgb_b.png); + top: 112px; + left: 212px; +} +.colorpicker_hsb_h { + background-image: url(../images/colorpicker_hsb_h.png); + top: 52px; + left: 282px; +} +.colorpicker_hsb_s { + background-image: url(../images/colorpicker_hsb_s.png); + top: 82px; + left: 282px; +} +.colorpicker_hsb_b { + background-image: url(../images/colorpicker_hsb_b.png); + top: 112px; + left: 282px; +} +.colorpicker_submit { + position: absolute; + width: 22px; + height: 22px; + background: url(../images/colorpicker_submit.png) top; + left: 322px; + top: 142px; + overflow: hidden; +} +.colorpicker_focus { + background-position: center; +} +.colorpicker_hex.colorpicker_focus { + background-position: bottom; +} +.colorpicker_submit.colorpicker_focus { + background-position: bottom; +} +.colorpicker_slider { + background-position: bottom; +} diff --git a/airtime_mvc/public/css/jquery.ui.timepicker.css b/airtime_mvc/public/css/jquery.ui.timepicker.css index 374da6bbb..01f57a5a9 100644 --- a/airtime_mvc/public/css/jquery.ui.timepicker.css +++ b/airtime_mvc/public/css/jquery.ui.timepicker.css @@ -1,72 +1,72 @@ -/* - * Timepicker stylesheet - * Highly inspired from datepicker - * FG - Nov 2010 - Web3R - * - * version 0.0.3 : Fixed some settings, more dynamic - * version 0.0.4 : Removed width:100% on tables - * version 0.1.1 : set width 0 on tables to fix an ie6 bug - */ - -.ui-timepicker-inline { display: inline; } - -#ui-timepicker-div { - padding: 0.2em; - z-index: 1000; -} -.ui-timepicker-table { display: inline-table; width: 0; } -.ui-timepicker-table table { margin:0.15em 0 0 0; border-collapse: collapse; } - -.ui-timepicker-hours, .ui-timepicker-minutes { padding: 0.2em; } - -.ui-timepicker-table .ui-timepicker-title { line-height: 1.8em; text-align: center; } -.ui-timepicker-table td { padding: 0.1em; width: 2.2em; } -.ui-timepicker-table th.periods { padding: 0.1em; width: 2.2em; } - -/* span for disabled cells */ -.ui-timepicker-table td span { - display:block; - padding:0.2em 0.3em 0.2em 0.5em; - width: 1.2em; - - text-align:right; - text-decoration:none; -} -/* anchors for clickable cells */ -.ui-timepicker-table td a { - display:block; - padding:0.2em 0.3em 0.2em 0.5em; - width: 1.2em; - cursor: pointer; - text-align:right; - text-decoration:none; -} - - -/* buttons and button pane styling */ -.ui-timepicker .ui-timepicker-buttonpane { - background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; -} -.ui-timepicker .ui-timepicker-buttonpane button { margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } -/* The close button */ -.ui-timepicker .ui-timepicker-close { float: right } - -/* the now button */ -.ui-timepicker .ui-timepicker-now { float: left; } - -/* the deselect button */ -.ui-timepicker .ui-timepicker-deselect { float: left; } - - -/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ -.ui-timepicker-cover { - display: none; /*sorry for IE5*/ - display/**/: block; /*sorry for IE5*/ - position: absolute; /*must have*/ - z-index: -1; /*must have*/ - filter: mask(); /*must have*/ - top: -4px; /*must have*/ - left: -4px; /*must have*/ - width: 200px; /*must have*/ - height: 200px; /*must have*/ +/* + * Timepicker stylesheet + * Highly inspired from datepicker + * FG - Nov 2010 - Web3R + * + * version 0.0.3 : Fixed some settings, more dynamic + * version 0.0.4 : Removed width:100% on tables + * version 0.1.1 : set width 0 on tables to fix an ie6 bug + */ + +.ui-timepicker-inline { display: inline; } + +#ui-timepicker-div { + padding: 0.2em; + z-index: 1000; +} +.ui-timepicker-table { display: inline-table; width: 0; } +.ui-timepicker-table table { margin:0.15em 0 0 0; border-collapse: collapse; } + +.ui-timepicker-hours, .ui-timepicker-minutes { padding: 0.2em; } + +.ui-timepicker-table .ui-timepicker-title { line-height: 1.8em; text-align: center; } +.ui-timepicker-table td { padding: 0.1em; width: 2.2em; } +.ui-timepicker-table th.periods { padding: 0.1em; width: 2.2em; } + +/* span for disabled cells */ +.ui-timepicker-table td span { + display:block; + padding:0.2em 0.3em 0.2em 0.5em; + width: 1.2em; + + text-align:right; + text-decoration:none; +} +/* anchors for clickable cells */ +.ui-timepicker-table td a { + display:block; + padding:0.2em 0.3em 0.2em 0.5em; + width: 1.2em; + cursor: pointer; + text-align:right; + text-decoration:none; +} + + +/* buttons and button pane styling */ +.ui-timepicker .ui-timepicker-buttonpane { + background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; +} +.ui-timepicker .ui-timepicker-buttonpane button { margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } +/* The close button */ +.ui-timepicker .ui-timepicker-close { float: right } + +/* the now button */ +.ui-timepicker .ui-timepicker-now { float: left; } + +/* the deselect button */ +.ui-timepicker .ui-timepicker-deselect { float: left; } + + +/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ +.ui-timepicker-cover { + display: none; /*sorry for IE5*/ + display/**/: block; /*sorry for IE5*/ + position: absolute; /*must have*/ + z-index: -1; /*must have*/ + filter: mask(); /*must have*/ + top: -4px; /*must have*/ + left: -4px; /*must have*/ + width: 200px; /*must have*/ + height: 200px; /*must have*/ } \ No newline at end of file diff --git a/airtime_mvc/public/css/plupload.queue.css b/airtime_mvc/public/css/plupload.queue.css index 3766a71f7..3d5f8d042 100644 --- a/airtime_mvc/public/css/plupload.queue.css +++ b/airtime_mvc/public/css/plupload.queue.css @@ -1,176 +1,176 @@ -/* - Plupload -------------------------------------------------------------------- */ - -.plupload_button { - display: -moz-inline-box; /* FF < 3*/ - display: inline-block; - font: normal 12px sans-serif; - text-decoration: none; - color: #42454a; - border: 1px solid #bababa; - padding: 2px 8px 3px 20px; - margin-right: 4px; - background: #f3f3f3 url('img/buttons.png') no-repeat 0 center; - outline: 0; - - /* Optional rounded corners for browsers that support it */ - -moz-border-radius: 3px; - -khtml-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; -} - -.plupload_button:hover { - color: #000; - text-decoration: none; -} - -.plupload_disabled, a.plupload_disabled:hover { - color: #737373; - border-color: #c5c5c5; - background: #ededed url('img/buttons-disabled.png') no-repeat 0 center; - cursor: default; -} - -.plupload_add { - background-position: -181px center; -} - -.plupload_wrapper { - font: normal 11px Verdana,sans-serif; - width: 100%; -} - -.plupload_container { - padding: 8px; - background: url('img/transp50.png'); - /*-moz-border-radius: 5px;*/ -} - -.plupload_container input { - border: 1px solid #DDD; - font: normal 11px Verdana,sans-serif; - width: 98%; -} - -.plupload_header {background: #2A2C2E url('img/backgrounds.gif') repeat-x;} -.plupload_header_content { - min-height: 56px; - padding-left: 10px; - color: #FFF; -} -.plupload_header_title { - font: normal 18px sans-serif; - padding: 6px 0 3px; -} -.plupload_header_text { - font: normal 12px sans-serif; -} - -.plupload_filelist { - margin: 0; - padding: 0; - list-style: none; -} - -.plupload_scroll .plupload_filelist { - height: 185px; - background: #F5F5F5; - overflow-y: scroll; -} - -.plupload_filelist li { - padding: 10px 8px; - background: #F5F5F5 url('img/backgrounds.gif') repeat-x 0 -156px; - border-bottom: 1px solid #DDD; -} - -.plupload_filelist_header, .plupload_filelist_footer { - background: #DFDFDF; - padding: 8px 8px; - color: #42454A; -} -.plupload_filelist_header { - border-top: 1px solid #EEE; - border-bottom: 1px solid #CDCDCD; -} - -.plupload_filelist_footer {border-top: 1px solid #FFF; height: 22px; line-height: 20px; vertical-align: middle;} -.plupload_file_name {float: left; overflow: hidden} -.plupload_file_status {color: #777;} -.plupload_file_status span {color: #42454A;} -.plupload_file_size, .plupload_file_status, .plupload_progress { - float: right; - width: 80px; -} -.plupload_file_size, .plupload_file_status, .plupload_file_action {text-align: right;} - -.plupload_filelist .plupload_file_name {width: 68%;} - -.plupload_file_action { - float: right; - width: 16px; - height: 16px; - margin-left: 15px; -} - -.plupload_file_action * { - display: none; - width: 16px; - height: 16px; -} - -li.plupload_uploading {background: #ECF3DC url('img/backgrounds.gif') repeat-x 0 -238px;} -li.plupload_done {color:#AAA} - -li.plupload_delete a { - background: url('img/delete.gif'); -} - -li.plupload_failed a { - background: url('img/error.gif'); - cursor: default; -} - -li.plupload_done a { - background: url('img/done.gif'); - cursor: default; -} - -.plupload_progress, .plupload_upload_status { - display: none; -} - -.plupload_progress_container { - margin-top: 3px; - border: 1px solid #CCC; - background: #FFF; - padding: 1px; -} -.plupload_progress_bar { - width: 0px; - height: 7px; - background: #CDEB8B; -} - -.plupload_scroll .plupload_filelist_header .plupload_file_action, .plupload_scroll .plupload_filelist_footer .plupload_file_action { - margin-right: 17px; -} - -/* Floats */ - -.plupload_clear,.plupload_clearer {clear: both;} -.plupload_clearer, .plupload_progress_bar { - display: block; - font-size: 0; - line-height: 0; -} - -li.plupload_droptext { - background: transparent; - text-align: center; - vertical-align: middle; - border: 0; - line-height: 165px; -} +/* + Plupload +------------------------------------------------------------------- */ + +.plupload_button { + display: -moz-inline-box; /* FF < 3*/ + display: inline-block; + font: normal 12px sans-serif; + text-decoration: none; + color: #42454a; + border: 1px solid #bababa; + padding: 2px 8px 3px 20px; + margin-right: 4px; + background: #f3f3f3 url('img/buttons.png') no-repeat 0 center; + outline: 0; + + /* Optional rounded corners for browsers that support it */ + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} + +.plupload_button:hover { + color: #000; + text-decoration: none; +} + +.plupload_disabled, a.plupload_disabled:hover { + color: #737373; + border-color: #c5c5c5; + background: #ededed url('img/buttons-disabled.png') no-repeat 0 center; + cursor: default; +} + +.plupload_add { + background-position: -181px center; +} + +.plupload_wrapper { + font: normal 11px Verdana,sans-serif; + width: 100%; +} + +.plupload_container { + padding: 8px; + background: url('img/transp50.png'); + /*-moz-border-radius: 5px;*/ +} + +.plupload_container input { + border: 1px solid #DDD; + font: normal 11px Verdana,sans-serif; + width: 98%; +} + +.plupload_header {background: #2A2C2E url('img/backgrounds.gif') repeat-x;} +.plupload_header_content { + min-height: 56px; + padding-left: 10px; + color: #FFF; +} +.plupload_header_title { + font: normal 18px sans-serif; + padding: 6px 0 3px; +} +.plupload_header_text { + font: normal 12px sans-serif; +} + +.plupload_filelist { + margin: 0; + padding: 0; + list-style: none; +} + +.plupload_scroll .plupload_filelist { + height: 185px; + background: #F5F5F5; + overflow-y: scroll; +} + +.plupload_filelist li { + padding: 10px 8px; + background: #F5F5F5 url('img/backgrounds.gif') repeat-x 0 -156px; + border-bottom: 1px solid #DDD; +} + +.plupload_filelist_header, .plupload_filelist_footer { + background: #DFDFDF; + padding: 8px 8px; + color: #42454A; +} +.plupload_filelist_header { + border-top: 1px solid #EEE; + border-bottom: 1px solid #CDCDCD; +} + +.plupload_filelist_footer {border-top: 1px solid #FFF; height: 22px; line-height: 20px; vertical-align: middle;} +.plupload_file_name {float: left; overflow: hidden} +.plupload_file_status {color: #777;} +.plupload_file_status span {color: #42454A;} +.plupload_file_size, .plupload_file_status, .plupload_progress { + float: right; + width: 80px; +} +.plupload_file_size, .plupload_file_status, .plupload_file_action {text-align: right;} + +.plupload_filelist .plupload_file_name {width: 68%;} + +.plupload_file_action { + float: right; + width: 16px; + height: 16px; + margin-left: 15px; +} + +.plupload_file_action * { + display: none; + width: 16px; + height: 16px; +} + +li.plupload_uploading {background: #ECF3DC url('img/backgrounds.gif') repeat-x 0 -238px;} +li.plupload_done {color:#AAA} + +li.plupload_delete a { + background: url('img/delete.gif'); +} + +li.plupload_failed a { + background: url('img/error.gif'); + cursor: default; +} + +li.plupload_done a { + background: url('img/done.gif'); + cursor: default; +} + +.plupload_progress, .plupload_upload_status { + display: none; +} + +.plupload_progress_container { + margin-top: 3px; + border: 1px solid #CCC; + background: #FFF; + padding: 1px; +} +.plupload_progress_bar { + width: 0px; + height: 7px; + background: #CDEB8B; +} + +.plupload_scroll .plupload_filelist_header .plupload_file_action, .plupload_scroll .plupload_filelist_footer .plupload_file_action { + margin-right: 17px; +} + +/* Floats */ + +.plupload_clear,.plupload_clearer {clear: both;} +.plupload_clearer, .plupload_progress_bar { + display: block; + font-size: 0; + line-height: 0; +} + +li.plupload_droptext { + background: transparent; + text-align: center; + vertical-align: middle; + border: 0; + line-height: 165px; +} diff --git a/airtime_mvc/public/css/pro_dropdown_3.css b/airtime_mvc/public/css/pro_dropdown_3.css index f83211876..ad31500ae 100644 --- a/airtime_mvc/public/css/pro_dropdown_3.css +++ b/airtime_mvc/public/css/pro_dropdown_3.css @@ -1,185 +1,185 @@ -/* ================================================================ -This copyright notice must be kept untouched in the stylesheet at -all times. - -The original version of this stylesheet and the associated (x)html -is available at http://www.stunicholls.com/menu/pro_dropdown_3.html -Copyright (c) 2005-2007 Stu Nicholls. All rights reserved. -This stylesheet and the associated (x)html may be modified in any -way to fit your requirements. -=================================================================== */ - -#nav { - padding:7px 0 0 6px; - margin:0; - list-style:none; - height:28px; - background:#353535; - position:relative; - z-index:500; - font-family:Arial, Helvetica, sans-serif; - border-top:1px solid #7e7e7e; - border-bottom:1px solid #242424; - -moz-box-shadow: 0 2px 5px rgba(0,0,0,.35); - -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.35); - box-shadow: 0 2px 5px rgba(0,0,0,.35); -} -#nav li.top { - display:block; - float:left; - margin:0 5px 0 0; -} -#nav li a.top_link { - display:block; - float:left; - height:18px; - color:#ccc; - text-decoration:none; - font-size:11px; - text-transform:uppercase; - font-weight:bold; - padding:4px 0 0 14px; - cursor:pointer; -} -#nav li a.top_link span { - float:left; - display:block; - padding:0 14px 0 0; -} -#nav li a.top_link span.down { - float:left; - display:block; - padding:0 28px 0 0px; - background:url(images/down_arrow.png) no-repeat right 50%; - -} -#nav li:hover a.top_link, #nav li.active a.top_link, #nav li.active:hover a.top_link { - color:#fff; - background:#000; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; -} -#nav li:hover a.top_link span { - -} -#nav li:hover a.top_link span.down { - background:url(images/down_arrow.png) no-repeat right 50%; -} -/* Default list styling */ - -#nav li:hover { - position:relative; - z-index:200; -} -#nav li:hover ul.sub { - left:1px; - top:22px; - background: #202020; - padding:3px; - border:1px solid #161616; - white-space:nowrap; - width:200px; - height:auto; - z-index:300; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; - -} -#nav li:hover ul.sub li { - display:block; - height:22px; - position:relative; - float:left; - width:200px; - font-weight:normal; -} -#nav li:hover ul.sub li a { - display:block; - font-size:12px; - height:20px; - width:198px; - line-height:20px; - text-indent:5px; - color:#fff; - text-decoration:none; - border:1px solid #202020; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - border-radius: 2px; -} -#nav li ul.sub li a.fly { - background:#202020 url(images/arrow.png) 190px 6px no-repeat; -} -#nav li:hover ul.sub li a:hover { - background:#3d3d3d; - color:#fff; - border-color:#4e4e4e; -} -#nav li:hover ul.sub li a.fly:hover { - background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; - color:#fff; -} -#nav li strong { - display:block; - font-size:12px; - height:20px; - width:198px; - line-height:20px; - margin-bottom:3px; - text-indent:6px; - color:#ff5d1a; - border-bottom:1px solid #414141; - cursor:default; - font-weight:bold; -} -#nav li:hover li:hover ul, #nav li:hover li:hover li:hover ul, #nav li:hover li:hover li:hover li:hover ul, #nav li:hover li:hover li:hover li:hover li:hover ul { - left:200px; - top:-4px; - background: #202020; - padding:3px; - border:1px solid #161616; - white-space:nowrap; - width:200px; - z-index:400; - height:auto; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; -} -#nav ul, #nav li:hover ul ul, #nav li:hover li:hover ul ul, #nav li:hover li:hover li:hover ul ul, #nav li:hover li:hover li:hover li:hover ul ul { - position:absolute; - left:-9999px; - top:-9999px; - width:0; - height:0; - margin:0; - padding:0; - list-style:none; -} -#nav li:hover li:hover a.fly, #nav li:hover li:hover li:hover a.fly, #nav li:hover li:hover li:hover li:hover a.fly, #nav li:hover li:hover li:hover li:hover li:hover a.fly { - background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; - color:#fff; - border-color:#4e4e4e; -} - - -#nav li:hover li:hover li:hover a.fly { - background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; - color:#fff; - border-color:#4e4e4e; -} -#nav li:hover li:hover li:hover li:hover li:hover a.fly { - background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; - color:#fff; - border-color:#4e4e4e; -} -#nav li:hover li:hover li a.fly, -#nav li:hover li:hover li:hover li a.fly, -#nav li:hover li:hover li:hover li:hover li a.fly { - background:#202020 url(images/arrow.png) 190px 6px no-repeat; - color:#fff; - border-color:#202020; -} - +/* ================================================================ +This copyright notice must be kept untouched in the stylesheet at +all times. + +The original version of this stylesheet and the associated (x)html +is available at http://www.stunicholls.com/menu/pro_dropdown_3.html +Copyright (c) 2005-2007 Stu Nicholls. All rights reserved. +This stylesheet and the associated (x)html may be modified in any +way to fit your requirements. +=================================================================== */ + +#nav { + padding:7px 0 0 6px; + margin:0; + list-style:none; + height:28px; + background:#353535; + position:relative; + z-index:500; + font-family:Arial, Helvetica, sans-serif; + border-top:1px solid #7e7e7e; + border-bottom:1px solid #242424; + -moz-box-shadow: 0 2px 5px rgba(0,0,0,.35); + -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.35); + box-shadow: 0 2px 5px rgba(0,0,0,.35); +} +#nav li.top { + display:block; + float:left; + margin:0 5px 0 0; +} +#nav li a.top_link { + display:block; + float:left; + height:18px; + color:#ccc; + text-decoration:none; + font-size:11px; + text-transform:uppercase; + font-weight:bold; + padding:4px 0 0 14px; + cursor:pointer; +} +#nav li a.top_link span { + float:left; + display:block; + padding:0 14px 0 0; +} +#nav li a.top_link span.down { + float:left; + display:block; + padding:0 28px 0 0px; + background:url(images/down_arrow.png) no-repeat right 50%; + +} +#nav li:hover a.top_link, #nav li.active a.top_link, #nav li.active:hover a.top_link { + color:#fff; + background:#000; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} +#nav li:hover a.top_link span { + +} +#nav li:hover a.top_link span.down { + background:url(images/down_arrow.png) no-repeat right 50%; +} +/* Default list styling */ + +#nav li:hover { + position:relative; + z-index:200; +} +#nav li:hover ul.sub { + left:1px; + top:22px; + background: #202020; + padding:3px; + border:1px solid #161616; + white-space:nowrap; + width:200px; + height:auto; + z-index:300; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; + +} +#nav li:hover ul.sub li { + display:block; + height:22px; + position:relative; + float:left; + width:200px; + font-weight:normal; +} +#nav li:hover ul.sub li a { + display:block; + font-size:12px; + height:20px; + width:198px; + line-height:20px; + text-indent:5px; + color:#fff; + text-decoration:none; + border:1px solid #202020; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + border-radius: 2px; +} +#nav li ul.sub li a.fly { + background:#202020 url(images/arrow.png) 190px 6px no-repeat; +} +#nav li:hover ul.sub li a:hover { + background:#3d3d3d; + color:#fff; + border-color:#4e4e4e; +} +#nav li:hover ul.sub li a.fly:hover { + background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; + color:#fff; +} +#nav li strong { + display:block; + font-size:12px; + height:20px; + width:198px; + line-height:20px; + margin-bottom:3px; + text-indent:6px; + color:#ff5d1a; + border-bottom:1px solid #414141; + cursor:default; + font-weight:bold; +} +#nav li:hover li:hover ul, #nav li:hover li:hover li:hover ul, #nav li:hover li:hover li:hover li:hover ul, #nav li:hover li:hover li:hover li:hover li:hover ul { + left:200px; + top:-4px; + background: #202020; + padding:3px; + border:1px solid #161616; + white-space:nowrap; + width:200px; + z-index:400; + height:auto; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} +#nav ul, #nav li:hover ul ul, #nav li:hover li:hover ul ul, #nav li:hover li:hover li:hover ul ul, #nav li:hover li:hover li:hover li:hover ul ul { + position:absolute; + left:-9999px; + top:-9999px; + width:0; + height:0; + margin:0; + padding:0; + list-style:none; +} +#nav li:hover li:hover a.fly, #nav li:hover li:hover li:hover a.fly, #nav li:hover li:hover li:hover li:hover a.fly, #nav li:hover li:hover li:hover li:hover li:hover a.fly { + background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; + color:#fff; + border-color:#4e4e4e; +} + + +#nav li:hover li:hover li:hover a.fly { + background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; + color:#fff; + border-color:#4e4e4e; +} +#nav li:hover li:hover li:hover li:hover li:hover a.fly { + background:#3d3d3d url(images/arrow_over.png) 190px 6px no-repeat; + color:#fff; + border-color:#4e4e4e; +} +#nav li:hover li:hover li a.fly, +#nav li:hover li:hover li:hover li a.fly, +#nav li:hover li:hover li:hover li:hover li a.fly { + background:#202020 url(images/arrow.png) 190px 6px no-repeat; + color:#fff; + border-color:#202020; +} + diff --git a/airtime_mvc/public/css/redmond/jquery-ui-1.8.8.custom.css b/airtime_mvc/public/css/redmond/jquery-ui-1.8.8.custom.css index 4956e096e..3ac07ab95 100644 --- a/airtime_mvc/public/css/redmond/jquery-ui-1.8.8.custom.css +++ b/airtime_mvc/public/css/redmond/jquery-ui-1.8.8.custom.css @@ -1,1524 +1,1524 @@ -/* - * jQuery UI CSS Framework 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Theming/API - */ - -/* Layout helpers -----------------------------------*/ -.ui-helper-hidden { - display: none; -} -.ui-helper-hidden-accessible { - position: absolute; - left: -99999999px; -} -.ui-helper-reset { - margin: 0; - padding: 0; - border: 0; - outline: 0; - line-height: 1.3; - text-decoration: none; - font-size: 100%; - list-style: none; -} -.ui-helper-clearfix:after { - content: "."; - display: block; - height: 0; - clear: both; - visibility: hidden; -} -.ui-helper-clearfix { - display: inline-block; -} -/* required comment for clearfix to work in Opera \*/ -* html .ui-helper-clearfix { - height:1%; -} -.ui-helper-clearfix { - display:block; -} -/* end clearfix */ -.ui-helper-zfix { - width: 100%; - height: 100%; - top: 0; - left: 0; - position: absolute; - opacity: 0; - filter:Alpha(Opacity=0); -} -/* Interaction Cues -----------------------------------*/ -.ui-state-disabled { - cursor: default !important; -} -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { - display: block; - text-indent: -99999px; - overflow: hidden; - background-repeat: no-repeat; -} -/* Misc visuals -----------------------------------*/ - -/* Overlays */ -.ui-widget-overlay { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; -} -/* - * jQuery UI CSS Framework 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Theming/API - * - * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Helvetica,%20Arial,%20sans-serif&fwDefault=bold&fsDefault=1.2em&cornerRadius=0px&bgColorHeader=ebebeb&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=50&borderColorHeader=d3d3d3&fcHeader=444444&iconColorHeader=007fb3&bgColorContent=ffffff&bgTextureContent=01_flat.png&bgImgOpacityContent=75&borderColorContent=dddddd&fcContent=444444&iconColorContent=ff0084&bgColorDefault=f6f6f6&bgTextureDefault=03_highlight_soft.png&bgImgOpacityDefault=100&borderColorDefault=d3d3d3&fcDefault=3b3b3b&iconColorDefault=666666&bgColorHover=007fb3&bgTextureHover=03_highlight_soft.png&bgImgOpacityHover=25&borderColorHover=007fb3&fcHover=ffffff&iconColorHover=ffffff&bgColorActive=ffffff&bgTextureActive=01_flat.png&bgImgOpacityActive=65&borderColorActive=d3d3d3&fcActive=007fb3&iconColorActive=454545&bgColorHighlight=eff6eb&bgTextureHighlight=01_flat.png&bgImgOpacityHighlight=55&borderColorHighlight=65a539&fcHighlight=65a539&iconColorHighlight=65a539&bgColorError=fae5e5&bgTextureError=01_flat.png&bgImgOpacityError=55&borderColorError=d00000&fcError=d00000&iconColorError=d00000&bgColorOverlay=9d9d9d&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=0&opacityOverlay=50&bgColorShadow=6c6c6c&bgTextureShadow=01_flat.png&bgImgOpacityShadow=0&opacityShadow=60&thicknessShadow=6px&offsetTopShadow=-6px&offsetLeftShadow=-6px&cornerRadiusShadow=0px - */ - - -/* Component containers -----------------------------------*/ -.ui-widget { - font-family: Helvetica, Arial, sans-serif; - font-size: 1.2em; -} -.ui-widget .ui-widget { - font-size: 1em; -} -.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { - font-family: Helvetica, Arial, sans-serif; - font-size: 12px; -} -.ui-widget-content { - border: 1px solid #5b5b5b; - background: #aaaaaa url(images/ui-bg_default_aaaaaa.png) repeat-x 0 0; - color: #1c1c1c; -} -.ui-widget-content a { - color: #444444; -} -.ui-widget-header { - border: 1px solid #5b5b5b; - background: #9a9a9a url(images/ui-bg_highlight.png) 0 0 repeat-x; - color: #444444; - font-weight: bold; -} -.ui-widget-header a { - color: #444444; -} -/* Interaction states -----------------------------------*/ - - -.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { - border: 1px solid #5b5b5b; - background-color: #6e6e6e; - background: -moz-linear-gradient(top, #868686 0, #6e6e6e 100%); - background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #868686), color-stop(100%, #6e6e6e)); - color: #ffffff; -} -.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { - color: #ffffff; - text-decoration: none; -} -.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { - border: 1px solid #242424; - background-color: #292929; - background: -moz-linear-gradient(top, #3b3b3b 0, #292929 100%); - background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #3b3b3b), color-stop(100%, #292929)); - color: #ffffff; -} -.ui-state-hover a, .ui-state-hover a:hover { - color: #ffffff; - text-decoration: none; -} -.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { - border: 1px solid #5b5b5b; - background: #c6c6c6; - color: #000; - outline:none; -} -.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { - color: #000; - text-decoration: none; -} -.ui-widget :active { - outline: none; -} -.ui-widget-header .ui-state-default, -.ui-widget-header .ui-state-hover, -.ui-widget-header .ui-state-focus, -.ui-widget-header .ui-state-active { - font-weight:bold; -} -/* Interaction Cues -----------------------------------*/ -.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { - border: 1px solid #65a539; - background: #eff6eb url(images/ui-bg_flat_55_eff6eb_40x100.png) 50% 50% repeat-x; - color: #65a539; -} -.ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a { - color: #65a539; -} -.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { - border: 1px solid #d00000; - background: #fae5e5 url(images/ui-bg_flat_55_fae5e5_40x100.png) 50% 50% repeat-x; - color: #d00000; -} -.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { - color: #d00000; -} -.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { - color: #d00000; -} -.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { - font-weight: bold; -} -.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { - opacity: .7; - filter:Alpha(Opacity=70); - font-weight: normal; -} -.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { - opacity: .35; - filter:Alpha(Opacity=35); - background-image: none; -} -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { - width: 16px; - height: 16px; - background-image: url(images/ui-icons_ffffff_256x240.png); -} -.ui-widget-content .ui-icon { - background-image: url(images/ui-icons_ffffff_256x240.png); -} -.ui-widget-header .ui-icon { - background-image: url(images/ui-icons_ffffff_256x240.png); -} -.ui-state-default .ui-icon { - background-image: url(images/ui-icons_ffffff_256x240.png); -} -.ui-state-hover .ui-icon, .ui-state-focus .ui-icon { - background-image: url(images/ui-icons_ff5d1a_256x240.png); -} -.ui-state-active .ui-icon { - background-image: url(images/ui-icons_ff5d1a_256x240.png); -} -.ui-state-highlight .ui-icon { - background-image: url(images/ui-icons_65a539_256x240.png); -} -.ui-state-error .ui-icon, .ui-state-error-text .ui-icon { - background-image: url(images/ui-icons_d00000_256x240.png); -} -/* positioning */ -.ui-icon-carat-1-n { - background-position: 0 0; -} -.ui-icon-carat-1-ne { - background-position: -16px 0; -} -.ui-icon-carat-1-e { - background-position: -32px 0; -} -.ui-icon-carat-1-se { - background-position: -48px 0; -} -.ui-icon-carat-1-s { - background-position: -64px 0; -} -.ui-icon-carat-1-sw { - background-position: -80px 0; -} -.ui-icon-carat-1-w { - background-position: -96px 0; -} -.ui-icon-carat-1-nw { - background-position: -112px 0; -} -.ui-icon-carat-2-n-s { - background-position: -128px 0; -} -.ui-icon-carat-2-e-w { - background-position: -144px 0; -} -.ui-icon-triangle-1-n { - background-position: 0 -16px; -} -.ui-icon-triangle-1-ne { - background-position: -16px -16px; -} -.ui-icon-triangle-1-e { - background-position: -32px -16px; -} -.ui-icon-triangle-1-se { - background-position: -48px -16px; -} -.ui-icon-triangle-1-s { - background-position: -64px -16px; -} -.ui-icon-triangle-1-sw { - background-position: -80px -16px; -} -.ui-icon-triangle-1-w { - background-position: -96px -16px; -} -.ui-icon-triangle-1-nw { - background-position: -112px -16px; -} -.ui-icon-triangle-2-n-s { - background-position: -128px -16px; -} -.ui-icon-triangle-2-e-w { - background-position: -144px -16px; -} -.ui-icon-arrow-1-n { - background-position: 0 -32px; -} -.ui-icon-arrow-1-ne { - background-position: -16px -32px; -} -.ui-icon-arrow-1-e { - background-position: -32px -32px; -} -.ui-icon-arrow-1-se { - background-position: -48px -32px; -} -.ui-icon-arrow-1-s { - background-position: -64px -32px; -} -.ui-icon-arrow-1-sw { - background-position: -80px -32px; -} -.ui-icon-arrow-1-w { - background-position: -96px -32px; -} -.ui-icon-arrow-1-nw { - background-position: -112px -32px; -} -.ui-icon-arrow-2-n-s { - background-position: -128px -32px; -} -.ui-icon-arrow-2-ne-sw { - background-position: -144px -32px; -} -.ui-icon-arrow-2-e-w { - background-position: -160px -32px; -} -.ui-icon-arrow-2-se-nw { - background-position: -176px -32px; -} -.ui-icon-arrowstop-1-n { - background-position: -192px -32px; -} -.ui-icon-arrowstop-1-e { - background-position: -208px -32px; -} -.ui-icon-arrowstop-1-s { - background-position: -224px -32px; -} -.ui-icon-arrowstop-1-w { - background-position: -240px -32px; -} -.ui-icon-arrowthick-1-n { - background-position: 0 -48px; -} -.ui-icon-arrowthick-1-ne { - background-position: -16px -48px; -} -.ui-icon-arrowthick-1-e { - background-position: -32px -48px; -} -.ui-icon-arrowthick-1-se { - background-position: -48px -48px; -} -.ui-icon-arrowthick-1-s { - background-position: -64px -48px; -} -.ui-icon-arrowthick-1-sw { - background-position: -80px -48px; -} -.ui-icon-arrowthick-1-w { - background-position: -96px -48px; -} -.ui-icon-arrowthick-1-nw { - background-position: -112px -48px; -} -.ui-icon-arrowthick-2-n-s { - background-position: -128px -48px; -} -.ui-icon-arrowthick-2-ne-sw { - background-position: -144px -48px; -} -.ui-icon-arrowthick-2-e-w { - background-position: -160px -48px; -} -.ui-icon-arrowthick-2-se-nw { - background-position: -176px -48px; -} -.ui-icon-arrowthickstop-1-n { - background-position: -192px -48px; -} -.ui-icon-arrowthickstop-1-e { - background-position: -208px -48px; -} -.ui-icon-arrowthickstop-1-s { - background-position: -224px -48px; -} -.ui-icon-arrowthickstop-1-w { - background-position: -240px -48px; -} -.ui-icon-arrowreturnthick-1-w { - background-position: 0 -64px; -} -.ui-icon-arrowreturnthick-1-n { - background-position: -16px -64px; -} -.ui-icon-arrowreturnthick-1-e { - background-position: -32px -64px; -} -.ui-icon-arrowreturnthick-1-s { - background-position: -48px -64px; -} -.ui-icon-arrowreturn-1-w { - background-position: -64px -64px; -} -.ui-icon-arrowreturn-1-n { - background-position: -80px -64px; -} -.ui-icon-arrowreturn-1-e { - background-position: -96px -64px; -} -.ui-icon-arrowreturn-1-s { - background-position: -112px -64px; -} -.ui-icon-arrowrefresh-1-w { - background-position: -128px -64px; -} -.ui-icon-arrowrefresh-1-n { - background-position: -144px -64px; -} -.ui-icon-arrowrefresh-1-e { - background-position: -160px -64px; -} -.ui-icon-arrowrefresh-1-s { - background-position: -176px -64px; -} -.ui-icon-arrow-4 { - background-position: 0 -80px; -} -.ui-icon-arrow-4-diag { - background-position: -16px -80px; -} -.ui-icon-extlink { - background-position: -32px -80px; -} -.ui-icon-newwin { - background-position: -48px -80px; -} -.ui-icon-refresh { - background-position: -64px -80px; -} -.ui-icon-shuffle { - background-position: -80px -80px; -} -.ui-icon-transfer-e-w { - background-position: -96px -80px; -} -.ui-icon-transferthick-e-w { - background-position: -112px -80px; -} -.ui-icon-folder-collapsed { - background-position: 0 -96px; -} -.ui-icon-folder-open { - background-position: -16px -96px; -} -.ui-icon-document { - background-position: -32px -96px; -} -.ui-icon-document-b { - background-position: -48px -96px; -} -.ui-icon-note { - background-position: -64px -96px; -} -.ui-icon-mail-closed { - background-position: -80px -96px; -} -.ui-icon-mail-open { - background-position: -96px -96px; -} -.ui-icon-suitcase { - background-position: -112px -96px; -} -.ui-icon-comment { - background-position: -128px -96px; -} -.ui-icon-person { - background-position: -144px -96px; -} -.ui-icon-print { - background-position: -160px -96px; -} -.ui-icon-trash { - background-position: -176px -96px; -} -.ui-icon-locked { - background-position: -192px -96px; -} -.ui-icon-unlocked { - background-position: -208px -96px; -} -.ui-icon-bookmark { - background-position: -224px -96px; -} -.ui-icon-tag { - background-position: -240px -96px; -} -.ui-icon-home { - background-position: 0 -112px; -} -.ui-icon-flag { - background-position: -16px -112px; -} -.ui-icon-calendar { - background-position: -32px -112px; -} -.ui-icon-cart { - background-position: -48px -112px; -} -.ui-icon-pencil { - background-position: -64px -112px; -} -.ui-icon-clock { - background-position: -80px -112px; -} -.ui-icon-disk { - background-position: -96px -112px; -} -.ui-icon-calculator { - background-position: -112px -112px; -} -.ui-icon-zoomin { - background-position: -128px -112px; -} -.ui-icon-zoomout { - background-position: -144px -112px; -} -.ui-icon-search { - background-position: -160px -112px; -} -.ui-icon-wrench { - background-position: -176px -112px; -} -.ui-icon-gear { - background-position: -192px -112px; -} -.ui-icon-heart { - background-position: -208px -112px; -} -.ui-icon-star { - background-position: -224px -112px; -} -.ui-icon-link { - background-position: -240px -112px; -} -.ui-icon-cancel { - background-position: 0 -128px; -} -.ui-icon-plus { - background-position: -16px -128px; -} -.ui-icon-plusthick { - background-position: -32px -128px; -} -.ui-icon-minus { - background-position: -48px -128px; -} -.ui-icon-minusthick { - background-position: -64px -128px; -} -.ui-icon-close { - background-position: -80px -128px; -} -.ui-icon-closethick { - background-position: -96px -128px; -} -.ui-icon-key { - background-position: -112px -128px; -} -.ui-icon-lightbulb { - background-position: -128px -128px; -} -.ui-icon-scissors { - background-position: -144px -128px; -} -.ui-icon-clipboard { - background-position: -160px -128px; -} -.ui-icon-copy { - background-position: -176px -128px; -} -.ui-icon-contact { - background-position: -192px -128px; -} -.ui-icon-image { - background-position: -208px -128px; -} -.ui-icon-video { - background-position: -224px -128px; -} -.ui-icon-script { - background-position: -240px -128px; -} -.ui-icon-alert { - background-position: 0 -144px; -} -.ui-icon-info { - background-position: -16px -144px; -} -.ui-icon-notice { - background-position: -32px -144px; -} -.ui-icon-help { - background-position: -48px -144px; -} -.ui-icon-check { - background-position: -64px -144px; -} -.ui-icon-bullet { - background-position: -80px -144px; -} -.ui-icon-radio-off { - background-position: -96px -144px; -} -.ui-icon-radio-on { - background-position: -112px -144px; -} -.ui-icon-pin-w { - background-position: -128px -144px; -} -.ui-icon-pin-s { - background-position: -144px -144px; -} -.ui-icon-play { - background-position: 0 -160px; -} -.ui-icon-pause { - background-position: -16px -160px; -} -.ui-icon-seek-next { - background-position: -32px -160px; -} -.ui-icon-seek-prev { - background-position: -48px -160px; -} -.ui-icon-seek-end { - background-position: -64px -160px; -} -.ui-icon-seek-start { - background-position: -80px -160px; -} -/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ -.ui-icon-seek-first { - background-position: -80px -160px; -} -.ui-icon-stop { - background-position: -96px -160px; -} -.ui-icon-eject { - background-position: -112px -160px; -} -.ui-icon-volume-off { - background-position: -128px -160px; -} -.ui-icon-volume-on { - background-position: -144px -160px; -} -.ui-icon-power { - background-position: 0 -176px; -} -.ui-icon-signal-diag { - background-position: -16px -176px; -} -.ui-icon-signal { - background-position: -32px -176px; -} -.ui-icon-battery-0 { - background-position: -48px -176px; -} -.ui-icon-battery-1 { - background-position: -64px -176px; -} -.ui-icon-battery-2 { - background-position: -80px -176px; -} -.ui-icon-battery-3 { - background-position: -96px -176px; -} -.ui-icon-circle-plus { - background-position: 0 -192px; -} -.ui-icon-circle-minus { - background-position: -16px -192px; -} -.ui-icon-circle-close { - background-position: -32px -192px; -} -.ui-icon-circle-triangle-e { - background-position: -48px -192px; -} -.ui-icon-circle-triangle-s { - background-position: -64px -192px; -} -.ui-icon-circle-triangle-w { - background-position: -80px -192px; -} -.ui-icon-circle-triangle-n { - background-position: -96px -192px; -} -.ui-icon-circle-arrow-e { - background-position: -112px -192px; -} -.ui-icon-circle-arrow-s { - background-position: -128px -192px; -} -.ui-icon-circle-arrow-w { - background-position: -144px -192px; -} -.ui-icon-circle-arrow-n { - background-position: -160px -192px; -} -.ui-icon-circle-zoomin { - background-position: -176px -192px; -} -.ui-icon-circle-zoomout { - background-position: -192px -192px; -} -.ui-icon-circle-check { - background-position: -208px -192px; -} -.ui-icon-circlesmall-plus { - background-position: 0 -208px; -} -.ui-icon-circlesmall-minus { - background-position: -16px -208px; -} -.ui-icon-circlesmall-close { - background-position: -32px -208px; -} -.ui-icon-squaresmall-plus { - background-position: -48px -208px; -} -.ui-icon-squaresmall-minus { - background-position: -64px -208px; -} -.ui-icon-squaresmall-close { - background-position: -80px -208px; -} -.ui-icon-grip-dotted-vertical { - background-position: 0 -224px; -} -.ui-icon-grip-dotted-horizontal { - background-position: -16px -224px; -} -.ui-icon-grip-solid-vertical { - background-position: -32px -224px; -} -.ui-icon-grip-solid-horizontal { - background-position: -48px -224px; -} -.ui-icon-gripsmall-diagonal-se { - background-position: -64px -224px; -} -.ui-icon-grip-diagonal-se { - background-position: -80px -224px; -} -/* Misc visuals -----------------------------------*/ - -/* Corner radius */ -.ui-corner-tl { - -moz-border-radius-topleft: 0px; - -webkit-border-top-left-radius: 0px; - border-top-left-radius: 0px; -} -.ui-corner-tr { - -moz-border-radius-topright: 0px; - -webkit-border-top-right-radius: 0px; - border-top-right-radius: 0px; -} -.ui-corner-bl { - -moz-border-radius-bottomleft: 0px; - -webkit-border-bottom-left-radius: 0px; - border-bottom-left-radius: 0px; -} -.ui-corner-br { - -moz-border-radius-bottomright: 0px; - -webkit-border-bottom-right-radius: 0px; - border-bottom-right-radius: 0px; -} -.ui-corner-top { - -moz-border-radius-topleft: 0px; - -webkit-border-top-left-radius: 0px; - border-top-left-radius: 0px; - -moz-border-radius-topright: 0px; - -webkit-border-top-right-radius: 0px; - border-top-right-radius: 0px; -} -.ui-corner-bottom { - -moz-border-radius-bottomleft: 0px; - -webkit-border-bottom-left-radius: 0px; - border-bottom-left-radius: 0px; - -moz-border-radius-bottomright: 0px; - -webkit-border-bottom-right-radius: 0px; - border-bottom-right-radius: 0px; -} -.ui-corner-right { - -moz-border-radius-topright: 0px; - -webkit-border-top-right-radius: 0px; - border-top-right-radius: 0px; - -moz-border-radius-bottomright: 0px; - -webkit-border-bottom-right-radius: 0px; - border-bottom-right-radius: 0px; -} -.ui-corner-left { - -moz-border-radius-topleft: 0px; - -webkit-border-top-left-radius: 0px; - border-top-left-radius: 0px; - -moz-border-radius-bottomleft: 0px; - -webkit-border-bottom-left-radius: 0px; - border-bottom-left-radius: 0px; -} -.ui-corner-all { - -moz-border-radius: 0px; - -webkit-border-radius: 0px; - border-radius: 0px; -} -/* Overlays */ -.ui-widget-overlay { - background: #9d9d9d url(images/ui-bg_flat_0_9d9d9d_40x100.png) 50% 50% repeat-x; - opacity: .50; - filter:Alpha(Opacity=50); -} -.ui-widget-shadow { - margin: -6px 0 0 -6px; - padding: 6px; - background: #6c6c6c url(images/ui-bg_flat_0_6c6c6c_40x100.png) 50% 50% repeat-x; - opacity: .60; - filter:Alpha(Opacity=60); - -moz-border-radius: 0px; - -webkit-border-radius: 0px; - border-radius: 0px; -}/* - * jQuery UI Resizable 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Resizable#theming - */ -.ui-resizable { - position: relative; -} -.ui-resizable-handle { - position: absolute; - font-size: 0.1px; - z-index: 99999; - display: block; -} -.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { - display: none; -} -.ui-resizable-n { - cursor: n-resize; - height: 7px; - width: 100%; - top: -5px; - left: 0; -} -.ui-resizable-s { - cursor: s-resize; - height: 7px; - width: 100%; - bottom: -5px; - left: 0; -} -.ui-resizable-e { - cursor: e-resize; - width: 7px; - right: -5px; - top: 0; - height: 100%; -} -.ui-resizable-w { - cursor: w-resize; - width: 7px; - left: -5px; - top: 0; - height: 100%; -} -.ui-resizable-se { - cursor: se-resize; - width: 12px; - height: 12px; - right: 1px; - bottom: 1px; -} -.ui-resizable-sw { - cursor: sw-resize; - width: 9px; - height: 9px; - left: -5px; - bottom: -5px; -} -.ui-resizable-nw { - cursor: nw-resize; - width: 9px; - height: 9px; - left: -5px; - top: -5px; -} -.ui-resizable-ne { - cursor: ne-resize; - width: 9px; - height: 9px; - right: -5px; - top: -5px; -}/* - * jQuery UI Selectable 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Selectable#theming - */ -.ui-selectable-helper { - position: absolute; - z-index: 100; - border:1px dotted black; -} -/* - * jQuery UI Accordion 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Accordion#theming - */ -/* IE/Win - Fix animation bug - #4615 */ -.ui-accordion { - width: 100%; -} -.ui-accordion .ui-accordion-header { - cursor: pointer; - position: relative; - margin-top: 1px; - zoom: 1; - font-weight:bold; -} -.ui-accordion .ui-accordion-li-fix { - display: inline; -} -.ui-accordion .ui-accordion-header-active { - border-bottom: 0 !important; -} -.ui-accordion .ui-accordion-header a { - display: block; - font-size: 1em; - padding: .5em .5em .5em .7em; -} -.ui-accordion-icons .ui-accordion-header a { - padding-left: 2.2em; -} -.ui-accordion .ui-accordion-header .ui-icon { - position: absolute; - left: .5em; - top: 50%; - margin-top: -8px; -} -.ui-accordion .ui-accordion-content { - padding: 10px; - border-top: 0; - margin-top: -2px; - position: relative; - top: 1px; - margin-bottom: 2px; - overflow: auto; - display: none; - zoom: 1; -} -.ui-accordion .ui-accordion-content-active { - display: block; -}/* - * jQuery UI Autocomplete 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Autocomplete#theming - */ -.ui-autocomplete { - position: absolute; - cursor: default; -} -/* workarounds */ -* html .ui-autocomplete { - width:1px; -} /* without this, the menu expands to 100% in IE6 */ -/* - * jQuery UI Menu 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Menu#theming - */ -.ui-menu { - list-style:none; - padding: 2px; - margin: 0; - display:block; - float: left; -} -.ui-menu .ui-menu { - margin-top: -3px; -} -.ui-menu .ui-menu-item { - margin:0; - padding: 0; - zoom: 1; - float: left; - clear: left; - width: 100%; -} -.ui-menu .ui-menu-item a { - text-decoration:none; - display:block; - padding:.2em .4em; - line-height:1.5; - zoom:1; -} -.ui-menu .ui-menu-item a.ui-state-hover, .ui-menu .ui-menu-item a.ui-state-active { - font-weight: normal; - margin: -1px; -} -/* - * jQuery UI Button 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Button#theming - */ -.ui-button { - display: inline-block; - position: relative; - padding: 0; - margin-right: .1em; - text-decoration: none !important; - cursor: pointer; - text-align: center; - zoom: 1; - overflow: visible; -} /* the overflow property removes extra width in IE */ -.ui-button-icon-only { - width: 2.2em; -} /* to make room for the icon, a width needs to be set here */ -button.ui-button-icon-only { - width: 2.4em; -} /* button elements seem to need a little more width */ -.ui-button-icons-only { - width: 3.4em; -} -button.ui-button-icons-only { - width: 3.7em; -} -/*button text element */ -.ui-button .ui-button-text { - display: block; - line-height: 1.4; -} -.ui-button-text-only .ui-button-text { - padding: .4em 1em; -} -.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { - padding: .4em; - text-indent: -9999999px; -} -.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { - padding: .4em 1em .4em 2.1em; -} -.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { - padding: .4em 2.1em .4em 1em; -} -.ui-button-text-icons .ui-button-text { - padding-left: 2.1em; - padding-right: 2.1em; -} -/* no icon support for input elements, provide padding by default */ -input.ui-button { - padding: .4em 1em; -} -/*button icon element(s) */ -.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { - position: absolute; - top: 50%; - margin-top: -8px; - left: 0.2em; -} -.ui-button-icon-only .ui-icon { - left: 50%; - margin-left: -8px; -} -.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { - left: .5em; -} -.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { - right: .5em; -} -.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { - right: .5em; -} -/*button sets*/ -.ui-buttonset { - margin-right: 7px; -} -.ui-buttonset .ui-button { - margin-left: 0; - margin-right: -.3em; -} - -/* workarounds */ - -button.ui-button.::-moz-focus-inner { - border: 0; - padding: 0; -} - - /* reset extra padding in Firefox */ -/* - * jQuery UI Dialog 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Dialog#theming - */ -.ui-dialog { - position: absolute; - padding: .4em; - width: 300px; - overflow: hidden; - border-width: 3px; -} -.ui-dialog .ui-dialog-titlebar { - padding: 6px 8px 6px 8px; - position: relative; -} -.ui-dialog .ui-dialog-title { - float: left; - margin: .1em 16px .2em 0; -} -.ui-dialog .ui-dialog-titlebar-close { - position: absolute; - right: .3em; - top: 50%; - width: 19px; - margin: -10px 0 0 0; - padding: 1px; - height: 18px; -} -.ui-dialog .ui-dialog-titlebar-close span { - display: block; - margin: 1px; -} -.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { - padding: 0; -} -.ui-dialog .ui-dialog-content { - position: relative; - border: 0; - padding: .5em 1em; - background: none; - overflow: auto; - zoom: 1; - -} -.ui-dialog .ui-dialog-buttonpane { - text-align: left; - border-width: 1px 0 0 0; - background: none; - margin: .5em 0 0 0; - margin: 0.3em -0.4em 0; - padding: 0.3em 1em 0 0.4em; - border-color: #9f9f9f; -} -.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { - float: right; -} -.ui-dialog .ui-dialog-buttonpane button { - margin: .5em .4em .5em 0; - cursor: pointer; -} -.ui-dialog .ui-resizable-se { - width: 14px; - height: 14px; - right: 3px; - bottom: 3px; -} -.ui-draggable .ui-dialog-titlebar { - cursor: move; -} -/* - * jQuery UI Slider 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Slider#theming - */ -.ui-slider { - position: relative; - text-align: left; -} -.ui-slider .ui-slider-handle { - position: absolute; - z-index: 2; - width: 1.2em; - height: 1.2em; - cursor: default; -} -.ui-slider .ui-slider-range { - position: absolute; - z-index: 1; - font-size: .7em; - display: block; - border: 0; - background-position: 0 0; -} -.ui-slider-horizontal { - height: .8em; -} -.ui-slider-horizontal .ui-slider-handle { - top: -.3em; - margin-left: -.6em; -} -.ui-slider-horizontal .ui-slider-range { - top: 0; - height: 100%; -} -.ui-slider-horizontal .ui-slider-range-min { - left: 0; -} -.ui-slider-horizontal .ui-slider-range-max { - right: 0; -} -.ui-slider-vertical { - width: .8em; - height: 100px; -} -.ui-slider-vertical .ui-slider-handle { - left: -.3em; - margin-left: 0; - margin-bottom: -.6em; -} -.ui-slider-vertical .ui-slider-range { - left: 0; - width: 100%; -} -.ui-slider-vertical .ui-slider-range-min { - bottom: 0; -} -.ui-slider-vertical .ui-slider-range-max { - top: 0; -}/* - * jQuery UI Tabs 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Tabs#theming - */ -.ui-tabs { - position: relative; - padding: 4px; - zoom: 1; -} /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ -.ui-tabs .ui-tabs-nav { - margin: 0; - padding: .2em .2em 0; -} -.ui-tabs .ui-tabs-nav li { - list-style: none; - float: left; - position: relative; - top: 1px; - margin: 0 .2em 1px 0; - border-bottom: 0 !important; - padding: 0; - white-space: nowrap; -} -.ui-tabs .ui-tabs-nav li a { - float: left; - padding: .5em 1em; - text-decoration: none; -} -.ui-tabs .ui-tabs-nav li.ui-tabs-selected { - margin-bottom: 0; - padding-bottom: 1px; -} -.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { - cursor: text; -} -.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { - cursor: pointer; -} /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ -.ui-tabs .ui-tabs-panel { - display: block; - border-width: 0; - /*padding: 1em 1.4em;*/ - background: none; -} -.ui-tabs .ui-tabs-hide { - display: none !important; -} -/* - * jQuery UI Datepicker 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Datepicker#theming - */ -.ui-datepicker { - width: 17em; - padding: .2em .2em 0; -} -.ui-datepicker .ui-datepicker-header { - position:relative; - padding:.2em 0; -} -.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { - position:absolute; - top: 2px; - width: 1.8em; - height: 1.8em; -} -.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { - top: 1px; -} -.ui-datepicker .ui-datepicker-prev { - left:2px; -} -.ui-datepicker .ui-datepicker-next { - right:2px; -} -.ui-datepicker .ui-datepicker-prev-hover { - left:1px; -} -.ui-datepicker .ui-datepicker-next-hover { - right:1px; -} -.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { - display: block; - position: absolute; - left: 50%; - margin-left: -8px; - top: 50%; - margin-top: -8px; -} -.ui-datepicker .ui-datepicker-title { - margin: 0 2.3em; - line-height: 1.8em; - text-align: center; -} -.ui-datepicker .ui-datepicker-title select { - font-size:1em; - margin:1px 0; -} -.ui-datepicker select.ui-datepicker-month-year { - width: 100%; -} -.ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year { - width: 49%; -} -.ui-datepicker table { - width: 100%; - font-size: .9em; - border-collapse: collapse; - margin:0 0 .4em; -} -.ui-datepicker th { - padding: .7em .3em; - text-align: center; - font-weight: bold; - border: 0; -} -.ui-datepicker td { - border: 0; - padding: 1px; -} -.ui-datepicker td span, .ui-datepicker td a { - display: block; - padding: .2em; - text-align: right; - text-decoration: none; -} -.ui-datepicker .ui-datepicker-buttonpane { - background-image: none; - margin: .7em 0 0 0; - padding:0 .2em; - border-left: 0; - border-right: 0; - border-bottom: 0; -} -.ui-datepicker .ui-datepicker-buttonpane button { - float: right; - margin: .5em .2em .4em; - cursor: pointer; - padding: .2em .6em .3em .6em; - width:auto; - overflow:visible; -} -.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { - float:left; -} -/* with multiple calendars */ -.ui-datepicker.ui-datepicker-multi { - width:auto; -} -.ui-datepicker-multi .ui-datepicker-group { - float:left; -} -.ui-datepicker-multi .ui-datepicker-group table { - width:95%; - margin:0 auto .4em; -} -.ui-datepicker-multi-2 .ui-datepicker-group { - width:50%; -} -.ui-datepicker-multi-3 .ui-datepicker-group { - width:33.3%; -} -.ui-datepicker-multi-4 .ui-datepicker-group { - width:25%; -} -.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { - border-left-width:0; -} -.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { - border-left-width:0; -} -.ui-datepicker-multi .ui-datepicker-buttonpane { - clear:left; -} -.ui-datepicker-row-break { - clear:both; - width:100%; -} -/* RTL support */ -.ui-datepicker-rtl { - direction: rtl; -} -.ui-datepicker-rtl .ui-datepicker-prev { - right: 2px; - left: auto; -} -.ui-datepicker-rtl .ui-datepicker-next { - left: 2px; - right: auto; -} -.ui-datepicker-rtl .ui-datepicker-prev:hover { - right: 1px; - left: auto; -} -.ui-datepicker-rtl .ui-datepicker-next:hover { - left: 1px; - right: auto; -} -.ui-datepicker-rtl .ui-datepicker-buttonpane { - clear:right; -} -.ui-datepicker-rtl .ui-datepicker-buttonpane button { - float: left; -} -.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { - float:right; -} -.ui-datepicker-rtl .ui-datepicker-group { - float:right; -} -.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { - border-right-width:0; - border-left-width:1px; -} -.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { - border-right-width:0; - border-left-width:1px; -} -/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ -.ui-datepicker-cover { - display: none; /*sorry for IE5*/ - display/**/: block; /*sorry for IE5*/ - position: absolute; /*must have*/ - z-index: -1; /*must have*/ - filter: mask(); /*must have*/ - top: -4px; /*must have*/ - left: -4px; /*must have*/ - width: 200px; /*must have*/ - height: 200px; /*must have*/ -}/* - * jQuery UI Progressbar 1.8.6 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Progressbar#theming - */ -.ui-progressbar { - height:2em; - text-align: left; -} -.ui-progressbar .ui-progressbar-value { - margin: -1px; - height:100%; -} - - -.ui-datepicker { - display:none; +/* + * jQuery UI CSS Framework 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming/API + */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { + display: none; +} +.ui-helper-hidden-accessible { + position: absolute; + left: -99999999px; +} +.ui-helper-reset { + margin: 0; + padding: 0; + border: 0; + outline: 0; + line-height: 1.3; + text-decoration: none; + font-size: 100%; + list-style: none; +} +.ui-helper-clearfix:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} +.ui-helper-clearfix { + display: inline-block; +} +/* required comment for clearfix to work in Opera \*/ +* html .ui-helper-clearfix { + height:1%; +} +.ui-helper-clearfix { + display:block; +} +/* end clearfix */ +.ui-helper-zfix { + width: 100%; + height: 100%; + top: 0; + left: 0; + position: absolute; + opacity: 0; + filter:Alpha(Opacity=0); +} +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { + cursor: default !important; +} +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + display: block; + text-indent: -99999px; + overflow: hidden; + background-repeat: no-repeat; +} +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +/* + * jQuery UI CSS Framework 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming/API + * + * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Helvetica,%20Arial,%20sans-serif&fwDefault=bold&fsDefault=1.2em&cornerRadius=0px&bgColorHeader=ebebeb&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=50&borderColorHeader=d3d3d3&fcHeader=444444&iconColorHeader=007fb3&bgColorContent=ffffff&bgTextureContent=01_flat.png&bgImgOpacityContent=75&borderColorContent=dddddd&fcContent=444444&iconColorContent=ff0084&bgColorDefault=f6f6f6&bgTextureDefault=03_highlight_soft.png&bgImgOpacityDefault=100&borderColorDefault=d3d3d3&fcDefault=3b3b3b&iconColorDefault=666666&bgColorHover=007fb3&bgTextureHover=03_highlight_soft.png&bgImgOpacityHover=25&borderColorHover=007fb3&fcHover=ffffff&iconColorHover=ffffff&bgColorActive=ffffff&bgTextureActive=01_flat.png&bgImgOpacityActive=65&borderColorActive=d3d3d3&fcActive=007fb3&iconColorActive=454545&bgColorHighlight=eff6eb&bgTextureHighlight=01_flat.png&bgImgOpacityHighlight=55&borderColorHighlight=65a539&fcHighlight=65a539&iconColorHighlight=65a539&bgColorError=fae5e5&bgTextureError=01_flat.png&bgImgOpacityError=55&borderColorError=d00000&fcError=d00000&iconColorError=d00000&bgColorOverlay=9d9d9d&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=0&opacityOverlay=50&bgColorShadow=6c6c6c&bgTextureShadow=01_flat.png&bgImgOpacityShadow=0&opacityShadow=60&thicknessShadow=6px&offsetTopShadow=-6px&offsetLeftShadow=-6px&cornerRadiusShadow=0px + */ + + +/* Component containers +----------------------------------*/ +.ui-widget { + font-family: Helvetica, Arial, sans-serif; + font-size: 1.2em; +} +.ui-widget .ui-widget { + font-size: 1em; +} +.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { + font-family: Helvetica, Arial, sans-serif; + font-size: 12px; +} +.ui-widget-content { + border: 1px solid #5b5b5b; + background: #aaaaaa url(images/ui-bg_default_aaaaaa.png) repeat-x 0 0; + color: #1c1c1c; +} +.ui-widget-content a { + color: #444444; +} +.ui-widget-header { + border: 1px solid #5b5b5b; + background: #9a9a9a url(images/ui-bg_highlight.png) 0 0 repeat-x; + color: #444444; + font-weight: bold; +} +.ui-widget-header a { + color: #444444; +} +/* Interaction states +----------------------------------*/ + + +.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { + border: 1px solid #5b5b5b; + background-color: #6e6e6e; + background: -moz-linear-gradient(top, #868686 0, #6e6e6e 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #868686), color-stop(100%, #6e6e6e)); + color: #ffffff; +} +.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { + color: #ffffff; + text-decoration: none; +} +.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { + border: 1px solid #242424; + background-color: #292929; + background: -moz-linear-gradient(top, #3b3b3b 0, #292929 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #3b3b3b), color-stop(100%, #292929)); + color: #ffffff; +} +.ui-state-hover a, .ui-state-hover a:hover { + color: #ffffff; + text-decoration: none; +} +.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { + border: 1px solid #5b5b5b; + background: #c6c6c6; + color: #000; + outline:none; +} +.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { + color: #000; + text-decoration: none; +} +.ui-widget :active { + outline: none; +} +.ui-widget-header .ui-state-default, +.ui-widget-header .ui-state-hover, +.ui-widget-header .ui-state-focus, +.ui-widget-header .ui-state-active { + font-weight:bold; +} +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight { + border: 1px solid #65a539; + background: #eff6eb url(images/ui-bg_flat_55_eff6eb_40x100.png) 50% 50% repeat-x; + color: #65a539; +} +.ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a { + color: #65a539; +} +.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error { + border: 1px solid #d00000; + background: #fae5e5 url(images/ui-bg_flat_55_fae5e5_40x100.png) 50% 50% repeat-x; + color: #d00000; +} +.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { + color: #d00000; +} +.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { + color: #d00000; +} +.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { + font-weight: bold; +} +.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { + opacity: .7; + filter:Alpha(Opacity=70); + font-weight: normal; +} +.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { + opacity: .35; + filter:Alpha(Opacity=35); + background-image: none; +} +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + width: 16px; + height: 16px; + background-image: url(images/ui-icons_ffffff_256x240.png); +} +.ui-widget-content .ui-icon { + background-image: url(images/ui-icons_ffffff_256x240.png); +} +.ui-widget-header .ui-icon { + background-image: url(images/ui-icons_ffffff_256x240.png); +} +.ui-state-default .ui-icon { + background-image: url(images/ui-icons_ffffff_256x240.png); +} +.ui-state-hover .ui-icon, .ui-state-focus .ui-icon { + background-image: url(images/ui-icons_ff5d1a_256x240.png); +} +.ui-state-active .ui-icon { + background-image: url(images/ui-icons_ff5d1a_256x240.png); +} +.ui-state-highlight .ui-icon { + background-image: url(images/ui-icons_65a539_256x240.png); +} +.ui-state-error .ui-icon, .ui-state-error-text .ui-icon { + background-image: url(images/ui-icons_d00000_256x240.png); +} +/* positioning */ +.ui-icon-carat-1-n { + background-position: 0 0; +} +.ui-icon-carat-1-ne { + background-position: -16px 0; +} +.ui-icon-carat-1-e { + background-position: -32px 0; +} +.ui-icon-carat-1-se { + background-position: -48px 0; +} +.ui-icon-carat-1-s { + background-position: -64px 0; +} +.ui-icon-carat-1-sw { + background-position: -80px 0; +} +.ui-icon-carat-1-w { + background-position: -96px 0; +} +.ui-icon-carat-1-nw { + background-position: -112px 0; +} +.ui-icon-carat-2-n-s { + background-position: -128px 0; +} +.ui-icon-carat-2-e-w { + background-position: -144px 0; +} +.ui-icon-triangle-1-n { + background-position: 0 -16px; +} +.ui-icon-triangle-1-ne { + background-position: -16px -16px; +} +.ui-icon-triangle-1-e { + background-position: -32px -16px; +} +.ui-icon-triangle-1-se { + background-position: -48px -16px; +} +.ui-icon-triangle-1-s { + background-position: -64px -16px; +} +.ui-icon-triangle-1-sw { + background-position: -80px -16px; +} +.ui-icon-triangle-1-w { + background-position: -96px -16px; +} +.ui-icon-triangle-1-nw { + background-position: -112px -16px; +} +.ui-icon-triangle-2-n-s { + background-position: -128px -16px; +} +.ui-icon-triangle-2-e-w { + background-position: -144px -16px; +} +.ui-icon-arrow-1-n { + background-position: 0 -32px; +} +.ui-icon-arrow-1-ne { + background-position: -16px -32px; +} +.ui-icon-arrow-1-e { + background-position: -32px -32px; +} +.ui-icon-arrow-1-se { + background-position: -48px -32px; +} +.ui-icon-arrow-1-s { + background-position: -64px -32px; +} +.ui-icon-arrow-1-sw { + background-position: -80px -32px; +} +.ui-icon-arrow-1-w { + background-position: -96px -32px; +} +.ui-icon-arrow-1-nw { + background-position: -112px -32px; +} +.ui-icon-arrow-2-n-s { + background-position: -128px -32px; +} +.ui-icon-arrow-2-ne-sw { + background-position: -144px -32px; +} +.ui-icon-arrow-2-e-w { + background-position: -160px -32px; +} +.ui-icon-arrow-2-se-nw { + background-position: -176px -32px; +} +.ui-icon-arrowstop-1-n { + background-position: -192px -32px; +} +.ui-icon-arrowstop-1-e { + background-position: -208px -32px; +} +.ui-icon-arrowstop-1-s { + background-position: -224px -32px; +} +.ui-icon-arrowstop-1-w { + background-position: -240px -32px; +} +.ui-icon-arrowthick-1-n { + background-position: 0 -48px; +} +.ui-icon-arrowthick-1-ne { + background-position: -16px -48px; +} +.ui-icon-arrowthick-1-e { + background-position: -32px -48px; +} +.ui-icon-arrowthick-1-se { + background-position: -48px -48px; +} +.ui-icon-arrowthick-1-s { + background-position: -64px -48px; +} +.ui-icon-arrowthick-1-sw { + background-position: -80px -48px; +} +.ui-icon-arrowthick-1-w { + background-position: -96px -48px; +} +.ui-icon-arrowthick-1-nw { + background-position: -112px -48px; +} +.ui-icon-arrowthick-2-n-s { + background-position: -128px -48px; +} +.ui-icon-arrowthick-2-ne-sw { + background-position: -144px -48px; +} +.ui-icon-arrowthick-2-e-w { + background-position: -160px -48px; +} +.ui-icon-arrowthick-2-se-nw { + background-position: -176px -48px; +} +.ui-icon-arrowthickstop-1-n { + background-position: -192px -48px; +} +.ui-icon-arrowthickstop-1-e { + background-position: -208px -48px; +} +.ui-icon-arrowthickstop-1-s { + background-position: -224px -48px; +} +.ui-icon-arrowthickstop-1-w { + background-position: -240px -48px; +} +.ui-icon-arrowreturnthick-1-w { + background-position: 0 -64px; +} +.ui-icon-arrowreturnthick-1-n { + background-position: -16px -64px; +} +.ui-icon-arrowreturnthick-1-e { + background-position: -32px -64px; +} +.ui-icon-arrowreturnthick-1-s { + background-position: -48px -64px; +} +.ui-icon-arrowreturn-1-w { + background-position: -64px -64px; +} +.ui-icon-arrowreturn-1-n { + background-position: -80px -64px; +} +.ui-icon-arrowreturn-1-e { + background-position: -96px -64px; +} +.ui-icon-arrowreturn-1-s { + background-position: -112px -64px; +} +.ui-icon-arrowrefresh-1-w { + background-position: -128px -64px; +} +.ui-icon-arrowrefresh-1-n { + background-position: -144px -64px; +} +.ui-icon-arrowrefresh-1-e { + background-position: -160px -64px; +} +.ui-icon-arrowrefresh-1-s { + background-position: -176px -64px; +} +.ui-icon-arrow-4 { + background-position: 0 -80px; +} +.ui-icon-arrow-4-diag { + background-position: -16px -80px; +} +.ui-icon-extlink { + background-position: -32px -80px; +} +.ui-icon-newwin { + background-position: -48px -80px; +} +.ui-icon-refresh { + background-position: -64px -80px; +} +.ui-icon-shuffle { + background-position: -80px -80px; +} +.ui-icon-transfer-e-w { + background-position: -96px -80px; +} +.ui-icon-transferthick-e-w { + background-position: -112px -80px; +} +.ui-icon-folder-collapsed { + background-position: 0 -96px; +} +.ui-icon-folder-open { + background-position: -16px -96px; +} +.ui-icon-document { + background-position: -32px -96px; +} +.ui-icon-document-b { + background-position: -48px -96px; +} +.ui-icon-note { + background-position: -64px -96px; +} +.ui-icon-mail-closed { + background-position: -80px -96px; +} +.ui-icon-mail-open { + background-position: -96px -96px; +} +.ui-icon-suitcase { + background-position: -112px -96px; +} +.ui-icon-comment { + background-position: -128px -96px; +} +.ui-icon-person { + background-position: -144px -96px; +} +.ui-icon-print { + background-position: -160px -96px; +} +.ui-icon-trash { + background-position: -176px -96px; +} +.ui-icon-locked { + background-position: -192px -96px; +} +.ui-icon-unlocked { + background-position: -208px -96px; +} +.ui-icon-bookmark { + background-position: -224px -96px; +} +.ui-icon-tag { + background-position: -240px -96px; +} +.ui-icon-home { + background-position: 0 -112px; +} +.ui-icon-flag { + background-position: -16px -112px; +} +.ui-icon-calendar { + background-position: -32px -112px; +} +.ui-icon-cart { + background-position: -48px -112px; +} +.ui-icon-pencil { + background-position: -64px -112px; +} +.ui-icon-clock { + background-position: -80px -112px; +} +.ui-icon-disk { + background-position: -96px -112px; +} +.ui-icon-calculator { + background-position: -112px -112px; +} +.ui-icon-zoomin { + background-position: -128px -112px; +} +.ui-icon-zoomout { + background-position: -144px -112px; +} +.ui-icon-search { + background-position: -160px -112px; +} +.ui-icon-wrench { + background-position: -176px -112px; +} +.ui-icon-gear { + background-position: -192px -112px; +} +.ui-icon-heart { + background-position: -208px -112px; +} +.ui-icon-star { + background-position: -224px -112px; +} +.ui-icon-link { + background-position: -240px -112px; +} +.ui-icon-cancel { + background-position: 0 -128px; +} +.ui-icon-plus { + background-position: -16px -128px; +} +.ui-icon-plusthick { + background-position: -32px -128px; +} +.ui-icon-minus { + background-position: -48px -128px; +} +.ui-icon-minusthick { + background-position: -64px -128px; +} +.ui-icon-close { + background-position: -80px -128px; +} +.ui-icon-closethick { + background-position: -96px -128px; +} +.ui-icon-key { + background-position: -112px -128px; +} +.ui-icon-lightbulb { + background-position: -128px -128px; +} +.ui-icon-scissors { + background-position: -144px -128px; +} +.ui-icon-clipboard { + background-position: -160px -128px; +} +.ui-icon-copy { + background-position: -176px -128px; +} +.ui-icon-contact { + background-position: -192px -128px; +} +.ui-icon-image { + background-position: -208px -128px; +} +.ui-icon-video { + background-position: -224px -128px; +} +.ui-icon-script { + background-position: -240px -128px; +} +.ui-icon-alert { + background-position: 0 -144px; +} +.ui-icon-info { + background-position: -16px -144px; +} +.ui-icon-notice { + background-position: -32px -144px; +} +.ui-icon-help { + background-position: -48px -144px; +} +.ui-icon-check { + background-position: -64px -144px; +} +.ui-icon-bullet { + background-position: -80px -144px; +} +.ui-icon-radio-off { + background-position: -96px -144px; +} +.ui-icon-radio-on { + background-position: -112px -144px; +} +.ui-icon-pin-w { + background-position: -128px -144px; +} +.ui-icon-pin-s { + background-position: -144px -144px; +} +.ui-icon-play { + background-position: 0 -160px; +} +.ui-icon-pause { + background-position: -16px -160px; +} +.ui-icon-seek-next { + background-position: -32px -160px; +} +.ui-icon-seek-prev { + background-position: -48px -160px; +} +.ui-icon-seek-end { + background-position: -64px -160px; +} +.ui-icon-seek-start { + background-position: -80px -160px; +} +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { + background-position: -80px -160px; +} +.ui-icon-stop { + background-position: -96px -160px; +} +.ui-icon-eject { + background-position: -112px -160px; +} +.ui-icon-volume-off { + background-position: -128px -160px; +} +.ui-icon-volume-on { + background-position: -144px -160px; +} +.ui-icon-power { + background-position: 0 -176px; +} +.ui-icon-signal-diag { + background-position: -16px -176px; +} +.ui-icon-signal { + background-position: -32px -176px; +} +.ui-icon-battery-0 { + background-position: -48px -176px; +} +.ui-icon-battery-1 { + background-position: -64px -176px; +} +.ui-icon-battery-2 { + background-position: -80px -176px; +} +.ui-icon-battery-3 { + background-position: -96px -176px; +} +.ui-icon-circle-plus { + background-position: 0 -192px; +} +.ui-icon-circle-minus { + background-position: -16px -192px; +} +.ui-icon-circle-close { + background-position: -32px -192px; +} +.ui-icon-circle-triangle-e { + background-position: -48px -192px; +} +.ui-icon-circle-triangle-s { + background-position: -64px -192px; +} +.ui-icon-circle-triangle-w { + background-position: -80px -192px; +} +.ui-icon-circle-triangle-n { + background-position: -96px -192px; +} +.ui-icon-circle-arrow-e { + background-position: -112px -192px; +} +.ui-icon-circle-arrow-s { + background-position: -128px -192px; +} +.ui-icon-circle-arrow-w { + background-position: -144px -192px; +} +.ui-icon-circle-arrow-n { + background-position: -160px -192px; +} +.ui-icon-circle-zoomin { + background-position: -176px -192px; +} +.ui-icon-circle-zoomout { + background-position: -192px -192px; +} +.ui-icon-circle-check { + background-position: -208px -192px; +} +.ui-icon-circlesmall-plus { + background-position: 0 -208px; +} +.ui-icon-circlesmall-minus { + background-position: -16px -208px; +} +.ui-icon-circlesmall-close { + background-position: -32px -208px; +} +.ui-icon-squaresmall-plus { + background-position: -48px -208px; +} +.ui-icon-squaresmall-minus { + background-position: -64px -208px; +} +.ui-icon-squaresmall-close { + background-position: -80px -208px; +} +.ui-icon-grip-dotted-vertical { + background-position: 0 -224px; +} +.ui-icon-grip-dotted-horizontal { + background-position: -16px -224px; +} +.ui-icon-grip-solid-vertical { + background-position: -32px -224px; +} +.ui-icon-grip-solid-horizontal { + background-position: -48px -224px; +} +.ui-icon-gripsmall-diagonal-se { + background-position: -64px -224px; +} +.ui-icon-grip-diagonal-se { + background-position: -80px -224px; +} +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-tl { + -moz-border-radius-topleft: 0px; + -webkit-border-top-left-radius: 0px; + border-top-left-radius: 0px; +} +.ui-corner-tr { + -moz-border-radius-topright: 0px; + -webkit-border-top-right-radius: 0px; + border-top-right-radius: 0px; +} +.ui-corner-bl { + -moz-border-radius-bottomleft: 0px; + -webkit-border-bottom-left-radius: 0px; + border-bottom-left-radius: 0px; +} +.ui-corner-br { + -moz-border-radius-bottomright: 0px; + -webkit-border-bottom-right-radius: 0px; + border-bottom-right-radius: 0px; +} +.ui-corner-top { + -moz-border-radius-topleft: 0px; + -webkit-border-top-left-radius: 0px; + border-top-left-radius: 0px; + -moz-border-radius-topright: 0px; + -webkit-border-top-right-radius: 0px; + border-top-right-radius: 0px; +} +.ui-corner-bottom { + -moz-border-radius-bottomleft: 0px; + -webkit-border-bottom-left-radius: 0px; + border-bottom-left-radius: 0px; + -moz-border-radius-bottomright: 0px; + -webkit-border-bottom-right-radius: 0px; + border-bottom-right-radius: 0px; +} +.ui-corner-right { + -moz-border-radius-topright: 0px; + -webkit-border-top-right-radius: 0px; + border-top-right-radius: 0px; + -moz-border-radius-bottomright: 0px; + -webkit-border-bottom-right-radius: 0px; + border-bottom-right-radius: 0px; +} +.ui-corner-left { + -moz-border-radius-topleft: 0px; + -webkit-border-top-left-radius: 0px; + border-top-left-radius: 0px; + -moz-border-radius-bottomleft: 0px; + -webkit-border-bottom-left-radius: 0px; + border-bottom-left-radius: 0px; +} +.ui-corner-all { + -moz-border-radius: 0px; + -webkit-border-radius: 0px; + border-radius: 0px; +} +/* Overlays */ +.ui-widget-overlay { + background: #9d9d9d url(images/ui-bg_flat_0_9d9d9d_40x100.png) 50% 50% repeat-x; + opacity: .50; + filter:Alpha(Opacity=50); +} +.ui-widget-shadow { + margin: -6px 0 0 -6px; + padding: 6px; + background: #6c6c6c url(images/ui-bg_flat_0_6c6c6c_40x100.png) 50% 50% repeat-x; + opacity: .60; + filter:Alpha(Opacity=60); + -moz-border-radius: 0px; + -webkit-border-radius: 0px; + border-radius: 0px; +}/* + * jQuery UI Resizable 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Resizable#theming + */ +.ui-resizable { + position: relative; +} +.ui-resizable-handle { + position: absolute; + font-size: 0.1px; + z-index: 99999; + display: block; +} +.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { + display: none; +} +.ui-resizable-n { + cursor: n-resize; + height: 7px; + width: 100%; + top: -5px; + left: 0; +} +.ui-resizable-s { + cursor: s-resize; + height: 7px; + width: 100%; + bottom: -5px; + left: 0; +} +.ui-resizable-e { + cursor: e-resize; + width: 7px; + right: -5px; + top: 0; + height: 100%; +} +.ui-resizable-w { + cursor: w-resize; + width: 7px; + left: -5px; + top: 0; + height: 100%; +} +.ui-resizable-se { + cursor: se-resize; + width: 12px; + height: 12px; + right: 1px; + bottom: 1px; +} +.ui-resizable-sw { + cursor: sw-resize; + width: 9px; + height: 9px; + left: -5px; + bottom: -5px; +} +.ui-resizable-nw { + cursor: nw-resize; + width: 9px; + height: 9px; + left: -5px; + top: -5px; +} +.ui-resizable-ne { + cursor: ne-resize; + width: 9px; + height: 9px; + right: -5px; + top: -5px; +}/* + * jQuery UI Selectable 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Selectable#theming + */ +.ui-selectable-helper { + position: absolute; + z-index: 100; + border:1px dotted black; +} +/* + * jQuery UI Accordion 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Accordion#theming + */ +/* IE/Win - Fix animation bug - #4615 */ +.ui-accordion { + width: 100%; +} +.ui-accordion .ui-accordion-header { + cursor: pointer; + position: relative; + margin-top: 1px; + zoom: 1; + font-weight:bold; +} +.ui-accordion .ui-accordion-li-fix { + display: inline; +} +.ui-accordion .ui-accordion-header-active { + border-bottom: 0 !important; +} +.ui-accordion .ui-accordion-header a { + display: block; + font-size: 1em; + padding: .5em .5em .5em .7em; +} +.ui-accordion-icons .ui-accordion-header a { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-header .ui-icon { + position: absolute; + left: .5em; + top: 50%; + margin-top: -8px; +} +.ui-accordion .ui-accordion-content { + padding: 10px; + border-top: 0; + margin-top: -2px; + position: relative; + top: 1px; + margin-bottom: 2px; + overflow: auto; + display: none; + zoom: 1; +} +.ui-accordion .ui-accordion-content-active { + display: block; +}/* + * jQuery UI Autocomplete 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Autocomplete#theming + */ +.ui-autocomplete { + position: absolute; + cursor: default; +} +/* workarounds */ +* html .ui-autocomplete { + width:1px; +} /* without this, the menu expands to 100% in IE6 */ +/* + * jQuery UI Menu 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Menu#theming + */ +.ui-menu { + list-style:none; + padding: 2px; + margin: 0; + display:block; + float: left; +} +.ui-menu .ui-menu { + margin-top: -3px; +} +.ui-menu .ui-menu-item { + margin:0; + padding: 0; + zoom: 1; + float: left; + clear: left; + width: 100%; +} +.ui-menu .ui-menu-item a { + text-decoration:none; + display:block; + padding:.2em .4em; + line-height:1.5; + zoom:1; +} +.ui-menu .ui-menu-item a.ui-state-hover, .ui-menu .ui-menu-item a.ui-state-active { + font-weight: normal; + margin: -1px; +} +/* + * jQuery UI Button 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Button#theming + */ +.ui-button { + display: inline-block; + position: relative; + padding: 0; + margin-right: .1em; + text-decoration: none !important; + cursor: pointer; + text-align: center; + zoom: 1; + overflow: visible; +} /* the overflow property removes extra width in IE */ +.ui-button-icon-only { + width: 2.2em; +} /* to make room for the icon, a width needs to be set here */ +button.ui-button-icon-only { + width: 2.4em; +} /* button elements seem to need a little more width */ +.ui-button-icons-only { + width: 3.4em; +} +button.ui-button-icons-only { + width: 3.7em; +} +/*button text element */ +.ui-button .ui-button-text { + display: block; + line-height: 1.4; +} +.ui-button-text-only .ui-button-text { + padding: .4em 1em; +} +.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { + padding: .4em; + text-indent: -9999999px; +} +.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { + padding: .4em 1em .4em 2.1em; +} +.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { + padding: .4em 2.1em .4em 1em; +} +.ui-button-text-icons .ui-button-text { + padding-left: 2.1em; + padding-right: 2.1em; +} +/* no icon support for input elements, provide padding by default */ +input.ui-button { + padding: .4em 1em; +} +/*button icon element(s) */ +.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { + position: absolute; + top: 50%; + margin-top: -8px; + left: 0.2em; +} +.ui-button-icon-only .ui-icon { + left: 50%; + margin-left: -8px; +} +.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { + left: .5em; +} +.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { + right: .5em; +} +.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { + right: .5em; +} +/*button sets*/ +.ui-buttonset { + margin-right: 7px; +} +.ui-buttonset .ui-button { + margin-left: 0; + margin-right: -.3em; +} + +/* workarounds */ + +button.ui-button.::-moz-focus-inner { + border: 0; + padding: 0; +} + + /* reset extra padding in Firefox */ +/* + * jQuery UI Dialog 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Dialog#theming + */ +.ui-dialog { + position: absolute; + padding: .4em; + width: 300px; + overflow: hidden; + border-width: 3px; +} +.ui-dialog .ui-dialog-titlebar { + padding: 6px 8px 6px 8px; + position: relative; +} +.ui-dialog .ui-dialog-title { + float: left; + margin: .1em 16px .2em 0; +} +.ui-dialog .ui-dialog-titlebar-close { + position: absolute; + right: .3em; + top: 50%; + width: 19px; + margin: -10px 0 0 0; + padding: 1px; + height: 18px; +} +.ui-dialog .ui-dialog-titlebar-close span { + display: block; + margin: 1px; +} +.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { + padding: 0; +} +.ui-dialog .ui-dialog-content { + position: relative; + border: 0; + padding: .5em 1em; + background: none; + overflow: auto; + zoom: 1; + +} +.ui-dialog .ui-dialog-buttonpane { + text-align: left; + border-width: 1px 0 0 0; + background: none; + margin: .5em 0 0 0; + margin: 0.3em -0.4em 0; + padding: 0.3em 1em 0 0.4em; + border-color: #9f9f9f; +} +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { + float: right; +} +.ui-dialog .ui-dialog-buttonpane button { + margin: .5em .4em .5em 0; + cursor: pointer; +} +.ui-dialog .ui-resizable-se { + width: 14px; + height: 14px; + right: 3px; + bottom: 3px; +} +.ui-draggable .ui-dialog-titlebar { + cursor: move; +} +/* + * jQuery UI Slider 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Slider#theming + */ +.ui-slider { + position: relative; + text-align: left; +} +.ui-slider .ui-slider-handle { + position: absolute; + z-index: 2; + width: 1.2em; + height: 1.2em; + cursor: default; +} +.ui-slider .ui-slider-range { + position: absolute; + z-index: 1; + font-size: .7em; + display: block; + border: 0; + background-position: 0 0; +} +.ui-slider-horizontal { + height: .8em; +} +.ui-slider-horizontal .ui-slider-handle { + top: -.3em; + margin-left: -.6em; +} +.ui-slider-horizontal .ui-slider-range { + top: 0; + height: 100%; +} +.ui-slider-horizontal .ui-slider-range-min { + left: 0; +} +.ui-slider-horizontal .ui-slider-range-max { + right: 0; +} +.ui-slider-vertical { + width: .8em; + height: 100px; +} +.ui-slider-vertical .ui-slider-handle { + left: -.3em; + margin-left: 0; + margin-bottom: -.6em; +} +.ui-slider-vertical .ui-slider-range { + left: 0; + width: 100%; +} +.ui-slider-vertical .ui-slider-range-min { + bottom: 0; +} +.ui-slider-vertical .ui-slider-range-max { + top: 0; +}/* + * jQuery UI Tabs 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Tabs#theming + */ +.ui-tabs { + position: relative; + padding: 4px; + zoom: 1; +} /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ +.ui-tabs .ui-tabs-nav { + margin: 0; + padding: .2em .2em 0; +} +.ui-tabs .ui-tabs-nav li { + list-style: none; + float: left; + position: relative; + top: 1px; + margin: 0 .2em 1px 0; + border-bottom: 0 !important; + padding: 0; + white-space: nowrap; +} +.ui-tabs .ui-tabs-nav li a { + float: left; + padding: .5em 1em; + text-decoration: none; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-selected { + margin-bottom: 0; + padding-bottom: 1px; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { + cursor: text; +} +.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { + cursor: pointer; +} /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ +.ui-tabs .ui-tabs-panel { + display: block; + border-width: 0; + /*padding: 1em 1.4em;*/ + background: none; +} +.ui-tabs .ui-tabs-hide { + display: none !important; +} +/* + * jQuery UI Datepicker 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Datepicker#theming + */ +.ui-datepicker { + width: 17em; + padding: .2em .2em 0; +} +.ui-datepicker .ui-datepicker-header { + position:relative; + padding:.2em 0; +} +.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { + position:absolute; + top: 2px; + width: 1.8em; + height: 1.8em; +} +.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { + top: 1px; +} +.ui-datepicker .ui-datepicker-prev { + left:2px; +} +.ui-datepicker .ui-datepicker-next { + right:2px; +} +.ui-datepicker .ui-datepicker-prev-hover { + left:1px; +} +.ui-datepicker .ui-datepicker-next-hover { + right:1px; +} +.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { + display: block; + position: absolute; + left: 50%; + margin-left: -8px; + top: 50%; + margin-top: -8px; +} +.ui-datepicker .ui-datepicker-title { + margin: 0 2.3em; + line-height: 1.8em; + text-align: center; +} +.ui-datepicker .ui-datepicker-title select { + font-size:1em; + margin:1px 0; +} +.ui-datepicker select.ui-datepicker-month-year { + width: 100%; +} +.ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year { + width: 49%; +} +.ui-datepicker table { + width: 100%; + font-size: .9em; + border-collapse: collapse; + margin:0 0 .4em; +} +.ui-datepicker th { + padding: .7em .3em; + text-align: center; + font-weight: bold; + border: 0; +} +.ui-datepicker td { + border: 0; + padding: 1px; +} +.ui-datepicker td span, .ui-datepicker td a { + display: block; + padding: .2em; + text-align: right; + text-decoration: none; +} +.ui-datepicker .ui-datepicker-buttonpane { + background-image: none; + margin: .7em 0 0 0; + padding:0 .2em; + border-left: 0; + border-right: 0; + border-bottom: 0; +} +.ui-datepicker .ui-datepicker-buttonpane button { + float: right; + margin: .5em .2em .4em; + cursor: pointer; + padding: .2em .6em .3em .6em; + width:auto; + overflow:visible; +} +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { + float:left; +} +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { + width:auto; +} +.ui-datepicker-multi .ui-datepicker-group { + float:left; +} +.ui-datepicker-multi .ui-datepicker-group table { + width:95%; + margin:0 auto .4em; +} +.ui-datepicker-multi-2 .ui-datepicker-group { + width:50%; +} +.ui-datepicker-multi-3 .ui-datepicker-group { + width:33.3%; +} +.ui-datepicker-multi-4 .ui-datepicker-group { + width:25%; +} +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { + border-left-width:0; +} +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { + border-left-width:0; +} +.ui-datepicker-multi .ui-datepicker-buttonpane { + clear:left; +} +.ui-datepicker-row-break { + clear:both; + width:100%; +} +/* RTL support */ +.ui-datepicker-rtl { + direction: rtl; +} +.ui-datepicker-rtl .ui-datepicker-prev { + right: 2px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next { + left: 2px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-prev:hover { + right: 1px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next:hover { + left: 1px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane { + clear:right; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button { + float: left; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { + float:right; +} +.ui-datepicker-rtl .ui-datepicker-group { + float:right; +} +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { + border-right-width:0; + border-left-width:1px; +} +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { + border-right-width:0; + border-left-width:1px; +} +/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ +.ui-datepicker-cover { + display: none; /*sorry for IE5*/ + display/**/: block; /*sorry for IE5*/ + position: absolute; /*must have*/ + z-index: -1; /*must have*/ + filter: mask(); /*must have*/ + top: -4px; /*must have*/ + left: -4px; /*must have*/ + width: 200px; /*must have*/ + height: 200px; /*must have*/ +}/* + * jQuery UI Progressbar 1.8.6 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Progressbar#theming + */ +.ui-progressbar { + height:2em; + text-align: left; +} +.ui-progressbar .ui-progressbar-value { + margin: -1px; + height:100%; +} + + +.ui-datepicker { + display:none; } \ No newline at end of file diff --git a/install_minimal/upgrades/airtime-2.1.0/common/Version20120405114454.php b/install_minimal/upgrades/airtime-2.1.0/common/Version20120405114454.php index 1f17976d0..073457cbb 100644 --- a/install_minimal/upgrades/airtime-2.1.0/common/Version20120405114454.php +++ b/install_minimal/upgrades/airtime-2.1.0/common/Version20120405114454.php @@ -9,16 +9,16 @@ class Version20120405114454 extends AbstractMigration { public function up(Schema $schema) { - //create cc_subjs_token table - $cc_subjs_token = $schema->createTable('cc_subjs_token'); - + //create cc_subjs_token table + $cc_subjs_token = $schema->createTable('cc_subjs_token'); + $cc_subjs_token->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true)); - $cc_subjs_token->addColumn('user_id', 'integer', array('notnull' => 1)); - $cc_subjs_token->addColumn('action', 'string', array('length' => 255, 'notnull' => 1)); + $cc_subjs_token->addColumn('user_id', 'integer', array('notnull' => 1)); + $cc_subjs_token->addColumn('action', 'string', array('length' => 255, 'notnull' => 1)); $cc_subjs_token->addColumn('token', 'string', array('length' => 40, 'notnull' => 1)); - $cc_subjs_token->addColumn('created', 'datetime', array('notnull' => 1)); - - $cc_subjs_token->setPrimaryKey(array('id')); + $cc_subjs_token->addColumn('created', 'datetime', array('notnull' => 1)); + + $cc_subjs_token->setPrimaryKey(array('id')); //end create cc_subjs_token table } diff --git a/install_minimal/upgrades/airtime-2.1.0/common/Version20120410104441.php b/install_minimal/upgrades/airtime-2.1.0/common/Version20120410104441.php index aada5793c..80db8b1b3 100644 --- a/install_minimal/upgrades/airtime-2.1.0/common/Version20120410104441.php +++ b/install_minimal/upgrades/airtime-2.1.0/common/Version20120410104441.php @@ -24,21 +24,21 @@ class Version20120410104441 extends AbstractMigration $this->_addSql("ALTER TABLE cc_files ADD temp_br integer"); $this->_addSql("ALTER TABLE cc_files ADD temp_sr integer"); - $this->_addSql("UPDATE cc_files SET temp_br = bit_rate::integer"); - $this->_addSql("UPDATE cc_files SET temp_sr = sample_rate::integer"); + $this->_addSql("UPDATE cc_files SET temp_br = bit_rate::integer"); + $this->_addSql("UPDATE cc_files SET temp_sr = sample_rate::integer"); - $this->_addSql("ALTER TABLE cc_files DROP COLUMN sample_rate"); + $this->_addSql("ALTER TABLE cc_files DROP COLUMN sample_rate"); $this->_addSql("ALTER TABLE cc_files DROP COLUMN bit_rate"); - - $this->_addSql("ALTER TABLE cc_files RENAME COLUMN temp_sr TO sample_rate"); + + $this->_addSql("ALTER TABLE cc_files RENAME COLUMN temp_sr TO sample_rate"); $this->_addSql("ALTER TABLE cc_files RENAME COLUMN temp_br TO bit_rate"); - //add utime, lptime - $this->_addSql("ALTER TABLE cc_files ADD utime timestamp"); + //add utime, lptime + $this->_addSql("ALTER TABLE cc_files ADD utime timestamp"); $this->_addSql("ALTER TABLE cc_files ADD lptime timestamp"); - //setting these to a default now for timeline refresh purposes. - $now = gmdate("Y-m-d H:i:s"); + //setting these to a default now for timeline refresh purposes. + $now = gmdate("Y-m-d H:i:s"); $this->_addSql("UPDATE cc_files SET utime = '$now'"); } diff --git a/install_minimal/upgrades/airtime-2.1.0/common/Version20120410143340.php b/install_minimal/upgrades/airtime-2.1.0/common/Version20120410143340.php index a4468606b..9cd72c7fc 100644 --- a/install_minimal/upgrades/airtime-2.1.0/common/Version20120410143340.php +++ b/install_minimal/upgrades/airtime-2.1.0/common/Version20120410143340.php @@ -12,7 +12,7 @@ class Version20120410143340 extends AbstractMigration */ public function up(Schema $schema) { - //convert column creator to be creator_id on cc_playlist + //convert column creator to be creator_id on cc_playlist $this->_addSql("ALTER TABLE cc_playlist ADD creator_id integer"); $this->_addSql("UPDATE cc_playlist SET creator_id = (SELECT id FROM cc_subjs WHERE creator = login)"); $this->_addSql("ALTER TABLE cc_playlist DROP COLUMN creator"); diff --git a/install_minimal/upgrades/airtime-2.1.0/propel/airtime/CcShowInstances.php b/install_minimal/upgrades/airtime-2.1.0/propel/airtime/CcShowInstances.php index 9cf5407ca..260fee1f9 100644 --- a/install_minimal/upgrades/airtime-2.1.0/propel/airtime/CcShowInstances.php +++ b/install_minimal/upgrades/airtime-2.1.0/propel/airtime/CcShowInstances.php @@ -136,36 +136,36 @@ class CcShowInstances extends BaseCcShowInstances { ->update(array('DbPlayoutStatus' => 0), $con); } - /** - * Computes the value of the aggregate column time_filled - * - * @param PropelPDO $con A connection object - * - * @return mixed The scalar result from the aggregate query - */ - public function computeDbTimeFilled(PropelPDO $con) - { - $stmt = $con->prepare('SELECT SUM(clip_length) FROM "cc_schedule" WHERE cc_schedule.INSTANCE_ID = :p1'); - $stmt->bindValue(':p1', $this->getDbId()); - $stmt->execute(); - return $stmt->fetchColumn(); - } - - /** - * Updates the aggregate column time_filled - * - * @param PropelPDO $con A connection object - */ - public function updateDbTimeFilled(PropelPDO $con) - { - $this->setDbTimeFilled($this->computeDbTimeFilled($con)); - $this->save($con); + /** + * Computes the value of the aggregate column time_filled + * + * @param PropelPDO $con A connection object + * + * @return mixed The scalar result from the aggregate query + */ + public function computeDbTimeFilled(PropelPDO $con) + { + $stmt = $con->prepare('SELECT SUM(clip_length) FROM "cc_schedule" WHERE cc_schedule.INSTANCE_ID = :p1'); + $stmt->bindValue(':p1', $this->getDbId()); + $stmt->execute(); + return $stmt->fetchColumn(); + } + + /** + * Updates the aggregate column time_filled + * + * @param PropelPDO $con A connection object + */ + public function updateDbTimeFilled(PropelPDO $con) + { + $this->setDbTimeFilled($this->computeDbTimeFilled($con)); + $this->save($con); } public function preInsert(PropelPDO $con = null) { - $now = new DateTime("now", new DateTimeZone("UTC")); - $this->setDbCreated($now); - return true; + $now = new DateTime("now", new DateTimeZone("UTC")); + $this->setDbCreated($now); + return true; } } // CcShowInstances diff --git a/install_minimal/upgrades/upgrade-template/UpgradeCommon.php b/install_minimal/upgrades/upgrade-template/UpgradeCommon.php index 218ecfa3c..8792c89cf 100644 --- a/install_minimal/upgrades/upgrade-template/UpgradeCommon.php +++ b/install_minimal/upgrades/upgrade-template/UpgradeCommon.php @@ -26,31 +26,31 @@ class UpgradeCommon { */ public static function connectToDatabase($p_exitOnError = true) { - try { - $con = Propel::getConnection(); - } catch (Exception $e) { - echo $e->getMessage().PHP_EOL; - echo "Database connection problem.".PHP_EOL; - echo "Check if database exists with corresponding permissions.".PHP_EOL; - if ($p_exitOnError) { - exit(1); - } - return false; - } - return true; + try { + $con = Propel::getConnection(); + } catch (Exception $e) { + echo $e->getMessage().PHP_EOL; + echo "Database connection problem.".PHP_EOL; + echo "Check if database exists with corresponding permissions.".PHP_EOL; + if ($p_exitOnError) { + exit(1); + } + return false; + } + return true; } public static function DbTableExists($p_name) { - $con = Propel::getConnection(); - try { - $sql = "SELECT * FROM ".$p_name." LIMIT 1"; - $con->query($sql); - } catch (PDOException $e){ - return false; - } - return true; + $con = Propel::getConnection(); + try { + $sql = "SELECT * FROM ".$p_name." LIMIT 1"; + $con->query($sql); + } catch (PDOException $e){ + return false; + } + return true; } private static function GetAirtimeSrcDir() diff --git a/python_apps/icecast2/airtime-icecast-status.xsl b/python_apps/icecast2/airtime-icecast-status.xsl index 565c81ebe..c69ba714d 100644 --- a/python_apps/icecast2/airtime-icecast-status.xsl +++ b/python_apps/icecast2/airtime-icecast-status.xsl @@ -1,7 +1,7 @@ -<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> - <xsl:template match="@*|node()"> - <xsl:copy> - <xsl:apply-templates select="@*|node()"/> - </xsl:copy> - </xsl:template> -</xsl:stylesheet> +<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> + <xsl:template match="@*|node()"> + <xsl:copy> + <xsl:apply-templates select="@*|node()"/> + </xsl:copy> + </xsl:template> +</xsl:stylesheet> diff --git a/widgets/css/airtime-widgets.css b/widgets/css/airtime-widgets.css index 7ff364ead..29527cc39 100644 --- a/widgets/css/airtime-widgets.css +++ b/widgets/css/airtime-widgets.css @@ -1,213 +1,213 @@ -@charset "utf-8"; -/* CSS Document */ - - -#headerLiveHolder { - overflow: hidden; - position:relative; - width:300px!important; - font-family: Arial,Helvetica,sans-serif; - font-size: 13px; - margin: 0; - padding: 0; - } - #headerLiveHolder * { - margin: 0; - padding: 0; - } - #headerLiveHolder ul { - list-style-type:none; - margin: 0; - padding: 0; - } - #headerLiveHolder h4 { - font-size:10px; - color:#68bd44; - text-transform:uppercase; - font-weight:normal; - line-height:12px; - } - #headerLiveHolder ul li { - overflow:hidden; - position:relative; - height:12px; - padding-right:70px; - font-size:11px; - color:#999999; - line-height:11px; - } - #headerLiveHolder ul li.current { - font-weight:bold; - color:#666666; - } - #headerLiveHolder ul li span { - position:absolute; - right:0px; - top:0px; - } - #headerLiveHolder ul li span#time-elapsed { - right: 50px; - } - #headerLiveHolder ul li span#time-elapsed:before { - content: "e."; - } - #headerLiveHolder ul li span#time-remaining:before { - content: "r."; - } - -#onAirToday { - width:300px; - margin-bottom:15px; - border:1px solid #999999; - font-family: Arial,Helvetica,sans-serif; - } - #onAirToday h3 { - margin:0; - padding:0 10px; - font-size:13px; - color:#ffffff; - line-height:28px; - background: #999999; - } - #onAirToday table { - border-collapse: collapse; - clear: both; - padding: 0; - } - #onAirToday table tbody { - color: #000; - font-size:12px; - } - #onAirToday table tbody tr { - height: 30px; - } - #onAirToday table tbody tr td { - border-bottom: 1px dotted #d9d9d9; - height: 30px; - padding-left: 10px; - font-weight:bold; - } - #onAirToday table tbody tr td a { - text-decoration:none; - } - #onAirToday table tbody tr td a:hover { - text-decoration:underline; - } - #onAirToday table tbody tr:last-child td { - border-bottom: none; - } - #onAirToday table tbody tr td.time { - font-weight:normal; - color: #666666; - } -/* = PROGRAM SCHEDULE ---------------- */ - - /* - + Center Column */ - #scheduleTabs { - font-family: Arial,Helvetica,sans-serif; - } - #scheduleTabs ul { - overflow:hidden; - height:28px; - background: url( widget-img/schedule-tabs-list-bgr.png) repeat-x left bottom; - list-style-type:none; - margin:0; - padding:0; - } - #scheduleTabs ul li { - float:left; - height:28px; - margin:0; - padding:0; - } - #scheduleTabs ul li a { - display:block; - float:left; - height:25px; - padding:0 10px; - margin-top:3px; - font-size:12px; - font-weight:bold; - color:#666; - line-height:25px; - border-right:1px solid #dbdbdb; - border-left:1px solid #f4f4f4; - text-decoration:none; - } - #scheduleTabs ul li a:hover { - color:#000; - text-decoration:none; - } - #scheduleTabs ul li.ui-tabs-selected a { - height:27px; - margin-top:0px; - line-height:27px; - color:#333333; - background:#ffffff; - border:1px solid #cac9c9; border-bottom:none; - } - #scheduleTabs table { - clear:both; - padding:0px; - border-collapse:collapse; - width:100%; - } - #scheduleTabs table thead { - height:35px; - font-size:12px; color:#333333; line-height:35px; - background-color: #fff; - background: -moz-linear-gradient(top, #ffffff 10%, #f4f4f4 100%); - background: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #ffffff), color-stop(100%, #f4f4f4)); - border-bottom:1px solid #d4d4d4; - } - #scheduleTabs table thead tr { - height:35px; - } - #scheduleTabs table thead tr td { - padding-left:10px; - font-size:11px; color:#999999; text-transform:uppercase; - } - #scheduleTabs table tfoot { - } - #scheduleTabs table tbody { - font-size:13px; color:#666666; font-weight:bold; - } - #scheduleTabs table tbody tr { - height:30px; - } - #scheduleTabs table tbody tr td { - height:30px; - padding-left:10px; - border-bottom:1px dotted #b3b3b3; - } - #scheduleTabs table tbody tr td h4 { - color:#333333; font-size:12px; - margin:0; - padding:0; - } - #scheduleTabs table tbody tr td ul { - background:none !important; - list-style-type:none; - } - #scheduleTabs table tbody tr td ul li { - float:left; - height:30px !important; - padding:0 2px; - font-size:12px; color:#cc0000; font-weight:normal; line-height:30px !important; - } - #scheduleTabs table tbody tr td ul li a { - height:30px !important; - margin:0px !important; padding:0px !important; - font-size:12px; color:#68BD44 !important; font-weight:normal !important; text-transform:uppercase; line-height:30px !important; - background:none !important; - border:none !important; - } - #scheduleTabs table tbody tr td ul li a:hover { - text-decoration:underline; - } - -#scheduleTabs.ui-tabs .ui-tabs-hide { - display: none; -} +@charset "utf-8"; +/* CSS Document */ + + +#headerLiveHolder { + overflow: hidden; + position:relative; + width:300px!important; + font-family: Arial,Helvetica,sans-serif; + font-size: 13px; + margin: 0; + padding: 0; + } + #headerLiveHolder * { + margin: 0; + padding: 0; + } + #headerLiveHolder ul { + list-style-type:none; + margin: 0; + padding: 0; + } + #headerLiveHolder h4 { + font-size:10px; + color:#68bd44; + text-transform:uppercase; + font-weight:normal; + line-height:12px; + } + #headerLiveHolder ul li { + overflow:hidden; + position:relative; + height:12px; + padding-right:70px; + font-size:11px; + color:#999999; + line-height:11px; + } + #headerLiveHolder ul li.current { + font-weight:bold; + color:#666666; + } + #headerLiveHolder ul li span { + position:absolute; + right:0px; + top:0px; + } + #headerLiveHolder ul li span#time-elapsed { + right: 50px; + } + #headerLiveHolder ul li span#time-elapsed:before { + content: "e."; + } + #headerLiveHolder ul li span#time-remaining:before { + content: "r."; + } + +#onAirToday { + width:300px; + margin-bottom:15px; + border:1px solid #999999; + font-family: Arial,Helvetica,sans-serif; + } + #onAirToday h3 { + margin:0; + padding:0 10px; + font-size:13px; + color:#ffffff; + line-height:28px; + background: #999999; + } + #onAirToday table { + border-collapse: collapse; + clear: both; + padding: 0; + } + #onAirToday table tbody { + color: #000; + font-size:12px; + } + #onAirToday table tbody tr { + height: 30px; + } + #onAirToday table tbody tr td { + border-bottom: 1px dotted #d9d9d9; + height: 30px; + padding-left: 10px; + font-weight:bold; + } + #onAirToday table tbody tr td a { + text-decoration:none; + } + #onAirToday table tbody tr td a:hover { + text-decoration:underline; + } + #onAirToday table tbody tr:last-child td { + border-bottom: none; + } + #onAirToday table tbody tr td.time { + font-weight:normal; + color: #666666; + } +/* = PROGRAM SCHEDULE ---------------- */ + + /* + + Center Column */ + #scheduleTabs { + font-family: Arial,Helvetica,sans-serif; + } + #scheduleTabs ul { + overflow:hidden; + height:28px; + background: url( widget-img/schedule-tabs-list-bgr.png) repeat-x left bottom; + list-style-type:none; + margin:0; + padding:0; + } + #scheduleTabs ul li { + float:left; + height:28px; + margin:0; + padding:0; + } + #scheduleTabs ul li a { + display:block; + float:left; + height:25px; + padding:0 10px; + margin-top:3px; + font-size:12px; + font-weight:bold; + color:#666; + line-height:25px; + border-right:1px solid #dbdbdb; + border-left:1px solid #f4f4f4; + text-decoration:none; + } + #scheduleTabs ul li a:hover { + color:#000; + text-decoration:none; + } + #scheduleTabs ul li.ui-tabs-selected a { + height:27px; + margin-top:0px; + line-height:27px; + color:#333333; + background:#ffffff; + border:1px solid #cac9c9; border-bottom:none; + } + #scheduleTabs table { + clear:both; + padding:0px; + border-collapse:collapse; + width:100%; + } + #scheduleTabs table thead { + height:35px; + font-size:12px; color:#333333; line-height:35px; + background-color: #fff; + background: -moz-linear-gradient(top, #ffffff 10%, #f4f4f4 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #ffffff), color-stop(100%, #f4f4f4)); + border-bottom:1px solid #d4d4d4; + } + #scheduleTabs table thead tr { + height:35px; + } + #scheduleTabs table thead tr td { + padding-left:10px; + font-size:11px; color:#999999; text-transform:uppercase; + } + #scheduleTabs table tfoot { + } + #scheduleTabs table tbody { + font-size:13px; color:#666666; font-weight:bold; + } + #scheduleTabs table tbody tr { + height:30px; + } + #scheduleTabs table tbody tr td { + height:30px; + padding-left:10px; + border-bottom:1px dotted #b3b3b3; + } + #scheduleTabs table tbody tr td h4 { + color:#333333; font-size:12px; + margin:0; + padding:0; + } + #scheduleTabs table tbody tr td ul { + background:none !important; + list-style-type:none; + } + #scheduleTabs table tbody tr td ul li { + float:left; + height:30px !important; + padding:0 2px; + font-size:12px; color:#cc0000; font-weight:normal; line-height:30px !important; + } + #scheduleTabs table tbody tr td ul li a { + height:30px !important; + margin:0px !important; padding:0px !important; + font-size:12px; color:#68BD44 !important; font-weight:normal !important; text-transform:uppercase; line-height:30px !important; + background:none !important; + border:none !important; + } + #scheduleTabs table tbody tr td ul li a:hover { + text-decoration:underline; + } + +#scheduleTabs.ui-tabs .ui-tabs-hide { + display: none; +} \ No newline at end of file diff --git a/widgets/widget_schedule.html b/widgets/widget_schedule.html index f7e8ae2de..66b02c546 100644 --- a/widgets/widget_schedule.html +++ b/widgets/widget_schedule.html @@ -1,1823 +1,1823 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> -<title>Airtime widgets - - - - - - - - - - - - - -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TimeProgram NameDetails
00:00 - 00:30

The Interview (EN)

00:30 - 01:00

The Interview (EN)

00:30 - 01:00

Applause (EN)

01:00 - 01:30

L'invité

01:30 - 02:00

Applaudissement (FR)

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

The Interview (EN)

03:00 - 03:30

Newslink

    -
  • -
03:30 - 04:00

Applause (EN)

04:00 - 04:30

L'invité

04:30 - 05:00

Applaudissement (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Well Body

08:00 - 08:30

L'info chez vous (FR)

09:00 - 09:30

Brèves - Music - Promo

09:30 - 10:00

Youth Connection

09:30 - 10:00

Growing Matters (EN)

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Well Body

13:00 - 13:30

L'info chez vous (FR)

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

17:00 - 17:30

L'Info Chez-Vous

18:30 - 19:00

Youth Connection

19:00 - 19:30

L'info chez vous (FR)

19:30 - 20:00

Réseau jeunesse

20:00 - 20:30

Newslink (EN)

20:30 - 21:00

Well Body

22:30 - 23:00

Youth Connection

23:30 - 00:00

Réseau jeunesse

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

01:00 - 01:30

L'Info chez-vous

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    -
  • -
03:30 - 04:00

Well Body

04:00 - 04:30

L'info chez-vous (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Choices (EN)

08:00 - 08:30

L'info chez vous (FR)

09:00 - 09:30

Brèves - Music - Promo

10:30 - 11:00

Le Grenier

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Choices (EN)

13:00 - 13:30

L'info chez vous (FR)

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

16:30 - 17:00

Applause (EN)

17:00 - 17:30

L'Info Chez-Vous

19:00 - 19:30

L'info chez vous (FR)

19:30 - 20:00

Le Grenier

20:00 - 20:30

Newslink (EN)

20:30 - 21:00

Choices (EN)

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

00:30 - 01:00

Applause (EN)

01:00 - 01:30

L'Info chez-vous

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    -
  • -
03:30 - 04:00

Choices (EN)

04:00 - 04:30

L'info chez-vous (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

08:00 - 08:30

L'info chez vous (FR)

08:30 - 09:00

Fifty Fifty (FR)

09:00 - 09:30

Brèves - Music - Promo

09:30 - 10:00

Well Body

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

13:00 - 13:30

L'info chez vous (FR)

13:30 - 14:00

Fifty Fifty (FR)

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

16:30 - 16:45

The Citizen (EN)

17:00 - 17:30

L'Info Chez-Vous

17:30 - 17:45

Le Citoyen

17:30 - 17:45

Le Citoyen

18:30 - 19:00

Well Body

19:00 - 19:30

L'info chez vous (FR)

20:00 - 20:30

Newslink (EN)

21:30 - 22:00

Fifty Fifty (FR)

22:00 - 22:15

The Citizen (EN)

22:30 - 23:00

Well Body (EN)

23:00 - 23:15

Le Citoyen

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

00:30 - 00:45

The Citizen (EN)

01:00 - 01:30

L'Info chez-vous

01:30 - 01:45

Le Citoyen

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    -
  • -
04:00 - 04:30

L'info chez-vous (FR)

04:30 - 05:00

Fifty Fifty (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Growing Matters (EN)

08:00 - 08:30

L'info chez vous (FR)

08:30 - 09:00

Le Grenier

09:00 - 09:30

Brèves - Music - Promo

09:30 - 10:00

Choices (EN)

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Growing Matters (EN)

13:00 - 13:30

L'info chez vous (FR)

13:30 - 14:00

Le Grenier

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

16:30 - 17:00

Pages of History (EN)

17:00 - 17:30

L'Info Chez-Vous

17:30 - 04:00

Pages d'histoire

18:30 - 19:00

Choices (EN)

19:00 - 19:30

L'info chez vous (FR)

20:00 - 20:30

Newslink (EN)

20:30 - 21:00

Growing Matters (EN)

21:30 - 22:00

Le Grenier

22:00 - 22:30

Pages of History (EN)

22:30 - 23:00

Choices (EN)

23:00 - 09:30

Pages d'histoire

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

00:30 - 01:00

Pages of History (EN)

01:00 - 01:30

L'Info chez-vous

01:30 - 12:00

Pages d'histoire

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    -
  • -
03:30 - 04:00

Growing Matters (EN)

04:00 - 04:30

L'info chez-vous (FR)

04:30 - 05:00

Le Grenier

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Youth Connection

08:00 - 08:30

L'info chez vous (FR)

08:30 - 09:00

Réseau jeunesse

09:00 - 09:30

Brèves - Music - Promo

10:30 - 11:00

Fifty Fifty (FR)

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Youth Connection

13:00 - 13:30

L'info chez vous (FR)

13:30 - 14:00

Réseau jeunesse

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

17:00 - 17:30

L'Info Chez-Vous

17:30 - 18:00

Mano River Press (EN)

19:00 - 19:30

L'info chez vous (FR)

19:30 - 20:00

Réseau jeunesse

20:00 - 20:30

Newslink (EN)

21:30 - 22:00

Fifty Fifty (FR)

22:30 - 23:00

Youth Connection

23:30 - 00:00

Réseau jeunesse

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

01:00 - 01:30

L'Info chez-vous

03:00 - 03:30

Newslink

    -
  • -
03:30 - 04:00

Youth Connection

04:00 - 04:30

L'info chez-vous (FR)

04:30 - 05:00

Réseau jeunesse

07:00 - 07:30

Mano River Press (EN)

07:30 - 08:00

Weekend Review (EN)

08:30 - 09:00

Focus (FR)

09:15 - 09:30

The Stadium (EN)

09:30 - 10:00

Echoes of Charles Taylor Trial

    -
  • -
11:45 - 12:00

The Stadium (EN)

12:30 - 13:00

Weekend Review (EN)

12:30 - 13:00

Mano River Press (EN)

13:30 - 14:00

Focus (FR)

16:00 - 16:30

Mano River Press (EN)

16:30 - 17:00

Weekend Review (EN)

17:30 - 18:00

Focus (FR)

18:00 - 18:15

The Stadium (EN)

18:30 - 19:00

Echoes of Charles Taylor Trial

    -
  • -
20:00 - 20:30

Mano River Press (EN)

20:30 - 21:00

Weekend Review (EN)

21:30 - 22:00

Focus (FR)

22:00 - 22:15

The Stadium (EN)

22:30 - 23:00

Echoes of Charles Taylor Trial

    -
  • -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TimeProgram NameDetails
00:00 - 00:30

Mano River Press (EN)

00:30 - 01:00

Weekend Review (EN)

01:30 - 02:00

Focus (FR)

03:00 - 03:30

Mano River Press (EN)

03:30 - 04:00

Weekend Review (EN)

04:30 - 05:00

Focus (FR)

07:00 - 07:30

The Interview (EN)

07:30 - 08:00

Applause (EN)

08:00 - 08:30

L'invité

08:30 - 09:00

Applaudissement (FR)

09:15 - 09:30

The Citizen (EN)

09:30 - 10:00

Pages of History (EN)

10:15 - 10:30

Le Citoyen

11:45 - 12:00

The Citizen (EN)

12:00 - 12:30

The Interview (EN)

12:30 - 13:00

Applause (EN)

13:00 - 13:30

L'invité

13:30 - 14:00

Applaudissement (FR)

16:00 - 16:30

The Interview (EN)

16:30 - 17:00

Applause (EN)

16:30 - 17:00

The Interview (EN)

17:00 - 17:30

L'invité

17:30 - 18:00

Applaudissement (FR)

18:00 - 18:15

The Citizen (EN)

18:30 - 19:00

Pages of History (EN)

19:00 - 19:15

Le Citoyen

20:00 - 20:30

The Interview (EN)

20:30 - 21:00

Applause (EN)

21:00 - 21:30

L'invité

21:30 - 22:00

Applaudissement (FR)

22:00 - 22:30

The Interview (EN)

22:00 - 22:30

Pages of History (EN)

-
-
- - + + + + +Airtime widgets + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TimeProgram NameDetails
00:00 - 00:30

The Interview (EN)

00:30 - 01:00

The Interview (EN)

00:30 - 01:00

Applause (EN)

01:00 - 01:30

L'invité

01:30 - 02:00

Applaudissement (FR)

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

The Interview (EN)

03:00 - 03:30

Newslink

    +
  • +
03:30 - 04:00

Applause (EN)

04:00 - 04:30

L'invité

04:30 - 05:00

Applaudissement (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Well Body

08:00 - 08:30

L'info chez vous (FR)

09:00 - 09:30

Brèves - Music - Promo

09:30 - 10:00

Youth Connection

09:30 - 10:00

Growing Matters (EN)

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Well Body

13:00 - 13:30

L'info chez vous (FR)

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

17:00 - 17:30

L'Info Chez-Vous

18:30 - 19:00

Youth Connection

19:00 - 19:30

L'info chez vous (FR)

19:30 - 20:00

Réseau jeunesse

20:00 - 20:30

Newslink (EN)

20:30 - 21:00

Well Body

22:30 - 23:00

Youth Connection

23:30 - 00:00

Réseau jeunesse

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

01:00 - 01:30

L'Info chez-vous

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    +
  • +
03:30 - 04:00

Well Body

04:00 - 04:30

L'info chez-vous (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Choices (EN)

08:00 - 08:30

L'info chez vous (FR)

09:00 - 09:30

Brèves - Music - Promo

10:30 - 11:00

Le Grenier

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Choices (EN)

13:00 - 13:30

L'info chez vous (FR)

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

16:30 - 17:00

Applause (EN)

17:00 - 17:30

L'Info Chez-Vous

19:00 - 19:30

L'info chez vous (FR)

19:30 - 20:00

Le Grenier

20:00 - 20:30

Newslink (EN)

20:30 - 21:00

Choices (EN)

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

00:30 - 01:00

Applause (EN)

01:00 - 01:30

L'Info chez-vous

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    +
  • +
03:30 - 04:00

Choices (EN)

04:00 - 04:30

L'info chez-vous (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

08:00 - 08:30

L'info chez vous (FR)

08:30 - 09:00

Fifty Fifty (FR)

09:00 - 09:30

Brèves - Music - Promo

09:30 - 10:00

Well Body

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

13:00 - 13:30

L'info chez vous (FR)

13:30 - 14:00

Fifty Fifty (FR)

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

16:30 - 16:45

The Citizen (EN)

17:00 - 17:30

L'Info Chez-Vous

17:30 - 17:45

Le Citoyen

17:30 - 17:45

Le Citoyen

18:30 - 19:00

Well Body

19:00 - 19:30

L'info chez vous (FR)

20:00 - 20:30

Newslink (EN)

21:30 - 22:00

Fifty Fifty (FR)

22:00 - 22:15

The Citizen (EN)

22:30 - 23:00

Well Body (EN)

23:00 - 23:15

Le Citoyen

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

00:30 - 00:45

The Citizen (EN)

01:00 - 01:30

L'Info chez-vous

01:30 - 01:45

Le Citoyen

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    +
  • +
04:00 - 04:30

L'info chez-vous (FR)

04:30 - 05:00

Fifty Fifty (FR)

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Growing Matters (EN)

08:00 - 08:30

L'info chez vous (FR)

08:30 - 09:00

Le Grenier

09:00 - 09:30

Brèves - Music - Promo

09:30 - 10:00

Choices (EN)

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Growing Matters (EN)

13:00 - 13:30

L'info chez vous (FR)

13:30 - 14:00

Le Grenier

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

16:30 - 17:00

Pages of History (EN)

17:00 - 17:30

L'Info Chez-Vous

17:30 - 04:00

Pages d'histoire

18:30 - 19:00

Choices (EN)

19:00 - 19:30

L'info chez vous (FR)

20:00 - 20:30

Newslink (EN)

20:30 - 21:00

Growing Matters (EN)

21:30 - 22:00

Le Grenier

22:00 - 22:30

Pages of History (EN)

22:30 - 23:00

Choices (EN)

23:00 - 09:30

Pages d'histoire

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

00:30 - 01:00

Pages of History (EN)

01:00 - 01:30

L'Info chez-vous

01:30 - 12:00

Pages d'histoire

02:00 - 02:30

Music From Countries - Promo

02:30 - 03:00

Music From Countries - Promo

03:00 - 03:30

Newslink

    +
  • +
03:30 - 04:00

Growing Matters (EN)

04:00 - 04:30

L'info chez-vous (FR)

04:30 - 05:00

Le Grenier

05:00 - 05:30

Music From Countries - Promo

05:30 - 06:00

Music From Countries - Promo

06:00 - 06:30

Music From Countries - Promo

06:30 - 07:00

Music From Countries - Promo

07:00 - 07:30

Newslink (EN)

07:30 - 08:00

Youth Connection

08:00 - 08:30

L'info chez vous (FR)

08:30 - 09:00

Réseau jeunesse

09:00 - 09:30

Brèves - Music - Promo

10:30 - 11:00

Fifty Fifty (FR)

11:00 - 12:00

Breves-Music-Promo

12:00 - 12:30

Newslink (EN)

12:30 - 13:00

Youth Connection

13:00 - 13:30

L'info chez vous (FR)

13:30 - 14:00

Réseau jeunesse

14:00 - 15:00

Brèves - Music - Promo

15:00 - 16:00

Brèves - Music - Promo

16:00 - 16:30

Newslink

17:00 - 17:30

L'Info Chez-Vous

17:30 - 18:00

Mano River Press (EN)

19:00 - 19:30

L'info chez vous (FR)

19:30 - 20:00

Réseau jeunesse

20:00 - 20:30

Newslink (EN)

21:30 - 22:00

Fifty Fifty (FR)

22:30 - 23:00

Youth Connection

23:30 - 00:00

Réseau jeunesse

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TimeProgram NameDetails
00:00 - 00:30

Newslink (EN)

01:00 - 01:30

L'Info chez-vous

03:00 - 03:30

Newslink

    +
  • +
03:30 - 04:00

Youth Connection

04:00 - 04:30

L'info chez-vous (FR)

04:30 - 05:00

Réseau jeunesse

07:00 - 07:30

Mano River Press (EN)

07:30 - 08:00

Weekend Review (EN)

08:30 - 09:00

Focus (FR)

09:15 - 09:30

The Stadium (EN)

09:30 - 10:00

Echoes of Charles Taylor Trial

    +
  • +
11:45 - 12:00

The Stadium (EN)

12:30 - 13:00

Weekend Review (EN)

12:30 - 13:00

Mano River Press (EN)

13:30 - 14:00

Focus (FR)

16:00 - 16:30

Mano River Press (EN)

16:30 - 17:00

Weekend Review (EN)

17:30 - 18:00

Focus (FR)

18:00 - 18:15

The Stadium (EN)

18:30 - 19:00

Echoes of Charles Taylor Trial

    +
  • +
20:00 - 20:30

Mano River Press (EN)

20:30 - 21:00

Weekend Review (EN)

21:30 - 22:00

Focus (FR)

22:00 - 22:15

The Stadium (EN)

22:30 - 23:00

Echoes of Charles Taylor Trial

    +
  • +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TimeProgram NameDetails
00:00 - 00:30

Mano River Press (EN)

00:30 - 01:00

Weekend Review (EN)

01:30 - 02:00

Focus (FR)

03:00 - 03:30

Mano River Press (EN)

03:30 - 04:00

Weekend Review (EN)

04:30 - 05:00

Focus (FR)

07:00 - 07:30

The Interview (EN)

07:30 - 08:00

Applause (EN)

08:00 - 08:30

L'invité

08:30 - 09:00

Applaudissement (FR)

09:15 - 09:30

The Citizen (EN)

09:30 - 10:00

Pages of History (EN)

10:15 - 10:30

Le Citoyen

11:45 - 12:00

The Citizen (EN)

12:00 - 12:30

The Interview (EN)

12:30 - 13:00

Applause (EN)

13:00 - 13:30

L'invité

13:30 - 14:00

Applaudissement (FR)

16:00 - 16:30

The Interview (EN)

16:30 - 17:00

Applause (EN)

16:30 - 17:00

The Interview (EN)

17:00 - 17:30

L'invité

17:30 - 18:00

Applaudissement (FR)

18:00 - 18:15

The Citizen (EN)

18:30 - 19:00

Pages of History (EN)

19:00 - 19:15

Le Citoyen

20:00 - 20:30

The Interview (EN)

20:30 - 21:00

Applause (EN)

21:00 - 21:30

L'invité

21:30 - 22:00

Applaudissement (FR)

22:00 - 22:30

The Interview (EN)

22:00 - 22:30

Pages of History (EN)

+
+
+ + diff --git a/widgets/widgets.html b/widgets/widgets.html index 0c1ba7e2c..c4b8bc4dc 100644 --- a/widgets/widgets.html +++ b/widgets/widgets.html @@ -1,51 +1,51 @@ - - - - -Airtime widgets - - - - -
-

On air now >>

-
    -
  • Current: Réseau jeunesse02:2227:37
  • - -
-
-
-
-
-

On air today

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
04:30 - 05:00Réseau jeunesse
07:00 - 07:30Mano River Press (EN)
07:30 - 08:00Weekend Review (EN)
08:30 - 09:00Focus (FR)
09:15 - 09:30The Stadium (EN)
09:30 - 10:00Echoes of Charles Taylor Trial
-
- - + + + + +Airtime widgets + + + + +
+

On air now >>

+
    +
  • Current: Réseau jeunesse02:2227:37
  • + +
+
+
+
+
+

On air today

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
04:30 - 05:00Réseau jeunesse
07:00 - 07:30Mano River Press (EN)
07:30 - 08:00Weekend Review (EN)
08:30 - 09:00Focus (FR)
09:15 - 09:30The Stadium (EN)
09:30 - 10:00Echoes of Charles Taylor Trial
+
+ + From cabe583a3b9327579fe98cd7150c4fe08cb64539 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 30 Oct 2012 15:01:46 -0400 Subject: [PATCH 133/157] CC-4649: Library -> Disable simple search if advanced search fields are open -done --- airtime_mvc/public/js/airtime/library/library.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/airtime_mvc/public/js/airtime/library/library.js b/airtime_mvc/public/js/airtime/library/library.js index a832134c1..c50b2a375 100644 --- a/airtime_mvc/public/js/airtime/library/library.js +++ b/airtime_mvc/public/js/airtime/library/library.js @@ -675,13 +675,16 @@ var AIRTIME = (function(AIRTIME) { oTable.fnSetFilteringDelay(350); $libContent.on("click", "legend", function(){ + $simpleSearch = $libContent.find("#library_display_filter label"); var $fs = $(this).parents("fieldset"); if ($fs.hasClass("closed")) { $fs.removeClass("closed"); + $simpleSearch.addClass("sp-invisible"); } else { $fs.addClass("closed"); + $simpleSearch.removeClass("sp-invisible"); } }); From 00947f9d7e93c8cedcf5ccede491b4460fb76768 Mon Sep 17 00:00:00 2001 From: denise Date: Tue, 30 Oct 2012 15:34:38 -0400 Subject: [PATCH 134/157] CC-4640: Automatically jump to current song when loading the Now Playing page. -small fix --- airtime_mvc/public/js/airtime/showbuilder/builder.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/airtime_mvc/public/js/airtime/showbuilder/builder.js b/airtime_mvc/public/js/airtime/showbuilder/builder.js index c64825393..de9142190 100644 --- a/airtime_mvc/public/js/airtime/showbuilder/builder.js +++ b/airtime_mvc/public/js/airtime/showbuilder/builder.js @@ -648,6 +648,8 @@ var AIRTIME = (function(AIRTIME){ $("#draggingContainer").remove(); }, "fnDrawCallback": function fnBuilderDrawCallback(oSettings, json) { + var isInitialized = false; + if (!isInitialized) { //when coming to 'Now Playing' page we want the page //to jump to the current track From 8c90c1a12f4048b68f066b92e4013f3478f0e38c Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Tue, 30 Oct 2012 17:19:40 -0400 Subject: [PATCH 135/157] CC-4645: Add support for x-scpls playlist types -fixed --- airtime_mvc/application/models/Webstream.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/airtime_mvc/application/models/Webstream.php b/airtime_mvc/application/models/Webstream.php index 45d3caf9a..90afbe973 100644 --- a/airtime_mvc/application/models/Webstream.php +++ b/airtime_mvc/application/models/Webstream.php @@ -185,7 +185,7 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable } $mediaUrl = self::getMediaUrl($url, $mime, $content_length_found); - if (preg_match("/(x-mpegurl)|(xspf\+xml)|(pls\+xml)/", $mime)) { + if (preg_match("/(x-mpegurl)|(xspf\+xml)|(pls\+xml)|(x-scpls)/", $mime)) { list($mime, $content_length_found) = self::discoverStreamMime($mediaUrl); } } catch (Exception $e) { @@ -307,7 +307,7 @@ class Application_Model_Webstream implements Application_Model_LibraryEditable $media_url = self::getM3uUrl($url); } elseif (preg_match("/xspf\+xml/", $mime)) { $media_url = self::getXspfUrl($url); - } elseif (preg_match("/pls\+xml/", $mime)) { + } elseif (preg_match("/pls\+xml/", $mime) || preg_match("/x-scpls/", $mime)) { $media_url = self::getPlsUrl($url); } elseif (preg_match("/(mpeg|ogg)/", $mime)) { if ($content_length_found) { From 9d495ebc03e0a1ab7c033917d2b105de5deeef8e Mon Sep 17 00:00:00 2001 From: James Date: Tue, 30 Oct 2012 17:57:58 -0400 Subject: [PATCH 136/157] CC-4639: Give an option to allow smart blocks to reuse tracks if not enough tracks meet the time limit. - done --- .../controllers/PlaylistController.php | 1 + .../application/forms/SmartBlockCriteria.php | 10 +++- airtime_mvc/application/models/Block.php | 60 ++++++++++++++++--- .../scripts/form/smart-block-criteria.phtml | 14 +++++ airtime_mvc/public/css/styles.css | 2 +- .../js/airtime/playlist/smart_blockbuilder.js | 22 +++++++ 6 files changed, 99 insertions(+), 10 deletions(-) diff --git a/airtime_mvc/application/controllers/PlaylistController.php b/airtime_mvc/application/controllers/PlaylistController.php index 2cca81ac2..0d2ead443 100644 --- a/airtime_mvc/application/controllers/PlaylistController.php +++ b/airtime_mvc/application/controllers/PlaylistController.php @@ -513,6 +513,7 @@ class PlaylistController extends Zend_Controller_Action } catch (BlockNotFoundException $e) { $this->playlistNotFound('block', true); } catch (Exception $e) { + Logging::info($e); $this->playlistUnknownError($e); } } diff --git a/airtime_mvc/application/forms/SmartBlockCriteria.php b/airtime_mvc/application/forms/SmartBlockCriteria.php index 55a28c79a..8d716b461 100644 --- a/airtime_mvc/application/forms/SmartBlockCriteria.php +++ b/airtime_mvc/application/forms/SmartBlockCriteria.php @@ -212,6 +212,14 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm }//for + $repeatTracks = new Zend_Form_Element_Checkbox('sp_repeat_tracks'); + $repeatTracks->setDecorators(array('viewHelper')) + ->setLabel('Allow Repeat Tracks:'); + if (isset($storedCrit["repeat_tracks"])) { + $repeatTracks->setChecked($storedCrit["repeat_tracks"]["value"] == 1?true:false); + } + $this->addElement($repeatTracks); + $limit = new Zend_Form_Element_Select('sp_limit_options'); $limit->setAttrib('class', 'sp_input_select') ->setDecorators(array('viewHelper')) @@ -220,7 +228,7 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm $limit->setValue($storedCrit["limit"]["modifier"]); } $this->addElement($limit); - + $limitValue = new Zend_Form_Element_Text('sp_limit_value'); $limitValue->setAttrib('class', 'sp_input_text_limit') ->setLabel('Limit to') diff --git a/airtime_mvc/application/models/Block.php b/airtime_mvc/application/models/Block.php index 80fae297d..364c11ef0 100644 --- a/airtime_mvc/application/models/Block.php +++ b/airtime_mvc/application/models/Block.php @@ -1093,6 +1093,14 @@ SQL; ->setDbValue($p_criteriaData['etc']['sp_limit_value']) ->setDbBlockId($this->id) ->save(); + + // insert repeate track option + $qry = new CcBlockcriteria(); + $qry->setDbCriteria("repeat_tracks") + ->setDbModifier("N/A") + ->setDbValue($p_criteriaData['etc']['sp_repeat_tracks']) + ->setDbBlockId($this->id) + ->save(); } /** @@ -1105,7 +1113,7 @@ SQL; $this->saveSmartBlockCriteria($p_criteria); $insertList = $this->getListOfFilesUnderLimit(); $this->deleteAllFilesFromBlock(); - $this->addAudioClips(array_keys($insertList)); + $this->addAudioClips(array_values($insertList)); // update length in playlist contents. $this->updateBlockLengthInAllPlaylist(); @@ -1134,6 +1142,7 @@ SQL; $info = $this->getListofFilesMeetCriteria(); $files = $info['files']; $limit = $info['limit']; + $repeat = $info['repeat_tracks']; $insertList = array(); $totalTime = 0; @@ -1142,19 +1151,45 @@ SQL; // this moves the pointer to the first element in the collection $files->getFirst(); $iterator = $files->getIterator(); - while ($iterator->valid() && $totalTime < $limit['time']) { + + $isBlockFull = false; + + while ($iterator->valid()) { $id = $iterator->current()->getDbId(); $length = Application_Common_DateHelper::calculateLengthInSeconds($iterator->current()->getDbLength()); - $insertList[$id] = $length; + $insertList[] = $id; $totalTime += $length; $totalItems++; - - if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500) { - break; + + if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) { + $isBlockFull = true; + break; } $iterator->next(); } + + // if block is not full and reapeat_track is check, fill up more + while (!$isBlockFull && $repeat == 1) { + if (!$iterator->valid()) { + $iterator->closeCursor(); + $info = $this->getListofFilesMeetCriteria(); + $files = $info['files']; + $files->getFirst(); + $iterator = $files->getIterator(); + } + $id = $iterator->current()->getDbId(); + $length = Application_Common_DateHelper::calculateLengthInSeconds($iterator->current()->getDbLength()); + $insertList[] = $id; + $totalTime += $length; + $totalItems++; + + if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) { + break; + } + + $iterator->next(); + } return $insertList; } @@ -1202,6 +1237,8 @@ SQL; if ($criteria == "limit") { $storedCrit["limit"] = array("value"=>$value, "modifier"=>$modifier); + } else if($criteria == "repeat_tracks") { + $storedCrit["repeat_tracks"] = array("value"=>$value); } else { $storedCrit["crit"][$criteria][] = array("criteria"=>$criteria, "value"=>$value, "modifier"=>$modifier, "extra"=>$extra, "display_name"=>$criteriaOptions[$criteria]); } @@ -1317,6 +1354,7 @@ SQL; } // construct limit restriction $limits = array(); + if (isset($storedCrit['limit'])) { if ($storedCrit['limit']['modifier'] == "items") { $limits['time'] = 1440 * 60; @@ -1328,10 +1366,16 @@ SQL; $limits['items'] = null; } } + + $repeatTracks = 0; + if (isset($storedCrit['repeat_tracks'])) { + $repeatTracks = $storedCrit['repeat_tracks']['value']; + } + try { $out = $qry->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)->find(); - return array("files"=>$out, "limit"=>$limits, "count"=>$out->count()); + return array("files"=>$out, "limit"=>$limits, "repeat_tracks"=> $repeatTracks, "count"=>$out->count()); } catch (Exception $e) { Logging::info($e); } @@ -1377,7 +1421,7 @@ SQL; $output['etc'][$ele['name']] = $ele['value']; } } - + return $output; } // smart block functions end diff --git a/airtime_mvc/application/views/scripts/form/smart-block-criteria.phtml b/airtime_mvc/application/views/scripts/form/smart-block-criteria.phtml index 0f27248ca..c75791fe1 100644 --- a/airtime_mvc/application/views/scripts/form/smart-block-criteria.phtml +++ b/airtime_mvc/application/views/scripts/form/smart-block-criteria.phtml @@ -59,6 +59,20 @@
+
+ element->getElement('sp_repeat_tracks')->getLabel() ?> + + element->getElement('sp_repeat_tracks')?> + element->getElement("sp_repeat_tracks")->hasErrors()) : ?> + element->getElement("sp_repeat_tracks")->getMessages() as $error): ?> + + + + + +
+
+
element->getElement('sp_limit_value')->getLabel() ?> element->getElement('sp_limit_value')?> diff --git a/airtime_mvc/public/css/styles.css b/airtime_mvc/public/css/styles.css index b14b77251..c47192450 100644 --- a/airtime_mvc/public/css/styles.css +++ b/airtime_mvc/public/css/styles.css @@ -105,7 +105,7 @@ select { } .airtime_auth_help_icon, .custom_auth_help_icon, .stream_username_help_icon, -.playlist_type_help_icon, .master_username_help_icon { +.playlist_type_help_icon, .master_username_help_icon, .repeat_tracks_help_icon{ cursor: help; position: relative; display:inline-block; zoom:1; diff --git a/airtime_mvc/public/js/airtime/playlist/smart_blockbuilder.js b/airtime_mvc/public/js/airtime/playlist/smart_blockbuilder.js index 0dc3bc0a9..fc736b84a 100644 --- a/airtime_mvc/public/js/airtime/playlist/smart_blockbuilder.js +++ b/airtime_mvc/public/js/airtime/playlist/smart_blockbuilder.js @@ -384,6 +384,28 @@ function setupUI() { at: "right center" }, }); + + $(".repeat_tracks_help_icon").qtip({ + content: { + text: "If your criteria is too strict, Airtime may not be able to fill up the desired smart block length." + + " Hence, if you check this option, tracks will be used more than once." + }, + hide: { + delay: 500, + fixed: true + }, + style: { + border: { + width: 0, + radius: 4 + }, + classes: "ui-tooltip-dark ui-tooltip-rounded" + }, + position: { + my: "left bottom", + at: "right center" + }, + }); } function enableAndShowExtraField(valEle, index) { From 1899d588eea2e0eb4b4cbedd9330999dbac385f0 Mon Sep 17 00:00:00 2001 From: James Date: Tue, 30 Oct 2012 18:03:03 -0400 Subject: [PATCH 137/157] - CRLF fix --- .../application/forms/SmartBlockCriteria.php | 8 +++---- airtime_mvc/application/models/Block.php | 24 +++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/airtime_mvc/application/forms/SmartBlockCriteria.php b/airtime_mvc/application/forms/SmartBlockCriteria.php index 8d716b461..e48fc7590 100644 --- a/airtime_mvc/application/forms/SmartBlockCriteria.php +++ b/airtime_mvc/application/forms/SmartBlockCriteria.php @@ -212,11 +212,11 @@ class Application_Form_SmartBlockCriteria extends Zend_Form_SubForm }//for - $repeatTracks = new Zend_Form_Element_Checkbox('sp_repeat_tracks'); - $repeatTracks->setDecorators(array('viewHelper')) + $repeatTracks = new Zend_Form_Element_Checkbox('sp_repeat_tracks'); + $repeatTracks->setDecorators(array('viewHelper')) ->setLabel('Allow Repeat Tracks:'); - if (isset($storedCrit["repeat_tracks"])) { - $repeatTracks->setChecked($storedCrit["repeat_tracks"]["value"] == 1?true:false); + if (isset($storedCrit["repeat_tracks"])) { + $repeatTracks->setChecked($storedCrit["repeat_tracks"]["value"] == 1?true:false); } $this->addElement($repeatTracks); diff --git a/airtime_mvc/application/models/Block.php b/airtime_mvc/application/models/Block.php index 364c11ef0..c0a3fe41f 100644 --- a/airtime_mvc/application/models/Block.php +++ b/airtime_mvc/application/models/Block.php @@ -1097,9 +1097,9 @@ SQL; // insert repeate track option $qry = new CcBlockcriteria(); $qry->setDbCriteria("repeat_tracks") - ->setDbModifier("N/A") - ->setDbValue($p_criteriaData['etc']['sp_repeat_tracks']) - ->setDbBlockId($this->id) + ->setDbModifier("N/A") + ->setDbValue($p_criteriaData['etc']['sp_repeat_tracks']) + ->setDbBlockId($this->id) ->save(); } @@ -1161,9 +1161,9 @@ SQL; $totalTime += $length; $totalItems++; - if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) { - $isBlockFull = true; - break; + if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) { + $isBlockFull = true; + break; } $iterator->next(); @@ -1172,10 +1172,10 @@ SQL; // if block is not full and reapeat_track is check, fill up more while (!$isBlockFull && $repeat == 1) { if (!$iterator->valid()) { - $iterator->closeCursor(); - $info = $this->getListofFilesMeetCriteria(); - $files = $info['files']; - $files->getFirst(); + $iterator->closeCursor(); + $info = $this->getListofFilesMeetCriteria(); + $files = $info['files']; + $files->getFirst(); $iterator = $files->getIterator(); } $id = $iterator->current()->getDbId(); @@ -1184,8 +1184,8 @@ SQL; $totalTime += $length; $totalItems++; - if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) { - break; + if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) { + break; } $iterator->next(); From 9293a26738afcf7fa01e2a515776dc251e7d429b Mon Sep 17 00:00:00 2001 From: james Date: Wed, 31 Oct 2012 12:05:17 -0400 Subject: [PATCH 138/157] CC-4639: Give an option to allow smart blocks to reuse tracks if not enough tracks meet the time limit - code optimazation --- .../controllers/PlaylistController.php | 2 +- airtime_mvc/application/models/Block.php | 27 +++++++++---------- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/airtime_mvc/application/controllers/PlaylistController.php b/airtime_mvc/application/controllers/PlaylistController.php index 0d2ead443..38dbd4fd2 100644 --- a/airtime_mvc/application/controllers/PlaylistController.php +++ b/airtime_mvc/application/controllers/PlaylistController.php @@ -513,7 +513,7 @@ class PlaylistController extends Zend_Controller_Action } catch (BlockNotFoundException $e) { $this->playlistNotFound('block', true); } catch (Exception $e) { - Logging::info($e); + //Logging::info($e); $this->playlistUnknownError($e); } } diff --git a/airtime_mvc/application/models/Block.php b/airtime_mvc/application/models/Block.php index c0a3fe41f..57018ad5f 100644 --- a/airtime_mvc/application/models/Block.php +++ b/airtime_mvc/application/models/Block.php @@ -1113,7 +1113,12 @@ SQL; $this->saveSmartBlockCriteria($p_criteria); $insertList = $this->getListOfFilesUnderLimit(); $this->deleteAllFilesFromBlock(); - $this->addAudioClips(array_values($insertList)); + // constrcut id array + $ids = array(); + foreach ($insertList as $ele) { + $ids[] = $ele['id']; + } + $this->addAudioClips(array_values($ids)); // update length in playlist contents. $this->updateBlockLengthInAllPlaylist(); @@ -1157,7 +1162,7 @@ SQL; while ($iterator->valid()) { $id = $iterator->current()->getDbId(); $length = Application_Common_DateHelper::calculateLengthInSeconds($iterator->current()->getDbLength()); - $insertList[] = $id; + $insertList[] = array('id'=>$id, 'length'=>$length); $totalTime += $length; $totalItems++; @@ -1169,26 +1174,18 @@ SQL; $iterator->next(); } + $sizeOfInsert = count($insertList); + // if block is not full and reapeat_track is check, fill up more while (!$isBlockFull && $repeat == 1) { - if (!$iterator->valid()) { - $iterator->closeCursor(); - $info = $this->getListofFilesMeetCriteria(); - $files = $info['files']; - $files->getFirst(); - $iterator = $files->getIterator(); - } - $id = $iterator->current()->getDbId(); - $length = Application_Common_DateHelper::calculateLengthInSeconds($iterator->current()->getDbLength()); - $insertList[] = $id; - $totalTime += $length; + $randomEleKey = array_rand(array_slice($insertList, 0, $sizeOfInsert)); + $insertList[] = $insertList[$randomEleKey]; + $totalTime += $insertList[$randomEleKey]['length']; $totalItems++; if ((!is_null($limit['items']) && $limit['items'] == count($insertList)) || $totalItems > 500 || $totalTime > $limit['time']) { break; } - - $iterator->next(); } return $insertList; From 2e4d5ec14259eb7d7f63a42c5b0d3f93515d796a Mon Sep 17 00:00:00 2001 From: james Date: Wed, 31 Oct 2012 12:32:40 -0400 Subject: [PATCH 139/157] CC-4539: Advanced search: Sample rate searched on Hz, but search results shown in kHz - fixed --- airtime_mvc/application/models/Datatables.php | 6 +++--- airtime_mvc/public/js/airtime/library/library.js | 2 +- .../public/js/datatables/plugin/dataTables.columnFilter.js | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/airtime_mvc/application/models/Datatables.php b/airtime_mvc/application/models/Datatables.php index 65e7b1256..7545aec71 100644 --- a/airtime_mvc/application/models/Datatables.php +++ b/airtime_mvc/application/models/Datatables.php @@ -13,9 +13,9 @@ class Application_Model_Datatables if ($dbname == 'utime' || $dbname == 'mtime') { $input1 = isset($info[0])?Application_Common_DateHelper::ConvertToUtcDateTimeString($info[0]):null; $input2 = isset($info[1])?Application_Common_DateHelper::ConvertToUtcDateTimeString($info[1]):null; - } else if($dbname == 'bit_rate') { - $input1 = isset($info[0])?intval($info[0]) * 1000:null; - $input2 = isset($info[1])?intval($info[1]) * 1000:null; + } else if($dbname == 'bit_rate' || $dbname == 'sample_rate') { + $input1 = isset($info[0])?doubleval($info[0]) * 1000:null; + $input2 = isset($info[1])?doubleval($info[1]) * 1000:null; } else { $input1 = isset($info[0])?$info[0]:null; $input2 = isset($info[1])?$info[1]:null; diff --git a/airtime_mvc/public/js/airtime/library/library.js b/airtime_mvc/public/js/airtime/library/library.js index c50b2a375..6a9b8b459 100644 --- a/airtime_mvc/public/js/airtime/library/library.js +++ b/airtime_mvc/public/js/airtime/library/library.js @@ -1195,7 +1195,7 @@ var validationTypes = { "owner_id" : "s", "rating" : "i", "replay_gain" : "n", - "sample_rate" : "i", + "sample_rate" : "n", "track_title" : "s", "track_number" : "i", "info_url" : "s", diff --git a/airtime_mvc/public/js/datatables/plugin/dataTables.columnFilter.js b/airtime_mvc/public/js/datatables/plugin/dataTables.columnFilter.js index 4084fbbdb..80cb011cf 100644 --- a/airtime_mvc/public/js/datatables/plugin/dataTables.columnFilter.js +++ b/airtime_mvc/public/js/datatables/plugin/dataTables.columnFilter.js @@ -190,7 +190,7 @@ } else if (th.attr('id') == "length") { label = " hh:mm:ss.t"; } else if (th.attr('id') == "sample_rate") { - label = " Hz"; + label = " kHz"; } th.html(_fnRangeLabelPart(0)); From fd0e1c3c95a00d77ff1dc60d7c262de9e3aaf6df Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 31 Oct 2012 12:36:45 -0400 Subject: [PATCH 140/157] CC-4641: Now Playing: Extending show's length won't change the overbooked track's style -fixed --- airtime_mvc/application/models/Show.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index 41ffbeefd..e52091968 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -270,6 +270,8 @@ SQL; try { //update the status flag in cc_schedule. + + CcShowInstancesPeer::clearInstancePool(); $instances = CcShowInstancesQuery::create() ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) ->filterByDbShowId($this->_showId) @@ -1253,6 +1255,7 @@ SQL; if ($data['add_show_id'] != -1) { $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $con->beginTransaction(); + //current timesamp in UTC. $current_timestamp = gmdate("Y-m-d H:i:s"); From cc40dfdf4ef29c1f3d7c2bb02bbfa408abe60fa5 Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 31 Oct 2012 14:16:16 -0400 Subject: [PATCH 141/157] CC-4641: Now Playing: Extending show's length won't change the overbooked track's style -added comment --- airtime_mvc/application/models/Show.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index e52091968..6f088046d 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -270,8 +270,13 @@ SQL; try { //update the status flag in cc_schedule. - + + /* Since we didn't use a propel object when updating + * cc_show_instances table we need to clear the instances + * so the correct information is retrieved from the db + */ CcShowInstancesPeer::clearInstancePool(); + $instances = CcShowInstancesQuery::create() ->filterByDbEnds($current_timestamp, Criteria::GREATER_THAN) ->filterByDbShowId($this->_showId) From dfd52eedf15f2b25ddf8b0df2dc1231db9e7891f Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 31 Oct 2012 15:24:50 -0400 Subject: [PATCH 142/157] CC-4654: Library -> Simple search still has effects even if you are doing an advanced search -fixed --- .../public/js/airtime/library/library.js | 210 ++++++++++-------- 1 file changed, 121 insertions(+), 89 deletions(-) diff --git a/airtime_mvc/public/js/airtime/library/library.js b/airtime_mvc/public/js/airtime/library/library.js index 6a9b8b459..504fa8b59 100644 --- a/airtime_mvc/public/js/airtime/library/library.js +++ b/airtime_mvc/public/js/airtime/library/library.js @@ -70,7 +70,7 @@ var AIRTIME = (function(AIRTIME) { }; mod.getChosenAudioFilesLength = function(){ - //var files = Object.keys(chosenItems), + // var files = Object.keys(chosenItems), var files, $trs, cItem, @@ -215,7 +215,7 @@ var AIRTIME = (function(AIRTIME) { mod.removeFromChosen = function($el) { var id = $el.attr("id"); - //used to not keep dragged items selected. + // used to not keep dragged items selected. if (!$el.hasClass(LIB_SELECTED_CLASS)) { delete chosenItems[id]; } @@ -252,11 +252,11 @@ var AIRTIME = (function(AIRTIME) { }; /* - * selects all items which the user can currently see. - * (behaviour taken from gmail) + * selects all items which the user can currently see. (behaviour taken from + * gmail) * - * by default the items are selected in reverse order - * so we need to reverse it back + * by default the items are selected in reverse order so we need to reverse + * it back */ mod.selectCurrentPage = function() { $.fn.reverse = [].reverse; @@ -276,8 +276,8 @@ var AIRTIME = (function(AIRTIME) { }; /* - * deselects all items that the user can currently see. - * (behaviour taken from gmail) + * deselects all items that the user can currently see. (behaviour taken + * from gmail) */ mod.deselectCurrentPage = function() { var $inputs = $libTable.find("tbody input:checkbox"), @@ -328,7 +328,7 @@ var AIRTIME = (function(AIRTIME) { temp, aMedia = []; - //process selected files/playlists. + // process selected files/playlists. for (item in aData) { temp = aData[item]; if (temp !== null && temp.hasOwnProperty('id') ) { @@ -433,36 +433,37 @@ var AIRTIME = (function(AIRTIME) { oTable = $libTable.dataTable( { - //put hidden columns at the top to insure they can never be visible on the table through column reordering. + // put hidden columns at the top to insure they can never be visible + // on the table through column reordering. "aoColumns": [ - /* ftype */ { "sTitle" : "" , "mDataProp" : "ftype" , "bSearchable" : false , "bVisible" : false } , - /* Checkbox */ { "sTitle" : "" , "mDataProp" : "checkbox" , "bSortable" : false , "bSearchable" : false , "sWidth" : "25px" , "sClass" : "library_checkbox" } , - /* Type */ { "sTitle" : "" , "mDataProp" : "image" , "bSearchable" : false , "sWidth" : "25px" , "sClass" : "library_type" , "iDataSort" : 0 } , - /* Title */ { "sTitle" : "Title" , "mDataProp" : "track_title" , "sClass" : "library_title" , "sWidth" : "170px" } , - /* Creator */ { "sTitle" : "Creator" , "mDataProp" : "artist_name" , "sClass" : "library_creator" , "sWidth" : "160px" } , - /* Album */ { "sTitle" : "Album" , "mDataProp" : "album_title" , "sClass" : "library_album" , "sWidth" : "150px" } , - /* Bit Rate */ { "sTitle" : "Bit Rate" , "mDataProp" : "bit_rate" , "bVisible" : false , "sClass" : "library_bitrate" , "sWidth" : "80px" }, - /* BPM */ { "sTitle" : "BPM" , "mDataProp" : "bpm" , "bVisible" : false , "sClass" : "library_bpm" , "sWidth" : "50px" }, - /* Composer */ { "sTitle" : "Composer" , "mDataProp" : "composer" , "bVisible" : false , "sClass" : "library_composer" , "sWidth" : "150px" }, - /* Conductor */ { "sTitle" : "Conductor" , "mDataProp" : "conductor" , "bVisible" : false , "sClass" : "library_conductor" , "sWidth" : "125px" }, - /* Copyright */ { "sTitle" : "Copyright" , "mDataProp" : "copyright" , "bVisible" : false , "sClass" : "library_copyright" , "sWidth" : "125px" }, - /* Encoded */ { "sTitle" : "Encoded By" , "mDataProp" : "encoded_by" , "bVisible" : false , "sClass" : "library_encoded" , "sWidth" : "150px" }, - /* Genre */ { "sTitle" : "Genre" , "mDataProp" : "genre" , "bVisible" : false , "sClass" : "library_genre" , "sWidth" : "100px" }, - /* ISRC Number */ { "sTitle" : "ISRC" , "mDataProp" : "isrc_number" , "bVisible" : false , "sClass" : "library_isrc" , "sWidth" : "150px" }, - /* Label */ { "sTitle" : "Label" , "mDataProp" : "label" , "bVisible" : false , "sClass" : "library_label" , "sWidth" : "125px" }, - /* Language */ { "sTitle" : "Language" , "mDataProp" : "language" , "bVisible" : false , "sClass" : "library_language" , "sWidth" : "125px" }, + /* ftype */ { "sTitle" : "" , "mDataProp" : "ftype" , "bSearchable" : false , "bVisible" : false } , + /* Checkbox */ { "sTitle" : "" , "mDataProp" : "checkbox" , "bSortable" : false , "bSearchable" : false , "sWidth" : "25px" , "sClass" : "library_checkbox" } , + /* Type */ { "sTitle" : "" , "mDataProp" : "image" , "bSearchable" : false , "sWidth" : "25px" , "sClass" : "library_type" , "iDataSort" : 0 } , + /* Title */ { "sTitle" : "Title" , "mDataProp" : "track_title" , "sClass" : "library_title" , "sWidth" : "170px" } , + /* Creator */ { "sTitle" : "Creator" , "mDataProp" : "artist_name" , "sClass" : "library_creator" , "sWidth" : "160px" } , + /* Album */ { "sTitle" : "Album" , "mDataProp" : "album_title" , "sClass" : "library_album" , "sWidth" : "150px" } , + /* Bit Rate */ { "sTitle" : "Bit Rate" , "mDataProp" : "bit_rate" , "bVisible" : false , "sClass" : "library_bitrate" , "sWidth" : "80px" }, + /* BPM */ { "sTitle" : "BPM" , "mDataProp" : "bpm" , "bVisible" : false , "sClass" : "library_bpm" , "sWidth" : "50px" }, + /* Composer */ { "sTitle" : "Composer" , "mDataProp" : "composer" , "bVisible" : false , "sClass" : "library_composer" , "sWidth" : "150px" }, + /* Conductor */ { "sTitle" : "Conductor" , "mDataProp" : "conductor" , "bVisible" : false , "sClass" : "library_conductor" , "sWidth" : "125px" }, + /* Copyright */ { "sTitle" : "Copyright" , "mDataProp" : "copyright" , "bVisible" : false , "sClass" : "library_copyright" , "sWidth" : "125px" }, + /* Encoded */ { "sTitle" : "Encoded By" , "mDataProp" : "encoded_by" , "bVisible" : false , "sClass" : "library_encoded" , "sWidth" : "150px" }, + /* Genre */ { "sTitle" : "Genre" , "mDataProp" : "genre" , "bVisible" : false , "sClass" : "library_genre" , "sWidth" : "100px" }, + /* ISRC Number */ { "sTitle" : "ISRC" , "mDataProp" : "isrc_number" , "bVisible" : false , "sClass" : "library_isrc" , "sWidth" : "150px" }, + /* Label */ { "sTitle" : "Label" , "mDataProp" : "label" , "bVisible" : false , "sClass" : "library_label" , "sWidth" : "125px" }, + /* Language */ { "sTitle" : "Language" , "mDataProp" : "language" , "bVisible" : false , "sClass" : "library_language" , "sWidth" : "125px" }, /* Last Modified */ { "sTitle" : "Last Modified" , "mDataProp" : "mtime" , "bVisible" : false , "sClass" : "library_modified_time" , "sWidth" : "125px" }, - /* Last Played */ { "sTitle" : "Last Played " , "mDataProp" : "lptime" , "bVisible" : false , "sClass" : "library_modified_time" , "sWidth" : "125px" }, - /* Length */ { "sTitle" : "Length" , "mDataProp" : "length" , "sClass" : "library_length" , "sWidth" : "80px" } , - /* Mime */ { "sTitle" : "Mime" , "mDataProp" : "mime" , "bVisible" : false , "sClass" : "library_mime" , "sWidth" : "80px" }, - /* Mood */ { "sTitle" : "Mood" , "mDataProp" : "mood" , "bVisible" : false , "sClass" : "library_mood" , "sWidth" : "70px" }, - /* Owner */ { "sTitle" : "Owner" , "mDataProp" : "owner_id" , "bVisible" : false , "sClass" : "library_language" , "sWidth" : "125px" }, - /* Replay Gain */ { "sTitle" : "Replay Gain" , "mDataProp" : "replay_gain" , "bVisible" : false , "sClass" : "library_replay_gain" , "sWidth" : "80px" }, - /* Sample Rate */ { "sTitle" : "Sample Rate" , "mDataProp" : "sample_rate" , "bVisible" : false , "sClass" : "library_sr" , "sWidth" : "80px" }, - /* Track Number */ { "sTitle" : "Track Number" , "mDataProp" : "track_number" , "bVisible" : false , "sClass" : "library_track" , "sWidth" : "65px" }, - /* Upload Time */ { "sTitle" : "Uploaded" , "mDataProp" : "utime" , "sClass" : "library_upload_time" , "sWidth" : "125px" } , - /* Website */ { "sTitle" : "Website" , "mDataProp" : "info_url" , "bVisible" : false , "sClass" : "library_url" , "sWidth" : "150px" }, - /* Year */ { "sTitle" : "Year" , "mDataProp" : "year" , "bVisible" : false , "sClass" : "library_year" , "sWidth" : "60px" } + /* Last Played */ { "sTitle" : "Last Played " , "mDataProp" : "lptime" , "bVisible" : false , "sClass" : "library_modified_time" , "sWidth" : "125px" }, + /* Length */ { "sTitle" : "Length" , "mDataProp" : "length" , "sClass" : "library_length" , "sWidth" : "80px" } , + /* Mime */ { "sTitle" : "Mime" , "mDataProp" : "mime" , "bVisible" : false , "sClass" : "library_mime" , "sWidth" : "80px" }, + /* Mood */ { "sTitle" : "Mood" , "mDataProp" : "mood" , "bVisible" : false , "sClass" : "library_mood" , "sWidth" : "70px" }, + /* Owner */ { "sTitle" : "Owner" , "mDataProp" : "owner_id" , "bVisible" : false , "sClass" : "library_language" , "sWidth" : "125px" }, + /* Replay Gain */ { "sTitle" : "Replay Gain" , "mDataProp" : "replay_gain" , "bVisible" : false , "sClass" : "library_replay_gain" , "sWidth" : "80px" }, + /* Sample Rate */ { "sTitle" : "Sample Rate" , "mDataProp" : "sample_rate" , "bVisible" : false , "sClass" : "library_sr" , "sWidth" : "80px" }, + /* Track Number */ { "sTitle" : "Track Number" , "mDataProp" : "track_number" , "bVisible" : false , "sClass" : "library_track" , "sWidth" : "65px" }, + /* Upload Time */ { "sTitle" : "Uploaded" , "mDataProp" : "utime" , "sClass" : "library_upload_time" , "sWidth" : "125px" } , + /* Website */ { "sTitle" : "Website" , "mDataProp" : "info_url" , "bVisible" : false , "sClass" : "library_url" , "sWidth" : "150px" }, + /* Year */ { "sTitle" : "Year" , "mDataProp" : "year" , "bVisible" : false , "sClass" : "library_year" , "sWidth" : "60px" } ], "bProcessing": true, @@ -472,7 +473,7 @@ var AIRTIME = (function(AIRTIME) { "bStateSave": true, "fnStateSaveParams": function (oSettings, oData) { - //remove oData components we don't want to save. + // remove oData components we don't want to save. delete oData.oSearch; delete oData.aoSearchCols; }, @@ -499,8 +500,8 @@ var AIRTIME = (function(AIRTIME) { length, a = oData.abVisCols; - //putting serialized data back into the correct js type to make - //sure everything works properly. + // putting serialized data back into the correct js type to make + // sure everything works properly. for (i = 0, length = a.length; i < length; i++) { if (typeof(a[i]) === "string") { a[i] = (a[i] === "true") ? true : false; @@ -524,11 +525,12 @@ var AIRTIME = (function(AIRTIME) { "sAjaxDataProp": "files", "fnServerData": function ( sSource, aoData, fnCallback ) { - /* The real validation check is done in dataTables.columnFilter.js - * We also need to check it here because datatable is redrawn everytime - * an action is performed in the Library page. - * In order for datatable to redraw the advanced search fields - * MUST all be valid. + /* + * The real validation check is done in + * dataTables.columnFilter.js We also need to check it here + * because datatable is redrawn everytime an action is performed + * in the Library page. In order for datatable to redraw the + * advanced search fields MUST all be valid. */ var advSearchFields = $("div#advanced_search").children(':visible'); var advSearchValid = validateAdvancedSearch(advSearchFields); @@ -536,7 +538,7 @@ var AIRTIME = (function(AIRTIME) { aoData.push( { name: "format", value: "json"} ); aoData.push( { name: "advSearch", value: advSearchValid} ); - //push whether to search files/playlists or all. + // push whether to search files/playlists or all. type = $("#library_display_type").find("select").val(); type = (type === undefined) ? 0 : type; aoData.push( { name: "type", value: type} ); @@ -552,30 +554,37 @@ var AIRTIME = (function(AIRTIME) { "fnRowCallback": AIRTIME.library.fnRowCallback, "fnCreatedRow": function( nRow, aData, iDataIndex ) { - //add the play function to the library_type td + // add the play function to the library_type td $(nRow).find('td.library_type').click(function(){ if (aData.ftype === 'playlist' && aData.length !== '0.0'){ - playlistIndex = $(this).parent().attr('id').substring(3); //remove the pl_ + playlistIndex = $(this).parent().attr('id').substring(3); // remove + // the + // pl_ open_playlist_preview(playlistIndex, 0); } else if (aData.ftype === 'audioclip') { open_audio_preview(aData.ftype, aData.audioFile, aData.track_title, aData.artist_name); } else if (aData.ftype == 'stream') { open_audio_preview(aData.ftype, aData.audioFile, aData.track_title, aData.artist_name); } else if (aData.ftype == 'block' && aData.bl_type == 'static') { - blockIndex = $(this).parent().attr('id').substring(3); //remove the bl_ + blockIndex = $(this).parent().attr('id').substring(3); // remove + // the + // bl_ open_block_preview(blockIndex, 0); } return false; }); alreadyclicked=false; - //call the context menu so we can prevent the event from propagating. + // call the context menu so we can prevent the event from + // propagating. $(nRow).find('td:not(.library_checkbox, .library_type)').click(function(e){ var el=$(this); if (alreadyclicked) { alreadyclicked=false; // reset - clearTimeout(alreadyclickedTimeout); // prevent this from happening + clearTimeout(alreadyclickedTimeout); // prevent this + // from + // happening // do what needs to happen on double click. $tr = $(el).parent(); @@ -587,8 +596,8 @@ var AIRTIME = (function(AIRTIME) { alreadyclicked=true; alreadyclickedTimeout=setTimeout(function(){ alreadyclicked=false; // reset when it happens - // do what needs to happen on single click. - // use el instead of $(this) because $(this) is + // do what needs to happen on single click. + // use el instead of $(this) because $(this) is // no longer the element el.contextMenu({x: e.pageX, y: e.pageY}); },300); // <-- dblclick tolerance here @@ -596,7 +605,8 @@ var AIRTIME = (function(AIRTIME) { return false; }); - //add a tool tip to appear when the user clicks on the type icon. + // add a tool tip to appear when the user clicks on the type + // icon. $(nRow).find("td:not(.library_checkbox, .library_type)").qtip({ content: { text: "Loading...", @@ -620,7 +630,8 @@ var AIRTIME = (function(AIRTIME) { }, my: 'left center', at: 'right center', - viewport: $(window), // Keep the tooltip on-screen at all times + viewport: $(window), // Keep the tooltip on-screen at + // all times effect: false // Disable positioning animation }, style: { @@ -638,10 +649,11 @@ var AIRTIME = (function(AIRTIME) { hide: {event:'mouseout', delay: 50, fixed:true} }); }, - //remove any selected nodes before the draw. + // remove any selected nodes before the draw. "fnPreDrawCallback": function( oSettings ) { - //make sure any dragging helpers are removed or else they'll be stranded on the screen. + // make sure any dragging helpers are removed or else they'll be + // stranded on the screen. $("#draggingContainer").remove(); }, "fnDrawCallback": AIRTIME.library.fnDrawCallback, @@ -673,18 +685,33 @@ var AIRTIME = (function(AIRTIME) { setColumnFilter(oTable); oTable.fnSetFilteringDelay(350); - + + var simpleSearchText; + $libContent.on("click", "legend", function(){ $simpleSearch = $libContent.find("#library_display_filter label"); var $fs = $(this).parents("fieldset"); if ($fs.hasClass("closed")) { $fs.removeClass("closed"); + + //keep value of simple search for when user switches back to it + simpleSearchText = $simpleSearch.find('input').val(); + + // clear the simple search text field and reset datatable + $(".dataTables_filter input").val("").keyup(); + $simpleSearch.addClass("sp-invisible"); } else { - $fs.addClass("closed"); + //clear the advanced search fields and reset datatable + $(".filter_column input").val("").keyup(); + + //reset datatable with previous simple search results (if any) + $(".dataTables_filter input").val(simpleSearchText).keyup(); + $simpleSearch.removeClass("sp-invisible"); + $fs.addClass("closed"); } }); @@ -737,7 +764,7 @@ var AIRTIME = (function(AIRTIME) { addQtipToSCIcons(); - //begin context menu initialization. + // begin context menu initialization. $.contextMenu({ selector: '#library_display td:not(.library_checkbox)', trigger: "left", @@ -752,7 +779,7 @@ var AIRTIME = (function(AIRTIME) { function processMenuItems(oItems) { - //define an add to playlist callback. + // define an add to playlist callback. if (oItems.pl_add !== undefined) { var aItems = []; @@ -764,7 +791,7 @@ var AIRTIME = (function(AIRTIME) { oItems.pl_add.callback = callback; } - //define an edit callback. + // define an edit callback. if (oItems.edit !== undefined) { if (data.ftype === "audioclip") { @@ -788,7 +815,7 @@ var AIRTIME = (function(AIRTIME) { oItems.edit.callback = callback; } - //define a play callback. + // define a play callback. if (oItems.play !== undefined) { if (oItems.play.mime !== undefined) { @@ -799,23 +826,28 @@ var AIRTIME = (function(AIRTIME) { callback = function() { if (data.ftype === 'playlist' && data.length !== '0.0'){ - playlistIndex = $(this).parent().attr('id').substring(3); //remove the pl_ + playlistIndex = $(this).parent().attr('id').substring(3); // remove + // the + // pl_ open_playlist_preview(playlistIndex, 0); } else if (data.ftype === 'audioclip' || data.ftype === 'stream') { open_audio_preview(data.ftype, data.audioFile, data.track_title, data.artist_name); } else if (data.ftype === 'block') { - blockIndex = $(this).parent().attr('id').substring(3); //remove the pl_ + blockIndex = $(this).parent().attr('id').substring(3); // remove + // the + // pl_ open_block_preview(blockIndex, 0); } }; oItems.play.callback = callback; } - //define a delete callback. + // define a delete callback. if (oItems.del !== undefined) { - //delete through the playlist controller, will reset - //playlist screen if this is the currently edited playlist. + // delete through the playlist controller, will reset + // playlist screen if this is the currently edited + // playlist. if ((data.ftype === "playlist" || data.ftype === "block") && screen === "playlist") { callback = function() { aMedia = []; @@ -849,7 +881,7 @@ var AIRTIME = (function(AIRTIME) { oItems.del.callback = callback; } - //define a download callback. + // define a download callback. if (oItems.download !== undefined) { callback = function() { @@ -857,11 +889,11 @@ var AIRTIME = (function(AIRTIME) { }; oItems.download.callback = callback; } - //add callbacks for Soundcloud menu items. + // add callbacks for Soundcloud menu items. if (oItems.soundcloud !== undefined) { var soundcloud = oItems.soundcloud.items; - //define an upload to soundcloud callback. + // define an upload to soundcloud callback. if (soundcloud.upload !== undefined) { callback = function() { @@ -872,7 +904,7 @@ var AIRTIME = (function(AIRTIME) { soundcloud.upload.callback = callback; } - //define a view on soundcloud callback + // define a view on soundcloud callback if (soundcloud.view !== undefined) { callback = function() { @@ -988,7 +1020,8 @@ function addQtipToSCIcons(){ viewport: $(window) }, show: { - ready: true // Needed to make it show on first mouseover event + ready: true // Needed to make it show on first mouseover + // event } }); } @@ -1015,7 +1048,8 @@ function addQtipToSCIcons(){ viewport: $(window) }, show: { - ready: true // Needed to make it show on first mouseover event + ready: true // Needed to make it show on first mouseover + // event } }); }else if($(this).hasClass("sc-error")){ @@ -1042,7 +1076,8 @@ function addQtipToSCIcons(){ viewport: $(window) }, show: { - ready: true // Needed to make it show on first mouseover event + ready: true // Needed to make it show on first mouseover + // event } }); } @@ -1096,7 +1131,7 @@ function validateAdvancedSearch(divs) { } } - //string fields do not need validation + // string fields do not need validation if (searchTermType !== "s") { valid = regExpr.test(searchTerm[i]); if (!valid) allValid = false; @@ -1104,11 +1139,11 @@ function validateAdvancedSearch(divs) { addRemoveValidationIcons(valid, $(field), searchTermType); - /* Empty fields should not have valid/invalid indicator - * Range values are considered valid even if only the - * 'From' value is provided. Therefore, if the 'To' value - * is empty but the 'From' value is not empty we need to - * keep the validation icon on screen. + /* + * Empty fields should not have valid/invalid indicator Range values + * are considered valid even if only the 'From' value is provided. + * Therefore, if the 'To' value is empty but the 'From' value is not + * empty we need to keep the validation icon on screen. */ } else if (searchTerm[0] === "" && searchTerm[1] !== "" || searchTerm[0] === "" && searchTerm[1] === ""){ @@ -1144,7 +1179,7 @@ function addRemoveValidationIcons(valid, field, searchTermType) { if (valid) { if (!field.closest('div').children(':last-child').hasClass('checked-icon')) { - //remove invalid icon before adding valid icon + // remove invalid icon before adding valid icon if (field.closest('div').children(':last-child').hasClass('not-available-icon')) { field.closest('div').children(':last-child').remove(); } @@ -1152,7 +1187,7 @@ function addRemoveValidationIcons(valid, field, searchTermType) { } } else { if (!field.closest('div').children(':last-child').hasClass('not-available-icon')) { - //remove valid icon before adding invalid icon + // remove valid icon before adding invalid icon if (field.closest('div').children(':last-child').hasClass('checked-icon')) { field.closest('div').children(':last-child').remove(); } @@ -1161,12 +1196,9 @@ function addRemoveValidationIcons(valid, field, searchTermType) { } } -/* Validation types: - * s => string - * i => integer - * n => numeric (positive/negative, whole/decimals) - * t => timestamp - * l => length +/* + * Validation types: s => string i => integer n => numeric (positive/negative, + * whole/decimals) t => timestamp l => length */ var validationTypes = { "album_title" : "s", From fc613aa597dd31f87373c0320e8c252a90edb857 Mon Sep 17 00:00:00 2001 From: denise Date: Wed, 31 Oct 2012 16:01:17 -0400 Subject: [PATCH 143/157] CC-4604: Edit Metadata: DJ's cannot edit metadata on their own files -fixed --- .../application/controllers/LibraryController.php | 13 ++++++++----- airtime_mvc/application/models/StoredFile.php | 4 ++++ .../views/scripts/library/edit-file-md.phtml | 2 +- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/airtime_mvc/application/controllers/LibraryController.php b/airtime_mvc/application/controllers/LibraryController.php index a1d0d245e..72111cbc1 100644 --- a/airtime_mvc/application/controllers/LibraryController.php +++ b/airtime_mvc/application/controllers/LibraryController.php @@ -181,7 +181,8 @@ class LibraryController extends Zend_Controller_Action } } } - if ($isAdminOrPM) { + + if ($isAdminOrPM || $file->getFileOwnerId() == $user->getId()) { $menu["del"] = array("name"=> "Delete", "icon" => "delete", "url" => "/library/delete"); $menu["edit"] = array("name"=> "Edit Metadata", "icon" => "edit", "url" => "/library/edit-file-md/id/{$id}"); } @@ -364,15 +365,17 @@ class LibraryController extends Zend_Controller_Action { $user = Application_Model_User::getCurrentUser(); $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - if (!$isAdminOrPM) { - return; - } $request = $this->getRequest(); - $form = new Application_Form_EditAudioMD(); $file_id = $this->_getParam('id', null); $file = Application_Model_StoredFile::Recall($file_id); + + if (!$isAdminOrPM && $file->getFileOwnerId() != $user->getId()) { + return; + } + + $form = new Application_Form_EditAudioMD(); $form->populate($file->getDbColMetadata()); if ($request->isPost()) { diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php index 2300f4eb7..41178f2e3 100644 --- a/airtime_mvc/application/models/StoredFile.php +++ b/airtime_mvc/application/models/StoredFile.php @@ -1161,6 +1161,10 @@ SQL; return $this->_file->getDbFileExists(); } + public function getFileOwnerId() + { + return $this->_file->getDbOwnerId(); + } // note: never call this method from controllers because it does a sleep public function uploadToSoundCloud() diff --git a/airtime_mvc/application/views/scripts/library/edit-file-md.phtml b/airtime_mvc/application/views/scripts/library/edit-file-md.phtml index 6b7696c0a..bdead9832 100644 --- a/airtime_mvc/application/views/scripts/library/edit-file-md.phtml +++ b/airtime_mvc/application/views/scripts/library/edit-file-md.phtml @@ -1,6 +1,6 @@

Edit Metadata

- form->setAction($this->url()); + form->setAction($this->url()); echo $this->form; ?>
From 766a17bc2bbbd099093e2f79c531ff2d9bc91d9a Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Wed, 31 Oct 2012 16:38:53 -0400 Subject: [PATCH 144/157] CC-4657: Don't use deb-multimedia.org for package liblame --- install_full/ubuntu/airtime-full-install | 4 ++-- install_full/ubuntu/airtime-full-install-nginx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/install_full/ubuntu/airtime-full-install b/install_full/ubuntu/airtime-full-install index 11bff85ec..955ec3ac7 100755 --- a/install_full/ubuntu/airtime-full-install +++ b/install_full/ubuntu/airtime-full-install @@ -27,11 +27,11 @@ code=`lsb_release -cs` if [ "$dist" = "Debian" ]; then set +e - grep -E "deb +http://www.deb-multimedia.org/? squeeze +main +non-free" /etc/apt/sources.list + grep -E "deb http://backports.debian.org/debian-backports squeeze-backports main" /etc/apt/sources.list returncode=$? set -e if [ "$returncode" -ne "0" ]; then - echo "deb http://www.deb-multimedia.org squeeze main non-free" >> /etc/apt/sources.list + echo "deb http://backports.debian.org/debian-backports squeeze-backports main" >> /etc/apt/sources.list fi fi diff --git a/install_full/ubuntu/airtime-full-install-nginx b/install_full/ubuntu/airtime-full-install-nginx index 6b802b3bb..7e38e34cb 100755 --- a/install_full/ubuntu/airtime-full-install-nginx +++ b/install_full/ubuntu/airtime-full-install-nginx @@ -29,9 +29,9 @@ dist=`lsb_release -is` code=`lsb_release -cs` if [ "$dist" -eq "Debian" ]; then - grep "deb http://www.deb-multimedia.org squeeze main non-free" /etc/apt/sources.list + grep "deb http://backports.debian.org/debian-backports squeeze-backports main" /etc/apt/sources.list if [ "$?" -ne "0" ]; then - echo "deb http://www.deb-multimedia.org squeeze main non-free" >> /etc/apt/sources.list + echo "deb http://backports.debian.org/debian-backports squeeze-backports main" >> /etc/apt/sources.list fi fi From 3478797744d2b8252c541d09dd5038584546f90c Mon Sep 17 00:00:00 2001 From: Martin Konecny Date: Fri, 2 Nov 2012 11:32:02 -0400 Subject: [PATCH 145/157] cc-4661: new database tables for listener stats --- .../configs/classmap-airtime-conf.php | 14 + .../models/airtime/CcListenerCount.php | 18 + .../models/airtime/CcListenerCountPeer.php | 18 + .../models/airtime/CcListenerCountQuery.php | 18 + .../models/airtime/CcTimestamp.php | 18 + .../models/airtime/CcTimestampPeer.php | 18 + .../models/airtime/CcTimestampQuery.php | 18 + .../airtime/map/CcListenerCountTableMap.php | 55 + .../airtime/map/CcTimestampTableMap.php | 54 + .../models/airtime/om/BaseCcListenerCount.php | 857 +++++++++++++++ .../airtime/om/BaseCcListenerCountPeer.php | 978 ++++++++++++++++++ .../airtime/om/BaseCcListenerCountQuery.php | 303 ++++++ .../models/airtime/om/BaseCcTimestamp.php | 920 ++++++++++++++++ .../models/airtime/om/BaseCcTimestampPeer.php | 742 +++++++++++++ .../airtime/om/BaseCcTimestampQuery.php | 268 +++++ airtime_mvc/build/schema.xml | 12 + airtime_mvc/build/sql/schema.sql | 39 + 17 files changed, 4350 insertions(+) create mode 100644 airtime_mvc/application/models/airtime/CcListenerCount.php create mode 100644 airtime_mvc/application/models/airtime/CcListenerCountPeer.php create mode 100644 airtime_mvc/application/models/airtime/CcListenerCountQuery.php create mode 100644 airtime_mvc/application/models/airtime/CcTimestamp.php create mode 100644 airtime_mvc/application/models/airtime/CcTimestampPeer.php create mode 100644 airtime_mvc/application/models/airtime/CcTimestampQuery.php create mode 100644 airtime_mvc/application/models/airtime/map/CcListenerCountTableMap.php create mode 100644 airtime_mvc/application/models/airtime/map/CcTimestampTableMap.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcListenerCount.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcListenerCountPeer.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcListenerCountQuery.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcTimestamp.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcTimestampPeer.php create mode 100644 airtime_mvc/application/models/airtime/om/BaseCcTimestampQuery.php diff --git a/airtime_mvc/application/configs/classmap-airtime-conf.php b/airtime_mvc/application/configs/classmap-airtime-conf.php index caaf5c8d6..bc786f729 100644 --- a/airtime_mvc/application/configs/classmap-airtime-conf.php +++ b/airtime_mvc/application/configs/classmap-airtime-conf.php @@ -183,4 +183,18 @@ return array ( 'BaseCcWebstreamMetadataPeer' => 'airtime/om/BaseCcWebstreamMetadataPeer.php', 'BaseCcWebstreamMetadata' => 'airtime/om/BaseCcWebstreamMetadata.php', 'BaseCcWebstreamMetadataQuery' => 'airtime/om/BaseCcWebstreamMetadataQuery.php', + 'CcTimestampTableMap' => 'airtime/map/CcTimestampTableMap.php', + 'CcTimestampPeer' => 'airtime/CcTimestampPeer.php', + 'CcTimestamp' => 'airtime/CcTimestamp.php', + 'CcTimestampQuery' => 'airtime/CcTimestampQuery.php', + 'BaseCcTimestampPeer' => 'airtime/om/BaseCcTimestampPeer.php', + 'BaseCcTimestamp' => 'airtime/om/BaseCcTimestamp.php', + 'BaseCcTimestampQuery' => 'airtime/om/BaseCcTimestampQuery.php', + 'CcListenerCountTableMap' => 'airtime/map/CcListenerCountTableMap.php', + 'CcListenerCountPeer' => 'airtime/CcListenerCountPeer.php', + 'CcListenerCount' => 'airtime/CcListenerCount.php', + 'CcListenerCountQuery' => 'airtime/CcListenerCountQuery.php', + 'BaseCcListenerCountPeer' => 'airtime/om/BaseCcListenerCountPeer.php', + 'BaseCcListenerCount' => 'airtime/om/BaseCcListenerCount.php', + 'BaseCcListenerCountQuery' => 'airtime/om/BaseCcListenerCountQuery.php', ); \ No newline at end of file diff --git a/airtime_mvc/application/models/airtime/CcListenerCount.php b/airtime_mvc/application/models/airtime/CcListenerCount.php new file mode 100644 index 000000000..c1f7a8bd3 --- /dev/null +++ b/airtime_mvc/application/models/airtime/CcListenerCount.php @@ -0,0 +1,18 @@ +setName('cc_listener_count'); + $this->setPhpName('CcListenerCount'); + $this->setClassname('CcListenerCount'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_listener_count_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addForeignKey('TIMESTAMP_ID', 'DbTimestampId', 'INTEGER', 'cc_timestamp', 'ID', true, null, null); + $this->addColumn('LISTENER_COUNT', 'DbListenerCount', 'INTEGER', true, null, null); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcTimestamp', 'CcTimestamp', RelationMap::MANY_TO_ONE, array('timestamp_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + +} // CcListenerCountTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcTimestampTableMap.php b/airtime_mvc/application/models/airtime/map/CcTimestampTableMap.php new file mode 100644 index 000000000..6df327d36 --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcTimestampTableMap.php @@ -0,0 +1,54 @@ +setName('cc_timestamp'); + $this->setPhpName('CcTimestamp'); + $this->setClassname('CcTimestamp'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_timestamp_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addColumn('TIMESTAMP', 'DbTimestamp', 'TIMESTAMP', true, null, null); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcListenerCount', 'CcListenerCount', RelationMap::ONE_TO_MANY, array('id' => 'timestamp_id', ), 'CASCADE', null); + } // buildRelations() + +} // CcTimestampTableMap diff --git a/airtime_mvc/application/models/airtime/om/BaseCcListenerCount.php b/airtime_mvc/application/models/airtime/om/BaseCcListenerCount.php new file mode 100644 index 000000000..ac145edbe --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcListenerCount.php @@ -0,0 +1,857 @@ +id; + } + + /** + * Get the [timestamp_id] column value. + * + * @return int + */ + public function getDbTimestampId() + { + return $this->timestamp_id; + } + + /** + * Get the [listener_count] column value. + * + * @return int + */ + public function getDbListenerCount() + { + return $this->listener_count; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return CcListenerCount The current object (for fluent API support) + */ + public function setDbId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = CcListenerCountPeer::ID; + } + + return $this; + } // setDbId() + + /** + * Set the value of [timestamp_id] column. + * + * @param int $v new value + * @return CcListenerCount The current object (for fluent API support) + */ + public function setDbTimestampId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->timestamp_id !== $v) { + $this->timestamp_id = $v; + $this->modifiedColumns[] = CcListenerCountPeer::TIMESTAMP_ID; + } + + if ($this->aCcTimestamp !== null && $this->aCcTimestamp->getDbId() !== $v) { + $this->aCcTimestamp = null; + } + + return $this; + } // setDbTimestampId() + + /** + * Set the value of [listener_count] column. + * + * @param int $v new value + * @return CcListenerCount The current object (for fluent API support) + */ + public function setDbListenerCount($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->listener_count !== $v) { + $this->listener_count = $v; + $this->modifiedColumns[] = CcListenerCountPeer::LISTENER_COUNT; + } + + return $this; + } // setDbListenerCount() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false) + { + try { + + $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; + $this->timestamp_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; + $this->listener_count = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = CcListenerCountPeer::NUM_COLUMNS - CcListenerCountPeer::NUM_LAZY_LOAD_COLUMNS). + + } catch (Exception $e) { + throw new PropelException("Error populating CcListenerCount object", $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + + if ($this->aCcTimestamp !== null && $this->timestamp_id !== $this->aCcTimestamp->getDbId()) { + $this->aCcTimestamp = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param PropelPDO $con (optional) The PropelPDO connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $stmt = CcListenerCountPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $row = $stmt->fetch(PDO::FETCH_NUM); + $stmt->closeCursor(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCcTimestamp = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param PropelPDO $con + * @return void + * @throws PropelException + * @see BaseObject::setDeleted() + * @see BaseObject::isDeleted() + */ + public function delete(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + try { + $ret = $this->preDelete($con); + if ($ret) { + CcListenerCountQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()) + ->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CcListenerCountPeer::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(PropelPDO $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcTimestamp !== null) { + if ($this->aCcTimestamp->isModified() || $this->aCcTimestamp->isNew()) { + $affectedRows += $this->aCcTimestamp->save($con); + } + $this->setCcTimestamp($this->aCcTimestamp); + } + + if ($this->isNew() ) { + $this->modifiedColumns[] = CcListenerCountPeer::ID; + } + + // If this object has been modified, then save it to the database. + if ($this->isModified()) { + if ($this->isNew()) { + $criteria = $this->buildCriteria(); + if ($criteria->keyContainsValue(CcListenerCountPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcListenerCountPeer::ID.')'); + } + + $pk = BasePeer::doInsert($criteria, $con); + $affectedRows += 1; + $this->setDbId($pk); //[IMV] update autoincrement primary key + $this->setNew(false); + } else { + $affectedRows += CcListenerCountPeer::doUpdate($this, $con); + } + + $this->resetModified(); // [HL] After being saved an object is no longer 'modified' + } + + $this->alreadyInSave = false; + + } + return $affectedRows; + } // doSave() + + /** + * Array of ValidationFailed objects. + * @var array ValidationFailed[] + */ + protected $validationFailures = array(); + + /** + * Gets any ValidationFailed objects that resulted from last call to validate(). + * + * + * @return array ValidationFailed[] + * @see validate() + */ + public function getValidationFailures() + { + return $this->validationFailures; + } + + /** + * Validates the objects modified field values and all objects related to this table. + * + * If $columns is either a column name or an array of column names + * only those columns are validated. + * + * @param mixed $columns Column name or an array of column names. + * @return boolean Whether all columns pass validation. + * @see doValidate() + * @see getValidationFailures() + */ + public function validate($columns = null) + { + $res = $this->doValidate($columns); + if ($res === true) { + $this->validationFailures = array(); + return true; + } else { + $this->validationFailures = $res; + return false; + } + } + + /** + * This function performs the validation work for complex object models. + * + * In addition to checking the current object, all related objects will + * also be validated. If all pass then true is returned; otherwise + * an aggreagated array of ValidationFailed objects will be returned. + * + * @param array $columns Array of column names to validate. + * @return mixed true if all validations pass; array of ValidationFailed objets otherwise. + */ + protected function doValidate($columns = null) + { + if (!$this->alreadyInValidation) { + $this->alreadyInValidation = true; + $retval = null; + + $failureMap = array(); + + + // We call the validate method on the following object(s) if they + // were passed to this object by their coresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCcTimestamp !== null) { + if (!$this->aCcTimestamp->validate($columns)) { + $failureMap = array_merge($failureMap, $this->aCcTimestamp->getValidationFailures()); + } + } + + + if (($retval = CcListenerCountPeer::doValidate($this, $columns)) !== true) { + $failureMap = array_merge($failureMap, $retval); + } + + + + $this->alreadyInValidation = false; + } + + return (!empty($failureMap) ? $failureMap : true); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return mixed Value of field. + */ + public function getByName($name, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcListenerCountPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $field = $this->getByPosition($pos); + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch($pos) { + case 0: + return $this->getDbId(); + break; + case 1: + return $this->getDbTimestampId(); + break; + case 2: + return $this->getDbListenerCount(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * Defaults to BasePeer::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $includeForeignObjects = false) + { + $keys = CcListenerCountPeer::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getDbId(), + $keys[1] => $this->getDbTimestampId(), + $keys[2] => $this->getDbListenerCount(), + ); + if ($includeForeignObjects) { + if (null !== $this->aCcTimestamp) { + $result['CcTimestamp'] = $this->aCcTimestamp->toArray($keyType, $includeLazyLoadColumns, true); + } + } + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name peer name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return void + */ + public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcListenerCountPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch($pos) { + case 0: + $this->setDbId($value); + break; + case 1: + $this->setDbTimestampId($value); + break; + case 2: + $this->setDbListenerCount($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * The default key type is the column's phpname (e.g. 'AuthorId') + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) + { + $keys = CcListenerCountPeer::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setDbTimestampId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setDbListenerCount($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CcListenerCountPeer::DATABASE_NAME); + + if ($this->isColumnModified(CcListenerCountPeer::ID)) $criteria->add(CcListenerCountPeer::ID, $this->id); + if ($this->isColumnModified(CcListenerCountPeer::TIMESTAMP_ID)) $criteria->add(CcListenerCountPeer::TIMESTAMP_ID, $this->timestamp_id); + if ($this->isColumnModified(CcListenerCountPeer::LISTENER_COUNT)) $criteria->add(CcListenerCountPeer::LISTENER_COUNT, $this->listener_count); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CcListenerCountPeer::DATABASE_NAME); + $criteria->add(CcListenerCountPeer::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getDbId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setDbId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + return null === $this->getDbId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of CcListenerCount (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false) + { + $copyObj->setDbTimestampId($this->timestamp_id); + $copyObj->setDbListenerCount($this->listener_count); + + $copyObj->setNew(true); + $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return CcListenerCount Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + return $copyObj; + } + + /** + * Returns a peer instance associated with this om. + * + * Since Peer classes are not to have any instance attributes, this method returns the + * same instance for all member of this class. The method could therefore + * be static, but this would prevent one from overriding the behavior. + * + * @return CcListenerCountPeer + */ + public function getPeer() + { + if (self::$peer === null) { + self::$peer = new CcListenerCountPeer(); + } + return self::$peer; + } + + /** + * Declares an association between this object and a CcTimestamp object. + * + * @param CcTimestamp $v + * @return CcListenerCount The current object (for fluent API support) + * @throws PropelException + */ + public function setCcTimestamp(CcTimestamp $v = null) + { + if ($v === null) { + $this->setDbTimestampId(NULL); + } else { + $this->setDbTimestampId($v->getDbId()); + } + + $this->aCcTimestamp = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the CcTimestamp object, it will not be re-added. + if ($v !== null) { + $v->addCcListenerCount($this); + } + + return $this; + } + + + /** + * Get the associated CcTimestamp object + * + * @param PropelPDO Optional Connection object. + * @return CcTimestamp The associated CcTimestamp object. + * @throws PropelException + */ + public function getCcTimestamp(PropelPDO $con = null) + { + if ($this->aCcTimestamp === null && ($this->timestamp_id !== null)) { + $this->aCcTimestamp = CcTimestampQuery::create()->findPk($this->timestamp_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCcTimestamp->addCcListenerCounts($this); + */ + } + return $this->aCcTimestamp; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->timestamp_id = null; + $this->listener_count = null; + $this->alreadyInSave = false; + $this->alreadyInValidation = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all collections of referencing foreign keys. + * + * This method is a user-space workaround for PHP's inability to garbage collect objects + * with circular references. This is currently necessary when using Propel in certain + * daemon or large-volumne/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all associated objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCcTimestamp = null; + } + + /** + * Catches calls to virtual methods + */ + public function __call($name, $params) + { + if (preg_match('/get(\w+)/', $name, $matches)) { + $virtualColumn = $matches[1]; + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + // no lcfirst in php<5.3... + $virtualColumn[0] = strtolower($virtualColumn[0]); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + throw new PropelException('Call to undefined method: ' . $name); + } + +} // BaseCcListenerCount diff --git a/airtime_mvc/application/models/airtime/om/BaseCcListenerCountPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcListenerCountPeer.php new file mode 100644 index 000000000..4123bfed5 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcListenerCountPeer.php @@ -0,0 +1,978 @@ + array ('DbId', 'DbTimestampId', 'DbListenerCount', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbTimestampId', 'dbListenerCount', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::TIMESTAMP_ID, self::LISTENER_COUNT, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'TIMESTAMP_ID', 'LISTENER_COUNT', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'timestamp_id', 'listener_count', ), + BasePeer::TYPE_NUM => array (0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 + */ + private static $fieldKeys = array ( + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbTimestampId' => 1, 'DbListenerCount' => 2, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbTimestampId' => 1, 'dbListenerCount' => 2, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::TIMESTAMP_ID => 1, self::LISTENER_COUNT => 2, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'TIMESTAMP_ID' => 1, 'LISTENER_COUNT' => 2, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'timestamp_id' => 1, 'listener_count' => 2, ), + BasePeer::TYPE_NUM => array (0, 1, 2, ) + ); + + /** + * Translates a fieldname to another type + * + * @param string $name field name + * @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @param string $toType One of the class type constants + * @return string translated name of the field. + * @throws PropelException - if the specified name could not be found in the fieldname mappings. + */ + static public function translateFieldName($name, $fromType, $toType) + { + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; + if ($key === null) { + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); + } + return $toNames[$key]; + } + + /** + * Returns an array of field names. + * + * @param string $type The type of fieldnames to return: + * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return array A list of field names + */ + + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) + { + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); + } + return self::$fieldNames[$type]; + } + + /** + * Convenience method which changes table.column to alias.column. + * + * Using this method you can maintain SQL abstraction while using column aliases. + * + * $c->addAlias("alias1", TablePeer::TABLE_NAME); + * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); + * + * @param string $alias The alias for the current table. + * @param string $column The column name for current table. (i.e. CcListenerCountPeer::COLUMN_NAME). + * @return string + */ + public static function alias($alias, $column) + { + return str_replace(CcListenerCountPeer::TABLE_NAME.'.', $alias.'.', $column); + } + + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CcListenerCountPeer::ID); + $criteria->addSelectColumn(CcListenerCountPeer::TIMESTAMP_ID); + $criteria->addSelectColumn(CcListenerCountPeer::LISTENER_COUNT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.TIMESTAMP_ID'); + $criteria->addSelectColumn($alias . '.LISTENER_COUNT'); + } + } + + /** + * Returns the number of rows matching criteria. + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @return int Number of matching rows. + */ + public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) + { + // we may modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcListenerCountPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcListenerCountPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + $criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName + + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + // BasePeer returns a PDOStatement + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + /** + * Method to select one object from the DB. + * + * @param Criteria $criteria object used to create the SELECT statement. + * @param PropelPDO $con + * @return CcListenerCount + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectOne(Criteria $criteria, PropelPDO $con = null) + { + $critcopy = clone $criteria; + $critcopy->setLimit(1); + $objects = CcListenerCountPeer::doSelect($critcopy, $con); + if ($objects) { + return $objects[0]; + } + return null; + } + /** + * Method to do selects. + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con + * @return array Array of selected Objects + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelect(Criteria $criteria, PropelPDO $con = null) + { + return CcListenerCountPeer::populateObjects(CcListenerCountPeer::doSelectStmt($criteria, $con)); + } + /** + * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. + * + * Use this method directly if you want to work with an executed statement durirectly (for example + * to perform your own object hydration). + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con The connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return PDOStatement The executed PDOStatement object. + * @see BasePeer::doSelect() + */ + public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + if (!$criteria->hasSelectClause()) { + $criteria = clone $criteria; + CcListenerCountPeer::addSelectColumns($criteria); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + // BasePeer returns a PDOStatement + return BasePeer::doSelect($criteria, $con); + } + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doSelect*() + * methods in your stub classes -- you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by doSelect*() + * and retrieveByPK*() calls. + * + * @param CcListenerCount $value A CcListenerCount object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool(CcListenerCount $obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if ($key === null) { + $key = (string) $obj->getDbId(); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A CcListenerCount object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && $value !== null) { + if (is_object($value) && $value instanceof CcListenerCount) { + $key = (string) $value->getDbId(); + } elseif (is_scalar($value)) { + // assume we've been passed a primary key + $key = (string) $value; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcListenerCount object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } // removeInstanceFromPool() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param string $key The key (@see getPrimaryKeyHash()) for this instance. + * @return CcListenerCount Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @see getPrimaryKeyHash() + */ + public static function getInstanceFromPool($key) + { + if (Propel::isInstancePoolingEnabled()) { + if (isset(self::$instances[$key])) { + return self::$instances[$key]; + } + } + return null; // just to be explicit + } + + /** + * Clear the instance pool. + * + * @return void + */ + public static function clearInstancePool() + { + self::$instances = array(); + } + + /** + * Method to invalidate the instance pool of all tables related to cc_listener_count + * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return string A string version of PK or NULL if the components of primary key in result array are all null. + */ + public static function getPrimaryKeyHashFromRow($row, $startcol = 0) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[$startcol] === null) { + return null; + } + return (string) $row[$startcol]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $startcol = 0) + { + return (int) $row[$startcol]; + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(PDOStatement $stmt) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = CcListenerCountPeer::getOMClass(false); + // populate the object(s) + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key = CcListenerCountPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcListenerCountPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CcListenerCountPeer::addInstanceToPool($obj, $key); + } // if key exists + } + $stmt->closeCursor(); + return $results; + } + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CcListenerCount object, last column rank) + */ + public static function populateObject($row, $startcol = 0) + { + $key = CcListenerCountPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcListenerCountPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $startcol, true); // rehydrate + $col = $startcol + CcListenerCountPeer::NUM_COLUMNS; + } else { + $cls = CcListenerCountPeer::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $startcol); + CcListenerCountPeer::addInstanceToPool($obj, $key); + } + return array($obj, $col); + } + + /** + * Returns the number of rows matching criteria, joining the related CcTimestamp table + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinCcTimestamp(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcListenerCountPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcListenerCountPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcListenerCountPeer::TIMESTAMP_ID, CcTimestampPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + + /** + * Selects a collection of CcListenerCount objects pre-filled with their CcTimestamp objects. + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcListenerCount objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinCcTimestamp(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcListenerCountPeer::addSelectColumns($criteria); + $startcol = (CcListenerCountPeer::NUM_COLUMNS - CcListenerCountPeer::NUM_LAZY_LOAD_COLUMNS); + CcTimestampPeer::addSelectColumns($criteria); + + $criteria->addJoin(CcListenerCountPeer::TIMESTAMP_ID, CcTimestampPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcListenerCountPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcListenerCountPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + + $cls = CcListenerCountPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcListenerCountPeer::addInstanceToPool($obj1, $key1); + } // if $obj1 already loaded + + $key2 = CcTimestampPeer::getPrimaryKeyHashFromRow($row, $startcol); + if ($key2 !== null) { + $obj2 = CcTimestampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcTimestampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol); + CcTimestampPeer::addInstanceToPool($obj2, $key2); + } // if obj2 already loaded + + // Add the $obj1 (CcListenerCount) to $obj2 (CcTimestamp) + $obj2->addCcListenerCount($obj1); + + } // if joined row was not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + + /** + * Returns the number of rows matching criteria, joining all related tables + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return int Number of matching rows. + */ + public static function doCountJoinAll(Criteria $criteria, $distinct = false, PropelPDO $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcListenerCountPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcListenerCountPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria->addJoin(CcListenerCountPeer::TIMESTAMP_ID, CcTimestampPeer::ID, $join_behavior); + + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + + /** + * Selects a collection of CcListenerCount objects pre-filled with all related objects. + * + * @param Criteria $criteria + * @param PropelPDO $con + * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN + * @return array Array of CcListenerCount objects. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectJoinAll(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) + { + $criteria = clone $criteria; + + // Set the correct dbName if it has not been overridden + if ($criteria->getDbName() == Propel::getDefaultDB()) { + $criteria->setDbName(self::DATABASE_NAME); + } + + CcListenerCountPeer::addSelectColumns($criteria); + $startcol2 = (CcListenerCountPeer::NUM_COLUMNS - CcListenerCountPeer::NUM_LAZY_LOAD_COLUMNS); + + CcTimestampPeer::addSelectColumns($criteria); + $startcol3 = $startcol2 + (CcTimestampPeer::NUM_COLUMNS - CcTimestampPeer::NUM_LAZY_LOAD_COLUMNS); + + $criteria->addJoin(CcListenerCountPeer::TIMESTAMP_ID, CcTimestampPeer::ID, $join_behavior); + + $stmt = BasePeer::doSelect($criteria, $con); + $results = array(); + + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key1 = CcListenerCountPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj1 = CcListenerCountPeer::getInstanceFromPool($key1))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj1->hydrate($row, 0, true); // rehydrate + } else { + $cls = CcListenerCountPeer::getOMClass(false); + + $obj1 = new $cls(); + $obj1->hydrate($row); + CcListenerCountPeer::addInstanceToPool($obj1, $key1); + } // if obj1 already loaded + + // Add objects for joined CcTimestamp rows + + $key2 = CcTimestampPeer::getPrimaryKeyHashFromRow($row, $startcol2); + if ($key2 !== null) { + $obj2 = CcTimestampPeer::getInstanceFromPool($key2); + if (!$obj2) { + + $cls = CcTimestampPeer::getOMClass(false); + + $obj2 = new $cls(); + $obj2->hydrate($row, $startcol2); + CcTimestampPeer::addInstanceToPool($obj2, $key2); + } // if obj2 loaded + + // Add the $obj1 (CcListenerCount) to the collection in $obj2 (CcTimestamp) + $obj2->addCcListenerCount($obj1); + } // if joined row not null + + $results[] = $obj1; + } + $stmt->closeCursor(); + return $results; + } + + /** + * Returns the TableMap related to this peer. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this peer class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getDatabaseMap(BaseCcListenerCountPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcListenerCountPeer::TABLE_NAME)) + { + $dbMap->addTableObject(new CcListenerCountTableMap()); + } + } + + /** + * The class that the Peer will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is tranalted into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CcListenerCountPeer::CLASS_DEFAULT : CcListenerCountPeer::OM_CLASS; + } + + /** + * Method perform an INSERT on the database, given a CcListenerCount or Criteria object. + * + * @param mixed $values Criteria or CcListenerCount object containing data that is used to create the INSERT statement. + * @param PropelPDO $con the PropelPDO connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } else { + $criteria = $values->buildCriteria(); // build Criteria from CcListenerCount object + } + + if ($criteria->containsKey(CcListenerCountPeer::ID) && $criteria->keyContainsValue(CcListenerCountPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcListenerCountPeer::ID.')'); + } + + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = BasePeer::doInsert($criteria, $con); + $con->commit(); + } catch(PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + + /** + * Method perform an UPDATE on the database, given a CcListenerCount or Criteria object. + * + * @param mixed $values Criteria or CcListenerCount object containing data that is used to create the UPDATE statement. + * @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions). + * @return int The number of affected rows (if supported by underlying database driver). + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doUpdate($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $selectCriteria = new Criteria(self::DATABASE_NAME); + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + + $comparison = $criteria->getComparison(CcListenerCountPeer::ID); + $value = $criteria->remove(CcListenerCountPeer::ID); + if ($value) { + $selectCriteria->add(CcListenerCountPeer::ID, $value, $comparison); + } else { + $selectCriteria->setPrimaryTableName(CcListenerCountPeer::TABLE_NAME); + } + + } else { // $values is CcListenerCount object + $criteria = $values->buildCriteria(); // gets full criteria + $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) + } + + // set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + return BasePeer::doUpdate($selectCriteria, $criteria, $con); + } + + /** + * Method to DELETE all rows from the cc_listener_count table. + * + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll($con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += BasePeer::doDeleteAll(CcListenerCountPeer::TABLE_NAME, $con, CcListenerCountPeer::DATABASE_NAME); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CcListenerCountPeer::clearInstancePool(); + CcListenerCountPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Method perform a DELETE on the database, given a CcListenerCount or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CcListenerCount object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param PropelPDO $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + // invalidate the cache for all objects of this type, since we have no + // way of knowing (without running a query) what objects should be invalidated + // from the cache based on this Criteria. + CcListenerCountPeer::clearInstancePool(); + // rename for clarity + $criteria = clone $values; + } elseif ($values instanceof CcListenerCount) { // it's a model object + // invalidate the cache for this single object + CcListenerCountPeer::removeInstanceFromPool($values); + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(CcListenerCountPeer::ID, (array) $values, Criteria::IN); + // invalidate the cache for this object(s) + foreach ((array) $values as $singleval) { + CcListenerCountPeer::removeInstanceFromPool($singleval); + } + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + $affectedRows += BasePeer::doDelete($criteria, $con); + CcListenerCountPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Validates all modified columns of given CcListenerCount object. + * If parameter $columns is either a single column name or an array of column names + * than only those columns are validated. + * + * NOTICE: This does not apply to primary or foreign keys for now. + * + * @param CcListenerCount $obj The object to validate. + * @param mixed $cols Column name or array of column names. + * + * @return mixed TRUE if all columns are valid or the error message of the first invalid column. + */ + public static function doValidate(CcListenerCount $obj, $cols = null) + { + $columns = array(); + + if ($cols) { + $dbMap = Propel::getDatabaseMap(CcListenerCountPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcListenerCountPeer::TABLE_NAME); + + if (! is_array($cols)) { + $cols = array($cols); + } + + foreach ($cols as $colName) { + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); + $columns[$colName] = $obj->$get(); + } + } + } else { + + } + + return BasePeer::doValidate(CcListenerCountPeer::DATABASE_NAME, CcListenerCountPeer::TABLE_NAME, $columns); + } + + /** + * Retrieve a single object by pkey. + * + * @param int $pk the primary key. + * @param PropelPDO $con the connection to use + * @return CcListenerCount + */ + public static function retrieveByPK($pk, PropelPDO $con = null) + { + + if (null !== ($obj = CcListenerCountPeer::getInstanceFromPool((string) $pk))) { + return $obj; + } + + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria = new Criteria(CcListenerCountPeer::DATABASE_NAME); + $criteria->add(CcListenerCountPeer::ID, $pk); + + $v = CcListenerCountPeer::doSelect($criteria, $con); + + return !empty($v) > 0 ? $v[0] : null; + } + + /** + * Retrieve multiple objects by pkey. + * + * @param array $pks List of primary keys + * @param PropelPDO $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function retrieveByPKs($pks, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcListenerCountPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $objs = null; + if (empty($pks)) { + $objs = array(); + } else { + $criteria = new Criteria(CcListenerCountPeer::DATABASE_NAME); + $criteria->add(CcListenerCountPeer::ID, $pks, Criteria::IN); + $objs = CcListenerCountPeer::doSelect($criteria, $con); + } + return $objs; + } + +} // BaseCcListenerCountPeer + +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BaseCcListenerCountPeer::buildTableMap(); + diff --git a/airtime_mvc/application/models/airtime/om/BaseCcListenerCountQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcListenerCountQuery.php new file mode 100644 index 000000000..3c59dc0ed --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcListenerCountQuery.php @@ -0,0 +1,303 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + return $query; + } + + /** + * Find object by primary key + * Use instance pooling to avoid a database query if the object exists + * + * $obj = $c->findPk(12, $con); + * + * @param mixed $key Primary key to use for the query + * @param PropelPDO $con an optional connection object + * + * @return CcListenerCount|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcListenerCountPeer::getInstanceFromPool((string) $key))) && $this->getFormatter()->isObjectFormatter()) { + // the object is alredy in the instance pool + return $obj; + } else { + // the object has not been requested yet, or the formatter is not an object formatter + $criteria = $this->isKeepQuery() ? clone $this : $this; + $stmt = $criteria + ->filterByPrimaryKey($key) + ->getSelectStatement($con); + return $criteria->getFormatter()->init($criteria)->formatOne($stmt); + } + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param PropelPDO $con an optional connection object + * + * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + $criteria = $this->isKeepQuery() ? clone $this : $this; + return $this + ->filterByPrimaryKeys($keys) + ->find($con); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcListenerCountPeer::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcListenerCountPeer::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * @param int|array $dbId The value to use as filter. + * Accepts an associative array('min' => $minValue, 'max' => $maxValue) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function filterByDbId($dbId = null, $comparison = null) + { + if (is_array($dbId) && null === $comparison) { + $comparison = Criteria::IN; + } + return $this->addUsingAlias(CcListenerCountPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the timestamp_id column + * + * @param int|array $dbTimestampId The value to use as filter. + * Accepts an associative array('min' => $minValue, 'max' => $maxValue) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function filterByDbTimestampId($dbTimestampId = null, $comparison = null) + { + if (is_array($dbTimestampId)) { + $useMinMax = false; + if (isset($dbTimestampId['min'])) { + $this->addUsingAlias(CcListenerCountPeer::TIMESTAMP_ID, $dbTimestampId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbTimestampId['max'])) { + $this->addUsingAlias(CcListenerCountPeer::TIMESTAMP_ID, $dbTimestampId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcListenerCountPeer::TIMESTAMP_ID, $dbTimestampId, $comparison); + } + + /** + * Filter the query on the listener_count column + * + * @param int|array $dbListenerCount The value to use as filter. + * Accepts an associative array('min' => $minValue, 'max' => $maxValue) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function filterByDbListenerCount($dbListenerCount = null, $comparison = null) + { + if (is_array($dbListenerCount)) { + $useMinMax = false; + if (isset($dbListenerCount['min'])) { + $this->addUsingAlias(CcListenerCountPeer::LISTENER_COUNT, $dbListenerCount['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbListenerCount['max'])) { + $this->addUsingAlias(CcListenerCountPeer::LISTENER_COUNT, $dbListenerCount['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcListenerCountPeer::LISTENER_COUNT, $dbListenerCount, $comparison); + } + + /** + * Filter the query by a related CcTimestamp object + * + * @param CcTimestamp $ccTimestamp the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function filterByCcTimestamp($ccTimestamp, $comparison = null) + { + return $this + ->addUsingAlias(CcListenerCountPeer::TIMESTAMP_ID, $ccTimestamp->getDbId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcTimestamp relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function joinCcTimestamp($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcTimestamp'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcTimestamp'); + } + + return $this; + } + + /** + * Use the CcTimestamp relation CcTimestamp object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcTimestampQuery A secondary query class using the current class as primary query + */ + public function useCcTimestampQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcTimestamp($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcTimestamp', 'CcTimestampQuery'); + } + + /** + * Exclude object from result + * + * @param CcListenerCount $ccListenerCount Object to remove from the list of results + * + * @return CcListenerCountQuery The current query, for fluid interface + */ + public function prune($ccListenerCount = null) + { + if ($ccListenerCount) { + $this->addUsingAlias(CcListenerCountPeer::ID, $ccListenerCount->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcListenerCountQuery diff --git a/airtime_mvc/application/models/airtime/om/BaseCcTimestamp.php b/airtime_mvc/application/models/airtime/om/BaseCcTimestamp.php new file mode 100644 index 000000000..5ede5b73c --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcTimestamp.php @@ -0,0 +1,920 @@ +id; + } + + /** + * Get the [optionally formatted] temporal [timestamp] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw DateTime object will be returned. + * @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getDbTimestamp($format = 'Y-m-d H:i:s') + { + if ($this->timestamp === null) { + return null; + } + + + + try { + $dt = new DateTime($this->timestamp); + } catch (Exception $x) { + throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->timestamp, true), $x); + } + + if ($format === null) { + // Because propel.useDateTimeClass is TRUE, we return a DateTime object. + return $dt; + } elseif (strpos($format, '%') !== false) { + return strftime($format, $dt->format('U')); + } else { + return $dt->format($format); + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return CcTimestamp The current object (for fluent API support) + */ + public function setDbId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[] = CcTimestampPeer::ID; + } + + return $this; + } // setDbId() + + /** + * Sets the value of [timestamp] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or DateTime value. Empty string will + * be treated as NULL for temporal objects. + * @return CcTimestamp The current object (for fluent API support) + */ + public function setDbTimestamp($v) + { + // we treat '' as NULL for temporal objects because DateTime('') == DateTime('now') + // -- which is unexpected, to say the least. + if ($v === null || $v === '') { + $dt = null; + } elseif ($v instanceof DateTime) { + $dt = $v; + } else { + // some string/numeric value passed; we normalize that so that we can + // validate it. + try { + if (is_numeric($v)) { // if it's a unix timestamp + $dt = new DateTime('@'.$v, new DateTimeZone('UTC')); + // We have to explicitly specify and then change the time zone because of a + // DateTime bug: http://bugs.php.net/bug.php?id=43003 + $dt->setTimeZone(new DateTimeZone(date_default_timezone_get())); + } else { + $dt = new DateTime($v); + } + } catch (Exception $x) { + throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x); + } + } + + if ( $this->timestamp !== null || $dt !== null ) { + // (nested ifs are a little easier to read in this case) + + $currNorm = ($this->timestamp !== null && $tmpDt = new DateTime($this->timestamp)) ? $tmpDt->format('Y-m-d\\TH:i:sO') : null; + $newNorm = ($dt !== null) ? $dt->format('Y-m-d\\TH:i:sO') : null; + + if ( ($currNorm !== $newNorm) // normalized values don't match + ) + { + $this->timestamp = ($dt ? $dt->format('Y-m-d\\TH:i:sO') : null); + $this->modifiedColumns[] = CcTimestampPeer::TIMESTAMP; + } + } // if either are not null + + return $this; + } // setDbTimestamp() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false) + { + try { + + $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; + $this->timestamp = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 2; // 2 = CcTimestampPeer::NUM_COLUMNS - CcTimestampPeer::NUM_LAZY_LOAD_COLUMNS). + + } catch (Exception $e) { + throw new PropelException("Error populating CcTimestamp object", $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param PropelPDO $con (optional) The PropelPDO connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $stmt = CcTimestampPeer::doSelectStmt($this->buildPkeyCriteria(), $con); + $row = $stmt->fetch(PDO::FETCH_NUM); + $stmt->closeCursor(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->collCcListenerCounts = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param PropelPDO $con + * @return void + * @throws PropelException + * @see BaseObject::setDeleted() + * @see BaseObject::isDeleted() + */ + public function delete(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + try { + $ret = $this->preDelete($con); + if ($ret) { + CcTimestampQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()) + ->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(PropelPDO $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CcTimestampPeer::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param PropelPDO $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(PropelPDO $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + if ($this->isNew() ) { + $this->modifiedColumns[] = CcTimestampPeer::ID; + } + + // If this object has been modified, then save it to the database. + if ($this->isModified()) { + if ($this->isNew()) { + $criteria = $this->buildCriteria(); + if ($criteria->keyContainsValue(CcTimestampPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcTimestampPeer::ID.')'); + } + + $pk = BasePeer::doInsert($criteria, $con); + $affectedRows = 1; + $this->setDbId($pk); //[IMV] update autoincrement primary key + $this->setNew(false); + } else { + $affectedRows = CcTimestampPeer::doUpdate($this, $con); + } + + $this->resetModified(); // [HL] After being saved an object is no longer 'modified' + } + + if ($this->collCcListenerCounts !== null) { + foreach ($this->collCcListenerCounts as $referrerFK) { + if (!$referrerFK->isDeleted()) { + $affectedRows += $referrerFK->save($con); + } + } + } + + $this->alreadyInSave = false; + + } + return $affectedRows; + } // doSave() + + /** + * Array of ValidationFailed objects. + * @var array ValidationFailed[] + */ + protected $validationFailures = array(); + + /** + * Gets any ValidationFailed objects that resulted from last call to validate(). + * + * + * @return array ValidationFailed[] + * @see validate() + */ + public function getValidationFailures() + { + return $this->validationFailures; + } + + /** + * Validates the objects modified field values and all objects related to this table. + * + * If $columns is either a column name or an array of column names + * only those columns are validated. + * + * @param mixed $columns Column name or an array of column names. + * @return boolean Whether all columns pass validation. + * @see doValidate() + * @see getValidationFailures() + */ + public function validate($columns = null) + { + $res = $this->doValidate($columns); + if ($res === true) { + $this->validationFailures = array(); + return true; + } else { + $this->validationFailures = $res; + return false; + } + } + + /** + * This function performs the validation work for complex object models. + * + * In addition to checking the current object, all related objects will + * also be validated. If all pass then true is returned; otherwise + * an aggreagated array of ValidationFailed objects will be returned. + * + * @param array $columns Array of column names to validate. + * @return mixed true if all validations pass; array of ValidationFailed objets otherwise. + */ + protected function doValidate($columns = null) + { + if (!$this->alreadyInValidation) { + $this->alreadyInValidation = true; + $retval = null; + + $failureMap = array(); + + + if (($retval = CcTimestampPeer::doValidate($this, $columns)) !== true) { + $failureMap = array_merge($failureMap, $retval); + } + + + if ($this->collCcListenerCounts !== null) { + foreach ($this->collCcListenerCounts as $referrerFK) { + if (!$referrerFK->validate($columns)) { + $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); + } + } + } + + + $this->alreadyInValidation = false; + } + + return (!empty($failureMap) ? $failureMap : true); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return mixed Value of field. + */ + public function getByName($name, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcTimestampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + $field = $this->getByPosition($pos); + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch($pos) { + case 0: + return $this->getDbId(); + break; + case 1: + return $this->getDbTimestamp(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * Defaults to BasePeer::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true) + { + $keys = CcTimestampPeer::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getDbId(), + $keys[1] => $this->getDbTimestamp(), + ); + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name peer name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return void + */ + public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) + { + $pos = CcTimestampPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch($pos) { + case 0: + $this->setDbId($value); + break; + case 1: + $this->setDbTimestamp($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. + * The default key type is the column's phpname (e.g. 'AuthorId') + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) + { + $keys = CcTimestampPeer::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setDbId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setDbTimestamp($arr[$keys[1]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CcTimestampPeer::DATABASE_NAME); + + if ($this->isColumnModified(CcTimestampPeer::ID)) $criteria->add(CcTimestampPeer::ID, $this->id); + if ($this->isColumnModified(CcTimestampPeer::TIMESTAMP)) $criteria->add(CcTimestampPeer::TIMESTAMP, $this->timestamp); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CcTimestampPeer::DATABASE_NAME); + $criteria->add(CcTimestampPeer::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getDbId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setDbId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + return null === $this->getDbId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of CcTimestamp (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false) + { + $copyObj->setDbTimestamp($this->timestamp); + + if ($deepCopy) { + // important: temporarily setNew(false) because this affects the behavior of + // the getter/setter methods for fkey referrer objects. + $copyObj->setNew(false); + + foreach ($this->getCcListenerCounts() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addCcListenerCount($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + + $copyObj->setNew(true); + $copyObj->setDbId(NULL); // this is a auto-increment column, so set to default value + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return CcTimestamp Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + return $copyObj; + } + + /** + * Returns a peer instance associated with this om. + * + * Since Peer classes are not to have any instance attributes, this method returns the + * same instance for all member of this class. The method could therefore + * be static, but this would prevent one from overriding the behavior. + * + * @return CcTimestampPeer + */ + public function getPeer() + { + if (self::$peer === null) { + self::$peer = new CcTimestampPeer(); + } + return self::$peer; + } + + /** + * Clears out the collCcListenerCounts collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addCcListenerCounts() + */ + public function clearCcListenerCounts() + { + $this->collCcListenerCounts = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Initializes the collCcListenerCounts collection. + * + * By default this just sets the collCcListenerCounts collection to an empty array (like clearcollCcListenerCounts()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @return void + */ + public function initCcListenerCounts() + { + $this->collCcListenerCounts = new PropelObjectCollection(); + $this->collCcListenerCounts->setModel('CcListenerCount'); + } + + /** + * Gets an array of CcListenerCount objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this CcTimestamp is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @return PropelCollection|array CcListenerCount[] List of CcListenerCount objects + * @throws PropelException + */ + public function getCcListenerCounts($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcListenerCounts || null !== $criteria) { + if ($this->isNew() && null === $this->collCcListenerCounts) { + // return empty collection + $this->initCcListenerCounts(); + } else { + $collCcListenerCounts = CcListenerCountQuery::create(null, $criteria) + ->filterByCcTimestamp($this) + ->find($con); + if (null !== $criteria) { + return $collCcListenerCounts; + } + $this->collCcListenerCounts = $collCcListenerCounts; + } + } + return $this->collCcListenerCounts; + } + + /** + * Returns the number of related CcListenerCount objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param PropelPDO $con + * @return int Count of related CcListenerCount objects. + * @throws PropelException + */ + public function countCcListenerCounts(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) + { + if(null === $this->collCcListenerCounts || null !== $criteria) { + if ($this->isNew() && null === $this->collCcListenerCounts) { + return 0; + } else { + $query = CcListenerCountQuery::create(null, $criteria); + if($distinct) { + $query->distinct(); + } + return $query + ->filterByCcTimestamp($this) + ->count($con); + } + } else { + return count($this->collCcListenerCounts); + } + } + + /** + * Method called to associate a CcListenerCount object to this object + * through the CcListenerCount foreign key attribute. + * + * @param CcListenerCount $l CcListenerCount + * @return void + * @throws PropelException + */ + public function addCcListenerCount(CcListenerCount $l) + { + if ($this->collCcListenerCounts === null) { + $this->initCcListenerCounts(); + } + if (!$this->collCcListenerCounts->contains($l)) { // only add it if the **same** object is not already associated + $this->collCcListenerCounts[]= $l; + $l->setCcTimestamp($this); + } + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->timestamp = null; + $this->alreadyInSave = false; + $this->alreadyInValidation = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all collections of referencing foreign keys. + * + * This method is a user-space workaround for PHP's inability to garbage collect objects + * with circular references. This is currently necessary when using Propel in certain + * daemon or large-volumne/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all associated objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + if ($this->collCcListenerCounts) { + foreach ((array) $this->collCcListenerCounts as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + $this->collCcListenerCounts = null; + } + + /** + * Catches calls to virtual methods + */ + public function __call($name, $params) + { + if (preg_match('/get(\w+)/', $name, $matches)) { + $virtualColumn = $matches[1]; + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + // no lcfirst in php<5.3... + $virtualColumn[0] = strtolower($virtualColumn[0]); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + throw new PropelException('Call to undefined method: ' . $name); + } + +} // BaseCcTimestamp diff --git a/airtime_mvc/application/models/airtime/om/BaseCcTimestampPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcTimestampPeer.php new file mode 100644 index 000000000..3d3b7d6ae --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcTimestampPeer.php @@ -0,0 +1,742 @@ + array ('DbId', 'DbTimestamp', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbTimestamp', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::TIMESTAMP, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'TIMESTAMP', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'timestamp', ), + BasePeer::TYPE_NUM => array (0, 1, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 + */ + private static $fieldKeys = array ( + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbTimestamp' => 1, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbTimestamp' => 1, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::TIMESTAMP => 1, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'TIMESTAMP' => 1, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'timestamp' => 1, ), + BasePeer::TYPE_NUM => array (0, 1, ) + ); + + /** + * Translates a fieldname to another type + * + * @param string $name field name + * @param string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @param string $toType One of the class type constants + * @return string translated name of the field. + * @throws PropelException - if the specified name could not be found in the fieldname mappings. + */ + static public function translateFieldName($name, $fromType, $toType) + { + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; + if ($key === null) { + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); + } + return $toNames[$key]; + } + + /** + * Returns an array of field names. + * + * @param string $type The type of fieldnames to return: + * One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME + * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM + * @return array A list of field names + */ + + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) + { + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); + } + return self::$fieldNames[$type]; + } + + /** + * Convenience method which changes table.column to alias.column. + * + * Using this method you can maintain SQL abstraction while using column aliases. + * + * $c->addAlias("alias1", TablePeer::TABLE_NAME); + * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); + * + * @param string $alias The alias for the current table. + * @param string $column The column name for current table. (i.e. CcTimestampPeer::COLUMN_NAME). + * @return string + */ + public static function alias($alias, $column) + { + return str_replace(CcTimestampPeer::TABLE_NAME.'.', $alias.'.', $column); + } + + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CcTimestampPeer::ID); + $criteria->addSelectColumn(CcTimestampPeer::TIMESTAMP); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.TIMESTAMP'); + } + } + + /** + * Returns the number of rows matching criteria. + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. + * @param PropelPDO $con + * @return int Number of matching rows. + */ + public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) + { + // we may modify criteria, so copy it first + $criteria = clone $criteria; + + // We need to set the primary table name, since in the case that there are no WHERE columns + // it will be impossible for the BasePeer::createSelectSql() method to determine which + // tables go into the FROM clause. + $criteria->setPrimaryTableName(CcTimestampPeer::TABLE_NAME); + + if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->setDistinct(); + } + + if (!$criteria->hasSelectClause()) { + CcTimestampPeer::addSelectColumns($criteria); + } + + $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count + $criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName + + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + // BasePeer returns a PDOStatement + $stmt = BasePeer::doCount($criteria, $con); + + if ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $count = (int) $row[0]; + } else { + $count = 0; // no rows returned; we infer that means 0 matches. + } + $stmt->closeCursor(); + return $count; + } + /** + * Method to select one object from the DB. + * + * @param Criteria $criteria object used to create the SELECT statement. + * @param PropelPDO $con + * @return CcTimestamp + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectOne(Criteria $criteria, PropelPDO $con = null) + { + $critcopy = clone $criteria; + $critcopy->setLimit(1); + $objects = CcTimestampPeer::doSelect($critcopy, $con); + if ($objects) { + return $objects[0]; + } + return null; + } + /** + * Method to do selects. + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con + * @return array Array of selected Objects + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelect(Criteria $criteria, PropelPDO $con = null) + { + return CcTimestampPeer::populateObjects(CcTimestampPeer::doSelectStmt($criteria, $con)); + } + /** + * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement. + * + * Use this method directly if you want to work with an executed statement durirectly (for example + * to perform your own object hydration). + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param PropelPDO $con The connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return PDOStatement The executed PDOStatement object. + * @see BasePeer::doSelect() + */ + public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + if (!$criteria->hasSelectClause()) { + $criteria = clone $criteria; + CcTimestampPeer::addSelectColumns($criteria); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + // BasePeer returns a PDOStatement + return BasePeer::doSelect($criteria, $con); + } + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doSelect*() + * methods in your stub classes -- you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by doSelect*() + * and retrieveByPK*() calls. + * + * @param CcTimestamp $value A CcTimestamp object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool(CcTimestamp $obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if ($key === null) { + $key = (string) $obj->getDbId(); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A CcTimestamp object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && $value !== null) { + if (is_object($value) && $value instanceof CcTimestamp) { + $key = (string) $value->getDbId(); + } elseif (is_scalar($value)) { + // assume we've been passed a primary key + $key = (string) $value; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or CcTimestamp object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } // removeInstanceFromPool() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param string $key The key (@see getPrimaryKeyHash()) for this instance. + * @return CcTimestamp Found object or NULL if 1) no instance exists for specified key or 2) instance pooling has been disabled. + * @see getPrimaryKeyHash() + */ + public static function getInstanceFromPool($key) + { + if (Propel::isInstancePoolingEnabled()) { + if (isset(self::$instances[$key])) { + return self::$instances[$key]; + } + } + return null; // just to be explicit + } + + /** + * Clear the instance pool. + * + * @return void + */ + public static function clearInstancePool() + { + self::$instances = array(); + } + + /** + * Method to invalidate the instance pool of all tables related to cc_timestamp + * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + // Invalidate objects in CcListenerCountPeer instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + CcListenerCountPeer::clearInstancePool(); + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return string A string version of PK or NULL if the components of primary key in result array are all null. + */ + public static function getPrimaryKeyHashFromRow($row, $startcol = 0) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[$startcol] === null) { + return null; + } + return (string) $row[$startcol]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $startcol = 0) + { + return (int) $row[$startcol]; + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(PDOStatement $stmt) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = CcTimestampPeer::getOMClass(false); + // populate the object(s) + while ($row = $stmt->fetch(PDO::FETCH_NUM)) { + $key = CcTimestampPeer::getPrimaryKeyHashFromRow($row, 0); + if (null !== ($obj = CcTimestampPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CcTimestampPeer::addInstanceToPool($obj, $key); + } // if key exists + } + $stmt->closeCursor(); + return $results; + } + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row PropelPDO resultset row. + * @param int $startcol The 0-based offset for reading from the resultset row. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (CcTimestamp object, last column rank) + */ + public static function populateObject($row, $startcol = 0) + { + $key = CcTimestampPeer::getPrimaryKeyHashFromRow($row, $startcol); + if (null !== ($obj = CcTimestampPeer::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $startcol, true); // rehydrate + $col = $startcol + CcTimestampPeer::NUM_COLUMNS; + } else { + $cls = CcTimestampPeer::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $startcol); + CcTimestampPeer::addInstanceToPool($obj, $key); + } + return array($obj, $col); + } + /** + * Returns the TableMap related to this peer. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this peer class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getDatabaseMap(BaseCcTimestampPeer::DATABASE_NAME); + if (!$dbMap->hasTable(BaseCcTimestampPeer::TABLE_NAME)) + { + $dbMap->addTableObject(new CcTimestampTableMap()); + } + } + + /** + * The class that the Peer will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is tranalted into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CcTimestampPeer::CLASS_DEFAULT : CcTimestampPeer::OM_CLASS; + } + + /** + * Method perform an INSERT on the database, given a CcTimestamp or Criteria object. + * + * @param mixed $values Criteria or CcTimestamp object containing data that is used to create the INSERT statement. + * @param PropelPDO $con the PropelPDO connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } else { + $criteria = $values->buildCriteria(); // build Criteria from CcTimestamp object + } + + if ($criteria->containsKey(CcTimestampPeer::ID) && $criteria->keyContainsValue(CcTimestampPeer::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CcTimestampPeer::ID.')'); + } + + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = BasePeer::doInsert($criteria, $con); + $con->commit(); + } catch(PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + + /** + * Method perform an UPDATE on the database, given a CcTimestamp or Criteria object. + * + * @param mixed $values Criteria or CcTimestamp object containing data that is used to create the UPDATE statement. + * @param PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions). + * @return int The number of affected rows (if supported by underlying database driver). + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doUpdate($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + $selectCriteria = new Criteria(self::DATABASE_NAME); + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + + $comparison = $criteria->getComparison(CcTimestampPeer::ID); + $value = $criteria->remove(CcTimestampPeer::ID); + if ($value) { + $selectCriteria->add(CcTimestampPeer::ID, $value, $comparison); + } else { + $selectCriteria->setPrimaryTableName(CcTimestampPeer::TABLE_NAME); + } + + } else { // $values is CcTimestamp object + $criteria = $values->buildCriteria(); // gets full criteria + $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) + } + + // set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + return BasePeer::doUpdate($selectCriteria, $criteria, $con); + } + + /** + * Method to DELETE all rows from the cc_timestamp table. + * + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll($con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += BasePeer::doDeleteAll(CcTimestampPeer::TABLE_NAME, $con, CcTimestampPeer::DATABASE_NAME); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CcTimestampPeer::clearInstancePool(); + CcTimestampPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Method perform a DELETE on the database, given a CcTimestamp or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or CcTimestamp object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param PropelPDO $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); + } + + if ($values instanceof Criteria) { + // invalidate the cache for all objects of this type, since we have no + // way of knowing (without running a query) what objects should be invalidated + // from the cache based on this Criteria. + CcTimestampPeer::clearInstancePool(); + // rename for clarity + $criteria = clone $values; + } elseif ($values instanceof CcTimestamp) { // it's a model object + // invalidate the cache for this single object + CcTimestampPeer::removeInstanceFromPool($values); + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(CcTimestampPeer::ID, (array) $values, Criteria::IN); + // invalidate the cache for this object(s) + foreach ((array) $values as $singleval) { + CcTimestampPeer::removeInstanceFromPool($singleval); + } + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + $affectedRows += BasePeer::doDelete($criteria, $con); + CcTimestampPeer::clearRelatedInstancePool(); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Validates all modified columns of given CcTimestamp object. + * If parameter $columns is either a single column name or an array of column names + * than only those columns are validated. + * + * NOTICE: This does not apply to primary or foreign keys for now. + * + * @param CcTimestamp $obj The object to validate. + * @param mixed $cols Column name or array of column names. + * + * @return mixed TRUE if all columns are valid or the error message of the first invalid column. + */ + public static function doValidate(CcTimestamp $obj, $cols = null) + { + $columns = array(); + + if ($cols) { + $dbMap = Propel::getDatabaseMap(CcTimestampPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(CcTimestampPeer::TABLE_NAME); + + if (! is_array($cols)) { + $cols = array($cols); + } + + foreach ($cols as $colName) { + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); + $columns[$colName] = $obj->$get(); + } + } + } else { + + } + + return BasePeer::doValidate(CcTimestampPeer::DATABASE_NAME, CcTimestampPeer::TABLE_NAME, $columns); + } + + /** + * Retrieve a single object by pkey. + * + * @param int $pk the primary key. + * @param PropelPDO $con the connection to use + * @return CcTimestamp + */ + public static function retrieveByPK($pk, PropelPDO $con = null) + { + + if (null !== ($obj = CcTimestampPeer::getInstanceFromPool((string) $pk))) { + return $obj; + } + + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $criteria = new Criteria(CcTimestampPeer::DATABASE_NAME); + $criteria->add(CcTimestampPeer::ID, $pk); + + $v = CcTimestampPeer::doSelect($criteria, $con); + + return !empty($v) > 0 ? $v[0] : null; + } + + /** + * Retrieve multiple objects by pkey. + * + * @param array $pks List of primary keys + * @param PropelPDO $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function retrieveByPKs($pks, PropelPDO $con = null) + { + if ($con === null) { + $con = Propel::getConnection(CcTimestampPeer::DATABASE_NAME, Propel::CONNECTION_READ); + } + + $objs = null; + if (empty($pks)) { + $objs = array(); + } else { + $criteria = new Criteria(CcTimestampPeer::DATABASE_NAME); + $criteria->add(CcTimestampPeer::ID, $pks, Criteria::IN); + $objs = CcTimestampPeer::doSelect($criteria, $con); + } + return $objs; + } + +} // BaseCcTimestampPeer + +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BaseCcTimestampPeer::buildTableMap(); + diff --git a/airtime_mvc/application/models/airtime/om/BaseCcTimestampQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcTimestampQuery.php new file mode 100644 index 000000000..a3f383112 --- /dev/null +++ b/airtime_mvc/application/models/airtime/om/BaseCcTimestampQuery.php @@ -0,0 +1,268 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + return $query; + } + + /** + * Find object by primary key + * Use instance pooling to avoid a database query if the object exists + * + * $obj = $c->findPk(12, $con); + * + * @param mixed $key Primary key to use for the query + * @param PropelPDO $con an optional connection object + * + * @return CcTimestamp|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ((null !== ($obj = CcTimestampPeer::getInstanceFromPool((string) $key))) && $this->getFormatter()->isObjectFormatter()) { + // the object is alredy in the instance pool + return $obj; + } else { + // the object has not been requested yet, or the formatter is not an object formatter + $criteria = $this->isKeepQuery() ? clone $this : $this; + $stmt = $criteria + ->filterByPrimaryKey($key) + ->getSelectStatement($con); + return $criteria->getFormatter()->init($criteria)->formatOne($stmt); + } + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param PropelPDO $con an optional connection object + * + * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + $criteria = $this->isKeepQuery() ? clone $this : $this; + return $this + ->filterByPrimaryKeys($keys) + ->find($con); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return CcTimestampQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + return $this->addUsingAlias(CcTimestampPeer::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return CcTimestampQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + return $this->addUsingAlias(CcTimestampPeer::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * @param int|array $dbId The value to use as filter. + * Accepts an associative array('min' => $minValue, 'max' => $maxValue) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcTimestampQuery The current query, for fluid interface + */ + public function filterByDbId($dbId = null, $comparison = null) + { + if (is_array($dbId) && null === $comparison) { + $comparison = Criteria::IN; + } + return $this->addUsingAlias(CcTimestampPeer::ID, $dbId, $comparison); + } + + /** + * Filter the query on the timestamp column + * + * @param string|array $dbTimestamp The value to use as filter. + * Accepts an associative array('min' => $minValue, 'max' => $maxValue) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcTimestampQuery The current query, for fluid interface + */ + public function filterByDbTimestamp($dbTimestamp = null, $comparison = null) + { + if (is_array($dbTimestamp)) { + $useMinMax = false; + if (isset($dbTimestamp['min'])) { + $this->addUsingAlias(CcTimestampPeer::TIMESTAMP, $dbTimestamp['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbTimestamp['max'])) { + $this->addUsingAlias(CcTimestampPeer::TIMESTAMP, $dbTimestamp['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcTimestampPeer::TIMESTAMP, $dbTimestamp, $comparison); + } + + /** + * Filter the query by a related CcListenerCount object + * + * @param CcListenerCount $ccListenerCount the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcTimestampQuery The current query, for fluid interface + */ + public function filterByCcListenerCount($ccListenerCount, $comparison = null) + { + return $this + ->addUsingAlias(CcTimestampPeer::ID, $ccListenerCount->getDbTimestampId(), $comparison); + } + + /** + * Adds a JOIN clause to the query using the CcListenerCount relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcTimestampQuery The current query, for fluid interface + */ + public function joinCcListenerCount($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CcListenerCount'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CcListenerCount'); + } + + return $this; + } + + /** + * Use the CcListenerCount relation CcListenerCount object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return CcListenerCountQuery A secondary query class using the current class as primary query + */ + public function useCcListenerCountQuery($relationAlias = '', $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCcListenerCount($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CcListenerCount', 'CcListenerCountQuery'); + } + + /** + * Exclude object from result + * + * @param CcTimestamp $ccTimestamp Object to remove from the list of results + * + * @return CcTimestampQuery The current query, for fluid interface + */ + public function prune($ccTimestamp = null) + { + if ($ccTimestamp) { + $this->addUsingAlias(CcTimestampPeer::ID, $ccTimestamp->getDbId(), Criteria::NOT_EQUAL); + } + + return $this; + } + +} // BaseCcTimestampQuery diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index fc3e6a51f..b13ed8f8a 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -437,4 +437,16 @@ + + + +
+ + + + + + + +
diff --git a/airtime_mvc/build/sql/schema.sql b/airtime_mvc/build/sql/schema.sql index d7e1107a4..efd765b43 100644 --- a/airtime_mvc/build/sql/schema.sql +++ b/airtime_mvc/build/sql/schema.sql @@ -666,6 +666,43 @@ CREATE TABLE "cc_webstream_metadata" COMMENT ON TABLE "cc_webstream_metadata" IS ''; +SET search_path TO public; +----------------------------------------------------------------------------- +-- cc_timestamp +----------------------------------------------------------------------------- + +DROP TABLE "cc_timestamp" CASCADE; + + +CREATE TABLE "cc_timestamp" +( + "id" serial NOT NULL, + "timestamp" TIMESTAMP NOT NULL, + PRIMARY KEY ("id") +); + +COMMENT ON TABLE "cc_timestamp" IS ''; + + +SET search_path TO public; +----------------------------------------------------------------------------- +-- cc_listener_count +----------------------------------------------------------------------------- + +DROP TABLE "cc_listener_count" CASCADE; + + +CREATE TABLE "cc_listener_count" +( + "id" serial NOT NULL, + "timestamp_id" INTEGER NOT NULL, + "listener_count" INTEGER NOT NULL, + PRIMARY KEY ("id") +); + +COMMENT ON TABLE "cc_listener_count" IS ''; + + SET search_path TO public; ALTER TABLE "cc_files" ADD CONSTRAINT "cc_files_owner_fkey" FOREIGN KEY ("owner_id") REFERENCES "cc_subjs" ("id"); @@ -718,3 +755,5 @@ ALTER TABLE "cc_sess" ADD CONSTRAINT "cc_sess_userid_fkey" FOREIGN KEY ("userid" ALTER TABLE "cc_subjs_token" ADD CONSTRAINT "cc_subjs_token_userid_fkey" FOREIGN KEY ("user_id") REFERENCES "cc_subjs" ("id") ON DELETE CASCADE; ALTER TABLE "cc_webstream_metadata" ADD CONSTRAINT "cc_schedule_inst_fkey" FOREIGN KEY ("instance_id") REFERENCES "cc_schedule" ("id") ON DELETE CASCADE; + +ALTER TABLE "cc_listener_count" ADD CONSTRAINT "cc_timestamp_inst_fkey" FOREIGN KEY ("timestamp_id") REFERENCES "cc_timestamp" ("id") ON DELETE CASCADE; From 7f27e5ff3fee70ede21beba53a64242f56e71022 Mon Sep 17 00:00:00 2001 From: James Date: Fri, 2 Nov 2012 16:27:29 -0400 Subject: [PATCH 146/157] - ListenerStat Model --- .../application/models/ListenerStat.php | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 airtime_mvc/application/models/ListenerStat.php diff --git a/airtime_mvc/application/models/ListenerStat.php b/airtime_mvc/application/models/ListenerStat.php new file mode 100644 index 000000000..bedd82453 --- /dev/null +++ b/airtime_mvc/application/models/ListenerStat.php @@ -0,0 +1,20 @@ +=:p1 AND cc_timestamp.TIMESTAMP<=:p2) +ORDER BY cc_timestamp.TIMESTAMP +SQL; + $data = Application_Common_Database::prepareAndExecute($sql, array('p1'=>$p_start, 'p2'=>$p_end)); + + return $data; + } +} \ No newline at end of file From 3af3cd5870c72887ca3dfa2b4220a637b537bcb6 Mon Sep 17 00:00:00 2001 From: James Date: Fri, 2 Nov 2012 16:59:39 -0400 Subject: [PATCH 147/157] CC-4661: Listener Statistics - frontend part --- airtime_mvc/application/configs/ACL.php | 2 + .../application/configs/navigation.php | 7 + .../controllers/ListenerstatController.php | 70 + .../views/scripts/listenerstat/index.phtml | 6 + .../js/airtime/listenerstat/listenerstat.js | 58 + airtime_mvc/public/js/flot/API.txt | 1201 +++ airtime_mvc/public/js/flot/FAQ.txt | 76 + airtime_mvc/public/js/flot/LICENSE.txt | 22 + airtime_mvc/public/js/flot/Makefile | 9 + airtime_mvc/public/js/flot/NEWS.txt | 508 + airtime_mvc/public/js/flot/PLUGINS.txt | 137 + airtime_mvc/public/js/flot/README.txt | 90 + airtime_mvc/public/js/flot/excanvas.js | 1427 +++ airtime_mvc/public/js/flot/excanvas.min.js | 1 + .../public/js/flot/jquery.colorhelpers.js | 179 + .../public/js/flot/jquery.flot.crosshair.js | 167 + .../public/js/flot/jquery.flot.fillbetween.js | 183 + .../public/js/flot/jquery.flot.image.js | 238 + airtime_mvc/public/js/flot/jquery.flot.js | 2599 ++++++ .../public/js/flot/jquery.flot.navigate.js | 336 + airtime_mvc/public/js/flot/jquery.flot.pie.js | 750 ++ .../public/js/flot/jquery.flot.resize.js | 60 + .../public/js/flot/jquery.flot.selection.js | 344 + .../public/js/flot/jquery.flot.stack.js | 184 + .../public/js/flot/jquery.flot.symbol.js | 70 + .../public/js/flot/jquery.flot.threshold.js | 103 + airtime_mvc/public/js/flot/jquery.js | 8316 +++++++++++++++++ 27 files changed, 17143 insertions(+) create mode 100644 airtime_mvc/application/controllers/ListenerstatController.php create mode 100644 airtime_mvc/application/views/scripts/listenerstat/index.phtml create mode 100644 airtime_mvc/public/js/airtime/listenerstat/listenerstat.js create mode 100644 airtime_mvc/public/js/flot/API.txt create mode 100644 airtime_mvc/public/js/flot/FAQ.txt create mode 100644 airtime_mvc/public/js/flot/LICENSE.txt create mode 100644 airtime_mvc/public/js/flot/Makefile create mode 100644 airtime_mvc/public/js/flot/NEWS.txt create mode 100644 airtime_mvc/public/js/flot/PLUGINS.txt create mode 100644 airtime_mvc/public/js/flot/README.txt create mode 100644 airtime_mvc/public/js/flot/excanvas.js create mode 100644 airtime_mvc/public/js/flot/excanvas.min.js create mode 100644 airtime_mvc/public/js/flot/jquery.colorhelpers.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.crosshair.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.fillbetween.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.image.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.navigate.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.pie.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.resize.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.selection.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.stack.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.symbol.js create mode 100644 airtime_mvc/public/js/flot/jquery.flot.threshold.js create mode 100644 airtime_mvc/public/js/flot/jquery.js diff --git a/airtime_mvc/application/configs/ACL.php b/airtime_mvc/application/configs/ACL.php index b89057194..6687011a4 100644 --- a/airtime_mvc/application/configs/ACL.php +++ b/airtime_mvc/application/configs/ACL.php @@ -23,6 +23,7 @@ $ccAcl->add(new Zend_Acl_Resource('library')) ->add(new Zend_Acl_Resource('preference')) ->add(new Zend_Acl_Resource('showbuilder')) ->add(new Zend_Acl_Resource('playouthistory')) + ->add(new Zend_Acl_Resource('listenerstat')) ->add(new Zend_Acl_Resource('usersettings')) ->add(new Zend_Acl_Resource('audiopreview')) ->add(new Zend_Acl_Resource('webstream')); @@ -43,6 +44,7 @@ $ccAcl->allow('G', 'index') ->allow('H', 'library') ->allow('H', 'playlist') ->allow('A', 'playouthistory') + ->allow('A', 'listenerstat') ->allow('A', 'user') ->allow('A', 'systemstatus') ->allow('A', 'preference'); diff --git a/airtime_mvc/application/configs/navigation.php b/airtime_mvc/application/configs/navigation.php index 724fa4c40..e2df2e3f5 100644 --- a/airtime_mvc/application/configs/navigation.php +++ b/airtime_mvc/application/configs/navigation.php @@ -85,6 +85,13 @@ $pages = array( 'controller' => 'playouthistory', 'action' => 'index', 'resource' => 'playouthistory' + ), + array( + 'label' => 'Listener Stat', + 'module' => 'default', + 'controller' => 'listenerstat', + 'action' => 'index', + 'resource' => 'listenerstat' ) ) ), diff --git a/airtime_mvc/application/controllers/ListenerstatController.php b/airtime_mvc/application/controllers/ListenerstatController.php new file mode 100644 index 000000000..2b0fcb6f7 --- /dev/null +++ b/airtime_mvc/application/controllers/ListenerstatController.php @@ -0,0 +1,70 @@ +_helper->getHelper('AjaxContext'); + $ajaxContext + ->addActionContext('get-data', 'json') + ->initContext(); + } + + public function indexAction() + { + global $CC_CONFIG; + + $request = $this->getRequest(); + $baseUrl = $request->getBaseUrl(); + + $this->view->headScript()->appendFile($baseUrl.'/js/flot/jquery.flot.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/listenerstat/listenerstat.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + $offset = date("Z") * -1; + $this->view->headScript()->appendScript("var serverTimezoneOffset = {$offset}; //in seconds"); + $this->view->headScript()->appendFile($baseUrl.'/js/timepicker/jquery.ui.timepicker.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/buttons/buttons.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + $this->view->headScript()->appendFile($baseUrl.'/js/airtime/utilities/utilities.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + //$this->view->headScript()->appendFile($baseUrl.'/js/airtime/playouthistory/historytable.js?'.$CC_CONFIG['airtime_version'],'text/javascript'); + + //$this->view->headLink()->appendStylesheet($baseUrl.'/js/datatables/plugin/TableTools/css/TableTools.css?'.$CC_CONFIG['airtime_version']); + $this->view->headLink()->appendStylesheet($baseUrl.'/css/jquery.ui.timepicker.css?'.$CC_CONFIG['airtime_version']); + //$this->view->headLink()->appendStylesheet($baseUrl.'/css/playouthistory.css?'.$CC_CONFIG['airtime_version']); + + //default time is the last 24 hours. + $now = time(); + $from = $request->getParam("from", $now - (24*60*60)); + $to = $request->getParam("to", $now); + + $start = DateTime::createFromFormat("U", $from, new DateTimeZone("UTC")); + $start->setTimezone(new DateTimeZone(date_default_timezone_get())); + $end = DateTime::createFromFormat("U", $to, new DateTimeZone("UTC")); + $end->setTimezone(new DateTimeZone(date_default_timezone_get())); + + $form = new Application_Form_DateRange(); + $form->populate(array( + 'his_date_start' => $start->format("Y-m-d"), + 'his_time_start' => $start->format("H:i"), + 'his_date_end' => $end->format("Y-m-d"), + 'his_time_end' => $end->format("H:i") + )); + + $this->view->date_form = $form; + } + + public function getDataAction(){ + $request = $this->getRequest(); + $current_time = time(); + + $params = $request->getParams(); + + $starts_epoch = $request->getParam("startTimestamp", $current_time - (60*60*24)); + $ends_epoch = $request->getParam("endTimestamp", $current_time); + + $startsDT = DateTime::createFromFormat("U", $starts_epoch, new DateTimeZone("UTC")); + $endsDT = DateTime::createFromFormat("U", $ends_epoch, new DateTimeZone("UTC")); + + $data = Application_Model_ListenerStat::getDataPointsWithinRange($startsDT->format("Y-m-d H:i:s"), $endsDT->format("Y-m-d H:i:s")); + die(json_encode($data)); + } +} diff --git a/airtime_mvc/application/views/scripts/listenerstat/index.phtml b/airtime_mvc/application/views/scripts/listenerstat/index.phtml new file mode 100644 index 000000000..dcd99520a --- /dev/null +++ b/airtime_mvc/application/views/scripts/listenerstat/index.phtml @@ -0,0 +1,6 @@ +
+ Timestamp vs Listener Count +
+ + date_form; ?> +
\ No newline at end of file diff --git a/airtime_mvc/public/js/airtime/listenerstat/listenerstat.js b/airtime_mvc/public/js/airtime/listenerstat/listenerstat.js new file mode 100644 index 000000000..c09011147 --- /dev/null +++ b/airtime_mvc/public/js/airtime/listenerstat/listenerstat.js @@ -0,0 +1,58 @@ +$(document).ready(function() { + listenerstat_content = $("#listenerstat_content") + dateStartId = "#his_date_start", + timeStartId = "#his_time_start", + dateEndId = "#his_date_end", + timeEndId = "#his_time_end"; + + getDataAndPlot(); + + listenerstat_content.find("#his_submit").click(function(ev){ + startTimestamp = AIRTIME.utilities.fnGetTimestamp(dateStartId, timeStartId); + endTimestamp = AIRTIME.utilities.fnGetTimestamp(dateEndId, timeEndId); + getDataAndPlot(startTimestamp, endTimestamp); + }); +}); + +function getDataAndPlot(startTimestamp, endTimestamp){ + // get data + $.get('/Listenerstat/get-data', {startTimestamp: startTimestamp, endTimestamp: endTimestamp}, function(data){ + data = JSON.parse(data); + out = new Array(); + $.each(data, function(index, v){ + temp = new Array(); + temp[0] = new Date(v.timestamp.replace(/-/g,"/")); + temp[1] = v.listener_count; + out.push(temp); + }); + plot(out); + }) +} + +function plot(d){ + oBaseDatePickerSettings = { + dateFormat: 'yy-mm-dd', + onSelect: function(sDate, oDatePicker) { + $(this).datepicker( "setDate", sDate ); + } + }; + + oBaseTimePickerSettings = { + showPeriodLabels: false, + showCloseButton: true, + showLeadingZero: false, + defaultTime: '0:00' + }; + + listenerstat_content.find(dateStartId).datepicker(oBaseDatePickerSettings); + listenerstat_content.find(timeStartId).timepicker(oBaseTimePickerSettings); + listenerstat_content.find(dateEndId).datepicker(oBaseDatePickerSettings); + listenerstat_content.find(timeEndId).timepicker(oBaseTimePickerSettings); + + $.plot($("#flot_placeholder"), [d], { xaxis: { mode: "time", timeformat: "%y/%m/%0d %H:%M:%S" } }); + + $("#whole").click(function () { + $.plot($("#flot_placeholder"), [d], { xaxis: { mode: "time" } }); + }); + + } \ No newline at end of file diff --git a/airtime_mvc/public/js/flot/API.txt b/airtime_mvc/public/js/flot/API.txt new file mode 100644 index 000000000..8a8dbc23d --- /dev/null +++ b/airtime_mvc/public/js/flot/API.txt @@ -0,0 +1,1201 @@ +Flot Reference +-------------- + +Consider a call to the plot function: + + var plot = $.plot(placeholder, data, options) + +The placeholder is a jQuery object or DOM element or jQuery expression +that the plot will be put into. This placeholder needs to have its +width and height set as explained in the README (go read that now if +you haven't, it's short). The plot will modify some properties of the +placeholder so it's recommended you simply pass in a div that you +don't use for anything else. Make sure you check any fancy styling +you apply to the div, e.g. background images have been reported to be a +problem on IE 7. + +The format of the data is documented below, as is the available +options. The plot object returned from the call has some methods you +can call. These are documented separately below. + +Note that in general Flot gives no guarantees if you change any of the +objects you pass in to the plot function or get out of it since +they're not necessarily deep-copied. + + +Data Format +----------- + +The data is an array of data series: + + [ series1, series2, ... ] + +A series can either be raw data or an object with properties. The raw +data format is an array of points: + + [ [x1, y1], [x2, y2], ... ] + +E.g. + + [ [1, 3], [2, 14.01], [3.5, 3.14] ] + +Note that to simplify the internal logic in Flot both the x and y +values must be numbers (even if specifying time series, see below for +how to do this). This is a common problem because you might retrieve +data from the database and serialize them directly to JSON without +noticing the wrong type. If you're getting mysterious errors, double +check that you're inputting numbers and not strings. + +If a null is specified as a point or if one of the coordinates is null +or couldn't be converted to a number, the point is ignored when +drawing. As a special case, a null value for lines is interpreted as a +line segment end, i.e. the points before and after the null value are +not connected. + +Lines and points take two coordinates. For filled lines and bars, you +can specify a third coordinate which is the bottom of the filled +area/bar (defaults to 0). + +The format of a single series object is as follows: + + { + color: color or number + data: rawdata + label: string + lines: specific lines options + bars: specific bars options + points: specific points options + xaxis: number + yaxis: number + clickable: boolean + hoverable: boolean + shadowSize: number + } + +You don't have to specify any of them except the data, the rest are +options that will get default values. Typically you'd only specify +label and data, like this: + + { + label: "y = 3", + data: [[0, 3], [10, 3]] + } + +The label is used for the legend, if you don't specify one, the series +will not show up in the legend. + +If you don't specify color, the series will get a color from the +auto-generated colors. The color is either a CSS color specification +(like "rgb(255, 100, 123)") or an integer that specifies which of +auto-generated colors to select, e.g. 0 will get color no. 0, etc. + +The latter is mostly useful if you let the user add and remove series, +in which case you can hard-code the color index to prevent the colors +from jumping around between the series. + +The "xaxis" and "yaxis" options specify which axis to use. The axes +are numbered from 1 (default), so { yaxis: 2} means that the series +should be plotted against the second y axis. + +"clickable" and "hoverable" can be set to false to disable +interactivity for specific series if interactivity is turned on in +the plot, see below. + +The rest of the options are all documented below as they are the same +as the default options passed in via the options parameter in the plot +commmand. When you specify them for a specific data series, they will +override the default options for the plot for that data series. + +Here's a complete example of a simple data specification: + + [ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] }, + { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] } ] + + +Plot Options +------------ + +All options are completely optional. They are documented individually +below, to change them you just specify them in an object, e.g. + + var options = { + series: { + lines: { show: true }, + points: { show: true } + } + }; + + $.plot(placeholder, data, options); + + +Customizing the legend +====================== + + legend: { + show: boolean + labelFormatter: null or (fn: string, series object -> string) + labelBoxBorderColor: color + noColumns: number + position: "ne" or "nw" or "se" or "sw" + margin: number of pixels or [x margin, y margin] + backgroundColor: null or color + backgroundOpacity: number between 0 and 1 + container: null or jQuery object/DOM element/jQuery expression + } + +The legend is generated as a table with the data series labels and +small label boxes with the color of the series. If you want to format +the labels in some way, e.g. make them to links, you can pass in a +function for "labelFormatter". Here's an example that makes them +clickable: + + labelFormatter: function(label, series) { + // series is the series object for the label + return '' + label + ''; + } + +"noColumns" is the number of columns to divide the legend table into. +"position" specifies the overall placement of the legend within the +plot (top-right, top-left, etc.) and margin the distance to the plot +edge (this can be either a number or an array of two numbers like [x, +y]). "backgroundColor" and "backgroundOpacity" specifies the +background. The default is a partly transparent auto-detected +background. + +If you want the legend to appear somewhere else in the DOM, you can +specify "container" as a jQuery object/expression to put the legend +table into. The "position" and "margin" etc. options will then be +ignored. Note that Flot will overwrite the contents of the container. + + +Customizing the axes +==================== + + xaxis, yaxis: { + show: null or true/false + position: "bottom" or "top" or "left" or "right" + mode: null or "time" + + color: null or color spec + tickColor: null or color spec + + min: null or number + max: null or number + autoscaleMargin: null or number + + transform: null or fn: number -> number + inverseTransform: null or fn: number -> number + + ticks: null or number or ticks array or (fn: range -> ticks array) + tickSize: number or array + minTickSize: number or array + tickFormatter: (fn: number, object -> string) or string + tickDecimals: null or number + + labelWidth: null or number + labelHeight: null or number + reserveSpace: null or true + + tickLength: null or number + + alignTicksWithAxis: null or number + } + +All axes have the same kind of options. The following describes how to +configure one axis, see below for what to do if you've got more than +one x axis or y axis. + +If you don't set the "show" option (i.e. it is null), visibility is +auto-detected, i.e. the axis will show up if there's data associated +with it. You can override this by setting the "show" option to true or +false. + +The "position" option specifies where the axis is placed, bottom or +top for x axes, left or right for y axes. The "mode" option determines +how the data is interpreted, the default of null means as decimal +numbers. Use "time" for time series data, see the time series data +section. + +The "color" option determines the color of the labels and ticks for +the axis (default is the grid color). For more fine-grained control +you can also set the color of the ticks separately with "tickColor" +(otherwise it's autogenerated as the base color with some +transparency). + +The options "min"/"max" are the precise minimum/maximum value on the +scale. If you don't specify either of them, a value will automatically +be chosen based on the minimum/maximum data values. Note that Flot +always examines all the data values you feed to it, even if a +restriction on another axis may make some of them invisible (this +makes interactive use more stable). + +The "autoscaleMargin" is a bit esoteric: it's the fraction of margin +that the scaling algorithm will add to avoid that the outermost points +ends up on the grid border. Note that this margin is only applied when +a min or max value is not explicitly set. If a margin is specified, +the plot will furthermore extend the axis end-point to the nearest +whole tick. The default value is "null" for the x axes and 0.02 for y +axes which seems appropriate for most cases. + +"transform" and "inverseTransform" are callbacks you can put in to +change the way the data is drawn. You can design a function to +compress or expand certain parts of the axis non-linearly, e.g. +suppress weekends or compress far away points with a logarithm or some +other means. When Flot draws the plot, each value is first put through +the transform function. Here's an example, the x axis can be turned +into a natural logarithm axis with the following code: + + xaxis: { + transform: function (v) { return Math.log(v); }, + inverseTransform: function (v) { return Math.exp(v); } + } + +Similarly, for reversing the y axis so the values appear in inverse +order: + + yaxis: { + transform: function (v) { return -v; }, + inverseTransform: function (v) { return -v; } + } + +Note that for finding extrema, Flot assumes that the transform +function does not reorder values (it should be monotone). + +The inverseTransform is simply the inverse of the transform function +(so v == inverseTransform(transform(v)) for all relevant v). It is +required for converting from canvas coordinates to data coordinates, +e.g. for a mouse interaction where a certain pixel is clicked. If you +don't use any interactive features of Flot, you may not need it. + + +The rest of the options deal with the ticks. + +If you don't specify any ticks, a tick generator algorithm will make +some for you. The algorithm has two passes. It first estimates how +many ticks would be reasonable and uses this number to compute a nice +round tick interval size. Then it generates the ticks. + +You can specify how many ticks the algorithm aims for by setting +"ticks" to a number. The algorithm always tries to generate reasonably +round tick values so even if you ask for three ticks, you might get +five if that fits better with the rounding. If you don't want any +ticks at all, set "ticks" to 0 or an empty array. + +Another option is to skip the rounding part and directly set the tick +interval size with "tickSize". If you set it to 2, you'll get ticks at +2, 4, 6, etc. Alternatively, you can specify that you just don't want +ticks at a size less than a specific tick size with "minTickSize". +Note that for time series, the format is an array like [2, "month"], +see the next section. + +If you want to completely override the tick algorithm, you can specify +an array for "ticks", either like this: + + ticks: [0, 1.2, 2.4] + +Or like this where the labels are also customized: + + ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]] + +You can mix the two if you like. + +For extra flexibility you can specify a function as the "ticks" +parameter. The function will be called with an object with the axis +min and max and should return a ticks array. Here's a simplistic tick +generator that spits out intervals of pi, suitable for use on the x +axis for trigonometric functions: + + function piTickGenerator(axis) { + var res = [], i = Math.floor(axis.min / Math.PI); + do { + var v = i * Math.PI; + res.push([v, i + "\u03c0"]); + ++i; + } while (v < axis.max); + + return res; + } + +You can control how the ticks look like with "tickDecimals", the +number of decimals to display (default is auto-detected). + +Alternatively, for ultimate control over how ticks are formatted you can +provide a function to "tickFormatter". The function is passed two +parameters, the tick value and an axis object with information, and +should return a string. The default formatter looks like this: + + function formatter(val, axis) { + return val.toFixed(axis.tickDecimals); + } + +The axis object has "min" and "max" with the range of the axis, +"tickDecimals" with the number of decimals to round the value to and +"tickSize" with the size of the interval between ticks as calculated +by the automatic axis scaling algorithm (or specified by you). Here's +an example of a custom formatter: + + function suffixFormatter(val, axis) { + if (val > 1000000) + return (val / 1000000).toFixed(axis.tickDecimals) + " MB"; + else if (val > 1000) + return (val / 1000).toFixed(axis.tickDecimals) + " kB"; + else + return val.toFixed(axis.tickDecimals) + " B"; + } + +"labelWidth" and "labelHeight" specifies a fixed size of the tick +labels in pixels. They're useful in case you need to align several +plots. "reserveSpace" means that even if an axis isn't shown, Flot +should reserve space for it - it is useful in combination with +labelWidth and labelHeight for aligning multi-axis charts. + +"tickLength" is the length of the tick lines in pixels. By default, the +innermost axes will have ticks that extend all across the plot, while +any extra axes use small ticks. A value of null means use the default, +while a number means small ticks of that length - set it to 0 to hide +the lines completely. + +If you set "alignTicksWithAxis" to the number of another axis, e.g. +alignTicksWithAxis: 1, Flot will ensure that the autogenerated ticks +of this axis are aligned with the ticks of the other axis. This may +improve the looks, e.g. if you have one y axis to the left and one to +the right, because the grid lines will then match the ticks in both +ends. The trade-off is that the forced ticks won't necessarily be at +natural places. + + +Multiple axes +============= + +If you need more than one x axis or y axis, you need to specify for +each data series which axis they are to use, as described under the +format of the data series, e.g. { data: [...], yaxis: 2 } specifies +that a series should be plotted against the second y axis. + +To actually configure that axis, you can't use the xaxis/yaxis options +directly - instead there are two arrays in the options: + + xaxes: [] + yaxes: [] + +Here's an example of configuring a single x axis and two y axes (we +can leave options of the first y axis empty as the defaults are fine): + + { + xaxes: [ { position: "top" } ], + yaxes: [ { }, { position: "right", min: 20 } ] + } + +The arrays get their default values from the xaxis/yaxis settings, so +say you want to have all y axes start at zero, you can simply specify +yaxis: { min: 0 } instead of adding a min parameter to all the axes. + +Generally, the various interfaces in Flot dealing with data points +either accept an xaxis/yaxis parameter to specify which axis number to +use (starting from 1), or lets you specify the coordinate directly as +x2/x3/... or x2axis/x3axis/... instead of "x" or "xaxis". + + +Time series data +================ + +Time series are a bit more difficult than scalar data because +calendars don't follow a simple base 10 system. For many cases, Flot +abstracts most of this away, but it can still be a bit difficult to +get the data into Flot. So we'll first discuss the data format. + +The time series support in Flot is based on Javascript timestamps, +i.e. everywhere a time value is expected or handed over, a Javascript +timestamp number is used. This is a number, not a Date object. A +Javascript timestamp is the number of milliseconds since January 1, +1970 00:00:00 UTC. This is almost the same as Unix timestamps, except it's +in milliseconds, so remember to multiply by 1000! + +You can see a timestamp like this + + alert((new Date()).getTime()) + +Normally you want the timestamps to be displayed according to a +certain time zone, usually the time zone in which the data has been +produced. However, Flot always displays timestamps according to UTC. +It has to as the only alternative with core Javascript is to interpret +the timestamps according to the time zone that the visitor is in, +which means that the ticks will shift unpredictably with the time zone +and daylight savings of each visitor. + +So given that there's no good support for custom time zones in +Javascript, you'll have to take care of this server-side. + +The easiest way to think about it is to pretend that the data +production time zone is UTC, even if it isn't. So if you have a +datapoint at 2002-02-20 08:00, you can generate a timestamp for eight +o'clock UTC even if it really happened eight o'clock UTC+0200. + +In PHP you can get an appropriate timestamp with +'strtotime("2002-02-20 UTC") * 1000', in Python with +'calendar.timegm(datetime_object.timetuple()) * 1000', in .NET with +something like: + + public static int GetJavascriptTimestamp(System.DateTime input) + { + System.TimeSpan span = new System.TimeSpan(System.DateTime.Parse("1/1/1970").Ticks); + System.DateTime time = input.Subtract(span); + return (long)(time.Ticks / 10000); + } + +Javascript also has some support for parsing date strings, so it is +possible to generate the timestamps manually client-side. + +If you've already got the real UTC timestamp, it's too late to use the +pretend trick described above. But you can fix up the timestamps by +adding the time zone offset, e.g. for UTC+0200 you would add 2 hours +to the UTC timestamp you got. Then it'll look right on the plot. Most +programming environments have some means of getting the timezone +offset for a specific date (note that you need to get the offset for +each individual timestamp to account for daylight savings). + +Once you've gotten the timestamps into the data and specified "time" +as the axis mode, Flot will automatically generate relevant ticks and +format them. As always, you can tweak the ticks via the "ticks" option +- just remember that the values should be timestamps (numbers), not +Date objects. + +Tick generation and formatting can also be controlled separately +through the following axis options: + + minTickSize: array + timeformat: null or format string + monthNames: null or array of size 12 of strings + twelveHourClock: boolean + +Here "timeformat" is a format string to use. You might use it like +this: + + xaxis: { + mode: "time" + timeformat: "%y/%m/%d" + } + +This will result in tick labels like "2000/12/24". The following +specifiers are supported + + %h: hours + %H: hours (left-padded with a zero) + %M: minutes (left-padded with a zero) + %S: seconds (left-padded with a zero) + %d: day of month (1-31), use %0d for zero-padding + %m: month (1-12), use %0m for zero-padding + %y: year (four digits) + %b: month name (customizable) + %p: am/pm, additionally switches %h/%H to 12 hour instead of 24 + %P: AM/PM (uppercase version of %p) + +Inserting a zero like %0m or %0d means that the specifier will be +left-padded with a zero if it's only single-digit. So %y-%0m-%0d +results in unambigious ISO timestamps like 2007-05-10 (for May 10th). + +You can customize the month names with the "monthNames" option. For +instance, for Danish you might specify: + + monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"] + +If you set "twelveHourClock" to true, the autogenerated timestamps +will use 12 hour AM/PM timestamps instead of 24 hour. + +The format string and month names are used by a very simple built-in +format function that takes a date object, a format string (and +optionally an array of month names) and returns the formatted string. +If needed, you can access it as $.plot.formatDate(date, formatstring, +monthNames) or even replace it with another more advanced function +from a date library if you're feeling adventurous. + +If everything else fails, you can control the formatting by specifying +a custom tick formatter function as usual. Here's a simple example +which will format December 24 as 24/12: + + tickFormatter: function (val, axis) { + var d = new Date(val); + return d.getUTCDate() + "/" + (d.getUTCMonth() + 1); + } + +Note that for the time mode "tickSize" and "minTickSize" are a bit +special in that they are arrays on the form "[value, unit]" where unit +is one of "second", "minute", "hour", "day", "month" and "year". So +you can specify + + minTickSize: [1, "month"] + +to get a tick interval size of at least 1 month and correspondingly, +if axis.tickSize is [2, "day"] in the tick formatter, the ticks have +been produced with two days in-between. + + + +Customizing the data series +=========================== + + series: { + lines, points, bars: { + show: boolean + lineWidth: number + fill: boolean or number + fillColor: null or color/gradient + } + + points: { + radius: number + symbol: "circle" or function + } + + bars: { + barWidth: number + align: "left" or "center" + horizontal: boolean + } + + lines: { + steps: boolean + } + + shadowSize: number + } + + colors: [ color1, color2, ... ] + +The options inside "series: {}" are copied to each of the series. So +you can specify that all series should have bars by putting it in the +global options, or override it for individual series by specifying +bars in a particular the series object in the array of data. + +The most important options are "lines", "points" and "bars" that +specify whether and how lines, points and bars should be shown for +each data series. In case you don't specify anything at all, Flot will +default to showing lines (you can turn this off with +lines: { show: false }). You can specify the various types +independently of each other, and Flot will happily draw each of them +in turn (this is probably only useful for lines and points), e.g. + + var options = { + series: { + lines: { show: true, fill: true, fillColor: "rgba(255, 255, 255, 0.8)" }, + points: { show: true, fill: false } + } + }; + +"lineWidth" is the thickness of the line or outline in pixels. You can +set it to 0 to prevent a line or outline from being drawn; this will +also hide the shadow. + +"fill" is whether the shape should be filled. For lines, this produces +area graphs. You can use "fillColor" to specify the color of the fill. +If "fillColor" evaluates to false (default for everything except +points which are filled with white), the fill color is auto-set to the +color of the data series. You can adjust the opacity of the fill by +setting fill to a number between 0 (fully transparent) and 1 (fully +opaque). + +For bars, fillColor can be a gradient, see the gradient documentation +below. "barWidth" is the width of the bars in units of the x axis (or +the y axis if "horizontal" is true), contrary to most other measures +that are specified in pixels. For instance, for time series the unit +is milliseconds so 24 * 60 * 60 * 1000 produces bars with the width of +a day. "align" specifies whether a bar should be left-aligned +(default) or centered on top of the value it represents. When +"horizontal" is on, the bars are drawn horizontally, i.e. from the y +axis instead of the x axis; note that the bar end points are still +defined in the same way so you'll probably want to swap the +coordinates if you've been plotting vertical bars first. + +For lines, "steps" specifies whether two adjacent data points are +connected with a straight (possibly diagonal) line or with first a +horizontal and then a vertical line. Note that this transforms the +data by adding extra points. + +For points, you can specify the radius and the symbol. The only +built-in symbol type is circles, for other types you can use a plugin +or define them yourself by specifying a callback: + + function cross(ctx, x, y, radius, shadow) { + var size = radius * Math.sqrt(Math.PI) / 2; + ctx.moveTo(x - size, y - size); + ctx.lineTo(x + size, y + size); + ctx.moveTo(x - size, y + size); + ctx.lineTo(x + size, y - size); + } + +The parameters are the drawing context, x and y coordinates of the +center of the point, a radius which corresponds to what the circle +would have used and whether the call is to draw a shadow (due to +limited canvas support, shadows are currently faked through extra +draws). It's good practice to ensure that the area covered by the +symbol is the same as for the circle with the given radius, this +ensures that all symbols have approximately the same visual weight. + +"shadowSize" is the default size of shadows in pixels. Set it to 0 to +remove shadows. + +The "colors" array specifies a default color theme to get colors for +the data series from. You can specify as many colors as you like, like +this: + + colors: ["#d18b2c", "#dba255", "#919733"] + +If there are more data series than colors, Flot will try to generate +extra colors by lightening and darkening colors in the theme. + + +Customizing the grid +==================== + + grid: { + show: boolean + aboveData: boolean + color: color + backgroundColor: color/gradient or null + labelMargin: number + axisMargin: number + markings: array of markings or (fn: axes -> array of markings) + borderWidth: number + borderColor: color or null + minBorderMargin: number or null + clickable: boolean + hoverable: boolean + autoHighlight: boolean + mouseActiveRadius: number + } + +The grid is the thing with the axes and a number of ticks. Many of the +things in the grid are configured under the individual axes, but not +all. "color" is the color of the grid itself whereas "backgroundColor" +specifies the background color inside the grid area, here null means +that the background is transparent. You can also set a gradient, see +the gradient documentation below. + +You can turn off the whole grid including tick labels by setting +"show" to false. "aboveData" determines whether the grid is drawn +above the data or below (below is default). + +"labelMargin" is the space in pixels between tick labels and axis +line, and "axisMargin" is the space in pixels between axes when there +are two next to each other. Note that you can style the tick labels +with CSS, e.g. to change the color. They have class "tickLabel". + +"borderWidth" is the width of the border around the plot. Set it to 0 +to disable the border. You can also set "borderColor" if you want the +border to have a different color than the grid lines. +"minBorderMargin" controls the default minimum margin around the +border - it's used to make sure that points aren't accidentally +clipped by the canvas edge so by default the value is computed from +the point radius. + +"markings" is used to draw simple lines and rectangular areas in the +background of the plot. You can either specify an array of ranges on +the form { xaxis: { from, to }, yaxis: { from, to } } (with multiple +axes, you can specify coordinates for other axes instead, e.g. as +x2axis/x3axis/...) or with a function that returns such an array given +the axes for the plot in an object as the first parameter. + +You can set the color of markings by specifying "color" in the ranges +object. Here's an example array: + + markings: [ { xaxis: { from: 0, to: 2 }, yaxis: { from: 10, to: 10 }, color: "#bb0000" }, ... ] + +If you leave out one of the values, that value is assumed to go to the +border of the plot. So for example if you only specify { xaxis: { +from: 0, to: 2 } } it means an area that extends from the top to the +bottom of the plot in the x range 0-2. + +A line is drawn if from and to are the same, e.g. + + markings: [ { yaxis: { from: 1, to: 1 } }, ... ] + +would draw a line parallel to the x axis at y = 1. You can control the +line width with "lineWidth" in the range object. + +An example function that makes vertical stripes might look like this: + + markings: function (axes) { + var markings = []; + for (var x = Math.floor(axes.xaxis.min); x < axes.xaxis.max; x += 2) + markings.push({ xaxis: { from: x, to: x + 1 } }); + return markings; + } + + +If you set "clickable" to true, the plot will listen for click events +on the plot area and fire a "plotclick" event on the placeholder with +a position and a nearby data item object as parameters. The coordinates +are available both in the unit of the axes (not in pixels) and in +global screen coordinates. + +Likewise, if you set "hoverable" to true, the plot will listen for +mouse move events on the plot area and fire a "plothover" event with +the same parameters as the "plotclick" event. If "autoHighlight" is +true (the default), nearby data items are highlighted automatically. +If needed, you can disable highlighting and control it yourself with +the highlight/unhighlight plot methods described elsewhere. + +You can use "plotclick" and "plothover" events like this: + + $.plot($("#placeholder"), [ d ], { grid: { clickable: true } }); + + $("#placeholder").bind("plotclick", function (event, pos, item) { + alert("You clicked at " + pos.x + ", " + pos.y); + // axis coordinates for other axes, if present, are in pos.x2, pos.x3, ... + // if you need global screen coordinates, they are pos.pageX, pos.pageY + + if (item) { + highlight(item.series, item.datapoint); + alert("You clicked a point!"); + } + }); + +The item object in this example is either null or a nearby object on the form: + + item: { + datapoint: the point, e.g. [0, 2] + dataIndex: the index of the point in the data array + series: the series object + seriesIndex: the index of the series + pageX, pageY: the global screen coordinates of the point + } + +For instance, if you have specified the data like this + + $.plot($("#placeholder"), [ { label: "Foo", data: [[0, 10], [7, 3]] } ], ...); + +and the mouse is near the point (7, 3), "datapoint" is [7, 3], +"dataIndex" will be 1, "series" is a normalized series object with +among other things the "Foo" label in series.label and the color in +series.color, and "seriesIndex" is 0. Note that plugins and options +that transform the data can shift the indexes from what you specified +in the original data array. + +If you use the above events to update some other information and want +to clear out that info in case the mouse goes away, you'll probably +also need to listen to "mouseout" events on the placeholder div. + +"mouseActiveRadius" specifies how far the mouse can be from an item +and still activate it. If there are two or more points within this +radius, Flot chooses the closest item. For bars, the top-most bar +(from the latest specified data series) is chosen. + +If you want to disable interactivity for a specific data series, you +can set "hoverable" and "clickable" to false in the options for that +series, like this { data: [...], label: "Foo", clickable: false }. + + +Specifying gradients +==================== + +A gradient is specified like this: + + { colors: [ color1, color2, ... ] } + +For instance, you might specify a background on the grid going from +black to gray like this: + + grid: { + backgroundColor: { colors: ["#000", "#999"] } + } + +For the series you can specify the gradient as an object that +specifies the scaling of the brightness and the opacity of the series +color, e.g. + + { colors: [{ opacity: 0.8 }, { brightness: 0.6, opacity: 0.8 } ] } + +where the first color simply has its alpha scaled, whereas the second +is also darkened. For instance, for bars the following makes the bars +gradually disappear, without outline: + + bars: { + show: true, + lineWidth: 0, + fill: true, + fillColor: { colors: [ { opacity: 0.8 }, { opacity: 0.1 } ] } + } + +Flot currently only supports vertical gradients drawn from top to +bottom because that's what works with IE. + + +Plot Methods +------------ + +The Plot object returned from the plot function has some methods you +can call: + + - highlight(series, datapoint) + + Highlight a specific datapoint in the data series. You can either + specify the actual objects, e.g. if you got them from a + "plotclick" event, or you can specify the indices, e.g. + highlight(1, 3) to highlight the fourth point in the second series + (remember, zero-based indexing). + + + - unhighlight(series, datapoint) or unhighlight() + + Remove the highlighting of the point, same parameters as + highlight. + + If you call unhighlight with no parameters, e.g. as + plot.unhighlight(), all current highlights are removed. + + + - setData(data) + + You can use this to reset the data used. Note that axis scaling, + ticks, legend etc. will not be recomputed (use setupGrid() to do + that). You'll probably want to call draw() afterwards. + + You can use this function to speed up redrawing a small plot if + you know that the axes won't change. Put in the new data with + setData(newdata), call draw(), and you're good to go. Note that + for large datasets, almost all the time is consumed in draw() + plotting the data so in this case don't bother. + + + - setupGrid() + + Recalculate and set axis scaling, ticks, legend etc. + + Note that because of the drawing model of the canvas, this + function will immediately redraw (actually reinsert in the DOM) + the labels and the legend, but not the actual tick lines because + they're drawn on the canvas. You need to call draw() to get the + canvas redrawn. + + - draw() + + Redraws the plot canvas. + + - triggerRedrawOverlay() + + Schedules an update of an overlay canvas used for drawing + interactive things like a selection and point highlights. This + is mostly useful for writing plugins. The redraw doesn't happen + immediately, instead a timer is set to catch multiple successive + redraws (e.g. from a mousemove). You can get to the overlay by + setting up a drawOverlay hook. + + - width()/height() + + Gets the width and height of the plotting area inside the grid. + This is smaller than the canvas or placeholder dimensions as some + extra space is needed (e.g. for labels). + + - offset() + + Returns the offset of the plotting area inside the grid relative + to the document, useful for instance for calculating mouse + positions (event.pageX/Y minus this offset is the pixel position + inside the plot). + + - pointOffset({ x: xpos, y: ypos }) + + Returns the calculated offset of the data point at (x, y) in data + space within the placeholder div. If you are working with multiple axes, you + can specify the x and y axis references, e.g. + + o = pointOffset({ x: xpos, y: ypos, xaxis: 2, yaxis: 3 }) + // o.left and o.top now contains the offset within the div + + - resize() + + Tells Flot to resize the drawing canvas to the size of the + placeholder. You need to run setupGrid() and draw() afterwards as + canvas resizing is a destructive operation. This is used + internally by the resize plugin. + + - shutdown() + + Cleans up any event handlers Flot has currently registered. This + is used internally. + + +There are also some members that let you peek inside the internal +workings of Flot which is useful in some cases. Note that if you change +something in the objects returned, you're changing the objects used by +Flot to keep track of its state, so be careful. + + - getData() + + Returns an array of the data series currently used in normalized + form with missing settings filled in according to the global + options. So for instance to find out what color Flot has assigned + to the data series, you could do this: + + var series = plot.getData(); + for (var i = 0; i < series.length; ++i) + alert(series[i].color); + + A notable other interesting field besides color is datapoints + which has a field "points" with the normalized data points in a + flat array (the field "pointsize" is the increment in the flat + array to get to the next point so for a dataset consisting only of + (x,y) pairs it would be 2). + + - getAxes() + + Gets an object with the axes. The axes are returned as the + attributes of the object, so for instance getAxes().xaxis is the + x axis. + + Various things are stuffed inside an axis object, e.g. you could + use getAxes().xaxis.ticks to find out what the ticks are for the + xaxis. Two other useful attributes are p2c and c2p, functions for + transforming from data point space to the canvas plot space and + back. Both returns values that are offset with the plot offset. + Check the Flot source code for the complete set of attributes (or + output an axis with console.log() and inspect it). + + With multiple axes, the extra axes are returned as x2axis, x3axis, + etc., e.g. getAxes().y2axis is the second y axis. You can check + y2axis.used to see whether the axis is associated with any data + points and y2axis.show to see if it is currently shown. + + - getPlaceholder() + + Returns placeholder that the plot was put into. This can be useful + for plugins for adding DOM elements or firing events. + + - getCanvas() + + Returns the canvas used for drawing in case you need to hack on it + yourself. You'll probably need to get the plot offset too. + + - getPlotOffset() + + Gets the offset that the grid has within the canvas as an object + with distances from the canvas edges as "left", "right", "top", + "bottom". I.e., if you draw a circle on the canvas with the center + placed at (left, top), its center will be at the top-most, left + corner of the grid. + + - getOptions() + + Gets the options for the plot, normalized, with default values + filled in. You get a reference to actual values used by Flot, so + if you modify the values in here, Flot will use the new values. + If you change something, you probably have to call draw() or + setupGrid() or triggerRedrawOverlay() to see the change. + + +Hooks +===== + +In addition to the public methods, the Plot object also has some hooks +that can be used to modify the plotting process. You can install a +callback function at various points in the process, the function then +gets access to the internal data structures in Flot. + +Here's an overview of the phases Flot goes through: + + 1. Plugin initialization, parsing options + + 2. Constructing the canvases used for drawing + + 3. Set data: parsing data specification, calculating colors, + copying raw data points into internal format, + normalizing them, finding max/min for axis auto-scaling + + 4. Grid setup: calculating axis spacing, ticks, inserting tick + labels, the legend + + 5. Draw: drawing the grid, drawing each of the series in turn + + 6. Setting up event handling for interactive features + + 7. Responding to events, if any + + 8. Shutdown: this mostly happens in case a plot is overwritten + +Each hook is simply a function which is put in the appropriate array. +You can add them through the "hooks" option, and they are also available +after the plot is constructed as the "hooks" attribute on the returned +plot object, e.g. + + // define a simple draw hook + function hellohook(plot, canvascontext) { alert("hello!"); }; + + // pass it in, in an array since we might want to specify several + var plot = $.plot(placeholder, data, { hooks: { draw: [hellohook] } }); + + // we can now find it again in plot.hooks.draw[0] unless a plugin + // has added other hooks + +The available hooks are described below. All hook callbacks get the +plot object as first parameter. You can find some examples of defined +hooks in the plugins bundled with Flot. + + - processOptions [phase 1] + + function(plot, options) + + Called after Flot has parsed and merged options. Useful in the + instance where customizations beyond simple merging of default + values is needed. A plugin might use it to detect that it has been + enabled and then turn on or off other options. + + + - processRawData [phase 3] + + function(plot, series, data, datapoints) + + Called before Flot copies and normalizes the raw data for the given + series. If the function fills in datapoints.points with normalized + points and sets datapoints.pointsize to the size of the points, + Flot will skip the copying/normalization step for this series. + + In any case, you might be interested in setting datapoints.format, + an array of objects for specifying how a point is normalized and + how it interferes with axis scaling. + + The default format array for points is something along the lines of: + + [ + { x: true, number: true, required: true }, + { y: true, number: true, required: true } + ] + + The first object means that for the first coordinate it should be + taken into account when scaling the x axis, that it must be a + number, and that it is required - so if it is null or cannot be + converted to a number, the whole point will be zeroed out with + nulls. Beyond these you can also specify "defaultValue", a value to + use if the coordinate is null. This is for instance handy for bars + where one can omit the third coordinate (the bottom of the bar) + which then defaults to 0. + + + - processDatapoints [phase 3] + + function(plot, series, datapoints) + + Called after normalization of the given series but before finding + min/max of the data points. This hook is useful for implementing data + transformations. "datapoints" contains the normalized data points in + a flat array as datapoints.points with the size of a single point + given in datapoints.pointsize. Here's a simple transform that + multiplies all y coordinates by 2: + + function multiply(plot, series, datapoints) { + var points = datapoints.points, ps = datapoints.pointsize; + for (var i = 0; i < points.length; i += ps) + points[i + 1] *= 2; + } + + Note that you must leave datapoints in a good condition as Flot + doesn't check it or do any normalization on it afterwards. + + + - drawSeries [phase 5] + + function(plot, canvascontext, series) + + Hook for custom drawing of a single series. Called just before the + standard drawing routine has been called in the loop that draws + each series. + + + - draw [phase 5] + + function(plot, canvascontext) + + Hook for drawing on the canvas. Called after the grid is drawn + (unless it's disabled or grid.aboveData is set) and the series have + been plotted (in case any points, lines or bars have been turned + on). For examples of how to draw things, look at the source code. + + + - bindEvents [phase 6] + + function(plot, eventHolder) + + Called after Flot has setup its event handlers. Should set any + necessary event handlers on eventHolder, a jQuery object with the + canvas, e.g. + + function (plot, eventHolder) { + eventHolder.mousedown(function (e) { + alert("You pressed the mouse at " + e.pageX + " " + e.pageY); + }); + } + + Interesting events include click, mousemove, mouseup/down. You can + use all jQuery events. Usually, the event handlers will update the + state by drawing something (add a drawOverlay hook and call + triggerRedrawOverlay) or firing an externally visible event for + user code. See the crosshair plugin for an example. + + Currently, eventHolder actually contains both the static canvas + used for the plot itself and the overlay canvas used for + interactive features because some versions of IE get the stacking + order wrong. The hook only gets one event, though (either for the + overlay or for the static canvas). + + Note that custom plot events generated by Flot are not generated on + eventHolder, but on the div placeholder supplied as the first + argument to the plot call. You can get that with + plot.getPlaceholder() - that's probably also the one you should use + if you need to fire a custom event. + + + - drawOverlay [phase 7] + + function (plot, canvascontext) + + The drawOverlay hook is used for interactive things that need a + canvas to draw on. The model currently used by Flot works the way + that an extra overlay canvas is positioned on top of the static + canvas. This overlay is cleared and then completely redrawn + whenever something interesting happens. This hook is called when + the overlay canvas is to be redrawn. + + "canvascontext" is the 2D context of the overlay canvas. You can + use this to draw things. You'll most likely need some of the + metrics computed by Flot, e.g. plot.width()/plot.height(). See the + crosshair plugin for an example. + + + - shutdown [phase 8] + + function (plot, eventHolder) + + Run when plot.shutdown() is called, which usually only happens in + case a plot is overwritten by a new plot. If you're writing a + plugin that adds extra DOM elements or event handlers, you should + add a callback to clean up after you. Take a look at the section in + PLUGINS.txt for more info. + + +Plugins +------- + +Plugins extend the functionality of Flot. To use a plugin, simply +include its Javascript file after Flot in the HTML page. + +If you're worried about download size/latency, you can concatenate all +the plugins you use, and Flot itself for that matter, into one big file +(make sure you get the order right), then optionally run it through a +Javascript minifier such as YUI Compressor. + +Here's a brief explanation of how the plugin plumbings work: + +Each plugin registers itself in the global array $.plot.plugins. When +you make a new plot object with $.plot, Flot goes through this array +calling the "init" function of each plugin and merging default options +from the "option" attribute of the plugin. The init function gets a +reference to the plot object created and uses this to register hooks +and add new public methods if needed. + +See the PLUGINS.txt file for details on how to write a plugin. As the +above description hints, it's actually pretty easy. + + +Version number +-------------- + +The version number of Flot is available in $.plot.version. diff --git a/airtime_mvc/public/js/flot/FAQ.txt b/airtime_mvc/public/js/flot/FAQ.txt new file mode 100644 index 000000000..e02b76188 --- /dev/null +++ b/airtime_mvc/public/js/flot/FAQ.txt @@ -0,0 +1,76 @@ +Frequently asked questions +-------------------------- + +Q: How much data can Flot cope with? + +A: Flot will happily draw everything you send to it so the answer +depends on the browser. The excanvas emulation used for IE (built with +VML) makes IE by far the slowest browser so be sure to test with that +if IE users are in your target group. + +1000 points is not a problem, but as soon as you start having more +points than the pixel width, you should probably start thinking about +downsampling/aggregation as this is near the resolution limit of the +chart anyway. If you downsample server-side, you also save bandwidth. + + +Q: Flot isn't working when I'm using JSON data as source! + +A: Actually, Flot loves JSON data, you just got the format wrong. +Double check that you're not inputting strings instead of numbers, +like [["0", "-2.13"], ["5", "4.3"]]. This is most common mistake, and +the error might not show up immediately because Javascript can do some +conversion automatically. + + +Q: Can I export the graph? + +A: This is a limitation of the canvas technology. There's a hook in +the canvas object for getting an image out, but you won't get the tick +labels. And it's not likely to be supported by IE. At this point, your +best bet is probably taking a screenshot, e.g. with PrtScn. + + +Q: The bars are all tiny in time mode? + +A: It's not really possible to determine the bar width automatically. +So you have to set the width with the barWidth option which is NOT in +pixels, but in the units of the x axis (or the y axis for horizontal +bars). For time mode that's milliseconds so the default value of 1 +makes the bars 1 millisecond wide. + + +Q: Can I use Flot with libraries like Mootools or Prototype? + +A: Yes, Flot supports it out of the box and it's easy! Just use jQuery +instead of $, e.g. call jQuery.plot instead of $.plot and use +jQuery(something) instead of $(something). As a convenience, you can +put in a DOM element for the graph placeholder where the examples and +the API documentation are using jQuery objects. + +Depending on how you include jQuery, you may have to add one line of +code to prevent jQuery from overwriting functions from the other +libraries, see the documentation in jQuery ("Using jQuery with other +libraries") for details. + + +Q: Flot doesn't work with [insert name of Javascript UI framework]! + +A: The only non-standard thing used by Flot is the canvas tag; +otherwise it is simply a series of absolute positioned divs within the +placeholder tag you put in. If this is not working, it's probably +because the framework you're using is doing something weird with the +DOM, or you're using it the wrong way. + +A common problem is that there's display:none on a container until the +user does something. Many tab widgets work this way, and there's +nothing wrong with it - you just can't call Flot inside a display:none +container as explained in the README so you need to hold off the Flot +call until the container is actually displayed (or use +visibility:hidden instead of display:none or move the container +off-screen). + +If you find there's a specific thing we can do to Flot to help, feel +free to submit a bug report. Otherwise, you're welcome to ask for help +on the forum/mailing list, but please don't submit a bug report to +Flot. diff --git a/airtime_mvc/public/js/flot/LICENSE.txt b/airtime_mvc/public/js/flot/LICENSE.txt new file mode 100644 index 000000000..07d5b2094 --- /dev/null +++ b/airtime_mvc/public/js/flot/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2007-2009 IOLA and Ole Laursen + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/airtime_mvc/public/js/flot/Makefile b/airtime_mvc/public/js/flot/Makefile new file mode 100644 index 000000000..b300f1a47 --- /dev/null +++ b/airtime_mvc/public/js/flot/Makefile @@ -0,0 +1,9 @@ +# Makefile for generating minified files + +.PHONY: all + +# we cheat and process all .js files instead of an exhaustive list +all: $(patsubst %.js,%.min.js,$(filter-out %.min.js,$(wildcard *.js))) + +%.min.js: %.js + yui-compressor $< -o $@ diff --git a/airtime_mvc/public/js/flot/NEWS.txt b/airtime_mvc/public/js/flot/NEWS.txt new file mode 100644 index 000000000..5f8e1a0c0 --- /dev/null +++ b/airtime_mvc/public/js/flot/NEWS.txt @@ -0,0 +1,508 @@ +Flot 0.7 +-------- + +API changes: + +Multiple axes support. Code using dual axes should be changed from +using x2axis/y2axis in the options to using an array (although +backwards-compatibility hooks are in place). For instance, + + { + xaxis: { ... }, x2axis: { ... }, + yaxis: { ... }, y2axis: { ... } + } + +becomes + + { + xaxes: [ { ... }, { ... } ], + yaxes: [ { ... }, { ... } ] + } + +Note that if you're just using one axis, continue to use the +xaxis/yaxis directly (it now sets the default settings for the +arrays). Plugins touching the axes must be ported to take the extra +axes into account, check the source to see some examples. + +A related change is that the visibility of axes is now auto-detected. +So if you were relying on an axis to show up even without any data in +the chart, you now need to set the axis "show" option explicitly. + +"tickColor" on the grid options is now deprecated in favour of a +corresponding option on the axes, so { grid: { tickColor: "#000" }} +becomes { xaxis: { tickColor: "#000"}, yaxis: { tickColor: "#000"} }, +but if you just configure a base color Flot will now autogenerate a +tick color by adding transparency. Backwards-compatibility hooks are +in place. + +Final note: now that IE 9 is coming out with canvas support, you may +want to adapt the excanvas include to skip loading it in IE 9 (the +examples have been adapted thanks to Ryley Breiddal). An alternative +to excanvas using Flash has also surfaced, if your graphs are slow in +IE, you may want to give it a spin: + + http://code.google.com/p/flashcanvas/ + + +Changes: + +- Support for specifying a bottom for each point for line charts when + filling them, this means that an arbitrary bottom can be used + instead of just the x axis (based on patches patiently provided by + Roman V. Prikhodchenko). +- New fillbetween plugin that can compute a bottom for a series from + another series, useful for filling areas between lines (see new + example percentiles.html for a use case). +- More predictable handling of gaps for the stacking plugin, now all + undefined ranges are skipped. +- Stacking plugin can stack horizontal bar charts. +- Navigate plugin now redraws the plot while panning instead of only + after the fact (can be disabled by setting the pan.frameRate option + to null), raised by lastthemy (issue 235). +- Date formatter now accepts %0m and %0d to get a zero-padded month or + day (issue raised by Maximillian Dornseif). +- Revamped internals to support an unlimited number of axes, not just + dual (sponsored by Flight Data Services, + www.flightdataservices.com). +- New setting on axes, "tickLength", to control the size of ticks or + turn them off without turning off the labels. +- Axis labels are now put in container divs with classes, for instance + labels in the x axes can be reached via ".xAxis .tickLabel". +- Support for setting the color of an axis (sponsored by Flight Data + Services, www.flightdataservices.com). +- Tick color is now auto-generated as the base color with some + transparency (unless you override it). +- Support for aligning ticks in the axes with "alignTicksWithAxis" to + ensure that they appear next to each other rather than in between, + at the expense of possibly awkward tick steps (sponsored by Flight + Data Services, www.flightdataservices.com). +- Support for customizing the point type through a callback when + plotting points and new symbol plugin with some predefined point + types (sponsored by Utility Data Corporation). +- Resize plugin for automatically redrawing when the placeholder + changes size, e.g. on window resizes (sponsored by Novus Partners). + A resize() method has been added to plot object facilitate this. +- Support Infinity/-Infinity for plotting asymptotes by hacking it + into +/-Number.MAX_VALUE (reported by rabaea.mircea). +- Support for restricting navigate plugin to not pan/zoom an axis (based + on patch by kkaefer). +- Support for providing the drag cursor for the navigate plugin as an + option (based on patch by Kelly T. Moore). +- Options for controlling whether an axis is shown or not (suggestion + by Timo Tuominen) and whether to reserve space for it even if it + isn't shown. +- New attribute $.plot.version with the Flot version as a string. +- The version comment is now included in the minified jquery.flot.min.js. +- New options.grid.minBorderMargin for adjusting the minimum margin + provided around the border (based on patch by corani, issue 188). +- Refactor replot behaviour so Flot tries to reuse the existing + canvas, adding shutdown() methods to the plot (based on patch by + Ryley Breiddal, issue 269). This prevents a memory leak in Chrome + and hopefully makes replotting faster for those who are using $.plot + instead of .setData()/.draw(). Also update jQuery to 1.5.1 to + prevent IE leaks fixed in jQuery. +- New real-time line chart example. + +- New hooks: drawSeries, shutdown + +Bug fixes: + +- Fixed problem with findNearbyItem and bars on top of each other + (reported by ragingchikn, issue 242). +- Fixed problem with ticks and the border (based on patch from + ultimatehustler69, issue 236). +- Fixed problem with plugins adding options to the series objects. +- Fixed a problem introduced in 0.6 with specifying a gradient with { + brightness: x, opacity: y }. +- Don't use $.browser.msie, check for getContext on the created canvas + element instead and try to use excanvas if it's not found (fixes IE + 9 compatibility). +- highlight(s, index) was looking up the point in the original s.data + instead of in the computed datapoints array, which breaks with + plugins that modify the datapoints (such as the stacking plugin). + Issue 316 reported by curlypaul924. +- More robust handling of axis from data passed in from getData() + (problem reported by Morgan). +- Fixed problem with turning off bar outline (issue 253, fix by Jordi + Castells). +- Check the selection passed into setSelection in the selection + plugin, to guard against errors when synchronizing plots (fix by Lau + Bech Lauritzen). +- Fix bug in crosshair code with mouseout resetting the crosshair even + if it is locked (fix by Lau Bech Lauritzen and Banko Adam). +- Fix bug with points plotting using line width from lines rather than + points. +- Fix bug with passing non-array 0 data (for plugins that don't expect + arrays, patch by vpapp1). +- Fix errors in JSON in examples so they work with jQuery 1.4.2 + (fix reported by honestbleeps, issue 357). +- Fix bug with tooltip in interacting.html, this makes the tooltip + much smoother (fix by bdkahn). Fix related bug inside highlighting + handler in Flot. +- Use closure trick to make inline colorhelpers plugin respect + jQuery.noConflict(true), renaming the global jQuery object (reported + by Nick Stielau). +- Listen for mouseleave events and fire a plothover event with empty + item when it occurs to drop highlights when the mouse leaves the + plot (reported by by outspirit). +- Fix bug with using aboveData with a background (reported by + amitayd). +- Fix possible excanvas leak (report and suggested fix by tom9729). +- Fix bug with backwards compatibility for shadowSize = 0 (report and + suggested fix by aspinak). +- Adapt examples to skip loading excanvas (fix by Ryley Breiddal). +- Fix bug that prevent a simple f(x) = -x transform from working + correctly (fix by Mike, issue 263). +- Fix bug in restoring cursor in navigate plugin (reported by Matteo + Gattanini, issue 395). +- Fix bug in picking items when transform/inverseTransform is in use + (reported by Ofri Raviv, and patches and analysis by Jan and Tom + Paton, issue 334 and 467). +- Fix problem with unaligned ticks and hover/click events caused by + padding on the placeholder by hardcoding the placeholder padding to + 0 (reported by adityadineshsaxena, Matt Sommer, Daniel Atos and some + other people, issue 301). +- Update colorhelpers plugin to avoid dying when trying to parse an + invalid string (reported by cadavor, issue 483). + + +Flot 0.6 +-------- + +API changes: + +1. Selection support has been moved to a plugin. Thus if you're +passing selection: { mode: something }, you MUST include the file +jquery.flot.selection.js after jquery.flot.js. This reduces the size +of base Flot and makes it easier to customize the selection as well as +improving code clarity. The change is based on a patch from andershol. + +2. In the global options specified in the $.plot command, +"lines", "points", "bars" and "shadowSize" have been moved to a +sub-object called "series", i.e. + + $.plot(placeholder, data, { lines: { show: true }}) + +should be changed to + + $.plot(placeholder, data, { series: { lines: { show: true }}}) + +All future series-specific options will go into this sub-object to +simplify plugin writing. Backward-compatibility code is in place, so +old code should not break. + +3. "plothover" no longer provides the original data point, but instead +a normalized one, since there may be no corresponding original point. + +4. Due to a bug in previous versions of jQuery, you now need at least +jQuery 1.2.6. But if you can, try jQuery 1.3.2 as it got some +improvements in event handling speed. + + +Changes: + +- Added support for disabling interactivity for specific data series + (request from Ronald Schouten and Steve Upton). + +- Flot now calls $() on the placeholder and optional legend container + passed in so you can specify DOM elements or CSS expressions to make + it easier to use Flot with libraries like Prototype or Mootools or + through raw JSON from Ajax responses. + +- A new "plotselecting" event is now emitted while the user is making + a selection. + +- The "plothover" event is now emitted immediately instead of at most + 10 times per second, you'll have to put in a setTimeout yourself if + you're doing something really expensive on this event. + +- The built-in date formatter can now be accessed as + $.plot.formatDate(...) (suggestion by Matt Manela) and even + replaced. + +- Added "borderColor" option to the grid (patch from Amaury Chamayou + and patch from Mike R. Williamson). + +- Added support for gradient backgrounds for the grid, take a look at + the "setting options" example (based on patch from Amaury Chamayou, + issue 90). + +- Gradient bars (suggestion by stefpet). + +- Added a "plotunselected" event which is triggered when the selection + is removed, see "selection" example (suggestion by Meda Ugo); + +- The option legend.margin can now specify horizontal and vertical + margins independently (suggestion by someone who's annoyed). + +- Data passed into Flot is now copied to a new canonical format to + enable further processing before it hits the drawing routines. As a + side-effect, this should make Flot more robust in the face of bad + data (and fixes issue 112). + +- Step-wise charting: line charts have a new option "steps" that when + set to true connects the points with horizontal/vertical steps + instead of diagonal lines. + +- The legend labelFormatter now passes the series in addition to just + the label (suggestion by Vincent Lemeltier). + +- Horizontal bars (based on patch by Jason LeBrun). + +- Support for partial bars by specifying a third coordinate, i.e. they + don't have to start from the axis. This can be used to make stacked + bars. + +- New option to disable the (grid.show). + +- Added pointOffset method for converting a point in data space to an + offset within the placeholder. + +- Plugin system: register an init method in the $.flot.plugins array + to get started, see PLUGINS.txt for details on how to write plugins + (it's easy). There are also some extra methods to enable access to + internal state. + +- Hooks: you can register functions that are called while Flot is + crunching the data and doing the plot. This can be used to modify + Flot without changing the source, useful for writing plugins. Some + hooks are defined, more are likely to come. + +- Threshold plugin: you can set a threshold and a color, and the data + points below that threshold will then get the color. Useful for + marking data below 0, for instance. + +- Stack plugin: you can specify a stack key for each series to have + them summed. This is useful for drawing additive/cumulative graphs + with bars and (currently unfilled) lines. + +- Crosshairs plugin: trace the mouse position on the axes, enable with + crosshair: { mode: "x"} (see the new tracking example for a use). + +- Image plugin: plot prerendered images. + +- Navigation plugin for panning and zooming a plot. + +- More configurable grid. + +- Axis transformation support, useful for non-linear plots, e.g. log + axes and compressed time axes (like omitting weekends). + +- Support for twelve-hour date formatting (patch by Forrest Aldridge). + +- The color parsing code in Flot has been cleaned up and split out so + it's now available as a separate jQuery plugin. It's included inline + in the Flot source to make dependency managing easier. This also + makes it really easy to use the color helpers in Flot plugins. + +Bug fixes: + +- Fixed two corner-case bugs when drawing filled curves (report and + analysis by Joshua Varner). +- Fix auto-adjustment code when setting min to 0 for an axis where the + dataset is completely flat on that axis (report by chovy). +- Fixed a bug with passing in data from getData to setData when the + secondary axes are used (issue 65, reported by nperelman). +- Fixed so that it is possible to turn lines off when no other chart + type is shown (based on problem reported by Glenn Vanderburg), and + fixed so that setting lineWidth to 0 also hides the shadow (based on + problem reported by Sergio Nunes). +- Updated mousemove position expression to the latest from jQuery (bug + reported by meyuchas). +- Use CSS borders instead of background in legend (fix printing issue 25 + and 45). +- Explicitly convert axis min/max to numbers. +- Fixed a bug with drawing marking lines with different colors + (reported by Khurram). +- Fixed a bug with returning y2 values in the selection event (fix + by exists, issue 75). +- Only set position relative on placeholder if it hasn't already a + position different from static (reported by kyberneticist, issue 95). +- Don't round markings to prevent sub-pixel problems (reported by Dan + Lipsitt). +- Make the grid border act similarly to a regular CSS border, i.e. + prevent it from overlapping the plot itself. This also fixes a + problem with anti-aliasing when the width is 1 pixel (reported by + Anthony Ettinger). +- Imported version 3 of excanvas and fixed two issues with the newer + version. Hopefully, this will make Flot work with IE8 (nudge by + Fabien Menager, further analysis by Booink, issue 133). +- Changed the shadow code for lines to hopefully look a bit better + with vertical lines. +- Round tick positions to avoid possible problems with fractions + (suggestion by Fred, issue 130). +- Made the heuristic for determining how many ticks to aim for a bit + smarter. +- Fix for uneven axis margins (report and patch by Paul Kienzle) and + snapping to ticks (concurrent report and patch by lifthrasiir). +- Fixed bug with slicing in findNearbyItems (patch by zollman). +- Make heuristic for x axis label widths more dynamic (patch by + rickinhethuis). +- Make sure points on top take precedence when finding nearby points + when hovering (reported by didroe, issue 224). + +Flot 0.5 +-------- + +Backwards API change summary: Timestamps are now in UTC. Also +"selected" event -> becomes "plotselected" with new data, the +parameters for setSelection are now different (but backwards +compatibility hooks are in place), coloredAreas becomes markings with +a new interface (but backwards compatibility hooks are in place). + + +Interactivity: added a new "plothover" event and this and the +"plotclick" event now returns the closest data item (based on patch by +/david, patch by Mark Byers for bar support). See the revamped +"interacting with the data" example for some hints on what you can do. + +Highlighting: you can now highlight points and datapoints are +autohighlighted when you hover over them (if hovering is turned on). + +Support for dual axis has been added (based on patch by someone who's +annoyed and /david). For each data series you can specify which axes +it belongs to, and there are two more axes, x2axis and y2axis, to +customize. This affects the "selected" event which has been renamed to +"plotselected" and spews out { xaxis: { from: -10, to: 20 } ... }, +setSelection in which the parameters are on a new form (backwards +compatible hooks are in place so old code shouldn't break) and +markings (formerly coloredAreas). + +Timestamps in time mode are now displayed according to +UTC instead of the time zone of the visitor. This affects the way the +timestamps should be input; you'll probably have to offset the +timestamps according to your local time zone. It also affects any +custom date handling code (which basically now should use the +equivalent UTC date mehods, e.g. .setUTCMonth() instead of +.setMonth(). + +Added support for specifying the size of tick labels (axis.labelWidth, +axis.labelHeight). Useful for specifying a max label size to keep +multiple plots aligned. + +Markings, previously coloredAreas, are now specified as ranges on the +axes, like { xaxis: { from: 0, to: 10 }}. Furthermore with markings +you can now draw horizontal/vertical lines by setting from and to to +the same coordinate (idea from line support patch by by Ryan Funduk). + +The "fill" option can now be a number that specifies the opacity of +the fill. + +You can now specify a coordinate as null (like [2, null]) and Flot +will take the other coordinate into account when scaling the axes +(based on patch by joebno). + +New option for bars "align". Set it to "center" to center the bars on +the value they represent. + +setSelection now takes a second parameter which you can use to prevent +the method from firing the "plotselected" handler. + +Using the "container" option in legend now overwrites the container +element instead of just appending to it (fixes infinite legend bug, +reported by several people, fix by Brad Dewey). + +Fixed a bug in calculating spacing around the plot (reported by +timothytoe). Fixed a bug in finding max values for all-negative data +sets. Prevent the possibility of eternal looping in tick calculations. +Fixed a bug when borderWidth is set to 0 (reported by +Rob/sanchothefat). Fixed a bug with drawing bars extending below 0 +(reported by James Hewitt, patch by Ryan Funduk). Fixed a +bug with line widths of bars (reported by MikeM). Fixed a bug with +'nw' and 'sw' legend positions. Improved the handling of axis +auto-scaling with bars. Fixed a bug with multi-line x-axis tick +labels (reported by Luca Ciano). IE-fix help by Savage Zhang. + + +Flot 0.4 +-------- + +API changes: deprecated axis.noTicks in favor of just specifying the +number as axis.ticks. So "xaxis: { noTicks: 10 }" becomes +"xaxis: { ticks: 10 }" + +Time series support. Specify axis.mode: "time", put in Javascript +timestamps as data, and Flot will automatically spit out sensible +ticks. Take a look at the two new examples. The format can be +customized with axis.timeformat and axis.monthNames, or if that fails +with axis.tickFormatter. + +Support for colored background areas via grid.coloredAreas. Specify an +array of { x1, y1, x2, y2 } objects or a function that returns these +given { xmin, xmax, ymin, ymax }. + +More members on the plot object (report by Chris Davies and others). +"getData" for inspecting the assigned settings on data series (e.g. +color) and "setData", "setupGrid" and "draw" for updating the contents +without a total replot. + +The default number of ticks to aim for is now dependent on the size of +the plot in pixels. Support for customizing tick interval sizes +directly with axis.minTickSize and axis.tickSize. + +Cleaned up the automatic axis scaling algorithm and fixed how it +interacts with ticks. Also fixed a couple of tick-related corner case +bugs (one reported by mainstreetmark, another reported by timothytoe). + +The option axis.tickFormatter now takes a function with two +parameters, the second parameter is an optional object with +information about the axis. It has min, max, tickDecimals, tickSize. + +Added support for segmented lines (based on patch from Michael +MacDonald) and for ignoring null and bad values (suggestion from Nick +Konidaris and joshwaihi). + +Added support for changing the border width (joebno and safoo). +Label colors can be changed via CSS by selecting the tickLabel class. + +Fixed a bug in handling single-item bar series (reported by Emil +Filipov). Fixed erratic behaviour when interacting with the plot +with IE 7 (reported by Lau Bech Lauritzen). Prevent IE/Safari text +selection when selecting stuff on the canvas. + + + +Flot 0.3 +-------- + +This is mostly a quick-fix release because jquery.js wasn't included +in the previous zip/tarball. + +Support clicking on the plot. Turn it on with grid: { clickable: true }, +then you get a "plotclick" event on the graph placeholder with the +position in units of the plot. + +Fixed a bug in dealing with data where min = max, thanks to Michael +Messinides. + +Include jquery.js in the zip/tarball. + + +Flot 0.2 +-------- + +Added support for putting a background behind the default legend. The +default is the partly transparent background color. Added +backgroundColor and backgroundOpacity to the legend options to control +this. + +The ticks options can now be a callback function that takes one +parameter, an object with the attributes min and max. The function +should return a ticks array. + +Added labelFormatter option in legend, useful for turning the legend +labels into links. + +Fixed a couple of bugs. + +The API should now be fully documented. + +Patch from Guy Fraser to make parts of the code smaller. + +API changes: Moved labelMargin option to grid from x/yaxis. + + +Flot 0.1 +-------- + +First public release. diff --git a/airtime_mvc/public/js/flot/PLUGINS.txt b/airtime_mvc/public/js/flot/PLUGINS.txt new file mode 100644 index 000000000..af3d90be5 --- /dev/null +++ b/airtime_mvc/public/js/flot/PLUGINS.txt @@ -0,0 +1,137 @@ +Writing plugins +--------------- + +All you need to do to make a new plugin is creating an init function +and a set of options (if needed), stuffing it into an object and +putting it in the $.plot.plugins array. For example: + + function myCoolPluginInit(plot) { + plot.coolstring = "Hello!"; + }; + + $.plot.plugins.push({ init: myCoolPluginInit, options: { ... } }); + + // if $.plot is called, it will return a plot object with the + // attribute "coolstring" + +Now, given that the plugin might run in many different places, it's +a good idea to avoid leaking names. The usual trick here is wrap the +above lines in an anonymous function which is called immediately, like +this: (function () { inner code ... })(). To make it even more robust +in case $ is not bound to jQuery but some other Javascript library, we +can write it as + + (function ($) { + // plugin definition + // ... + })(jQuery); + +There's a complete example below, but you should also check out the +plugins bundled with Flot. + + +Complete example +---------------- + +Here is a simple debug plugin which alerts each of the series in the +plot. It has a single option that control whether it is enabled and +how much info to output: + + (function ($) { + function init(plot) { + var debugLevel = 1; + + function checkDebugEnabled(plot, options) { + if (options.debug) { + debugLevel = options.debug; + + plot.hooks.processDatapoints.push(alertSeries); + } + } + + function alertSeries(plot, series, datapoints) { + var msg = "series " + series.label; + if (debugLevel > 1) + msg += " with " + series.data.length + " points"; + alert(msg); + } + + plot.hooks.processOptions.push(checkDebugEnabled); + } + + var options = { debug: 0 }; + + $.plot.plugins.push({ + init: init, + options: options, + name: "simpledebug", + version: "0.1" + }); + })(jQuery); + +We also define "name" and "version". It's not used by Flot, but might +be helpful for other plugins in resolving dependencies. + +Put the above in a file named "jquery.flot.debug.js", include it in an +HTML page and then it can be used with: + + $.plot($("#placeholder"), [...], { debug: 2 }); + +This simple plugin illustrates a couple of points: + + - It uses the anonymous function trick to avoid name pollution. + - It can be enabled/disabled through an option. + - Variables in the init function can be used to store plot-specific + state between the hooks. + +The two last points are important because there may be multiple plots +on the same page, and you'd want to make sure they are not mixed up. + + +Shutting down a plugin +---------------------- + +Each plot object has a shutdown hook which is run when plot.shutdown() +is called. This usually mostly happens in case another plot is made on +top of an existing one. + +The purpose of the hook is to give you a chance to unbind any event +handlers you've registered and remove any extra DOM things you've +inserted. + +The problem with event handlers is that you can have registered a +handler which is run in some point in the future, e.g. with +setTimeout(). Meanwhile, the plot may have been shutdown and removed, +but because your event handler is still referencing it, it can't be +garbage collected yet, and worse, if your handler eventually runs, it +may overwrite stuff on a completely different plot. + + +Some hints on the options +------------------------- + +Plugins should always support appropriate options to enable/disable +them because the plugin user may have several plots on the same page +where only one should use the plugin. In most cases it's probably a +good idea if the plugin is turned off rather than on per default, just +like most of the powerful features in Flot. + +If the plugin needs options that are specific to each series, like the +points or lines options in core Flot, you can put them in "series" in +the options object, e.g. + + var options = { + series: { + downsample: { + algorithm: null, + maxpoints: 1000 + } + } + } + +Then they will be copied by Flot into each series, providing default +values in case none are specified. + +Think hard and long about naming the options. These names are going to +be public API, and code is going to depend on them if the plugin is +successful. diff --git a/airtime_mvc/public/js/flot/README.txt b/airtime_mvc/public/js/flot/README.txt new file mode 100644 index 000000000..1e49787a0 --- /dev/null +++ b/airtime_mvc/public/js/flot/README.txt @@ -0,0 +1,90 @@ +About +----- + +Flot is a Javascript plotting library for jQuery. Read more at the +website: + + http://code.google.com/p/flot/ + +Take a look at the examples linked from above, they should give a good +impression of what Flot can do and the source code of the examples is +probably the fastest way to learn how to use Flot. + + +Installation +------------ + +Just include the Javascript file after you've included jQuery. + +Generally, all browsers that support the HTML5 canvas tag are +supported. + +For support for Internet Explorer < 9, you can use Excanvas, a canvas +emulator; this is used in the examples bundled with Flot. You just +include the excanvas script like this: + + + +If it's not working on your development IE 6.0, check that it has +support for VML which Excanvas is relying on. It appears that some +stripped down versions used for test environments on virtual machines +lack the VML support. + +You can also try using Flashcanvas (see +http://code.google.com/p/flashcanvas/), which uses Flash to do the +emulation. Although Flash can be a bit slower to load than VML, if +you've got a lot of points, the Flash version can be much faster +overall. Flot contains some wrapper code for activating Excanvas which +Flashcanvas is compatible with. + +You need at least jQuery 1.2.6, but try at least 1.3.2 for interactive +charts because of performance improvements in event handling. + + +Basic usage +----------- + +Create a placeholder div to put the graph in: + +
+ +You need to set the width and height of this div, otherwise the plot +library doesn't know how to scale the graph. You can do it inline like +this: + +
+ +You can also do it with an external stylesheet. Make sure that the +placeholder isn't within something with a display:none CSS property - +in that case, Flot has trouble measuring label dimensions which +results in garbled looks and might have trouble measuring the +placeholder dimensions which is fatal (it'll throw an exception). + +Then when the div is ready in the DOM, which is usually on document +ready, run the plot function: + + $.plot($("#placeholder"), data, options); + +Here, data is an array of data series and options is an object with +settings if you want to customize the plot. Take a look at the +examples for some ideas of what to put in or look at the reference +in the file "API.txt". Here's a quick example that'll draw a line from +(0, 0) to (1, 1): + + $.plot($("#placeholder"), [ [[0, 0], [1, 1]] ], { yaxis: { max: 1 } }); + +The plot function immediately draws the chart and then returns a plot +object with a couple of methods. + + +What's with the name? +--------------------- + +First: it's pronounced with a short o, like "plot". Not like "flawed". + +So "Flot" rhymes with "plot". + +And if you look up "flot" in a Danish-to-English dictionary, some up +the words that come up are "good-looking", "attractive", "stylish", +"smart", "impressive", "extravagant". One of the main goals with Flot +is pretty looks. diff --git a/airtime_mvc/public/js/flot/excanvas.js b/airtime_mvc/public/js/flot/excanvas.js new file mode 100644 index 000000000..c40d6f701 --- /dev/null +++ b/airtime_mvc/public/js/flot/excanvas.js @@ -0,0 +1,1427 @@ +// Copyright 2006 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// Known Issues: +// +// * Patterns only support repeat. +// * Radial gradient are not implemented. The VML version of these look very +// different from the canvas one. +// * Clipping paths are not implemented. +// * Coordsize. The width and height attribute have higher priority than the +// width and height style values which isn't correct. +// * Painting mode isn't implemented. +// * Canvas width/height should is using content-box by default. IE in +// Quirks mode will draw the canvas using border-box. Either change your +// doctype to HTML5 +// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) +// or use Box Sizing Behavior from WebFX +// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) +// * Non uniform scaling does not correctly scale strokes. +// * Filling very large shapes (above 5000 points) is buggy. +// * Optimize. There is always room for speed improvements. + +// Only add this code if we do not already have a canvas implementation +if (!document.createElement('canvas').getContext) { + +(function() { + + // alias some functions to make (compiled) code shorter + var m = Math; + var mr = m.round; + var ms = m.sin; + var mc = m.cos; + var abs = m.abs; + var sqrt = m.sqrt; + + // this is used for sub pixel precision + var Z = 10; + var Z2 = Z / 2; + + /** + * This funtion is assigned to the elements as element.getContext(). + * @this {HTMLElement} + * @return {CanvasRenderingContext2D_} + */ + function getContext() { + return this.context_ || + (this.context_ = new CanvasRenderingContext2D_(this)); + } + + var slice = Array.prototype.slice; + + /** + * Binds a function to an object. The returned function will always use the + * passed in {@code obj} as {@code this}. + * + * Example: + * + * g = bind(f, obj, a, b) + * g(c, d) // will do f.call(obj, a, b, c, d) + * + * @param {Function} f The function to bind the object to + * @param {Object} obj The object that should act as this when the function + * is called + * @param {*} var_args Rest arguments that will be used as the initial + * arguments when the function is called + * @return {Function} A new function that has bound this + */ + function bind(f, obj, var_args) { + var a = slice.call(arguments, 2); + return function() { + return f.apply(obj, a.concat(slice.call(arguments))); + }; + } + + function encodeHtmlAttribute(s) { + return String(s).replace(/&/g, '&').replace(/"/g, '"'); + } + + function addNamespacesAndStylesheet(doc) { + // create xmlns + if (!doc.namespaces['g_vml_']) { + doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml', + '#default#VML'); + + } + if (!doc.namespaces['g_o_']) { + doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office', + '#default#VML'); + } + + // Setup default CSS. Only add one style sheet per document + if (!doc.styleSheets['ex_canvas_']) { + var ss = doc.createStyleSheet(); + ss.owningElement.id = 'ex_canvas_'; + ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + + // default size is 300x150 in Gecko and Opera + 'text-align:left;width:300px;height:150px}'; + } + } + + // Add namespaces and stylesheet at startup. + addNamespacesAndStylesheet(document); + + var G_vmlCanvasManager_ = { + init: function(opt_doc) { + if (/MSIE/.test(navigator.userAgent) && !window.opera) { + var doc = opt_doc || document; + // Create a dummy element so that IE will allow canvas elements to be + // recognized. + doc.createElement('canvas'); + doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); + } + }, + + init_: function(doc) { + // find all canvas elements + var els = doc.getElementsByTagName('canvas'); + for (var i = 0; i < els.length; i++) { + this.initElement(els[i]); + } + }, + + /** + * Public initializes a canvas element so that it can be used as canvas + * element from now on. This is called automatically before the page is + * loaded but if you are creating elements using createElement you need to + * make sure this is called on the element. + * @param {HTMLElement} el The canvas element to initialize. + * @return {HTMLElement} the element that was created. + */ + initElement: function(el) { + if (!el.getContext) { + el.getContext = getContext; + + // Add namespaces and stylesheet to document of the element. + addNamespacesAndStylesheet(el.ownerDocument); + + // Remove fallback content. There is no way to hide text nodes so we + // just remove all childNodes. We could hide all elements and remove + // text nodes but who really cares about the fallback content. + el.innerHTML = ''; + + // do not use inline function because that will leak memory + el.attachEvent('onpropertychange', onPropertyChange); + el.attachEvent('onresize', onResize); + + var attrs = el.attributes; + if (attrs.width && attrs.width.specified) { + // TODO: use runtimeStyle and coordsize + // el.getContext().setWidth_(attrs.width.nodeValue); + el.style.width = attrs.width.nodeValue + 'px'; + } else { + el.width = el.clientWidth; + } + if (attrs.height && attrs.height.specified) { + // TODO: use runtimeStyle and coordsize + // el.getContext().setHeight_(attrs.height.nodeValue); + el.style.height = attrs.height.nodeValue + 'px'; + } else { + el.height = el.clientHeight; + } + //el.getContext().setCoordsize_() + } + return el; + } + }; + + function onPropertyChange(e) { + var el = e.srcElement; + + switch (e.propertyName) { + case 'width': + el.getContext().clearRect(); + el.style.width = el.attributes.width.nodeValue + 'px'; + // In IE8 this does not trigger onresize. + el.firstChild.style.width = el.clientWidth + 'px'; + break; + case 'height': + el.getContext().clearRect(); + el.style.height = el.attributes.height.nodeValue + 'px'; + el.firstChild.style.height = el.clientHeight + 'px'; + break; + } + } + + function onResize(e) { + var el = e.srcElement; + if (el.firstChild) { + el.firstChild.style.width = el.clientWidth + 'px'; + el.firstChild.style.height = el.clientHeight + 'px'; + } + } + + G_vmlCanvasManager_.init(); + + // precompute "00" to "FF" + var decToHex = []; + for (var i = 0; i < 16; i++) { + for (var j = 0; j < 16; j++) { + decToHex[i * 16 + j] = i.toString(16) + j.toString(16); + } + } + + function createMatrixIdentity() { + return [ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1] + ]; + } + + function matrixMultiply(m1, m2) { + var result = createMatrixIdentity(); + + for (var x = 0; x < 3; x++) { + for (var y = 0; y < 3; y++) { + var sum = 0; + + for (var z = 0; z < 3; z++) { + sum += m1[x][z] * m2[z][y]; + } + + result[x][y] = sum; + } + } + return result; + } + + function copyState(o1, o2) { + o2.fillStyle = o1.fillStyle; + o2.lineCap = o1.lineCap; + o2.lineJoin = o1.lineJoin; + o2.lineWidth = o1.lineWidth; + o2.miterLimit = o1.miterLimit; + o2.shadowBlur = o1.shadowBlur; + o2.shadowColor = o1.shadowColor; + o2.shadowOffsetX = o1.shadowOffsetX; + o2.shadowOffsetY = o1.shadowOffsetY; + o2.strokeStyle = o1.strokeStyle; + o2.globalAlpha = o1.globalAlpha; + o2.font = o1.font; + o2.textAlign = o1.textAlign; + o2.textBaseline = o1.textBaseline; + o2.arcScaleX_ = o1.arcScaleX_; + o2.arcScaleY_ = o1.arcScaleY_; + o2.lineScale_ = o1.lineScale_; + } + + var colorData = { + aliceblue: '#F0F8FF', + antiquewhite: '#FAEBD7', + aquamarine: '#7FFFD4', + azure: '#F0FFFF', + beige: '#F5F5DC', + bisque: '#FFE4C4', + black: '#000000', + blanchedalmond: '#FFEBCD', + blueviolet: '#8A2BE2', + brown: '#A52A2A', + burlywood: '#DEB887', + cadetblue: '#5F9EA0', + chartreuse: '#7FFF00', + chocolate: '#D2691E', + coral: '#FF7F50', + cornflowerblue: '#6495ED', + cornsilk: '#FFF8DC', + crimson: '#DC143C', + cyan: '#00FFFF', + darkblue: '#00008B', + darkcyan: '#008B8B', + darkgoldenrod: '#B8860B', + darkgray: '#A9A9A9', + darkgreen: '#006400', + darkgrey: '#A9A9A9', + darkkhaki: '#BDB76B', + darkmagenta: '#8B008B', + darkolivegreen: '#556B2F', + darkorange: '#FF8C00', + darkorchid: '#9932CC', + darkred: '#8B0000', + darksalmon: '#E9967A', + darkseagreen: '#8FBC8F', + darkslateblue: '#483D8B', + darkslategray: '#2F4F4F', + darkslategrey: '#2F4F4F', + darkturquoise: '#00CED1', + darkviolet: '#9400D3', + deeppink: '#FF1493', + deepskyblue: '#00BFFF', + dimgray: '#696969', + dimgrey: '#696969', + dodgerblue: '#1E90FF', + firebrick: '#B22222', + floralwhite: '#FFFAF0', + forestgreen: '#228B22', + gainsboro: '#DCDCDC', + ghostwhite: '#F8F8FF', + gold: '#FFD700', + goldenrod: '#DAA520', + grey: '#808080', + greenyellow: '#ADFF2F', + honeydew: '#F0FFF0', + hotpink: '#FF69B4', + indianred: '#CD5C5C', + indigo: '#4B0082', + ivory: '#FFFFF0', + khaki: '#F0E68C', + lavender: '#E6E6FA', + lavenderblush: '#FFF0F5', + lawngreen: '#7CFC00', + lemonchiffon: '#FFFACD', + lightblue: '#ADD8E6', + lightcoral: '#F08080', + lightcyan: '#E0FFFF', + lightgoldenrodyellow: '#FAFAD2', + lightgreen: '#90EE90', + lightgrey: '#D3D3D3', + lightpink: '#FFB6C1', + lightsalmon: '#FFA07A', + lightseagreen: '#20B2AA', + lightskyblue: '#87CEFA', + lightslategray: '#778899', + lightslategrey: '#778899', + lightsteelblue: '#B0C4DE', + lightyellow: '#FFFFE0', + limegreen: '#32CD32', + linen: '#FAF0E6', + magenta: '#FF00FF', + mediumaquamarine: '#66CDAA', + mediumblue: '#0000CD', + mediumorchid: '#BA55D3', + mediumpurple: '#9370DB', + mediumseagreen: '#3CB371', + mediumslateblue: '#7B68EE', + mediumspringgreen: '#00FA9A', + mediumturquoise: '#48D1CC', + mediumvioletred: '#C71585', + midnightblue: '#191970', + mintcream: '#F5FFFA', + mistyrose: '#FFE4E1', + moccasin: '#FFE4B5', + navajowhite: '#FFDEAD', + oldlace: '#FDF5E6', + olivedrab: '#6B8E23', + orange: '#FFA500', + orangered: '#FF4500', + orchid: '#DA70D6', + palegoldenrod: '#EEE8AA', + palegreen: '#98FB98', + paleturquoise: '#AFEEEE', + palevioletred: '#DB7093', + papayawhip: '#FFEFD5', + peachpuff: '#FFDAB9', + peru: '#CD853F', + pink: '#FFC0CB', + plum: '#DDA0DD', + powderblue: '#B0E0E6', + rosybrown: '#BC8F8F', + royalblue: '#4169E1', + saddlebrown: '#8B4513', + salmon: '#FA8072', + sandybrown: '#F4A460', + seagreen: '#2E8B57', + seashell: '#FFF5EE', + sienna: '#A0522D', + skyblue: '#87CEEB', + slateblue: '#6A5ACD', + slategray: '#708090', + slategrey: '#708090', + snow: '#FFFAFA', + springgreen: '#00FF7F', + steelblue: '#4682B4', + tan: '#D2B48C', + thistle: '#D8BFD8', + tomato: '#FF6347', + turquoise: '#40E0D0', + violet: '#EE82EE', + wheat: '#F5DEB3', + whitesmoke: '#F5F5F5', + yellowgreen: '#9ACD32' + }; + + + function getRgbHslContent(styleString) { + var start = styleString.indexOf('(', 3); + var end = styleString.indexOf(')', start + 1); + var parts = styleString.substring(start + 1, end).split(','); + // add alpha if needed + if (parts.length == 4 && styleString.substr(3, 1) == 'a') { + alpha = Number(parts[3]); + } else { + parts[3] = 1; + } + return parts; + } + + function percent(s) { + return parseFloat(s) / 100; + } + + function clamp(v, min, max) { + return Math.min(max, Math.max(min, v)); + } + + function hslToRgb(parts){ + var r, g, b; + h = parseFloat(parts[0]) / 360 % 360; + if (h < 0) + h++; + s = clamp(percent(parts[1]), 0, 1); + l = clamp(percent(parts[2]), 0, 1); + if (s == 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hueToRgb(p, q, h + 1 / 3); + g = hueToRgb(p, q, h); + b = hueToRgb(p, q, h - 1 / 3); + } + + return '#' + decToHex[Math.floor(r * 255)] + + decToHex[Math.floor(g * 255)] + + decToHex[Math.floor(b * 255)]; + } + + function hueToRgb(m1, m2, h) { + if (h < 0) + h++; + if (h > 1) + h--; + + if (6 * h < 1) + return m1 + (m2 - m1) * 6 * h; + else if (2 * h < 1) + return m2; + else if (3 * h < 2) + return m1 + (m2 - m1) * (2 / 3 - h) * 6; + else + return m1; + } + + function processStyle(styleString) { + var str, alpha = 1; + + styleString = String(styleString); + if (styleString.charAt(0) == '#') { + str = styleString; + } else if (/^rgb/.test(styleString)) { + var parts = getRgbHslContent(styleString); + var str = '#', n; + for (var i = 0; i < 3; i++) { + if (parts[i].indexOf('%') != -1) { + n = Math.floor(percent(parts[i]) * 255); + } else { + n = Number(parts[i]); + } + str += decToHex[clamp(n, 0, 255)]; + } + alpha = parts[3]; + } else if (/^hsl/.test(styleString)) { + var parts = getRgbHslContent(styleString); + str = hslToRgb(parts); + alpha = parts[3]; + } else { + str = colorData[styleString] || styleString; + } + return {color: str, alpha: alpha}; + } + + var DEFAULT_STYLE = { + style: 'normal', + variant: 'normal', + weight: 'normal', + size: 10, + family: 'sans-serif' + }; + + // Internal text style cache + var fontStyleCache = {}; + + function processFontStyle(styleString) { + if (fontStyleCache[styleString]) { + return fontStyleCache[styleString]; + } + + var el = document.createElement('div'); + var style = el.style; + try { + style.font = styleString; + } catch (ex) { + // Ignore failures to set to invalid font. + } + + return fontStyleCache[styleString] = { + style: style.fontStyle || DEFAULT_STYLE.style, + variant: style.fontVariant || DEFAULT_STYLE.variant, + weight: style.fontWeight || DEFAULT_STYLE.weight, + size: style.fontSize || DEFAULT_STYLE.size, + family: style.fontFamily || DEFAULT_STYLE.family + }; + } + + function getComputedStyle(style, element) { + var computedStyle = {}; + + for (var p in style) { + computedStyle[p] = style[p]; + } + + // Compute the size + var canvasFontSize = parseFloat(element.currentStyle.fontSize), + fontSize = parseFloat(style.size); + + if (typeof style.size == 'number') { + computedStyle.size = style.size; + } else if (style.size.indexOf('px') != -1) { + computedStyle.size = fontSize; + } else if (style.size.indexOf('em') != -1) { + computedStyle.size = canvasFontSize * fontSize; + } else if(style.size.indexOf('%') != -1) { + computedStyle.size = (canvasFontSize / 100) * fontSize; + } else if (style.size.indexOf('pt') != -1) { + computedStyle.size = fontSize / .75; + } else { + computedStyle.size = canvasFontSize; + } + + // Different scaling between normal text and VML text. This was found using + // trial and error to get the same size as non VML text. + computedStyle.size *= 0.981; + + return computedStyle; + } + + function buildStyle(style) { + return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + + style.size + 'px ' + style.family; + } + + function processLineCap(lineCap) { + switch (lineCap) { + case 'butt': + return 'flat'; + case 'round': + return 'round'; + case 'square': + default: + return 'square'; + } + } + + /** + * This class implements CanvasRenderingContext2D interface as described by + * the WHATWG. + * @param {HTMLElement} surfaceElement The element that the 2D context should + * be associated with + */ + function CanvasRenderingContext2D_(surfaceElement) { + this.m_ = createMatrixIdentity(); + + this.mStack_ = []; + this.aStack_ = []; + this.currentPath_ = []; + + // Canvas context properties + this.strokeStyle = '#000'; + this.fillStyle = '#000'; + + this.lineWidth = 1; + this.lineJoin = 'miter'; + this.lineCap = 'butt'; + this.miterLimit = Z * 1; + this.globalAlpha = 1; + this.font = '10px sans-serif'; + this.textAlign = 'left'; + this.textBaseline = 'alphabetic'; + this.canvas = surfaceElement; + + var el = surfaceElement.ownerDocument.createElement('div'); + el.style.width = surfaceElement.clientWidth + 'px'; + el.style.height = surfaceElement.clientHeight + 'px'; + el.style.overflow = 'hidden'; + el.style.position = 'absolute'; + surfaceElement.appendChild(el); + + this.element_ = el; + this.arcScaleX_ = 1; + this.arcScaleY_ = 1; + this.lineScale_ = 1; + } + + var contextPrototype = CanvasRenderingContext2D_.prototype; + contextPrototype.clearRect = function() { + if (this.textMeasureEl_) { + this.textMeasureEl_.removeNode(true); + this.textMeasureEl_ = null; + } + this.element_.innerHTML = ''; + }; + + contextPrototype.beginPath = function() { + // TODO: Branch current matrix so that save/restore has no effect + // as per safari docs. + this.currentPath_ = []; + }; + + contextPrototype.moveTo = function(aX, aY) { + var p = this.getCoords_(aX, aY); + this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); + this.currentX_ = p.x; + this.currentY_ = p.y; + }; + + contextPrototype.lineTo = function(aX, aY) { + var p = this.getCoords_(aX, aY); + this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); + + this.currentX_ = p.x; + this.currentY_ = p.y; + }; + + contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, + aCP2x, aCP2y, + aX, aY) { + var p = this.getCoords_(aX, aY); + var cp1 = this.getCoords_(aCP1x, aCP1y); + var cp2 = this.getCoords_(aCP2x, aCP2y); + bezierCurveTo(this, cp1, cp2, p); + }; + + // Helper function that takes the already fixed cordinates. + function bezierCurveTo(self, cp1, cp2, p) { + self.currentPath_.push({ + type: 'bezierCurveTo', + cp1x: cp1.x, + cp1y: cp1.y, + cp2x: cp2.x, + cp2y: cp2.y, + x: p.x, + y: p.y + }); + self.currentX_ = p.x; + self.currentY_ = p.y; + } + + contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { + // the following is lifted almost directly from + // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes + + var cp = this.getCoords_(aCPx, aCPy); + var p = this.getCoords_(aX, aY); + + var cp1 = { + x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), + y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) + }; + var cp2 = { + x: cp1.x + (p.x - this.currentX_) / 3.0, + y: cp1.y + (p.y - this.currentY_) / 3.0 + }; + + bezierCurveTo(this, cp1, cp2, p); + }; + + contextPrototype.arc = function(aX, aY, aRadius, + aStartAngle, aEndAngle, aClockwise) { + aRadius *= Z; + var arcType = aClockwise ? 'at' : 'wa'; + + var xStart = aX + mc(aStartAngle) * aRadius - Z2; + var yStart = aY + ms(aStartAngle) * aRadius - Z2; + + var xEnd = aX + mc(aEndAngle) * aRadius - Z2; + var yEnd = aY + ms(aEndAngle) * aRadius - Z2; + + // IE won't render arches drawn counter clockwise if xStart == xEnd. + if (xStart == xEnd && !aClockwise) { + xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something + // that can be represented in binary + } + + var p = this.getCoords_(aX, aY); + var pStart = this.getCoords_(xStart, yStart); + var pEnd = this.getCoords_(xEnd, yEnd); + + this.currentPath_.push({type: arcType, + x: p.x, + y: p.y, + radius: aRadius, + xStart: pStart.x, + yStart: pStart.y, + xEnd: pEnd.x, + yEnd: pEnd.y}); + + }; + + contextPrototype.rect = function(aX, aY, aWidth, aHeight) { + this.moveTo(aX, aY); + this.lineTo(aX + aWidth, aY); + this.lineTo(aX + aWidth, aY + aHeight); + this.lineTo(aX, aY + aHeight); + this.closePath(); + }; + + contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { + var oldPath = this.currentPath_; + this.beginPath(); + + this.moveTo(aX, aY); + this.lineTo(aX + aWidth, aY); + this.lineTo(aX + aWidth, aY + aHeight); + this.lineTo(aX, aY + aHeight); + this.closePath(); + this.stroke(); + + this.currentPath_ = oldPath; + }; + + contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { + var oldPath = this.currentPath_; + this.beginPath(); + + this.moveTo(aX, aY); + this.lineTo(aX + aWidth, aY); + this.lineTo(aX + aWidth, aY + aHeight); + this.lineTo(aX, aY + aHeight); + this.closePath(); + this.fill(); + + this.currentPath_ = oldPath; + }; + + contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { + var gradient = new CanvasGradient_('gradient'); + gradient.x0_ = aX0; + gradient.y0_ = aY0; + gradient.x1_ = aX1; + gradient.y1_ = aY1; + return gradient; + }; + + contextPrototype.createRadialGradient = function(aX0, aY0, aR0, + aX1, aY1, aR1) { + var gradient = new CanvasGradient_('gradientradial'); + gradient.x0_ = aX0; + gradient.y0_ = aY0; + gradient.r0_ = aR0; + gradient.x1_ = aX1; + gradient.y1_ = aY1; + gradient.r1_ = aR1; + return gradient; + }; + + contextPrototype.drawImage = function(image, var_args) { + var dx, dy, dw, dh, sx, sy, sw, sh; + + // to find the original width we overide the width and height + var oldRuntimeWidth = image.runtimeStyle.width; + var oldRuntimeHeight = image.runtimeStyle.height; + image.runtimeStyle.width = 'auto'; + image.runtimeStyle.height = 'auto'; + + // get the original size + var w = image.width; + var h = image.height; + + // and remove overides + image.runtimeStyle.width = oldRuntimeWidth; + image.runtimeStyle.height = oldRuntimeHeight; + + if (arguments.length == 3) { + dx = arguments[1]; + dy = arguments[2]; + sx = sy = 0; + sw = dw = w; + sh = dh = h; + } else if (arguments.length == 5) { + dx = arguments[1]; + dy = arguments[2]; + dw = arguments[3]; + dh = arguments[4]; + sx = sy = 0; + sw = w; + sh = h; + } else if (arguments.length == 9) { + sx = arguments[1]; + sy = arguments[2]; + sw = arguments[3]; + sh = arguments[4]; + dx = arguments[5]; + dy = arguments[6]; + dw = arguments[7]; + dh = arguments[8]; + } else { + throw Error('Invalid number of arguments'); + } + + var d = this.getCoords_(dx, dy); + + var w2 = sw / 2; + var h2 = sh / 2; + + var vmlStr = []; + + var W = 10; + var H = 10; + + // For some reason that I've now forgotten, using divs didn't work + vmlStr.push(' ' , + '', + ''); + + this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); + }; + + contextPrototype.stroke = function(aFill) { + var W = 10; + var H = 10; + // Divide the shape into chunks if it's too long because IE has a limit + // somewhere for how long a VML shape can be. This simple division does + // not work with fills, only strokes, unfortunately. + var chunkSize = 5000; + + var min = {x: null, y: null}; + var max = {x: null, y: null}; + + for (var j = 0; j < this.currentPath_.length; j += chunkSize) { + var lineStr = []; + var lineOpen = false; + + lineStr.push(''); + + if (!aFill) { + appendStroke(this, lineStr); + } else { + appendFill(this, lineStr, min, max); + } + + lineStr.push(''); + + this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); + } + }; + + function appendStroke(ctx, lineStr) { + var a = processStyle(ctx.strokeStyle); + var color = a.color; + var opacity = a.alpha * ctx.globalAlpha; + var lineWidth = ctx.lineScale_ * ctx.lineWidth; + + // VML cannot correctly render a line if the width is less than 1px. + // In that case, we dilute the color to make the line look thinner. + if (lineWidth < 1) { + opacity *= lineWidth; + } + + lineStr.push( + '' + ); + } + + function appendFill(ctx, lineStr, min, max) { + var fillStyle = ctx.fillStyle; + var arcScaleX = ctx.arcScaleX_; + var arcScaleY = ctx.arcScaleY_; + var width = max.x - min.x; + var height = max.y - min.y; + if (fillStyle instanceof CanvasGradient_) { + // TODO: Gradients transformed with the transformation matrix. + var angle = 0; + var focus = {x: 0, y: 0}; + + // additional offset + var shift = 0; + // scale factor for offset + var expansion = 1; + + if (fillStyle.type_ == 'gradient') { + var x0 = fillStyle.x0_ / arcScaleX; + var y0 = fillStyle.y0_ / arcScaleY; + var x1 = fillStyle.x1_ / arcScaleX; + var y1 = fillStyle.y1_ / arcScaleY; + var p0 = ctx.getCoords_(x0, y0); + var p1 = ctx.getCoords_(x1, y1); + var dx = p1.x - p0.x; + var dy = p1.y - p0.y; + angle = Math.atan2(dx, dy) * 180 / Math.PI; + + // The angle should be a non-negative number. + if (angle < 0) { + angle += 360; + } + + // Very small angles produce an unexpected result because they are + // converted to a scientific notation string. + if (angle < 1e-6) { + angle = 0; + } + } else { + var p0 = ctx.getCoords_(fillStyle.x0_, fillStyle.y0_); + focus = { + x: (p0.x - min.x) / width, + y: (p0.y - min.y) / height + }; + + width /= arcScaleX * Z; + height /= arcScaleY * Z; + var dimension = m.max(width, height); + shift = 2 * fillStyle.r0_ / dimension; + expansion = 2 * fillStyle.r1_ / dimension - shift; + } + + // We need to sort the color stops in ascending order by offset, + // otherwise IE won't interpret it correctly. + var stops = fillStyle.colors_; + stops.sort(function(cs1, cs2) { + return cs1.offset - cs2.offset; + }); + + var length = stops.length; + var color1 = stops[0].color; + var color2 = stops[length - 1].color; + var opacity1 = stops[0].alpha * ctx.globalAlpha; + var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; + + var colors = []; + for (var i = 0; i < length; i++) { + var stop = stops[i]; + colors.push(stop.offset * expansion + shift + ' ' + stop.color); + } + + // When colors attribute is used, the meanings of opacity and o:opacity2 + // are reversed. + lineStr.push(''); + } else if (fillStyle instanceof CanvasPattern_) { + if (width && height) { + var deltaLeft = -min.x; + var deltaTop = -min.y; + lineStr.push(''); + } + } else { + var a = processStyle(ctx.fillStyle); + var color = a.color; + var opacity = a.alpha * ctx.globalAlpha; + lineStr.push(''); + } + } + + contextPrototype.fill = function() { + this.stroke(true); + }; + + contextPrototype.closePath = function() { + this.currentPath_.push({type: 'close'}); + }; + + /** + * @private + */ + contextPrototype.getCoords_ = function(aX, aY) { + var m = this.m_; + return { + x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, + y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 + }; + }; + + contextPrototype.save = function() { + var o = {}; + copyState(this, o); + this.aStack_.push(o); + this.mStack_.push(this.m_); + this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); + }; + + contextPrototype.restore = function() { + if (this.aStack_.length) { + copyState(this.aStack_.pop(), this); + this.m_ = this.mStack_.pop(); + } + }; + + function matrixIsFinite(m) { + return isFinite(m[0][0]) && isFinite(m[0][1]) && + isFinite(m[1][0]) && isFinite(m[1][1]) && + isFinite(m[2][0]) && isFinite(m[2][1]); + } + + function setM(ctx, m, updateLineScale) { + if (!matrixIsFinite(m)) { + return; + } + ctx.m_ = m; + + if (updateLineScale) { + // Get the line scale. + // Determinant of this.m_ means how much the area is enlarged by the + // transformation. So its square root can be used as a scale factor + // for width. + var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; + ctx.lineScale_ = sqrt(abs(det)); + } + } + + contextPrototype.translate = function(aX, aY) { + var m1 = [ + [1, 0, 0], + [0, 1, 0], + [aX, aY, 1] + ]; + + setM(this, matrixMultiply(m1, this.m_), false); + }; + + contextPrototype.rotate = function(aRot) { + var c = mc(aRot); + var s = ms(aRot); + + var m1 = [ + [c, s, 0], + [-s, c, 0], + [0, 0, 1] + ]; + + setM(this, matrixMultiply(m1, this.m_), false); + }; + + contextPrototype.scale = function(aX, aY) { + this.arcScaleX_ *= aX; + this.arcScaleY_ *= aY; + var m1 = [ + [aX, 0, 0], + [0, aY, 0], + [0, 0, 1] + ]; + + setM(this, matrixMultiply(m1, this.m_), true); + }; + + contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { + var m1 = [ + [m11, m12, 0], + [m21, m22, 0], + [dx, dy, 1] + ]; + + setM(this, matrixMultiply(m1, this.m_), true); + }; + + contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { + var m = [ + [m11, m12, 0], + [m21, m22, 0], + [dx, dy, 1] + ]; + + setM(this, m, true); + }; + + /** + * The text drawing function. + * The maxWidth argument isn't taken in account, since no browser supports + * it yet. + */ + contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { + var m = this.m_, + delta = 1000, + left = 0, + right = delta, + offset = {x: 0, y: 0}, + lineStr = []; + + var fontStyle = getComputedStyle(processFontStyle(this.font), + this.element_); + + var fontStyleString = buildStyle(fontStyle); + + var elementStyle = this.element_.currentStyle; + var textAlign = this.textAlign.toLowerCase(); + switch (textAlign) { + case 'left': + case 'center': + case 'right': + break; + case 'end': + textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; + break; + case 'start': + textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; + break; + default: + textAlign = 'left'; + } + + // 1.75 is an arbitrary number, as there is no info about the text baseline + switch (this.textBaseline) { + case 'hanging': + case 'top': + offset.y = fontStyle.size / 1.75; + break; + case 'middle': + break; + default: + case null: + case 'alphabetic': + case 'ideographic': + case 'bottom': + offset.y = -fontStyle.size / 2.25; + break; + } + + switch(textAlign) { + case 'right': + left = delta; + right = 0.05; + break; + case 'center': + left = right = delta / 2; + break; + } + + var d = this.getCoords_(x + offset.x, y + offset.y); + + lineStr.push(''); + + if (stroke) { + appendStroke(this, lineStr); + } else { + // TODO: Fix the min and max params. + appendFill(this, lineStr, {x: -left, y: 0}, + {x: right, y: fontStyle.size}); + } + + var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; + + var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); + + lineStr.push('', + '', + ''); + + this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); + }; + + contextPrototype.fillText = function(text, x, y, maxWidth) { + this.drawText_(text, x, y, maxWidth, false); + }; + + contextPrototype.strokeText = function(text, x, y, maxWidth) { + this.drawText_(text, x, y, maxWidth, true); + }; + + contextPrototype.measureText = function(text) { + if (!this.textMeasureEl_) { + var s = ''; + this.element_.insertAdjacentHTML('beforeEnd', s); + this.textMeasureEl_ = this.element_.lastChild; + } + var doc = this.element_.ownerDocument; + this.textMeasureEl_.innerHTML = ''; + this.textMeasureEl_.style.font = this.font; + // Don't use innerHTML or innerText because they allow markup/whitespace. + this.textMeasureEl_.appendChild(doc.createTextNode(text)); + return {width: this.textMeasureEl_.offsetWidth}; + }; + + /******** STUBS ********/ + contextPrototype.clip = function() { + // TODO: Implement + }; + + contextPrototype.arcTo = function() { + // TODO: Implement + }; + + contextPrototype.createPattern = function(image, repetition) { + return new CanvasPattern_(image, repetition); + }; + + // Gradient / Pattern Stubs + function CanvasGradient_(aType) { + this.type_ = aType; + this.x0_ = 0; + this.y0_ = 0; + this.r0_ = 0; + this.x1_ = 0; + this.y1_ = 0; + this.r1_ = 0; + this.colors_ = []; + } + + CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { + aColor = processStyle(aColor); + this.colors_.push({offset: aOffset, + color: aColor.color, + alpha: aColor.alpha}); + }; + + function CanvasPattern_(image, repetition) { + assertImageIsValid(image); + switch (repetition) { + case 'repeat': + case null: + case '': + this.repetition_ = 'repeat'; + break + case 'repeat-x': + case 'repeat-y': + case 'no-repeat': + this.repetition_ = repetition; + break; + default: + throwException('SYNTAX_ERR'); + } + + this.src_ = image.src; + this.width_ = image.width; + this.height_ = image.height; + } + + function throwException(s) { + throw new DOMException_(s); + } + + function assertImageIsValid(img) { + if (!img || img.nodeType != 1 || img.tagName != 'IMG') { + throwException('TYPE_MISMATCH_ERR'); + } + if (img.readyState != 'complete') { + throwException('INVALID_STATE_ERR'); + } + } + + function DOMException_(s) { + this.code = this[s]; + this.message = s +': DOM Exception ' + this.code; + } + var p = DOMException_.prototype = new Error; + p.INDEX_SIZE_ERR = 1; + p.DOMSTRING_SIZE_ERR = 2; + p.HIERARCHY_REQUEST_ERR = 3; + p.WRONG_DOCUMENT_ERR = 4; + p.INVALID_CHARACTER_ERR = 5; + p.NO_DATA_ALLOWED_ERR = 6; + p.NO_MODIFICATION_ALLOWED_ERR = 7; + p.NOT_FOUND_ERR = 8; + p.NOT_SUPPORTED_ERR = 9; + p.INUSE_ATTRIBUTE_ERR = 10; + p.INVALID_STATE_ERR = 11; + p.SYNTAX_ERR = 12; + p.INVALID_MODIFICATION_ERR = 13; + p.NAMESPACE_ERR = 14; + p.INVALID_ACCESS_ERR = 15; + p.VALIDATION_ERR = 16; + p.TYPE_MISMATCH_ERR = 17; + + // set up externs + G_vmlCanvasManager = G_vmlCanvasManager_; + CanvasRenderingContext2D = CanvasRenderingContext2D_; + CanvasGradient = CanvasGradient_; + CanvasPattern = CanvasPattern_; + DOMException = DOMException_; +})(); + +} // if diff --git a/airtime_mvc/public/js/flot/excanvas.min.js b/airtime_mvc/public/js/flot/excanvas.min.js new file mode 100644 index 000000000..12c74f7be --- /dev/null +++ b/airtime_mvc/public/js/flot/excanvas.min.js @@ -0,0 +1 @@ +if(!document.createElement("canvas").getContext){(function(){var z=Math;var K=z.round;var J=z.sin;var U=z.cos;var b=z.abs;var k=z.sqrt;var D=10;var F=D/2;function T(){return this.context_||(this.context_=new W(this))}var O=Array.prototype.slice;function G(i,j,m){var Z=O.call(arguments,2);return function(){return i.apply(j,Z.concat(O.call(arguments)))}}function AD(Z){return String(Z).replace(/&/g,"&").replace(/"/g,""")}function r(i){if(!i.namespaces.g_vml_){i.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML")}if(!i.namespaces.g_o_){i.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML")}if(!i.styleSheets.ex_canvas_){var Z=i.createStyleSheet();Z.owningElement.id="ex_canvas_";Z.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}r(document);var E={init:function(Z){if(/MSIE/.test(navigator.userAgent)&&!window.opera){var i=Z||document;i.createElement("canvas");i.attachEvent("onreadystatechange",G(this.init_,this,i))}},init_:function(m){var j=m.getElementsByTagName("canvas");for(var Z=0;Z1){j--}if(6*j<1){return i+(Z-i)*6*j}else{if(2*j<1){return Z}else{if(3*j<2){return i+(Z-i)*(2/3-j)*6}else{return i}}}}function Y(Z){var AE,p=1;Z=String(Z);if(Z.charAt(0)=="#"){AE=Z}else{if(/^rgb/.test(Z)){var m=g(Z);var AE="#",AF;for(var j=0;j<3;j++){if(m[j].indexOf("%")!=-1){AF=Math.floor(C(m[j])*255)}else{AF=Number(m[j])}AE+=I[N(AF,0,255)]}p=m[3]}else{if(/^hsl/.test(Z)){var m=g(Z);AE=c(m);p=m[3]}else{AE=B[Z]||Z}}}return{color:AE,alpha:p}}var L={style:"normal",variant:"normal",weight:"normal",size:10,family:"sans-serif"};var f={};function X(Z){if(f[Z]){return f[Z]}var m=document.createElement("div");var j=m.style;try{j.font=Z}catch(i){}return f[Z]={style:j.fontStyle||L.style,variant:j.fontVariant||L.variant,weight:j.fontWeight||L.weight,size:j.fontSize||L.size,family:j.fontFamily||L.family}}function P(j,i){var Z={};for(var AF in j){Z[AF]=j[AF]}var AE=parseFloat(i.currentStyle.fontSize),m=parseFloat(j.size);if(typeof j.size=="number"){Z.size=j.size}else{if(j.size.indexOf("px")!=-1){Z.size=m}else{if(j.size.indexOf("em")!=-1){Z.size=AE*m}else{if(j.size.indexOf("%")!=-1){Z.size=(AE/100)*m}else{if(j.size.indexOf("pt")!=-1){Z.size=m/0.75}else{Z.size=AE}}}}}Z.size*=0.981;return Z}function AA(Z){return Z.style+" "+Z.variant+" "+Z.weight+" "+Z.size+"px "+Z.family}function t(Z){switch(Z){case"butt":return"flat";case"round":return"round";case"square":default:return"square"}}function W(i){this.m_=V();this.mStack_=[];this.aStack_=[];this.currentPath_=[];this.strokeStyle="#000";this.fillStyle="#000";this.lineWidth=1;this.lineJoin="miter";this.lineCap="butt";this.miterLimit=D*1;this.globalAlpha=1;this.font="10px sans-serif";this.textAlign="left";this.textBaseline="alphabetic";this.canvas=i;var Z=i.ownerDocument.createElement("div");Z.style.width=i.clientWidth+"px";Z.style.height=i.clientHeight+"px";Z.style.overflow="hidden";Z.style.position="absolute";i.appendChild(Z);this.element_=Z;this.arcScaleX_=1;this.arcScaleY_=1;this.lineScale_=1}var M=W.prototype;M.clearRect=function(){if(this.textMeasureEl_){this.textMeasureEl_.removeNode(true);this.textMeasureEl_=null}this.element_.innerHTML=""};M.beginPath=function(){this.currentPath_=[]};M.moveTo=function(i,Z){var j=this.getCoords_(i,Z);this.currentPath_.push({type:"moveTo",x:j.x,y:j.y});this.currentX_=j.x;this.currentY_=j.y};M.lineTo=function(i,Z){var j=this.getCoords_(i,Z);this.currentPath_.push({type:"lineTo",x:j.x,y:j.y});this.currentX_=j.x;this.currentY_=j.y};M.bezierCurveTo=function(j,i,AI,AH,AG,AE){var Z=this.getCoords_(AG,AE);var AF=this.getCoords_(j,i);var m=this.getCoords_(AI,AH);e(this,AF,m,Z)};function e(Z,m,j,i){Z.currentPath_.push({type:"bezierCurveTo",cp1x:m.x,cp1y:m.y,cp2x:j.x,cp2y:j.y,x:i.x,y:i.y});Z.currentX_=i.x;Z.currentY_=i.y}M.quadraticCurveTo=function(AG,j,i,Z){var AF=this.getCoords_(AG,j);var AE=this.getCoords_(i,Z);var AH={x:this.currentX_+2/3*(AF.x-this.currentX_),y:this.currentY_+2/3*(AF.y-this.currentY_)};var m={x:AH.x+(AE.x-this.currentX_)/3,y:AH.y+(AE.y-this.currentY_)/3};e(this,AH,m,AE)};M.arc=function(AJ,AH,AI,AE,i,j){AI*=D;var AN=j?"at":"wa";var AK=AJ+U(AE)*AI-F;var AM=AH+J(AE)*AI-F;var Z=AJ+U(i)*AI-F;var AL=AH+J(i)*AI-F;if(AK==Z&&!j){AK+=0.125}var m=this.getCoords_(AJ,AH);var AG=this.getCoords_(AK,AM);var AF=this.getCoords_(Z,AL);this.currentPath_.push({type:AN,x:m.x,y:m.y,radius:AI,xStart:AG.x,yStart:AG.y,xEnd:AF.x,yEnd:AF.y})};M.rect=function(j,i,Z,m){this.moveTo(j,i);this.lineTo(j+Z,i);this.lineTo(j+Z,i+m);this.lineTo(j,i+m);this.closePath()};M.strokeRect=function(j,i,Z,m){var p=this.currentPath_;this.beginPath();this.moveTo(j,i);this.lineTo(j+Z,i);this.lineTo(j+Z,i+m);this.lineTo(j,i+m);this.closePath();this.stroke();this.currentPath_=p};M.fillRect=function(j,i,Z,m){var p=this.currentPath_;this.beginPath();this.moveTo(j,i);this.lineTo(j+Z,i);this.lineTo(j+Z,i+m);this.lineTo(j,i+m);this.closePath();this.fill();this.currentPath_=p};M.createLinearGradient=function(i,m,Z,j){var p=new v("gradient");p.x0_=i;p.y0_=m;p.x1_=Z;p.y1_=j;return p};M.createRadialGradient=function(m,AE,j,i,p,Z){var AF=new v("gradientradial");AF.x0_=m;AF.y0_=AE;AF.r0_=j;AF.x1_=i;AF.y1_=p;AF.r1_=Z;return AF};M.drawImage=function(AO,j){var AH,AF,AJ,AV,AM,AK,AQ,AX;var AI=AO.runtimeStyle.width;var AN=AO.runtimeStyle.height;AO.runtimeStyle.width="auto";AO.runtimeStyle.height="auto";var AG=AO.width;var AT=AO.height;AO.runtimeStyle.width=AI;AO.runtimeStyle.height=AN;if(arguments.length==3){AH=arguments[1];AF=arguments[2];AM=AK=0;AQ=AJ=AG;AX=AV=AT}else{if(arguments.length==5){AH=arguments[1];AF=arguments[2];AJ=arguments[3];AV=arguments[4];AM=AK=0;AQ=AG;AX=AT}else{if(arguments.length==9){AM=arguments[1];AK=arguments[2];AQ=arguments[3];AX=arguments[4];AH=arguments[5];AF=arguments[6];AJ=arguments[7];AV=arguments[8]}else{throw Error("Invalid number of arguments")}}}var AW=this.getCoords_(AH,AF);var m=AQ/2;var i=AX/2;var AU=[];var Z=10;var AE=10;AU.push(" ','","");this.element_.insertAdjacentHTML("BeforeEnd",AU.join(""))};M.stroke=function(AM){var m=10;var AN=10;var AE=5000;var AG={x:null,y:null};var AL={x:null,y:null};for(var AH=0;AHAL.x){AL.x=Z.x}if(AG.y==null||Z.yAL.y){AL.y=Z.y}}}AK.push(' ">');if(!AM){R(this,AK)}else{a(this,AK,AG,AL)}AK.push("");this.element_.insertAdjacentHTML("beforeEnd",AK.join(""))}};function R(j,AE){var i=Y(j.strokeStyle);var m=i.color;var p=i.alpha*j.globalAlpha;var Z=j.lineScale_*j.lineWidth;if(Z<1){p*=Z}AE.push("')}function a(AO,AG,Ah,AP){var AH=AO.fillStyle;var AY=AO.arcScaleX_;var AX=AO.arcScaleY_;var Z=AP.x-Ah.x;var m=AP.y-Ah.y;if(AH instanceof v){var AL=0;var Ac={x:0,y:0};var AU=0;var AK=1;if(AH.type_=="gradient"){var AJ=AH.x0_/AY;var j=AH.y0_/AX;var AI=AH.x1_/AY;var Aj=AH.y1_/AX;var Ag=AO.getCoords_(AJ,j);var Af=AO.getCoords_(AI,Aj);var AE=Af.x-Ag.x;var p=Af.y-Ag.y;AL=Math.atan2(AE,p)*180/Math.PI;if(AL<0){AL+=360}if(AL<0.000001){AL=0}}else{var Ag=AO.getCoords_(AH.x0_,AH.y0_);Ac={x:(Ag.x-Ah.x)/Z,y:(Ag.y-Ah.y)/m};Z/=AY*D;m/=AX*D;var Aa=z.max(Z,m);AU=2*AH.r0_/Aa;AK=2*AH.r1_/Aa-AU}var AS=AH.colors_;AS.sort(function(Ak,i){return Ak.offset-i.offset});var AN=AS.length;var AR=AS[0].color;var AQ=AS[AN-1].color;var AW=AS[0].alpha*AO.globalAlpha;var AV=AS[AN-1].alpha*AO.globalAlpha;var Ab=[];for(var Ae=0;Ae')}else{if(AH instanceof u){if(Z&&m){var AF=-Ah.x;var AZ=-Ah.y;AG.push("')}}else{var Ai=Y(AO.fillStyle);var AT=Ai.color;var Ad=Ai.alpha*AO.globalAlpha;AG.push('')}}}M.fill=function(){this.stroke(true)};M.closePath=function(){this.currentPath_.push({type:"close"})};M.getCoords_=function(j,i){var Z=this.m_;return{x:D*(j*Z[0][0]+i*Z[1][0]+Z[2][0])-F,y:D*(j*Z[0][1]+i*Z[1][1]+Z[2][1])-F}};M.save=function(){var Z={};Q(this,Z);this.aStack_.push(Z);this.mStack_.push(this.m_);this.m_=d(V(),this.m_)};M.restore=function(){if(this.aStack_.length){Q(this.aStack_.pop(),this);this.m_=this.mStack_.pop()}};function H(Z){return isFinite(Z[0][0])&&isFinite(Z[0][1])&&isFinite(Z[1][0])&&isFinite(Z[1][1])&&isFinite(Z[2][0])&&isFinite(Z[2][1])}function y(i,Z,j){if(!H(Z)){return }i.m_=Z;if(j){var p=Z[0][0]*Z[1][1]-Z[0][1]*Z[1][0];i.lineScale_=k(b(p))}}M.translate=function(j,i){var Z=[[1,0,0],[0,1,0],[j,i,1]];y(this,d(Z,this.m_),false)};M.rotate=function(i){var m=U(i);var j=J(i);var Z=[[m,j,0],[-j,m,0],[0,0,1]];y(this,d(Z,this.m_),false)};M.scale=function(j,i){this.arcScaleX_*=j;this.arcScaleY_*=i;var Z=[[j,0,0],[0,i,0],[0,0,1]];y(this,d(Z,this.m_),true)};M.transform=function(p,m,AF,AE,i,Z){var j=[[p,m,0],[AF,AE,0],[i,Z,1]];y(this,d(j,this.m_),true)};M.setTransform=function(AE,p,AG,AF,j,i){var Z=[[AE,p,0],[AG,AF,0],[j,i,1]];y(this,Z,true)};M.drawText_=function(AK,AI,AH,AN,AG){var AM=this.m_,AQ=1000,i=0,AP=AQ,AF={x:0,y:0},AE=[];var Z=P(X(this.font),this.element_);var j=AA(Z);var AR=this.element_.currentStyle;var p=this.textAlign.toLowerCase();switch(p){case"left":case"center":case"right":break;case"end":p=AR.direction=="ltr"?"right":"left";break;case"start":p=AR.direction=="rtl"?"right":"left";break;default:p="left"}switch(this.textBaseline){case"hanging":case"top":AF.y=Z.size/1.75;break;case"middle":break;default:case null:case"alphabetic":case"ideographic":case"bottom":AF.y=-Z.size/2.25;break}switch(p){case"right":i=AQ;AP=0.05;break;case"center":i=AP=AQ/2;break}var AO=this.getCoords_(AI+AF.x,AH+AF.y);AE.push('');if(AG){R(this,AE)}else{a(this,AE,{x:-i,y:0},{x:AP,y:Z.size})}var AL=AM[0][0].toFixed(3)+","+AM[1][0].toFixed(3)+","+AM[0][1].toFixed(3)+","+AM[1][1].toFixed(3)+",0,0";var AJ=K(AO.x/D)+","+K(AO.y/D);AE.push('','','');this.element_.insertAdjacentHTML("beforeEnd",AE.join(""))};M.fillText=function(j,Z,m,i){this.drawText_(j,Z,m,i,false)};M.strokeText=function(j,Z,m,i){this.drawText_(j,Z,m,i,true)};M.measureText=function(j){if(!this.textMeasureEl_){var Z='';this.element_.insertAdjacentHTML("beforeEnd",Z);this.textMeasureEl_=this.element_.lastChild}var i=this.element_.ownerDocument;this.textMeasureEl_.innerHTML="";this.textMeasureEl_.style.font=this.font;this.textMeasureEl_.appendChild(i.createTextNode(j));return{width:this.textMeasureEl_.offsetWidth}};M.clip=function(){};M.arcTo=function(){};M.createPattern=function(i,Z){return new u(i,Z)};function v(Z){this.type_=Z;this.x0_=0;this.y0_=0;this.r0_=0;this.x1_=0;this.y1_=0;this.r1_=0;this.colors_=[]}v.prototype.addColorStop=function(i,Z){Z=Y(Z);this.colors_.push({offset:i,color:Z.color,alpha:Z.alpha})};function u(i,Z){q(i);switch(Z){case"repeat":case null:case"":this.repetition_="repeat";break;case"repeat-x":case"repeat-y":case"no-repeat":this.repetition_=Z;break;default:n("SYNTAX_ERR")}this.src_=i.src;this.width_=i.width;this.height_=i.height}function n(Z){throw new o(Z)}function q(Z){if(!Z||Z.nodeType!=1||Z.tagName!="IMG"){n("TYPE_MISMATCH_ERR")}if(Z.readyState!="complete"){n("INVALID_STATE_ERR")}}function o(Z){this.code=this[Z];this.message=Z+": DOM Exception "+this.code}var x=o.prototype=new Error;x.INDEX_SIZE_ERR=1;x.DOMSTRING_SIZE_ERR=2;x.HIERARCHY_REQUEST_ERR=3;x.WRONG_DOCUMENT_ERR=4;x.INVALID_CHARACTER_ERR=5;x.NO_DATA_ALLOWED_ERR=6;x.NO_MODIFICATION_ALLOWED_ERR=7;x.NOT_FOUND_ERR=8;x.NOT_SUPPORTED_ERR=9;x.INUSE_ATTRIBUTE_ERR=10;x.INVALID_STATE_ERR=11;x.SYNTAX_ERR=12;x.INVALID_MODIFICATION_ERR=13;x.NAMESPACE_ERR=14;x.INVALID_ACCESS_ERR=15;x.VALIDATION_ERR=16;x.TYPE_MISMATCH_ERR=17;G_vmlCanvasManager=E;CanvasRenderingContext2D=W;CanvasGradient=v;CanvasPattern=u;DOMException=o})()}; \ No newline at end of file diff --git a/airtime_mvc/public/js/flot/jquery.colorhelpers.js b/airtime_mvc/public/js/flot/jquery.colorhelpers.js new file mode 100644 index 000000000..d3524d786 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.colorhelpers.js @@ -0,0 +1,179 @@ +/* Plugin for jQuery for working with colors. + * + * Version 1.1. + * + * Inspiration from jQuery color animation plugin by John Resig. + * + * Released under the MIT license by Ole Laursen, October 2009. + * + * Examples: + * + * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() + * var c = $.color.extract($("#mydiv"), 'background-color'); + * console.log(c.r, c.g, c.b, c.a); + * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" + * + * Note that .scale() and .add() return the same modified object + * instead of making a new one. + * + * V. 1.1: Fix error handling so e.g. parsing an empty string does + * produce a color rather than just crashing. + */ + +(function($) { + $.color = {}; + + // construct color object with some convenient chainable helpers + $.color.make = function (r, g, b, a) { + var o = {}; + o.r = r || 0; + o.g = g || 0; + o.b = b || 0; + o.a = a != null ? a : 1; + + o.add = function (c, d) { + for (var i = 0; i < c.length; ++i) + o[c.charAt(i)] += d; + return o.normalize(); + }; + + o.scale = function (c, f) { + for (var i = 0; i < c.length; ++i) + o[c.charAt(i)] *= f; + return o.normalize(); + }; + + o.toString = function () { + if (o.a >= 1.0) { + return "rgb("+[o.r, o.g, o.b].join(",")+")"; + } else { + return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")"; + } + }; + + o.normalize = function () { + function clamp(min, value, max) { + return value < min ? min: (value > max ? max: value); + } + + o.r = clamp(0, parseInt(o.r), 255); + o.g = clamp(0, parseInt(o.g), 255); + o.b = clamp(0, parseInt(o.b), 255); + o.a = clamp(0, o.a, 1); + return o; + }; + + o.clone = function () { + return $.color.make(o.r, o.b, o.g, o.a); + }; + + return o.normalize(); + } + + // extract CSS color property from element, going up in the DOM + // if it's "transparent" + $.color.extract = function (elem, css) { + var c; + do { + c = elem.css(css).toLowerCase(); + // keep going until we find an element that has color, or + // we hit the body + if (c != '' && c != 'transparent') + break; + elem = elem.parent(); + } while (!$.nodeName(elem.get(0), "body")); + + // catch Safari's way of signalling transparent + if (c == "rgba(0, 0, 0, 0)") + c = "transparent"; + + return $.color.parse(c); + } + + // parse CSS color string (like "rgb(10, 32, 43)" or "#fff"), + // returns color object, if parsing failed, you get black (0, 0, + // 0) out + $.color.parse = function (str) { + var res, m = $.color.make; + + // Look for rgb(num,num,num) + if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) + return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10)); + + // Look for rgba(num,num,num,num) + if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) + return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4])); + + // Look for rgb(num%,num%,num%) + if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) + return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55); + + // Look for rgba(num%,num%,num%,num) + if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) + return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4])); + + // Look for #a0b1c2 + if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) + return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16)); + + // Look for #fff + if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) + return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16)); + + // Otherwise, we're most likely dealing with a named color + var name = $.trim(str).toLowerCase(); + if (name == "transparent") + return m(255, 255, 255, 0); + else { + // default to black + res = lookupColors[name] || [0, 0, 0]; + return m(res[0], res[1], res[2]); + } + } + + var lookupColors = { + aqua:[0,255,255], + azure:[240,255,255], + beige:[245,245,220], + black:[0,0,0], + blue:[0,0,255], + brown:[165,42,42], + cyan:[0,255,255], + darkblue:[0,0,139], + darkcyan:[0,139,139], + darkgrey:[169,169,169], + darkgreen:[0,100,0], + darkkhaki:[189,183,107], + darkmagenta:[139,0,139], + darkolivegreen:[85,107,47], + darkorange:[255,140,0], + darkorchid:[153,50,204], + darkred:[139,0,0], + darksalmon:[233,150,122], + darkviolet:[148,0,211], + fuchsia:[255,0,255], + gold:[255,215,0], + green:[0,128,0], + indigo:[75,0,130], + khaki:[240,230,140], + lightblue:[173,216,230], + lightcyan:[224,255,255], + lightgreen:[144,238,144], + lightgrey:[211,211,211], + lightpink:[255,182,193], + lightyellow:[255,255,224], + lime:[0,255,0], + magenta:[255,0,255], + maroon:[128,0,0], + navy:[0,0,128], + olive:[128,128,0], + orange:[255,165,0], + pink:[255,192,203], + purple:[128,0,128], + violet:[128,0,128], + red:[255,0,0], + silver:[192,192,192], + white:[255,255,255], + yellow:[255,255,0] + }; +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.crosshair.js b/airtime_mvc/public/js/flot/jquery.flot.crosshair.js new file mode 100644 index 000000000..1d433f007 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.crosshair.js @@ -0,0 +1,167 @@ +/* +Flot plugin for showing crosshairs, thin lines, when the mouse hovers +over the plot. + + crosshair: { + mode: null or "x" or "y" or "xy" + color: color + lineWidth: number + } + +Set the mode to one of "x", "y" or "xy". The "x" mode enables a +vertical crosshair that lets you trace the values on the x axis, "y" +enables a horizontal crosshair and "xy" enables them both. "color" is +the color of the crosshair (default is "rgba(170, 0, 0, 0.80)"), +"lineWidth" is the width of the drawn lines (default is 1). + +The plugin also adds four public methods: + + - setCrosshair(pos) + + Set the position of the crosshair. Note that this is cleared if + the user moves the mouse. "pos" is in coordinates of the plot and + should be on the form { x: xpos, y: ypos } (you can use x2/x3/... + if you're using multiple axes), which is coincidentally the same + format as what you get from a "plothover" event. If "pos" is null, + the crosshair is cleared. + + - clearCrosshair() + + Clear the crosshair. + + - lockCrosshair(pos) + + Cause the crosshair to lock to the current location, no longer + updating if the user moves the mouse. Optionally supply a position + (passed on to setCrosshair()) to move it to. + + Example usage: + var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } }; + $("#graph").bind("plothover", function (evt, position, item) { + if (item) { + // Lock the crosshair to the data point being hovered + myFlot.lockCrosshair({ x: item.datapoint[0], y: item.datapoint[1] }); + } + else { + // Return normal crosshair operation + myFlot.unlockCrosshair(); + } + }); + + - unlockCrosshair() + + Free the crosshair to move again after locking it. +*/ + +(function ($) { + var options = { + crosshair: { + mode: null, // one of null, "x", "y" or "xy", + color: "rgba(170, 0, 0, 0.80)", + lineWidth: 1 + } + }; + + function init(plot) { + // position of crosshair in pixels + var crosshair = { x: -1, y: -1, locked: false }; + + plot.setCrosshair = function setCrosshair(pos) { + if (!pos) + crosshair.x = -1; + else { + var o = plot.p2c(pos); + crosshair.x = Math.max(0, Math.min(o.left, plot.width())); + crosshair.y = Math.max(0, Math.min(o.top, plot.height())); + } + + plot.triggerRedrawOverlay(); + }; + + plot.clearCrosshair = plot.setCrosshair; // passes null for pos + + plot.lockCrosshair = function lockCrosshair(pos) { + if (pos) + plot.setCrosshair(pos); + crosshair.locked = true; + } + + plot.unlockCrosshair = function unlockCrosshair() { + crosshair.locked = false; + } + + function onMouseOut(e) { + if (crosshair.locked) + return; + + if (crosshair.x != -1) { + crosshair.x = -1; + plot.triggerRedrawOverlay(); + } + } + + function onMouseMove(e) { + if (crosshair.locked) + return; + + if (plot.getSelection && plot.getSelection()) { + crosshair.x = -1; // hide the crosshair while selecting + return; + } + + var offset = plot.offset(); + crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width())); + crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height())); + plot.triggerRedrawOverlay(); + } + + plot.hooks.bindEvents.push(function (plot, eventHolder) { + if (!plot.getOptions().crosshair.mode) + return; + + eventHolder.mouseout(onMouseOut); + eventHolder.mousemove(onMouseMove); + }); + + plot.hooks.drawOverlay.push(function (plot, ctx) { + var c = plot.getOptions().crosshair; + if (!c.mode) + return; + + var plotOffset = plot.getPlotOffset(); + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + if (crosshair.x != -1) { + ctx.strokeStyle = c.color; + ctx.lineWidth = c.lineWidth; + ctx.lineJoin = "round"; + + ctx.beginPath(); + if (c.mode.indexOf("x") != -1) { + ctx.moveTo(crosshair.x, 0); + ctx.lineTo(crosshair.x, plot.height()); + } + if (c.mode.indexOf("y") != -1) { + ctx.moveTo(0, crosshair.y); + ctx.lineTo(plot.width(), crosshair.y); + } + ctx.stroke(); + } + ctx.restore(); + }); + + plot.hooks.shutdown.push(function (plot, eventHolder) { + eventHolder.unbind("mouseout", onMouseOut); + eventHolder.unbind("mousemove", onMouseMove); + }); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'crosshair', + version: '1.0' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.fillbetween.js b/airtime_mvc/public/js/flot/jquery.flot.fillbetween.js new file mode 100644 index 000000000..69700e79c --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.fillbetween.js @@ -0,0 +1,183 @@ +/* +Flot plugin for computing bottoms for filled line and bar charts. + +The case: you've got two series that you want to fill the area +between. In Flot terms, you need to use one as the fill bottom of the +other. You can specify the bottom of each data point as the third +coordinate manually, or you can use this plugin to compute it for you. + +In order to name the other series, you need to give it an id, like this + + var dataset = [ + { data: [ ... ], id: "foo" } , // use default bottom + { data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom + ]; + + $.plot($("#placeholder"), dataset, { line: { show: true, fill: true }}); + +As a convenience, if the id given is a number that doesn't appear as +an id in the series, it is interpreted as the index in the array +instead (so fillBetween: 0 can also mean the first series). + +Internally, the plugin modifies the datapoints in each series. For +line series, extra data points might be inserted through +interpolation. Note that at points where the bottom line is not +defined (due to a null point or start/end of line), the current line +will show a gap too. The algorithm comes from the jquery.flot.stack.js +plugin, possibly some code could be shared. +*/ + +(function ($) { + var options = { + series: { fillBetween: null } // or number + }; + + function init(plot) { + function findBottomSeries(s, allseries) { + var i; + for (i = 0; i < allseries.length; ++i) { + if (allseries[i].id == s.fillBetween) + return allseries[i]; + } + + if (typeof s.fillBetween == "number") { + i = s.fillBetween; + + if (i < 0 || i >= allseries.length) + return null; + + return allseries[i]; + } + + return null; + } + + function computeFillBottoms(plot, s, datapoints) { + if (s.fillBetween == null) + return; + + var other = findBottomSeries(s, plot.getData()); + if (!other) + return; + + var ps = datapoints.pointsize, + points = datapoints.points, + otherps = other.datapoints.pointsize, + otherpoints = other.datapoints.points, + newpoints = [], + px, py, intery, qx, qy, bottom, + withlines = s.lines.show, + withbottom = ps > 2 && datapoints.format[2].y, + withsteps = withlines && s.lines.steps, + fromgap = true, + i = 0, j = 0, l; + + while (true) { + if (i >= points.length) + break; + + l = newpoints.length; + + if (points[i] == null) { + // copy gaps + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + i += ps; + } + else if (j >= otherpoints.length) { + // for lines, we can't use the rest of the points + if (!withlines) { + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + } + i += ps; + } + else if (otherpoints[j] == null) { + // oops, got a gap + for (m = 0; m < ps; ++m) + newpoints.push(null); + fromgap = true; + j += otherps; + } + else { + // cases where we actually got two points + px = points[i]; + py = points[i + 1]; + qx = otherpoints[j]; + qy = otherpoints[j + 1]; + bottom = 0; + + if (px == qx) { + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + + //newpoints[l + 1] += qy; + bottom = qy; + + i += ps; + j += otherps; + } + else if (px > qx) { + // we got past point below, might need to + // insert interpolated extra point + if (withlines && i > 0 && points[i - ps] != null) { + intery = py + (points[i - ps + 1] - py) * (qx - px) / (points[i - ps] - px); + newpoints.push(qx); + newpoints.push(intery) + for (m = 2; m < ps; ++m) + newpoints.push(points[i + m]); + bottom = qy; + } + + j += otherps; + } + else { // px < qx + if (fromgap && withlines) { + // if we come from a gap, we just skip this point + i += ps; + continue; + } + + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + + // we might be able to interpolate a point below, + // this can give us a better y + if (withlines && j > 0 && otherpoints[j - otherps] != null) + bottom = qy + (otherpoints[j - otherps + 1] - qy) * (px - qx) / (otherpoints[j - otherps] - qx); + + //newpoints[l + 1] += bottom; + + i += ps; + } + + fromgap = false; + + if (l != newpoints.length && withbottom) + newpoints[l + 2] = bottom; + } + + // maintain the line steps invariant + if (withsteps && l != newpoints.length && l > 0 + && newpoints[l] != null + && newpoints[l] != newpoints[l - ps] + && newpoints[l + 1] != newpoints[l - ps + 1]) { + for (m = 0; m < ps; ++m) + newpoints[l + ps + m] = newpoints[l + m]; + newpoints[l + 1] = newpoints[l - ps + 1]; + } + } + + datapoints.points = newpoints; + } + + plot.hooks.processDatapoints.push(computeFillBottoms); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'fillbetween', + version: '1.0' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.image.js b/airtime_mvc/public/js/flot/jquery.flot.image.js new file mode 100644 index 000000000..29ccb125f --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.image.js @@ -0,0 +1,238 @@ +/* +Flot plugin for plotting images, e.g. useful for putting ticks on a +prerendered complex visualization. + +The data syntax is [[image, x1, y1, x2, y2], ...] where (x1, y1) and +(x2, y2) are where you intend the two opposite corners of the image to +end up in the plot. Image must be a fully loaded Javascript image (you +can make one with new Image()). If the image is not complete, it's +skipped when plotting. + +There are two helpers included for retrieving images. The easiest work +the way that you put in URLs instead of images in the data (like +["myimage.png", 0, 0, 10, 10]), then call $.plot.image.loadData(data, +options, callback) where data and options are the same as you pass in +to $.plot. This loads the images, replaces the URLs in the data with +the corresponding images and calls "callback" when all images are +loaded (or failed loading). In the callback, you can then call $.plot +with the data set. See the included example. + +A more low-level helper, $.plot.image.load(urls, callback) is also +included. Given a list of URLs, it calls callback with an object +mapping from URL to Image object when all images are loaded or have +failed loading. + +Options for the plugin are + + series: { + images: { + show: boolean + anchor: "corner" or "center" + alpha: [0,1] + } + } + +which can be specified for a specific series + + $.plot($("#placeholder"), [{ data: [ ... ], images: { ... } ]) + +Note that because the data format is different from usual data points, +you can't use images with anything else in a specific data series. + +Setting "anchor" to "center" causes the pixels in the image to be +anchored at the corner pixel centers inside of at the pixel corners, +effectively letting half a pixel stick out to each side in the plot. + + +A possible future direction could be support for tiling for large +images (like Google Maps). + +*/ + +(function ($) { + var options = { + series: { + images: { + show: false, + alpha: 1, + anchor: "corner" // or "center" + } + } + }; + + $.plot.image = {}; + + $.plot.image.loadDataImages = function (series, options, callback) { + var urls = [], points = []; + + var defaultShow = options.series.images.show; + + $.each(series, function (i, s) { + if (!(defaultShow || s.images.show)) + return; + + if (s.data) + s = s.data; + + $.each(s, function (i, p) { + if (typeof p[0] == "string") { + urls.push(p[0]); + points.push(p); + } + }); + }); + + $.plot.image.load(urls, function (loadedImages) { + $.each(points, function (i, p) { + var url = p[0]; + if (loadedImages[url]) + p[0] = loadedImages[url]; + }); + + callback(); + }); + } + + $.plot.image.load = function (urls, callback) { + var missing = urls.length, loaded = {}; + if (missing == 0) + callback({}); + + $.each(urls, function (i, url) { + var handler = function () { + --missing; + + loaded[url] = this; + + if (missing == 0) + callback(loaded); + }; + + $('').load(handler).error(handler).attr('src', url); + }); + } + + function drawSeries(plot, ctx, series) { + var plotOffset = plot.getPlotOffset(); + + if (!series.images || !series.images.show) + return; + + var points = series.datapoints.points, + ps = series.datapoints.pointsize; + + for (var i = 0; i < points.length; i += ps) { + var img = points[i], + x1 = points[i + 1], y1 = points[i + 2], + x2 = points[i + 3], y2 = points[i + 4], + xaxis = series.xaxis, yaxis = series.yaxis, + tmp; + + // actually we should check img.complete, but it + // appears to be a somewhat unreliable indicator in + // IE6 (false even after load event) + if (!img || img.width <= 0 || img.height <= 0) + continue; + + if (x1 > x2) { + tmp = x2; + x2 = x1; + x1 = tmp; + } + if (y1 > y2) { + tmp = y2; + y2 = y1; + y1 = tmp; + } + + // if the anchor is at the center of the pixel, expand the + // image by 1/2 pixel in each direction + if (series.images.anchor == "center") { + tmp = 0.5 * (x2-x1) / (img.width - 1); + x1 -= tmp; + x2 += tmp; + tmp = 0.5 * (y2-y1) / (img.height - 1); + y1 -= tmp; + y2 += tmp; + } + + // clip + if (x1 == x2 || y1 == y2 || + x1 >= xaxis.max || x2 <= xaxis.min || + y1 >= yaxis.max || y2 <= yaxis.min) + continue; + + var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height; + if (x1 < xaxis.min) { + sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1); + x1 = xaxis.min; + } + + if (x2 > xaxis.max) { + sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1); + x2 = xaxis.max; + } + + if (y1 < yaxis.min) { + sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1); + y1 = yaxis.min; + } + + if (y2 > yaxis.max) { + sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1); + y2 = yaxis.max; + } + + x1 = xaxis.p2c(x1); + x2 = xaxis.p2c(x2); + y1 = yaxis.p2c(y1); + y2 = yaxis.p2c(y2); + + // the transformation may have swapped us + if (x1 > x2) { + tmp = x2; + x2 = x1; + x1 = tmp; + } + if (y1 > y2) { + tmp = y2; + y2 = y1; + y1 = tmp; + } + + tmp = ctx.globalAlpha; + ctx.globalAlpha *= series.images.alpha; + ctx.drawImage(img, + sx1, sy1, sx2 - sx1, sy2 - sy1, + x1 + plotOffset.left, y1 + plotOffset.top, + x2 - x1, y2 - y1); + ctx.globalAlpha = tmp; + } + } + + function processRawData(plot, series, data, datapoints) { + if (!series.images.show) + return; + + // format is Image, x1, y1, x2, y2 (opposite corners) + datapoints.format = [ + { required: true }, + { x: true, number: true, required: true }, + { y: true, number: true, required: true }, + { x: true, number: true, required: true }, + { y: true, number: true, required: true } + ]; + } + + function init(plot) { + plot.hooks.processRawData.push(processRawData); + plot.hooks.drawSeries.push(drawSeries); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'image', + version: '1.1' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.js b/airtime_mvc/public/js/flot/jquery.flot.js new file mode 100644 index 000000000..aabc544e9 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.js @@ -0,0 +1,2599 @@ +/*! Javascript plotting library for jQuery, v. 0.7. + * + * Released under the MIT license by IOLA, December 2007. + * + */ + +// first an inline dependency, jquery.colorhelpers.js, we inline it here +// for convenience + +/* Plugin for jQuery for working with colors. + * + * Version 1.1. + * + * Inspiration from jQuery color animation plugin by John Resig. + * + * Released under the MIT license by Ole Laursen, October 2009. + * + * Examples: + * + * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() + * var c = $.color.extract($("#mydiv"), 'background-color'); + * console.log(c.r, c.g, c.b, c.a); + * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" + * + * Note that .scale() and .add() return the same modified object + * instead of making a new one. + * + * V. 1.1: Fix error handling so e.g. parsing an empty string does + * produce a color rather than just crashing. + */ +(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return KI?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); + +// the actual Flot code +(function($) { + function Plot(placeholder, data_, options_, plugins) { + // data is on the form: + // [ series1, series2 ... ] + // where series is either just the data as [ [x1, y1], [x2, y2], ... ] + // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } + + var series = [], + options = { + // the color theme used for graphs + colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], + legend: { + show: true, + noColumns: 1, // number of colums in legend table + labelFormatter: null, // fn: string -> string + labelBoxBorderColor: "#ccc", // border color for the little label boxes + container: null, // container (as jQuery object) to put legend in, null means default on top of graph + position: "ne", // position of default legend container within plot + margin: 5, // distance from grid edge to default legend container within plot + backgroundColor: null, // null means auto-detect + backgroundOpacity: 0.85 // set to 0 to avoid background + }, + xaxis: { + show: null, // null = auto-detect, true = always, false = never + position: "bottom", // or "top" + mode: null, // null or "time" + color: null, // base color, labels, ticks + tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" + transform: null, // null or f: number -> number to transform axis + inverseTransform: null, // if transform is set, this should be the inverse function + min: null, // min. value to show, null means set automatically + max: null, // max. value to show, null means set automatically + autoscaleMargin: null, // margin in % to add if auto-setting min/max + ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks + tickFormatter: null, // fn: number -> string + labelWidth: null, // size of tick labels in pixels + labelHeight: null, + reserveSpace: null, // whether to reserve space even if axis isn't shown + tickLength: null, // size in pixels of ticks, or "full" for whole line + alignTicksWithAxis: null, // axis number or null for no sync + + // mode specific options + tickDecimals: null, // no. of decimals, null means auto + tickSize: null, // number or [number, "unit"] + minTickSize: null, // number or [number, "unit"] + monthNames: null, // list of names of months + timeformat: null, // format string to use + twelveHourClock: false // 12 or 24 time in time mode + }, + yaxis: { + autoscaleMargin: 0.02, + position: "left" // or "right" + }, + xaxes: [], + yaxes: [], + series: { + points: { + show: false, + radius: 3, + lineWidth: 2, // in pixels + fill: true, + fillColor: "#ffffff", + symbol: "circle" // or callback + }, + lines: { + // we don't put in show: false so we can see + // whether lines were actively disabled + lineWidth: 2, // in pixels + fill: false, + fillColor: null, + steps: false + }, + bars: { + show: false, + lineWidth: 2, // in pixels + barWidth: 1, // in units of the x axis + fill: true, + fillColor: null, + align: "left", // or "center" + horizontal: false + }, + shadowSize: 3 + }, + grid: { + show: true, + aboveData: false, + color: "#545454", // primary color used for outline and labels + backgroundColor: null, // null for transparent, else color + borderColor: null, // set if different from the grid color + tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)" + labelMargin: 5, // in pixels + axisMargin: 8, // in pixels + borderWidth: 2, // in pixels + minBorderMargin: null, // in pixels, null means taken from points radius + markings: null, // array of ranges or fn: axes -> array of ranges + markingsColor: "#f4f4f4", + markingsLineWidth: 2, + // interactive stuff + clickable: false, + hoverable: false, + autoHighlight: true, // highlight in case mouse is near + mouseActiveRadius: 10 // how far the mouse can be away to activate an item + }, + hooks: {} + }, + canvas = null, // the canvas for the plot itself + overlay = null, // canvas for interactive stuff on top of plot + eventHolder = null, // jQuery object that events should be bound to + ctx = null, octx = null, + xaxes = [], yaxes = [], + plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, + canvasWidth = 0, canvasHeight = 0, + plotWidth = 0, plotHeight = 0, + hooks = { + processOptions: [], + processRawData: [], + processDatapoints: [], + drawSeries: [], + draw: [], + bindEvents: [], + drawOverlay: [], + shutdown: [] + }, + plot = this; + + // public functions + plot.setData = setData; + plot.setupGrid = setupGrid; + plot.draw = draw; + plot.getPlaceholder = function() { return placeholder; }; + plot.getCanvas = function() { return canvas; }; + plot.getPlotOffset = function() { return plotOffset; }; + plot.width = function () { return plotWidth; }; + plot.height = function () { return plotHeight; }; + plot.offset = function () { + var o = eventHolder.offset(); + o.left += plotOffset.left; + o.top += plotOffset.top; + return o; + }; + plot.getData = function () { return series; }; + plot.getAxes = function () { + var res = {}, i; + $.each(xaxes.concat(yaxes), function (_, axis) { + if (axis) + res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis; + }); + return res; + }; + plot.getXAxes = function () { return xaxes; }; + plot.getYAxes = function () { return yaxes; }; + plot.c2p = canvasToAxisCoords; + plot.p2c = axisToCanvasCoords; + plot.getOptions = function () { return options; }; + plot.highlight = highlight; + plot.unhighlight = unhighlight; + plot.triggerRedrawOverlay = triggerRedrawOverlay; + plot.pointOffset = function(point) { + return { + left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left), + top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top) + }; + }; + plot.shutdown = shutdown; + plot.resize = function () { + getCanvasDimensions(); + resizeCanvas(canvas); + resizeCanvas(overlay); + }; + + // public attributes + plot.hooks = hooks; + + // initialize + initPlugins(plot); + parseOptions(options_); + setupCanvases(); + setData(data_); + setupGrid(); + draw(); + bindEvents(); + + + function executeHooks(hook, args) { + args = [plot].concat(args); + for (var i = 0; i < hook.length; ++i) + hook[i].apply(this, args); + } + + function initPlugins() { + for (var i = 0; i < plugins.length; ++i) { + var p = plugins[i]; + p.init(plot); + if (p.options) + $.extend(true, options, p.options); + } + } + + function parseOptions(opts) { + var i; + + $.extend(true, options, opts); + + if (options.xaxis.color == null) + options.xaxis.color = options.grid.color; + if (options.yaxis.color == null) + options.yaxis.color = options.grid.color; + + if (options.xaxis.tickColor == null) // backwards-compatibility + options.xaxis.tickColor = options.grid.tickColor; + if (options.yaxis.tickColor == null) // backwards-compatibility + options.yaxis.tickColor = options.grid.tickColor; + + if (options.grid.borderColor == null) + options.grid.borderColor = options.grid.color; + if (options.grid.tickColor == null) + options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); + + // fill in defaults in axes, copy at least always the + // first as the rest of the code assumes it'll be there + for (i = 0; i < Math.max(1, options.xaxes.length); ++i) + options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]); + for (i = 0; i < Math.max(1, options.yaxes.length); ++i) + options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]); + + // backwards compatibility, to be removed in future + if (options.xaxis.noTicks && options.xaxis.ticks == null) + options.xaxis.ticks = options.xaxis.noTicks; + if (options.yaxis.noTicks && options.yaxis.ticks == null) + options.yaxis.ticks = options.yaxis.noTicks; + if (options.x2axis) { + options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); + options.xaxes[1].position = "top"; + } + if (options.y2axis) { + options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); + options.yaxes[1].position = "right"; + } + if (options.grid.coloredAreas) + options.grid.markings = options.grid.coloredAreas; + if (options.grid.coloredAreasColor) + options.grid.markingsColor = options.grid.coloredAreasColor; + if (options.lines) + $.extend(true, options.series.lines, options.lines); + if (options.points) + $.extend(true, options.series.points, options.points); + if (options.bars) + $.extend(true, options.series.bars, options.bars); + if (options.shadowSize != null) + options.series.shadowSize = options.shadowSize; + + // save options on axes for future reference + for (i = 0; i < options.xaxes.length; ++i) + getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i]; + for (i = 0; i < options.yaxes.length; ++i) + getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i]; + + // add hooks from options + for (var n in hooks) + if (options.hooks[n] && options.hooks[n].length) + hooks[n] = hooks[n].concat(options.hooks[n]); + + executeHooks(hooks.processOptions, [options]); + } + + function setData(d) { + series = parseData(d); + fillInSeriesOptions(); + processData(); + } + + function parseData(d) { + var res = []; + for (var i = 0; i < d.length; ++i) { + var s = $.extend(true, {}, options.series); + + if (d[i].data != null) { + s.data = d[i].data; // move the data instead of deep-copy + delete d[i].data; + + $.extend(true, s, d[i]); + + d[i].data = s.data; + } + else + s.data = d[i]; + res.push(s); + } + + return res; + } + + function axisNumber(obj, coord) { + var a = obj[coord + "axis"]; + if (typeof a == "object") // if we got a real axis, extract number + a = a.n; + if (typeof a != "number") + a = 1; // default to first axis + return a; + } + + function allAxes() { + // return flat array without annoying null entries + return $.grep(xaxes.concat(yaxes), function (a) { return a; }); + } + + function canvasToAxisCoords(pos) { + // return an object with x/y corresponding to all used axes + var res = {}, i, axis; + for (i = 0; i < xaxes.length; ++i) { + axis = xaxes[i]; + if (axis && axis.used) + res["x" + axis.n] = axis.c2p(pos.left); + } + + for (i = 0; i < yaxes.length; ++i) { + axis = yaxes[i]; + if (axis && axis.used) + res["y" + axis.n] = axis.c2p(pos.top); + } + + if (res.x1 !== undefined) + res.x = res.x1; + if (res.y1 !== undefined) + res.y = res.y1; + + return res; + } + + function axisToCanvasCoords(pos) { + // get canvas coords from the first pair of x/y found in pos + var res = {}, i, axis, key; + + for (i = 0; i < xaxes.length; ++i) { + axis = xaxes[i]; + if (axis && axis.used) { + key = "x" + axis.n; + if (pos[key] == null && axis.n == 1) + key = "x"; + + if (pos[key] != null) { + res.left = axis.p2c(pos[key]); + break; + } + } + } + + for (i = 0; i < yaxes.length; ++i) { + axis = yaxes[i]; + if (axis && axis.used) { + key = "y" + axis.n; + if (pos[key] == null && axis.n == 1) + key = "y"; + + if (pos[key] != null) { + res.top = axis.p2c(pos[key]); + break; + } + } + } + + return res; + } + + function getOrCreateAxis(axes, number) { + if (!axes[number - 1]) + axes[number - 1] = { + n: number, // save the number for future reference + direction: axes == xaxes ? "x" : "y", + options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) + }; + + return axes[number - 1]; + } + + function fillInSeriesOptions() { + var i; + + // collect what we already got of colors + var neededColors = series.length, + usedColors = [], + assignedColors = []; + for (i = 0; i < series.length; ++i) { + var sc = series[i].color; + if (sc != null) { + --neededColors; + if (typeof sc == "number") + assignedColors.push(sc); + else + usedColors.push($.color.parse(series[i].color)); + } + } + + // we might need to generate more colors if higher indices + // are assigned + for (i = 0; i < assignedColors.length; ++i) { + neededColors = Math.max(neededColors, assignedColors[i] + 1); + } + + // produce colors as needed + var colors = [], variation = 0; + i = 0; + while (colors.length < neededColors) { + var c; + if (options.colors.length == i) // check degenerate case + c = $.color.make(100, 100, 100); + else + c = $.color.parse(options.colors[i]); + + // vary color if needed + var sign = variation % 2 == 1 ? -1 : 1; + c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2) + + // FIXME: if we're getting to close to something else, + // we should probably skip this one + colors.push(c); + + ++i; + if (i >= options.colors.length) { + i = 0; + ++variation; + } + } + + // fill in the options + var colori = 0, s; + for (i = 0; i < series.length; ++i) { + s = series[i]; + + // assign colors + if (s.color == null) { + s.color = colors[colori].toString(); + ++colori; + } + else if (typeof s.color == "number") + s.color = colors[s.color].toString(); + + // turn on lines automatically in case nothing is set + if (s.lines.show == null) { + var v, show = true; + for (v in s) + if (s[v] && s[v].show) { + show = false; + break; + } + if (show) + s.lines.show = true; + } + + // setup axes + s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); + s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); + } + } + + function processData() { + var topSentry = Number.POSITIVE_INFINITY, + bottomSentry = Number.NEGATIVE_INFINITY, + fakeInfinity = Number.MAX_VALUE, + i, j, k, m, length, + s, points, ps, x, y, axis, val, f, p; + + function updateAxis(axis, min, max) { + if (min < axis.datamin && min != -fakeInfinity) + axis.datamin = min; + if (max > axis.datamax && max != fakeInfinity) + axis.datamax = max; + } + + $.each(allAxes(), function (_, axis) { + // init axis + axis.datamin = topSentry; + axis.datamax = bottomSentry; + axis.used = false; + }); + + for (i = 0; i < series.length; ++i) { + s = series[i]; + s.datapoints = { points: [] }; + + executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); + } + + // first pass: clean and copy data + for (i = 0; i < series.length; ++i) { + s = series[i]; + + var data = s.data, format = s.datapoints.format; + + if (!format) { + format = []; + // find out how to copy + format.push({ x: true, number: true, required: true }); + format.push({ y: true, number: true, required: true }); + + if (s.bars.show || (s.lines.show && s.lines.fill)) { + format.push({ y: true, number: true, required: false, defaultValue: 0 }); + if (s.bars.horizontal) { + delete format[format.length - 1].y; + format[format.length - 1].x = true; + } + } + + s.datapoints.format = format; + } + + if (s.datapoints.pointsize != null) + continue; // already filled in + + s.datapoints.pointsize = format.length; + + ps = s.datapoints.pointsize; + points = s.datapoints.points; + + insertSteps = s.lines.show && s.lines.steps; + s.xaxis.used = s.yaxis.used = true; + + for (j = k = 0; j < data.length; ++j, k += ps) { + p = data[j]; + + var nullify = p == null; + if (!nullify) { + for (m = 0; m < ps; ++m) { + val = p[m]; + f = format[m]; + + if (f) { + if (f.number && val != null) { + val = +val; // convert to number + if (isNaN(val)) + val = null; + else if (val == Infinity) + val = fakeInfinity; + else if (val == -Infinity) + val = -fakeInfinity; + } + + if (val == null) { + if (f.required) + nullify = true; + + if (f.defaultValue != null) + val = f.defaultValue; + } + } + + points[k + m] = val; + } + } + + if (nullify) { + for (m = 0; m < ps; ++m) { + val = points[k + m]; + if (val != null) { + f = format[m]; + // extract min/max info + if (f.x) + updateAxis(s.xaxis, val, val); + if (f.y) + updateAxis(s.yaxis, val, val); + } + points[k + m] = null; + } + } + else { + // a little bit of line specific stuff that + // perhaps shouldn't be here, but lacking + // better means... + if (insertSteps && k > 0 + && points[k - ps] != null + && points[k - ps] != points[k] + && points[k - ps + 1] != points[k + 1]) { + // copy the point to make room for a middle point + for (m = 0; m < ps; ++m) + points[k + ps + m] = points[k + m]; + + // middle point has same y + points[k + 1] = points[k - ps + 1]; + + // we've added a point, better reflect that + k += ps; + } + } + } + } + + // give the hooks a chance to run + for (i = 0; i < series.length; ++i) { + s = series[i]; + + executeHooks(hooks.processDatapoints, [ s, s.datapoints]); + } + + // second pass: find datamax/datamin for auto-scaling + for (i = 0; i < series.length; ++i) { + s = series[i]; + points = s.datapoints.points, + ps = s.datapoints.pointsize; + + var xmin = topSentry, ymin = topSentry, + xmax = bottomSentry, ymax = bottomSentry; + + for (j = 0; j < points.length; j += ps) { + if (points[j] == null) + continue; + + for (m = 0; m < ps; ++m) { + val = points[j + m]; + f = format[m]; + if (!f || val == fakeInfinity || val == -fakeInfinity) + continue; + + if (f.x) { + if (val < xmin) + xmin = val; + if (val > xmax) + xmax = val; + } + if (f.y) { + if (val < ymin) + ymin = val; + if (val > ymax) + ymax = val; + } + } + } + + if (s.bars.show) { + // make sure we got room for the bar on the dancing floor + var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2; + if (s.bars.horizontal) { + ymin += delta; + ymax += delta + s.bars.barWidth; + } + else { + xmin += delta; + xmax += delta + s.bars.barWidth; + } + } + + updateAxis(s.xaxis, xmin, xmax); + updateAxis(s.yaxis, ymin, ymax); + } + + $.each(allAxes(), function (_, axis) { + if (axis.datamin == topSentry) + axis.datamin = null; + if (axis.datamax == bottomSentry) + axis.datamax = null; + }); + } + + function makeCanvas(skipPositioning, cls) { + var c = document.createElement('canvas'); + c.className = cls; + c.width = canvasWidth; + c.height = canvasHeight; + + if (!skipPositioning) + $(c).css({ position: 'absolute', left: 0, top: 0 }); + + $(c).appendTo(placeholder); + + if (!c.getContext) // excanvas hack + c = window.G_vmlCanvasManager.initElement(c); + + // used for resetting in case we get replotted + c.getContext("2d").save(); + + return c; + } + + function getCanvasDimensions() { + canvasWidth = placeholder.width(); + canvasHeight = placeholder.height(); + + if (canvasWidth <= 0 || canvasHeight <= 0) + throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; + } + + function resizeCanvas(c) { + // resizing should reset the state (excanvas seems to be + // buggy though) + if (c.width != canvasWidth) + c.width = canvasWidth; + + if (c.height != canvasHeight) + c.height = canvasHeight; + + // so try to get back to the initial state (even if it's + // gone now, this should be safe according to the spec) + var cctx = c.getContext("2d"); + cctx.restore(); + + // and save again + cctx.save(); + } + + function setupCanvases() { + var reused, + existingCanvas = placeholder.children("canvas.base"), + existingOverlay = placeholder.children("canvas.overlay"); + + if (existingCanvas.length == 0 || existingOverlay == 0) { + // init everything + + placeholder.html(""); // make sure placeholder is clear + + placeholder.css({ padding: 0 }); // padding messes up the positioning + + if (placeholder.css("position") == 'static') + placeholder.css("position", "relative"); // for positioning labels and overlay + + getCanvasDimensions(); + + canvas = makeCanvas(true, "base"); + overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features + + reused = false; + } + else { + // reuse existing elements + + canvas = existingCanvas.get(0); + overlay = existingOverlay.get(0); + + reused = true; + } + + ctx = canvas.getContext("2d"); + octx = overlay.getContext("2d"); + + // we include the canvas in the event holder too, because IE 7 + // sometimes has trouble with the stacking order + eventHolder = $([overlay, canvas]); + + if (reused) { + // run shutdown in the old plot object + placeholder.data("plot").shutdown(); + + // reset reused canvases + plot.resize(); + + // make sure overlay pixels are cleared (canvas is cleared when we redraw) + octx.clearRect(0, 0, canvasWidth, canvasHeight); + + // then whack any remaining obvious garbage left + eventHolder.unbind(); + placeholder.children().not([canvas, overlay]).remove(); + } + + // save in case we get replotted + placeholder.data("plot", plot); + } + + function bindEvents() { + // bind events + if (options.grid.hoverable) { + eventHolder.mousemove(onMouseMove); + eventHolder.mouseleave(onMouseLeave); + } + + if (options.grid.clickable) + eventHolder.click(onClick); + + executeHooks(hooks.bindEvents, [eventHolder]); + } + + function shutdown() { + if (redrawTimeout) + clearTimeout(redrawTimeout); + + eventHolder.unbind("mousemove", onMouseMove); + eventHolder.unbind("mouseleave", onMouseLeave); + eventHolder.unbind("click", onClick); + + executeHooks(hooks.shutdown, [eventHolder]); + } + + function setTransformationHelpers(axis) { + // set helper functions on the axis, assumes plot area + // has been computed already + + function identity(x) { return x; } + + var s, m, t = axis.options.transform || identity, + it = axis.options.inverseTransform; + + // precompute how much the axis is scaling a point + // in canvas space + if (axis.direction == "x") { + s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min)); + m = Math.min(t(axis.max), t(axis.min)); + } + else { + s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min)); + s = -s; + m = Math.max(t(axis.max), t(axis.min)); + } + + // data point to canvas coordinate + if (t == identity) // slight optimization + axis.p2c = function (p) { return (p - m) * s; }; + else + axis.p2c = function (p) { return (t(p) - m) * s; }; + // canvas coordinate to data point + if (!it) + axis.c2p = function (c) { return m + c / s; }; + else + axis.c2p = function (c) { return it(m + c / s); }; + } + + function measureTickLabels(axis) { + var opts = axis.options, i, ticks = axis.ticks || [], labels = [], + l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv; + + function makeDummyDiv(labels, width) { + return $('
' + + '
' + + labels.join("") + '
') + .appendTo(placeholder); + } + + if (axis.direction == "x") { + // to avoid measuring the widths of the labels (it's slow), we + // construct fixed-size boxes and put the labels inside + // them, we don't need the exact figures and the + // fixed-size box content is easy to center + if (w == null) + w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1)); + + // measure x label heights + if (h == null) { + labels = []; + for (i = 0; i < ticks.length; ++i) { + l = ticks[i].label; + if (l) + labels.push('
' + l + '
'); + } + + if (labels.length > 0) { + // stick them all in the same div and measure + // collective height + labels.push('
'); + dummyDiv = makeDummyDiv(labels, "width:10000px;"); + h = dummyDiv.height(); + dummyDiv.remove(); + } + } + } + else if (w == null || h == null) { + // calculate y label dimensions + for (i = 0; i < ticks.length; ++i) { + l = ticks[i].label; + if (l) + labels.push('
' + l + '
'); + } + + if (labels.length > 0) { + dummyDiv = makeDummyDiv(labels, ""); + if (w == null) + w = dummyDiv.children().width(); + if (h == null) + h = dummyDiv.find("div.tickLabel").height(); + dummyDiv.remove(); + } + } + + if (w == null) + w = 0; + if (h == null) + h = 0; + + axis.labelWidth = w; + axis.labelHeight = h; + } + + function allocateAxisBoxFirstPhase(axis) { + // find the bounding box of the axis by looking at label + // widths/heights and ticks, make room by diminishing the + // plotOffset + + var lw = axis.labelWidth, + lh = axis.labelHeight, + pos = axis.options.position, + tickLength = axis.options.tickLength, + axismargin = options.grid.axisMargin, + padding = options.grid.labelMargin, + all = axis.direction == "x" ? xaxes : yaxes, + index; + + // determine axis margin + var samePosition = $.grep(all, function (a) { + return a && a.options.position == pos && a.reserveSpace; + }); + if ($.inArray(axis, samePosition) == samePosition.length - 1) + axismargin = 0; // outermost + + // determine tick length - if we're innermost, we can use "full" + if (tickLength == null) + tickLength = "full"; + + var sameDirection = $.grep(all, function (a) { + return a && a.reserveSpace; + }); + + var innermost = $.inArray(axis, sameDirection) == 0; + if (!innermost && tickLength == "full") + tickLength = 5; + + if (!isNaN(+tickLength)) + padding += +tickLength; + + // compute box + if (axis.direction == "x") { + lh += padding; + + if (pos == "bottom") { + plotOffset.bottom += lh + axismargin; + axis.box = { top: canvasHeight - plotOffset.bottom, height: lh }; + } + else { + axis.box = { top: plotOffset.top + axismargin, height: lh }; + plotOffset.top += lh + axismargin; + } + } + else { + lw += padding; + + if (pos == "left") { + axis.box = { left: plotOffset.left + axismargin, width: lw }; + plotOffset.left += lw + axismargin; + } + else { + plotOffset.right += lw + axismargin; + axis.box = { left: canvasWidth - plotOffset.right, width: lw }; + } + } + + // save for future reference + axis.position = pos; + axis.tickLength = tickLength; + axis.box.padding = padding; + axis.innermost = innermost; + } + + function allocateAxisBoxSecondPhase(axis) { + // set remaining bounding box coordinates + if (axis.direction == "x") { + axis.box.left = plotOffset.left; + axis.box.width = plotWidth; + } + else { + axis.box.top = plotOffset.top; + axis.box.height = plotHeight; + } + } + + function setupGrid() { + var i, axes = allAxes(); + + // first calculate the plot and axis box dimensions + + $.each(axes, function (_, axis) { + axis.show = axis.options.show; + if (axis.show == null) + axis.show = axis.used; // by default an axis is visible if it's got data + + axis.reserveSpace = axis.show || axis.options.reserveSpace; + + setRange(axis); + }); + + allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); + + plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0; + if (options.grid.show) { + $.each(allocatedAxes, function (_, axis) { + // make the ticks + setupTickGeneration(axis); + setTicks(axis); + snapRangeToTicks(axis, axis.ticks); + + // find labelWidth/Height for axis + measureTickLabels(axis); + }); + + // with all dimensions in house, we can compute the + // axis boxes, start from the outside (reverse order) + for (i = allocatedAxes.length - 1; i >= 0; --i) + allocateAxisBoxFirstPhase(allocatedAxes[i]); + + // make sure we've got enough space for things that + // might stick out + var minMargin = options.grid.minBorderMargin; + if (minMargin == null) { + minMargin = 0; + for (i = 0; i < series.length; ++i) + minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2); + } + + for (var a in plotOffset) { + plotOffset[a] += options.grid.borderWidth; + plotOffset[a] = Math.max(minMargin, plotOffset[a]); + } + } + + plotWidth = canvasWidth - plotOffset.left - plotOffset.right; + plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; + + // now we got the proper plotWidth/Height, we can compute the scaling + $.each(axes, function (_, axis) { + setTransformationHelpers(axis); + }); + + if (options.grid.show) { + $.each(allocatedAxes, function (_, axis) { + allocateAxisBoxSecondPhase(axis); + }); + + insertAxisLabels(); + } + + insertLegend(); + } + + function setRange(axis) { + var opts = axis.options, + min = +(opts.min != null ? opts.min : axis.datamin), + max = +(opts.max != null ? opts.max : axis.datamax), + delta = max - min; + + if (delta == 0.0) { + // degenerate case + var widen = max == 0 ? 1 : 0.01; + + if (opts.min == null) + min -= widen; + // always widen max if we couldn't widen min to ensure we + // don't fall into min == max which doesn't work + if (opts.max == null || opts.min != null) + max += widen; + } + else { + // consider autoscaling + var margin = opts.autoscaleMargin; + if (margin != null) { + if (opts.min == null) { + min -= delta * margin; + // make sure we don't go below zero if all values + // are positive + if (min < 0 && axis.datamin != null && axis.datamin >= 0) + min = 0; + } + if (opts.max == null) { + max += delta * margin; + if (max > 0 && axis.datamax != null && axis.datamax <= 0) + max = 0; + } + } + } + axis.min = min; + axis.max = max; + } + + function setupTickGeneration(axis) { + var opts = axis.options; + + // estimate number of ticks + var noTicks; + if (typeof opts.ticks == "number" && opts.ticks > 0) + noTicks = opts.ticks; + else + // heuristic based on the model a*sqrt(x) fitted to + // some data points that seemed reasonable + noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight); + + var delta = (axis.max - axis.min) / noTicks, + size, generator, unit, formatter, i, magn, norm; + + if (opts.mode == "time") { + // pretty handling of time + + // map of app. size of time units in milliseconds + var timeUnitSize = { + "second": 1000, + "minute": 60 * 1000, + "hour": 60 * 60 * 1000, + "day": 24 * 60 * 60 * 1000, + "month": 30 * 24 * 60 * 60 * 1000, + "year": 365.2425 * 24 * 60 * 60 * 1000 + }; + + + // the allowed tick sizes, after 1 year we use + // an integer algorithm + var spec = [ + [1, "second"], [2, "second"], [5, "second"], [10, "second"], + [30, "second"], + [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], + [30, "minute"], + [1, "hour"], [2, "hour"], [4, "hour"], + [8, "hour"], [12, "hour"], + [1, "day"], [2, "day"], [3, "day"], + [0.25, "month"], [0.5, "month"], [1, "month"], + [2, "month"], [3, "month"], [6, "month"], + [1, "year"] + ]; + + var minSize = 0; + if (opts.minTickSize != null) { + if (typeof opts.tickSize == "number") + minSize = opts.tickSize; + else + minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; + } + + for (var i = 0; i < spec.length - 1; ++i) + if (delta < (spec[i][0] * timeUnitSize[spec[i][1]] + + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 + && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) + break; + size = spec[i][0]; + unit = spec[i][1]; + + // special-case the possibility of several years + if (unit == "year") { + magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10)); + norm = (delta / timeUnitSize.year) / magn; + if (norm < 1.5) + size = 1; + else if (norm < 3) + size = 2; + else if (norm < 7.5) + size = 5; + else + size = 10; + + size *= magn; + } + + axis.tickSize = opts.tickSize || [size, unit]; + + generator = function(axis) { + var ticks = [], + tickSize = axis.tickSize[0], unit = axis.tickSize[1], + d = new Date(axis.min); + + var step = tickSize * timeUnitSize[unit]; + + if (unit == "second") + d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize)); + if (unit == "minute") + d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize)); + if (unit == "hour") + d.setUTCHours(floorInBase(d.getUTCHours(), tickSize)); + if (unit == "month") + d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize)); + if (unit == "year") + d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize)); + + // reset smaller components + d.setUTCMilliseconds(0); + if (step >= timeUnitSize.minute) + d.setUTCSeconds(0); + if (step >= timeUnitSize.hour) + d.setUTCMinutes(0); + if (step >= timeUnitSize.day) + d.setUTCHours(0); + if (step >= timeUnitSize.day * 4) + d.setUTCDate(1); + if (step >= timeUnitSize.year) + d.setUTCMonth(0); + + + var carry = 0, v = Number.NaN, prev; + do { + prev = v; + v = d.getTime(); + ticks.push(v); + if (unit == "month") { + if (tickSize < 1) { + // a bit complicated - we'll divide the month + // up but we need to take care of fractions + // so we don't end up in the middle of a day + d.setUTCDate(1); + var start = d.getTime(); + d.setUTCMonth(d.getUTCMonth() + 1); + var end = d.getTime(); + d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); + carry = d.getUTCHours(); + d.setUTCHours(0); + } + else + d.setUTCMonth(d.getUTCMonth() + tickSize); + } + else if (unit == "year") { + d.setUTCFullYear(d.getUTCFullYear() + tickSize); + } + else + d.setTime(v + step); + } while (v < axis.max && v != prev); + + return ticks; + }; + + formatter = function (v, axis) { + var d = new Date(v); + + // first check global format + if (opts.timeformat != null) + return $.plot.formatDate(d, opts.timeformat, opts.monthNames); + + var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; + var span = axis.max - axis.min; + var suffix = (opts.twelveHourClock) ? " %p" : ""; + + if (t < timeUnitSize.minute) + fmt = "%h:%M:%S" + suffix; + else if (t < timeUnitSize.day) { + if (span < 2 * timeUnitSize.day) + fmt = "%h:%M" + suffix; + else + fmt = "%b %d %h:%M" + suffix; + } + else if (t < timeUnitSize.month) + fmt = "%b %d"; + else if (t < timeUnitSize.year) { + if (span < timeUnitSize.year) + fmt = "%b"; + else + fmt = "%b %y"; + } + else + fmt = "%y"; + + return $.plot.formatDate(d, fmt, opts.monthNames); + }; + } + else { + // pretty rounding of base-10 numbers + var maxDec = opts.tickDecimals; + var dec = -Math.floor(Math.log(delta) / Math.LN10); + if (maxDec != null && dec > maxDec) + dec = maxDec; + + magn = Math.pow(10, -dec); + norm = delta / magn; // norm is between 1.0 and 10.0 + + if (norm < 1.5) + size = 1; + else if (norm < 3) { + size = 2; + // special case for 2.5, requires an extra decimal + if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { + size = 2.5; + ++dec; + } + } + else if (norm < 7.5) + size = 5; + else + size = 10; + + size *= magn; + + if (opts.minTickSize != null && size < opts.minTickSize) + size = opts.minTickSize; + + axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); + axis.tickSize = opts.tickSize || size; + + generator = function (axis) { + var ticks = []; + + // spew out all possible ticks + var start = floorInBase(axis.min, axis.tickSize), + i = 0, v = Number.NaN, prev; + do { + prev = v; + v = start + i * axis.tickSize; + ticks.push(v); + ++i; + } while (v < axis.max && v != prev); + return ticks; + }; + + formatter = function (v, axis) { + return v.toFixed(axis.tickDecimals); + }; + } + + if (opts.alignTicksWithAxis != null) { + var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; + if (otherAxis && otherAxis.used && otherAxis != axis) { + // consider snapping min/max to outermost nice ticks + var niceTicks = generator(axis); + if (niceTicks.length > 0) { + if (opts.min == null) + axis.min = Math.min(axis.min, niceTicks[0]); + if (opts.max == null && niceTicks.length > 1) + axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); + } + + generator = function (axis) { + // copy ticks, scaled to this axis + var ticks = [], v, i; + for (i = 0; i < otherAxis.ticks.length; ++i) { + v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min); + v = axis.min + v * (axis.max - axis.min); + ticks.push(v); + } + return ticks; + }; + + // we might need an extra decimal since forced + // ticks don't necessarily fit naturally + if (axis.mode != "time" && opts.tickDecimals == null) { + var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1), + ts = generator(axis); + + // only proceed if the tick interval rounded + // with an extra decimal doesn't give us a + // zero at end + if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) + axis.tickDecimals = extraDec; + } + } + } + + axis.tickGenerator = generator; + if ($.isFunction(opts.tickFormatter)) + axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; + else + axis.tickFormatter = formatter; + } + + function setTicks(axis) { + var oticks = axis.options.ticks, ticks = []; + if (oticks == null || (typeof oticks == "number" && oticks > 0)) + ticks = axis.tickGenerator(axis); + else if (oticks) { + if ($.isFunction(oticks)) + // generate the ticks + ticks = oticks({ min: axis.min, max: axis.max }); + else + ticks = oticks; + } + + // clean up/labelify the supplied ticks, copy them over + var i, v; + axis.ticks = []; + for (i = 0; i < ticks.length; ++i) { + var label = null; + var t = ticks[i]; + if (typeof t == "object") { + v = +t[0]; + if (t.length > 1) + label = t[1]; + } + else + v = +t; + if (label == null) + label = axis.tickFormatter(v, axis); + if (!isNaN(v)) + axis.ticks.push({ v: v, label: label }); + } + } + + function snapRangeToTicks(axis, ticks) { + if (axis.options.autoscaleMargin && ticks.length > 0) { + // snap to ticks + if (axis.options.min == null) + axis.min = Math.min(axis.min, ticks[0].v); + if (axis.options.max == null && ticks.length > 1) + axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); + } + } + + function draw() { + ctx.clearRect(0, 0, canvasWidth, canvasHeight); + + var grid = options.grid; + + // draw background, if any + if (grid.show && grid.backgroundColor) + drawBackground(); + + if (grid.show && !grid.aboveData) + drawGrid(); + + for (var i = 0; i < series.length; ++i) { + executeHooks(hooks.drawSeries, [ctx, series[i]]); + drawSeries(series[i]); + } + + executeHooks(hooks.draw, [ctx]); + + if (grid.show && grid.aboveData) + drawGrid(); + } + + function extractRange(ranges, coord) { + var axis, from, to, key, axes = allAxes(); + + for (i = 0; i < axes.length; ++i) { + axis = axes[i]; + if (axis.direction == coord) { + key = coord + axis.n + "axis"; + if (!ranges[key] && axis.n == 1) + key = coord + "axis"; // support x1axis as xaxis + if (ranges[key]) { + from = ranges[key].from; + to = ranges[key].to; + break; + } + } + } + + // backwards-compat stuff - to be removed in future + if (!ranges[key]) { + axis = coord == "x" ? xaxes[0] : yaxes[0]; + from = ranges[coord + "1"]; + to = ranges[coord + "2"]; + } + + // auto-reverse as an added bonus + if (from != null && to != null && from > to) { + var tmp = from; + from = to; + to = tmp; + } + + return { from: from, to: to, axis: axis }; + } + + function drawBackground() { + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); + ctx.fillRect(0, 0, plotWidth, plotHeight); + ctx.restore(); + } + + function drawGrid() { + var i; + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + // draw markings + var markings = options.grid.markings; + if (markings) { + if ($.isFunction(markings)) { + var axes = plot.getAxes(); + // xmin etc. is backwards compatibility, to be + // removed in the future + axes.xmin = axes.xaxis.min; + axes.xmax = axes.xaxis.max; + axes.ymin = axes.yaxis.min; + axes.ymax = axes.yaxis.max; + + markings = markings(axes); + } + + for (i = 0; i < markings.length; ++i) { + var m = markings[i], + xrange = extractRange(m, "x"), + yrange = extractRange(m, "y"); + + // fill in missing + if (xrange.from == null) + xrange.from = xrange.axis.min; + if (xrange.to == null) + xrange.to = xrange.axis.max; + if (yrange.from == null) + yrange.from = yrange.axis.min; + if (yrange.to == null) + yrange.to = yrange.axis.max; + + // clip + if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || + yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) + continue; + + xrange.from = Math.max(xrange.from, xrange.axis.min); + xrange.to = Math.min(xrange.to, xrange.axis.max); + yrange.from = Math.max(yrange.from, yrange.axis.min); + yrange.to = Math.min(yrange.to, yrange.axis.max); + + if (xrange.from == xrange.to && yrange.from == yrange.to) + continue; + + // then draw + xrange.from = xrange.axis.p2c(xrange.from); + xrange.to = xrange.axis.p2c(xrange.to); + yrange.from = yrange.axis.p2c(yrange.from); + yrange.to = yrange.axis.p2c(yrange.to); + + if (xrange.from == xrange.to || yrange.from == yrange.to) { + // draw line + ctx.beginPath(); + ctx.strokeStyle = m.color || options.grid.markingsColor; + ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; + ctx.moveTo(xrange.from, yrange.from); + ctx.lineTo(xrange.to, yrange.to); + ctx.stroke(); + } + else { + // fill area + ctx.fillStyle = m.color || options.grid.markingsColor; + ctx.fillRect(xrange.from, yrange.to, + xrange.to - xrange.from, + yrange.from - yrange.to); + } + } + } + + // draw the ticks + var axes = allAxes(), bw = options.grid.borderWidth; + + for (var j = 0; j < axes.length; ++j) { + var axis = axes[j], box = axis.box, + t = axis.tickLength, x, y, xoff, yoff; + if (!axis.show || axis.ticks.length == 0) + continue + + ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString(); + ctx.lineWidth = 1; + + // find the edges + if (axis.direction == "x") { + x = 0; + if (t == "full") + y = (axis.position == "top" ? 0 : plotHeight); + else + y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0); + } + else { + y = 0; + if (t == "full") + x = (axis.position == "left" ? 0 : plotWidth); + else + x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); + } + + // draw tick bar + if (!axis.innermost) { + ctx.beginPath(); + xoff = yoff = 0; + if (axis.direction == "x") + xoff = plotWidth; + else + yoff = plotHeight; + + if (ctx.lineWidth == 1) { + x = Math.floor(x) + 0.5; + y = Math.floor(y) + 0.5; + } + + ctx.moveTo(x, y); + ctx.lineTo(x + xoff, y + yoff); + ctx.stroke(); + } + + // draw ticks + ctx.beginPath(); + for (i = 0; i < axis.ticks.length; ++i) { + var v = axis.ticks[i].v; + + xoff = yoff = 0; + + if (v < axis.min || v > axis.max + // skip those lying on the axes if we got a border + || (t == "full" && bw > 0 + && (v == axis.min || v == axis.max))) + continue; + + if (axis.direction == "x") { + x = axis.p2c(v); + yoff = t == "full" ? -plotHeight : t; + + if (axis.position == "top") + yoff = -yoff; + } + else { + y = axis.p2c(v); + xoff = t == "full" ? -plotWidth : t; + + if (axis.position == "left") + xoff = -xoff; + } + + if (ctx.lineWidth == 1) { + if (axis.direction == "x") + x = Math.floor(x) + 0.5; + else + y = Math.floor(y) + 0.5; + } + + ctx.moveTo(x, y); + ctx.lineTo(x + xoff, y + yoff); + } + + ctx.stroke(); + } + + + // draw border + if (bw) { + ctx.lineWidth = bw; + ctx.strokeStyle = options.grid.borderColor; + ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); + } + + ctx.restore(); + } + + function insertAxisLabels() { + placeholder.find(".tickLabels").remove(); + + var html = ['
']; + + var axes = allAxes(); + for (var j = 0; j < axes.length; ++j) { + var axis = axes[j], box = axis.box; + if (!axis.show) + continue; + //debug: html.push('
') + html.push('
'); + for (var i = 0; i < axis.ticks.length; ++i) { + var tick = axis.ticks[i]; + if (!tick.label || tick.v < axis.min || tick.v > axis.max) + continue; + + var pos = {}, align; + + if (axis.direction == "x") { + align = "center"; + pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2); + if (axis.position == "bottom") + pos.top = box.top + box.padding; + else + pos.bottom = canvasHeight - (box.top + box.height - box.padding); + } + else { + pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2); + if (axis.position == "left") { + pos.right = canvasWidth - (box.left + box.width - box.padding) + align = "right"; + } + else { + pos.left = box.left + box.padding; + align = "left"; + } + } + + pos.width = axis.labelWidth; + + var style = ["position:absolute", "text-align:" + align ]; + for (var a in pos) + style.push(a + ":" + pos[a] + "px") + + html.push('
' + tick.label + '
'); + } + html.push('
'); + } + + html.push('
'); + + placeholder.append(html.join("")); + } + + function drawSeries(series) { + if (series.lines.show) + drawSeriesLines(series); + if (series.bars.show) + drawSeriesBars(series); + if (series.points.show) + drawSeriesPoints(series); + } + + function drawSeriesLines(series) { + function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { + var points = datapoints.points, + ps = datapoints.pointsize, + prevx = null, prevy = null; + + ctx.beginPath(); + for (var i = ps; i < points.length; i += ps) { + var x1 = points[i - ps], y1 = points[i - ps + 1], + x2 = points[i], y2 = points[i + 1]; + + if (x1 == null || x2 == null) + continue; + + // clip with ymin + if (y1 <= y2 && y1 < axisy.min) { + if (y2 < axisy.min) + continue; // line segment is outside + // compute new intersection point + x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.min; + } + else if (y2 <= y1 && y2 < axisy.min) { + if (y1 < axisy.min) + continue; + x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.min; + } + + // clip with ymax + if (y1 >= y2 && y1 > axisy.max) { + if (y2 > axisy.max) + continue; + x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.max; + } + else if (y2 >= y1 && y2 > axisy.max) { + if (y1 > axisy.max) + continue; + x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.max; + } + + // clip with xmin + if (x1 <= x2 && x1 < axisx.min) { + if (x2 < axisx.min) + continue; + y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.min; + } + else if (x2 <= x1 && x2 < axisx.min) { + if (x1 < axisx.min) + continue; + y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.min; + } + + // clip with xmax + if (x1 >= x2 && x1 > axisx.max) { + if (x2 > axisx.max) + continue; + y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.max; + } + else if (x2 >= x1 && x2 > axisx.max) { + if (x1 > axisx.max) + continue; + y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.max; + } + + if (x1 != prevx || y1 != prevy) + ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); + + prevx = x2; + prevy = y2; + ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); + } + ctx.stroke(); + } + + function plotLineArea(datapoints, axisx, axisy) { + var points = datapoints.points, + ps = datapoints.pointsize, + bottom = Math.min(Math.max(0, axisy.min), axisy.max), + i = 0, top, areaOpen = false, + ypos = 1, segmentStart = 0, segmentEnd = 0; + + // we process each segment in two turns, first forward + // direction to sketch out top, then once we hit the + // end we go backwards to sketch the bottom + while (true) { + if (ps > 0 && i > points.length + ps) + break; + + i += ps; // ps is negative if going backwards + + var x1 = points[i - ps], + y1 = points[i - ps + ypos], + x2 = points[i], y2 = points[i + ypos]; + + if (areaOpen) { + if (ps > 0 && x1 != null && x2 == null) { + // at turning point + segmentEnd = i; + ps = -ps; + ypos = 2; + continue; + } + + if (ps < 0 && i == segmentStart + ps) { + // done with the reverse sweep + ctx.fill(); + areaOpen = false; + ps = -ps; + ypos = 1; + i = segmentStart = segmentEnd + ps; + continue; + } + } + + if (x1 == null || x2 == null) + continue; + + // clip x values + + // clip with xmin + if (x1 <= x2 && x1 < axisx.min) { + if (x2 < axisx.min) + continue; + y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.min; + } + else if (x2 <= x1 && x2 < axisx.min) { + if (x1 < axisx.min) + continue; + y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.min; + } + + // clip with xmax + if (x1 >= x2 && x1 > axisx.max) { + if (x2 > axisx.max) + continue; + y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.max; + } + else if (x2 >= x1 && x2 > axisx.max) { + if (x1 > axisx.max) + continue; + y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.max; + } + + if (!areaOpen) { + // open area + ctx.beginPath(); + ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); + areaOpen = true; + } + + // now first check the case where both is outside + if (y1 >= axisy.max && y2 >= axisy.max) { + ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); + continue; + } + else if (y1 <= axisy.min && y2 <= axisy.min) { + ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); + continue; + } + + // else it's a bit more complicated, there might + // be a flat maxed out rectangle first, then a + // triangular cutout or reverse; to find these + // keep track of the current x values + var x1old = x1, x2old = x2; + + // clip the y values, without shortcutting, we + // go through all cases in turn + + // clip with ymin + if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { + x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.min; + } + else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { + x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.min; + } + + // clip with ymax + if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { + x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.max; + } + else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { + x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.max; + } + + // if the x value was changed we got a rectangle + // to fill + if (x1 != x1old) { + ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); + // it goes to (x1, y1), but we fill that below + } + + // fill triangular section, this sometimes result + // in redundant points if (x1, y1) hasn't changed + // from previous line to, but we just ignore that + ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); + + // fill the other rectangle if it's there + if (x2 != x2old) { + ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); + ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); + } + } + } + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + ctx.lineJoin = "round"; + + var lw = series.lines.lineWidth, + sw = series.shadowSize; + // FIXME: consider another form of shadow when filling is turned on + if (lw > 0 && sw > 0) { + // draw shadow as a thick and thin line with transparency + ctx.lineWidth = sw; + ctx.strokeStyle = "rgba(0,0,0,0.1)"; + // position shadow at angle from the mid of line + var angle = Math.PI/18; + plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); + ctx.lineWidth = sw/2; + plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); + } + + ctx.lineWidth = lw; + ctx.strokeStyle = series.color; + var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); + if (fillStyle) { + ctx.fillStyle = fillStyle; + plotLineArea(series.datapoints, series.xaxis, series.yaxis); + } + + if (lw > 0) + plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); + ctx.restore(); + } + + function drawSeriesPoints(series) { + function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) { + var points = datapoints.points, ps = datapoints.pointsize; + + for (var i = 0; i < points.length; i += ps) { + var x = points[i], y = points[i + 1]; + if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) + continue; + + ctx.beginPath(); + x = axisx.p2c(x); + y = axisy.p2c(y) + offset; + if (symbol == "circle") + ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false); + else + symbol(ctx, x, y, radius, shadow); + ctx.closePath(); + + if (fillStyle) { + ctx.fillStyle = fillStyle; + ctx.fill(); + } + ctx.stroke(); + } + } + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + var lw = series.points.lineWidth, + sw = series.shadowSize, + radius = series.points.radius, + symbol = series.points.symbol; + if (lw > 0 && sw > 0) { + // draw shadow in two steps + var w = sw / 2; + ctx.lineWidth = w; + ctx.strokeStyle = "rgba(0,0,0,0.1)"; + plotPoints(series.datapoints, radius, null, w + w/2, true, + series.xaxis, series.yaxis, symbol); + + ctx.strokeStyle = "rgba(0,0,0,0.2)"; + plotPoints(series.datapoints, radius, null, w/2, true, + series.xaxis, series.yaxis, symbol); + } + + ctx.lineWidth = lw; + ctx.strokeStyle = series.color; + plotPoints(series.datapoints, radius, + getFillStyle(series.points, series.color), 0, false, + series.xaxis, series.yaxis, symbol); + ctx.restore(); + } + + function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { + var left, right, bottom, top, + drawLeft, drawRight, drawTop, drawBottom, + tmp; + + // in horizontal mode, we start the bar from the left + // instead of from the bottom so it appears to be + // horizontal rather than vertical + if (horizontal) { + drawBottom = drawRight = drawTop = true; + drawLeft = false; + left = b; + right = x; + top = y + barLeft; + bottom = y + barRight; + + // account for negative bars + if (right < left) { + tmp = right; + right = left; + left = tmp; + drawLeft = true; + drawRight = false; + } + } + else { + drawLeft = drawRight = drawTop = true; + drawBottom = false; + left = x + barLeft; + right = x + barRight; + bottom = b; + top = y; + + // account for negative bars + if (top < bottom) { + tmp = top; + top = bottom; + bottom = tmp; + drawBottom = true; + drawTop = false; + } + } + + // clip + if (right < axisx.min || left > axisx.max || + top < axisy.min || bottom > axisy.max) + return; + + if (left < axisx.min) { + left = axisx.min; + drawLeft = false; + } + + if (right > axisx.max) { + right = axisx.max; + drawRight = false; + } + + if (bottom < axisy.min) { + bottom = axisy.min; + drawBottom = false; + } + + if (top > axisy.max) { + top = axisy.max; + drawTop = false; + } + + left = axisx.p2c(left); + bottom = axisy.p2c(bottom); + right = axisx.p2c(right); + top = axisy.p2c(top); + + // fill the bar + if (fillStyleCallback) { + c.beginPath(); + c.moveTo(left, bottom); + c.lineTo(left, top); + c.lineTo(right, top); + c.lineTo(right, bottom); + c.fillStyle = fillStyleCallback(bottom, top); + c.fill(); + } + + // draw outline + if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) { + c.beginPath(); + + // FIXME: inline moveTo is buggy with excanvas + c.moveTo(left, bottom + offset); + if (drawLeft) + c.lineTo(left, top + offset); + else + c.moveTo(left, top + offset); + if (drawTop) + c.lineTo(right, top + offset); + else + c.moveTo(right, top + offset); + if (drawRight) + c.lineTo(right, bottom + offset); + else + c.moveTo(right, bottom + offset); + if (drawBottom) + c.lineTo(left, bottom + offset); + else + c.moveTo(left, bottom + offset); + c.stroke(); + } + } + + function drawSeriesBars(series) { + function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { + var points = datapoints.points, ps = datapoints.pointsize; + + for (var i = 0; i < points.length; i += ps) { + if (points[i] == null) + continue; + drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); + } + } + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + // FIXME: figure out a way to add shadows (for instance along the right edge) + ctx.lineWidth = series.bars.lineWidth; + ctx.strokeStyle = series.color; + var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; + var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; + plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis); + ctx.restore(); + } + + function getFillStyle(filloptions, seriesColor, bottom, top) { + var fill = filloptions.fill; + if (!fill) + return null; + + if (filloptions.fillColor) + return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); + + var c = $.color.parse(seriesColor); + c.a = typeof fill == "number" ? fill : 0.4; + c.normalize(); + return c.toString(); + } + + function insertLegend() { + placeholder.find(".legend").remove(); + + if (!options.legend.show) + return; + + var fragments = [], rowStarted = false, + lf = options.legend.labelFormatter, s, label; + for (var i = 0; i < series.length; ++i) { + s = series[i]; + label = s.label; + if (!label) + continue; + + if (i % options.legend.noColumns == 0) { + if (rowStarted) + fragments.push(''); + fragments.push(''); + rowStarted = true; + } + + if (lf) + label = lf(label, s); + + fragments.push( + '
' + + '' + label + ''); + } + if (rowStarted) + fragments.push(''); + + if (fragments.length == 0) + return; + + var table = '' + fragments.join("") + '
'; + if (options.legend.container != null) + $(options.legend.container).html(table); + else { + var pos = "", + p = options.legend.position, + m = options.legend.margin; + if (m[0] == null) + m = [m, m]; + if (p.charAt(0) == "n") + pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; + else if (p.charAt(0) == "s") + pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; + if (p.charAt(1) == "e") + pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; + else if (p.charAt(1) == "w") + pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; + var legend = $('
' + table.replace('style="', 'style="position:absolute;' + pos +';') + '
').appendTo(placeholder); + if (options.legend.backgroundOpacity != 0.0) { + // put in the transparent background + // separately to avoid blended labels and + // label boxes + var c = options.legend.backgroundColor; + if (c == null) { + c = options.grid.backgroundColor; + if (c && typeof c == "string") + c = $.color.parse(c); + else + c = $.color.extract(legend, 'background-color'); + c.a = 1; + c = c.toString(); + } + var div = legend.children(); + $('
').prependTo(legend).css('opacity', options.legend.backgroundOpacity); + } + } + } + + + // interactive features + + var highlights = [], + redrawTimeout = null; + + // returns the data item the mouse is over, or null if none is found + function findNearbyItem(mouseX, mouseY, seriesFilter) { + var maxDistance = options.grid.mouseActiveRadius, + smallestDistance = maxDistance * maxDistance + 1, + item = null, foundPoint = false, i, j; + + for (i = series.length - 1; i >= 0; --i) { + if (!seriesFilter(series[i])) + continue; + + var s = series[i], + axisx = s.xaxis, + axisy = s.yaxis, + points = s.datapoints.points, + ps = s.datapoints.pointsize, + mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster + my = axisy.c2p(mouseY), + maxx = maxDistance / axisx.scale, + maxy = maxDistance / axisy.scale; + + // with inverse transforms, we can't use the maxx/maxy + // optimization, sadly + if (axisx.options.inverseTransform) + maxx = Number.MAX_VALUE; + if (axisy.options.inverseTransform) + maxy = Number.MAX_VALUE; + + if (s.lines.show || s.points.show) { + for (j = 0; j < points.length; j += ps) { + var x = points[j], y = points[j + 1]; + if (x == null) + continue; + + // For points and lines, the cursor must be within a + // certain distance to the data point + if (x - mx > maxx || x - mx < -maxx || + y - my > maxy || y - my < -maxy) + continue; + + // We have to calculate distances in pixels, not in + // data units, because the scales of the axes may be different + var dx = Math.abs(axisx.p2c(x) - mouseX), + dy = Math.abs(axisy.p2c(y) - mouseY), + dist = dx * dx + dy * dy; // we save the sqrt + + // use <= to ensure last point takes precedence + // (last generally means on top of) + if (dist < smallestDistance) { + smallestDistance = dist; + item = [i, j / ps]; + } + } + } + + if (s.bars.show && !item) { // no other point can be nearby + var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2, + barRight = barLeft + s.bars.barWidth; + + for (j = 0; j < points.length; j += ps) { + var x = points[j], y = points[j + 1], b = points[j + 2]; + if (x == null) + continue; + + // for a bar graph, the cursor must be inside the bar + if (series[i].bars.horizontal ? + (mx <= Math.max(b, x) && mx >= Math.min(b, x) && + my >= y + barLeft && my <= y + barRight) : + (mx >= x + barLeft && mx <= x + barRight && + my >= Math.min(b, y) && my <= Math.max(b, y))) + item = [i, j / ps]; + } + } + } + + if (item) { + i = item[0]; + j = item[1]; + ps = series[i].datapoints.pointsize; + + return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), + dataIndex: j, + series: series[i], + seriesIndex: i }; + } + + return null; + } + + function onMouseMove(e) { + if (options.grid.hoverable) + triggerClickHoverEvent("plothover", e, + function (s) { return s["hoverable"] != false; }); + } + + function onMouseLeave(e) { + if (options.grid.hoverable) + triggerClickHoverEvent("plothover", e, + function (s) { return false; }); + } + + function onClick(e) { + triggerClickHoverEvent("plotclick", e, + function (s) { return s["clickable"] != false; }); + } + + // trigger click or hover event (they send the same parameters + // so we share their code) + function triggerClickHoverEvent(eventname, event, seriesFilter) { + var offset = eventHolder.offset(), + canvasX = event.pageX - offset.left - plotOffset.left, + canvasY = event.pageY - offset.top - plotOffset.top, + pos = canvasToAxisCoords({ left: canvasX, top: canvasY }); + + pos.pageX = event.pageX; + pos.pageY = event.pageY; + + var item = findNearbyItem(canvasX, canvasY, seriesFilter); + + if (item) { + // fill in mouse pos for any listeners out there + item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left); + item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top); + } + + if (options.grid.autoHighlight) { + // clear auto-highlights + for (var i = 0; i < highlights.length; ++i) { + var h = highlights[i]; + if (h.auto == eventname && + !(item && h.series == item.series && + h.point[0] == item.datapoint[0] && + h.point[1] == item.datapoint[1])) + unhighlight(h.series, h.point); + } + + if (item) + highlight(item.series, item.datapoint, eventname); + } + + placeholder.trigger(eventname, [ pos, item ]); + } + + function triggerRedrawOverlay() { + if (!redrawTimeout) + redrawTimeout = setTimeout(drawOverlay, 30); + } + + function drawOverlay() { + redrawTimeout = null; + + // draw highlights + octx.save(); + octx.clearRect(0, 0, canvasWidth, canvasHeight); + octx.translate(plotOffset.left, plotOffset.top); + + var i, hi; + for (i = 0; i < highlights.length; ++i) { + hi = highlights[i]; + + if (hi.series.bars.show) + drawBarHighlight(hi.series, hi.point); + else + drawPointHighlight(hi.series, hi.point); + } + octx.restore(); + + executeHooks(hooks.drawOverlay, [octx]); + } + + function highlight(s, point, auto) { + if (typeof s == "number") + s = series[s]; + + if (typeof point == "number") { + var ps = s.datapoints.pointsize; + point = s.datapoints.points.slice(ps * point, ps * (point + 1)); + } + + var i = indexOfHighlight(s, point); + if (i == -1) { + highlights.push({ series: s, point: point, auto: auto }); + + triggerRedrawOverlay(); + } + else if (!auto) + highlights[i].auto = false; + } + + function unhighlight(s, point) { + if (s == null && point == null) { + highlights = []; + triggerRedrawOverlay(); + } + + if (typeof s == "number") + s = series[s]; + + if (typeof point == "number") + point = s.data[point]; + + var i = indexOfHighlight(s, point); + if (i != -1) { + highlights.splice(i, 1); + + triggerRedrawOverlay(); + } + } + + function indexOfHighlight(s, p) { + for (var i = 0; i < highlights.length; ++i) { + var h = highlights[i]; + if (h.series == s && h.point[0] == p[0] + && h.point[1] == p[1]) + return i; + } + return -1; + } + + function drawPointHighlight(series, point) { + var x = point[0], y = point[1], + axisx = series.xaxis, axisy = series.yaxis; + + if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) + return; + + var pointRadius = series.points.radius + series.points.lineWidth / 2; + octx.lineWidth = pointRadius; + octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); + var radius = 1.5 * pointRadius, + x = axisx.p2c(x), + y = axisy.p2c(y); + + octx.beginPath(); + if (series.points.symbol == "circle") + octx.arc(x, y, radius, 0, 2 * Math.PI, false); + else + series.points.symbol(octx, x, y, radius, false); + octx.closePath(); + octx.stroke(); + } + + function drawBarHighlight(series, point) { + octx.lineWidth = series.bars.lineWidth; + octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); + var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString(); + var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; + drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, + 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); + } + + function getColorOrGradient(spec, bottom, top, defaultColor) { + if (typeof spec == "string") + return spec; + else { + // assume this is a gradient spec; IE currently only + // supports a simple vertical gradient properly, so that's + // what we support too + var gradient = ctx.createLinearGradient(0, top, 0, bottom); + + for (var i = 0, l = spec.colors.length; i < l; ++i) { + var c = spec.colors[i]; + if (typeof c != "string") { + var co = $.color.parse(defaultColor); + if (c.brightness != null) + co = co.scale('rgb', c.brightness) + if (c.opacity != null) + co.a *= c.opacity; + c = co.toString(); + } + gradient.addColorStop(i / (l - 1), c); + } + + return gradient; + } + } + } + + $.plot = function(placeholder, data, options) { + //var t0 = new Date(); + var plot = new Plot($(placeholder), data, options, $.plot.plugins); + //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime())); + return plot; + }; + + $.plot.version = "0.7"; + + $.plot.plugins = []; + + // returns a string with the date d formatted according to fmt + $.plot.formatDate = function(d, fmt, monthNames) { + var leftPad = function(n) { + n = "" + n; + return n.length == 1 ? "0" + n : n; + }; + + var r = []; + var escape = false, padNext = false; + var hours = d.getUTCHours(); + var isAM = hours < 12; + if (monthNames == null) + monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + + if (fmt.search(/%p|%P/) != -1) { + if (hours > 12) { + hours = hours - 12; + } else if (hours == 0) { + hours = 12; + } + } + for (var i = 0; i < fmt.length; ++i) { + var c = fmt.charAt(i); + + if (escape) { + switch (c) { + case 'h': c = "" + hours; break; + case 'H': c = leftPad(hours); break; + case 'M': c = leftPad(d.getUTCMinutes()); break; + case 'S': c = leftPad(d.getUTCSeconds()); break; + case 'd': c = "" + d.getUTCDate(); break; + case 'm': c = "" + (d.getUTCMonth() + 1); break; + case 'y': c = "" + d.getUTCFullYear(); break; + case 'b': c = "" + monthNames[d.getUTCMonth()]; break; + case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; + case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; + case '0': c = ""; padNext = true; break; + } + if (c && padNext) { + c = leftPad(c); + padNext = false; + } + r.push(c); + if (!padNext) + escape = false; + } + else { + if (c == "%") + escape = true; + else + r.push(c); + } + } + return r.join(""); + }; + + // round to nearby lower multiple of base + function floorInBase(n, base) { + return base * Math.floor(n / base); + } + +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.navigate.js b/airtime_mvc/public/js/flot/jquery.flot.navigate.js new file mode 100644 index 000000000..f2b97603c --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.navigate.js @@ -0,0 +1,336 @@ +/* +Flot plugin for adding panning and zooming capabilities to a plot. + +The default behaviour is double click and scrollwheel up/down to zoom +in, drag to pan. The plugin defines plot.zoom({ center }), +plot.zoomOut() and plot.pan(offset) so you easily can add custom +controls. It also fires a "plotpan" and "plotzoom" event when +something happens, useful for synchronizing plots. + +Options: + + zoom: { + interactive: false + trigger: "dblclick" // or "click" for single click + amount: 1.5 // 2 = 200% (zoom in), 0.5 = 50% (zoom out) + } + + pan: { + interactive: false + cursor: "move" // CSS mouse cursor value used when dragging, e.g. "pointer" + frameRate: 20 + } + + xaxis, yaxis, x2axis, y2axis: { + zoomRange: null // or [number, number] (min range, max range) or false + panRange: null // or [number, number] (min, max) or false + } + +"interactive" enables the built-in drag/click behaviour. If you enable +interactive for pan, then you'll have a basic plot that supports +moving around; the same for zoom. + +"amount" specifies the default amount to zoom in (so 1.5 = 150%) +relative to the current viewport. + +"cursor" is a standard CSS mouse cursor string used for visual +feedback to the user when dragging. + +"frameRate" specifies the maximum number of times per second the plot +will update itself while the user is panning around on it (set to null +to disable intermediate pans, the plot will then not update until the +mouse button is released). + +"zoomRange" is the interval in which zooming can happen, e.g. with +zoomRange: [1, 100] the zoom will never scale the axis so that the +difference between min and max is smaller than 1 or larger than 100. +You can set either end to null to ignore, e.g. [1, null]. If you set +zoomRange to false, zooming on that axis will be disabled. + +"panRange" confines the panning to stay within a range, e.g. with +panRange: [-10, 20] panning stops at -10 in one end and at 20 in the +other. Either can be null, e.g. [-10, null]. If you set +panRange to false, panning on that axis will be disabled. + +Example API usage: + + plot = $.plot(...); + + // zoom default amount in on the pixel (10, 20) + plot.zoom({ center: { left: 10, top: 20 } }); + + // zoom out again + plot.zoomOut({ center: { left: 10, top: 20 } }); + + // zoom 200% in on the pixel (10, 20) + plot.zoom({ amount: 2, center: { left: 10, top: 20 } }); + + // pan 100 pixels to the left and 20 down + plot.pan({ left: -100, top: 20 }) + +Here, "center" specifies where the center of the zooming should +happen. Note that this is defined in pixel space, not the space of the +data points (you can use the p2c helpers on the axes in Flot to help +you convert between these). + +"amount" is the amount to zoom the viewport relative to the current +range, so 1 is 100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is +70% (zoom out). You can set the default in the options. + +*/ + + +// First two dependencies, jquery.event.drag.js and +// jquery.mousewheel.js, we put them inline here to save people the +// effort of downloading them. + +/* +jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com) +Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt +*/ +(function(E){E.fn.drag=function(L,K,J){if(K){this.bind("dragstart",L)}if(J){this.bind("dragend",J)}return !L?this.trigger("drag"):this.bind("drag",K?K:L)};var A=E.event,B=A.special,F=B.drag={not:":input",distance:0,which:1,dragging:false,setup:function(J){J=E.extend({distance:F.distance,which:F.which,not:F.not},J||{});J.distance=I(J.distance);A.add(this,"mousedown",H,J);if(this.attachEvent){this.attachEvent("ondragstart",D)}},teardown:function(){A.remove(this,"mousedown",H);if(this===F.dragging){F.dragging=F.proxy=false}G(this,true);if(this.detachEvent){this.detachEvent("ondragstart",D)}}};B.dragstart=B.dragend={setup:function(){},teardown:function(){}};function H(L){var K=this,J,M=L.data||{};if(M.elem){K=L.dragTarget=M.elem;L.dragProxy=F.proxy||K;L.cursorOffsetX=M.pageX-M.left;L.cursorOffsetY=M.pageY-M.top;L.offsetX=L.pageX-L.cursorOffsetX;L.offsetY=L.pageY-L.cursorOffsetY}else{if(F.dragging||(M.which>0&&L.which!=M.which)||E(L.target).is(M.not)){return }}switch(L.type){case"mousedown":E.extend(M,E(K).offset(),{elem:K,target:L.target,pageX:L.pageX,pageY:L.pageY});A.add(document,"mousemove mouseup",H,M);G(K,false);F.dragging=null;return false;case !F.dragging&&"mousemove":if(I(L.pageX-M.pageX)+I(L.pageY-M.pageY) max) { + // make sure min < max + var tmp = min; + min = max; + max = tmp; + } + + var range = max - min; + if (zr && + ((zr[0] != null && range < zr[0]) || + (zr[1] != null && range > zr[1]))) + return; + + opts.min = min; + opts.max = max; + }); + + plot.setupGrid(); + plot.draw(); + + if (!args.preventEvent) + plot.getPlaceholder().trigger("plotzoom", [ plot ]); + } + + plot.pan = function (args) { + var delta = { + x: +args.left, + y: +args.top + }; + + if (isNaN(delta.x)) + delta.x = 0; + if (isNaN(delta.y)) + delta.y = 0; + + $.each(plot.getAxes(), function (_, axis) { + var opts = axis.options, + min, max, d = delta[axis.direction]; + + min = axis.c2p(axis.p2c(axis.min) + d), + max = axis.c2p(axis.p2c(axis.max) + d); + + var pr = opts.panRange; + if (pr === false) // no panning on this axis + return; + + if (pr) { + // check whether we hit the wall + if (pr[0] != null && pr[0] > min) { + d = pr[0] - min; + min += d; + max += d; + } + + if (pr[1] != null && pr[1] < max) { + d = pr[1] - max; + min += d; + max += d; + } + } + + opts.min = min; + opts.max = max; + }); + + plot.setupGrid(); + plot.draw(); + + if (!args.preventEvent) + plot.getPlaceholder().trigger("plotpan", [ plot ]); + } + + function shutdown(plot, eventHolder) { + eventHolder.unbind(plot.getOptions().zoom.trigger, onZoomClick); + eventHolder.unbind("mousewheel", onMouseWheel); + eventHolder.unbind("dragstart", onDragStart); + eventHolder.unbind("drag", onDrag); + eventHolder.unbind("dragend", onDragEnd); + if (panTimeout) + clearTimeout(panTimeout); + } + + plot.hooks.bindEvents.push(bindEvents); + plot.hooks.shutdown.push(shutdown); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'navigate', + version: '1.3' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.pie.js b/airtime_mvc/public/js/flot/jquery.flot.pie.js new file mode 100644 index 000000000..b46c03c27 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.pie.js @@ -0,0 +1,750 @@ +/* +Flot plugin for rendering pie charts. The plugin assumes the data is +coming is as a single data value for each series, and each of those +values is a positive value or zero (negative numbers don't make +any sense and will cause strange effects). The data values do +NOT need to be passed in as percentage values because it +internally calculates the total and percentages. + +* Created by Brian Medendorp, June 2009 +* Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars + +* Changes: + 2009-10-22: lineJoin set to round + 2009-10-23: IE full circle fix, donut + 2009-11-11: Added basic hover from btburnett3 - does not work in IE, and center is off in Chrome and Opera + 2009-11-17: Added IE hover capability submitted by Anthony Aragues + 2009-11-18: Added bug fix submitted by Xavi Ivars (issues with arrays when other JS libraries are included as well) + + +Available options are: +series: { + pie: { + show: true/false + radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto' + innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect + startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result + tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show) + offset: { + top: integer value to move the pie up or down + left: integer value to move the pie left or right, or 'auto' + }, + stroke: { + color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF') + width: integer pixel width of the stroke + }, + label: { + show: true/false, or 'auto' + formatter: a user-defined function that modifies the text/style of the label text + radius: 0-1 for percentage of fullsize, or a specified pixel length + background: { + color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000') + opacity: 0-1 + }, + threshold: 0-1 for the percentage value at which to hide labels (if they're too small) + }, + combine: { + threshold: 0-1 for the percentage value at which to combine slices (if they're too small) + color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined + label: any text value of what the combined slice should be labeled + } + highlight: { + opacity: 0-1 + } + } +} + +More detail and specific examples can be found in the included HTML file. + +*/ + +(function ($) +{ + function init(plot) // this is the "body" of the plugin + { + var canvas = null; + var target = null; + var maxRadius = null; + var centerLeft = null; + var centerTop = null; + var total = 0; + var redraw = true; + var redrawAttempts = 10; + var shrink = 0.95; + var legendWidth = 0; + var processed = false; + var raw = false; + + // interactive variables + var highlights = []; + + // add hook to determine if pie plugin in enabled, and then perform necessary operations + plot.hooks.processOptions.push(checkPieEnabled); + plot.hooks.bindEvents.push(bindEvents); + + // check to see if the pie plugin is enabled + function checkPieEnabled(plot, options) + { + if (options.series.pie.show) + { + //disable grid + options.grid.show = false; + + // set labels.show + if (options.series.pie.label.show=='auto') + if (options.legend.show) + options.series.pie.label.show = false; + else + options.series.pie.label.show = true; + + // set radius + if (options.series.pie.radius=='auto') + if (options.series.pie.label.show) + options.series.pie.radius = 3/4; + else + options.series.pie.radius = 1; + + // ensure sane tilt + if (options.series.pie.tilt>1) + options.series.pie.tilt=1; + if (options.series.pie.tilt<0) + options.series.pie.tilt=0; + + // add processData hook to do transformations on the data + plot.hooks.processDatapoints.push(processDatapoints); + plot.hooks.drawOverlay.push(drawOverlay); + + // add draw hook + plot.hooks.draw.push(draw); + } + } + + // bind hoverable events + function bindEvents(plot, eventHolder) + { + var options = plot.getOptions(); + + if (options.series.pie.show && options.grid.hoverable) + eventHolder.unbind('mousemove').mousemove(onMouseMove); + + if (options.series.pie.show && options.grid.clickable) + eventHolder.unbind('click').click(onClick); + } + + + // debugging function that prints out an object + function alertObject(obj) + { + var msg = ''; + function traverse(obj, depth) + { + if (!depth) + depth = 0; + for (var i = 0; i < obj.length; ++i) + { + for (var j=0; jcanvas.width-maxRadius) + centerLeft = canvas.width-maxRadius; + } + + function fixData(data) + { + for (var i = 0; i < data.length; ++i) + { + if (typeof(data[i].data)=='number') + data[i].data = [[1,data[i].data]]; + else if (typeof(data[i].data)=='undefined' || typeof(data[i].data[0])=='undefined') + { + if (typeof(data[i].data)!='undefined' && typeof(data[i].data.label)!='undefined') + data[i].label = data[i].data.label; // fix weirdness coming from flot + data[i].data = [[1,0]]; + + } + } + return data; + } + + function combine(data) + { + data = fixData(data); + calcTotal(data); + var combined = 0; + var numCombined = 0; + var color = options.series.pie.combine.color; + + var newdata = []; + for (var i = 0; i < data.length; ++i) + { + // make sure its a number + data[i].data[0][1] = parseFloat(data[i].data[0][1]); + if (!data[i].data[0][1]) + data[i].data[0][1] = 0; + + if (data[i].data[0][1]/total<=options.series.pie.combine.threshold) + { + combined += data[i].data[0][1]; + numCombined++; + if (!color) + color = data[i].color; + } + else + { + newdata.push({ + data: [[1,data[i].data[0][1]]], + color: data[i].color, + label: data[i].label, + angle: (data[i].data[0][1]*(Math.PI*2))/total, + percent: (data[i].data[0][1]/total*100) + }); + } + } + if (numCombined>0) + newdata.push({ + data: [[1,combined]], + color: color, + label: options.series.pie.combine.label, + angle: (combined*(Math.PI*2))/total, + percent: (combined/total*100) + }); + return newdata; + } + + function draw(plot, newCtx) + { + if (!target) return; // if no series were passed + ctx = newCtx; + + setupPie(); + var slices = plot.getData(); + + var attempts = 0; + while (redraw && attempts0) + maxRadius *= shrink; + attempts += 1; + clear(); + if (options.series.pie.tilt<=0.8) + drawShadow(); + drawPie(); + } + if (attempts >= redrawAttempts) { + clear(); + target.prepend('
Could not draw pie with labels contained inside canvas
'); + } + + if ( plot.setSeries && plot.insertLegend ) + { + plot.setSeries(slices); + plot.insertLegend(); + } + + // we're actually done at this point, just defining internal functions at this point + + function clear() + { + ctx.clearRect(0,0,canvas.width,canvas.height); + target.children().filter('.pieLabel, .pieLabelBackground').remove(); + } + + function drawShadow() + { + var shadowLeft = 5; + var shadowTop = 15; + var edge = 10; + var alpha = 0.02; + + // set radius + if (options.series.pie.radius>1) + var radius = options.series.pie.radius; + else + var radius = maxRadius * options.series.pie.radius; + + if (radius>=(canvas.width/2)-shadowLeft || radius*options.series.pie.tilt>=(canvas.height/2)-shadowTop || radius<=edge) + return; // shadow would be outside canvas, so don't draw it + + ctx.save(); + ctx.translate(shadowLeft,shadowTop); + ctx.globalAlpha = alpha; + ctx.fillStyle = '#000'; + + // center and rotate to starting position + ctx.translate(centerLeft,centerTop); + ctx.scale(1, options.series.pie.tilt); + + //radius -= edge; + for (var i=1; i<=edge; i++) + { + ctx.beginPath(); + ctx.arc(0,0,radius,0,Math.PI*2,false); + ctx.fill(); + radius -= i; + } + + ctx.restore(); + } + + function drawPie() + { + startAngle = Math.PI*options.series.pie.startAngle; + + // set radius + if (options.series.pie.radius>1) + var radius = options.series.pie.radius; + else + var radius = maxRadius * options.series.pie.radius; + + // center and rotate to starting position + ctx.save(); + ctx.translate(centerLeft,centerTop); + ctx.scale(1, options.series.pie.tilt); + //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera + + // draw slices + ctx.save(); + var currentAngle = startAngle; + for (var i = 0; i < slices.length; ++i) + { + slices[i].startAngle = currentAngle; + drawSlice(slices[i].angle, slices[i].color, true); + } + ctx.restore(); + + // draw slice outlines + ctx.save(); + ctx.lineWidth = options.series.pie.stroke.width; + currentAngle = startAngle; + for (var i = 0; i < slices.length; ++i) + drawSlice(slices[i].angle, options.series.pie.stroke.color, false); + ctx.restore(); + + // draw donut hole + drawDonutHole(ctx); + + // draw labels + if (options.series.pie.label.show) + drawLabels(); + + // restore to original state + ctx.restore(); + + function drawSlice(angle, color, fill) + { + if (angle<=0) + return; + + if (fill) + ctx.fillStyle = color; + else + { + ctx.strokeStyle = color; + ctx.lineJoin = 'round'; + } + + ctx.beginPath(); + if (Math.abs(angle - Math.PI*2) > 0.000000001) + ctx.moveTo(0,0); // Center of the pie + else if ($.browser.msie) + angle -= 0.0001; + //ctx.arc(0,0,radius,0,angle,false); // This doesn't work properly in Opera + ctx.arc(0,0,radius,currentAngle,currentAngle+angle,false); + ctx.closePath(); + //ctx.rotate(angle); // This doesn't work properly in Opera + currentAngle += angle; + + if (fill) + ctx.fill(); + else + ctx.stroke(); + } + + function drawLabels() + { + var currentAngle = startAngle; + + // set radius + if (options.series.pie.label.radius>1) + var radius = options.series.pie.label.radius; + else + var radius = maxRadius * options.series.pie.label.radius; + + for (var i = 0; i < slices.length; ++i) + { + if (slices[i].percent >= options.series.pie.label.threshold*100) + drawLabel(slices[i], currentAngle, i); + currentAngle += slices[i].angle; + } + + function drawLabel(slice, startAngle, index) + { + if (slice.data[0][1]==0) + return; + + // format label text + var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter; + if (lf) + text = lf(slice.label, slice); + else + text = slice.label; + if (plf) + text = plf(text, slice); + + var halfAngle = ((startAngle+slice.angle) + startAngle)/2; + var x = centerLeft + Math.round(Math.cos(halfAngle) * radius); + var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt; + + var html = '' + text + ""; + target.append(html); + var label = target.children('#pieLabel'+index); + var labelTop = (y - label.height()/2); + var labelLeft = (x - label.width()/2); + label.css('top', labelTop); + label.css('left', labelLeft); + + // check to make sure that the label is not outside the canvas + if (0-labelTop>0 || 0-labelLeft>0 || canvas.height-(labelTop+label.height())<0 || canvas.width-(labelLeft+label.width())<0) + redraw = true; + + if (options.series.pie.label.background.opacity != 0) { + // put in the transparent background separately to avoid blended labels and label boxes + var c = options.series.pie.label.background.color; + if (c == null) { + c = slice.color; + } + var pos = 'top:'+labelTop+'px;left:'+labelLeft+'px;'; + $('
').insertBefore(label).css('opacity', options.series.pie.label.background.opacity); + } + } // end individual label function + } // end drawLabels function + } // end drawPie function + } // end draw function + + // Placed here because it needs to be accessed from multiple locations + function drawDonutHole(layer) + { + // draw donut hole + if(options.series.pie.innerRadius > 0) + { + // subtract the center + layer.save(); + innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius; + layer.globalCompositeOperation = 'destination-out'; // this does not work with excanvas, but it will fall back to using the stroke color + layer.beginPath(); + layer.fillStyle = options.series.pie.stroke.color; + layer.arc(0,0,innerRadius,0,Math.PI*2,false); + layer.fill(); + layer.closePath(); + layer.restore(); + + // add inner stroke + layer.save(); + layer.beginPath(); + layer.strokeStyle = options.series.pie.stroke.color; + layer.arc(0,0,innerRadius,0,Math.PI*2,false); + layer.stroke(); + layer.closePath(); + layer.restore(); + // TODO: add extra shadow inside hole (with a mask) if the pie is tilted. + } + } + + //-- Additional Interactive related functions -- + + function isPointInPoly(poly, pt) + { + for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) + ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1])) + && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]) + && (c = !c); + return c; + } + + function findNearbySlice(mouseX, mouseY) + { + var slices = plot.getData(), + options = plot.getOptions(), + radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; + + for (var i = 0; i < slices.length; ++i) + { + var s = slices[i]; + + if(s.pie.show) + { + ctx.save(); + ctx.beginPath(); + ctx.moveTo(0,0); // Center of the pie + //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here. + ctx.arc(0,0,radius,s.startAngle,s.startAngle+s.angle,false); + ctx.closePath(); + x = mouseX-centerLeft; + y = mouseY-centerTop; + if(ctx.isPointInPath) + { + if (ctx.isPointInPath(mouseX-centerLeft, mouseY-centerTop)) + { + //alert('found slice!'); + ctx.restore(); + return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i}; + } + } + else + { + // excanvas for IE doesn;t support isPointInPath, this is a workaround. + p1X = (radius * Math.cos(s.startAngle)); + p1Y = (radius * Math.sin(s.startAngle)); + p2X = (radius * Math.cos(s.startAngle+(s.angle/4))); + p2Y = (radius * Math.sin(s.startAngle+(s.angle/4))); + p3X = (radius * Math.cos(s.startAngle+(s.angle/2))); + p3Y = (radius * Math.sin(s.startAngle+(s.angle/2))); + p4X = (radius * Math.cos(s.startAngle+(s.angle/1.5))); + p4Y = (radius * Math.sin(s.startAngle+(s.angle/1.5))); + p5X = (radius * Math.cos(s.startAngle+s.angle)); + p5Y = (radius * Math.sin(s.startAngle+s.angle)); + arrPoly = [[0,0],[p1X,p1Y],[p2X,p2Y],[p3X,p3Y],[p4X,p4Y],[p5X,p5Y]]; + arrPoint = [x,y]; + // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt? + if(isPointInPoly(arrPoly, arrPoint)) + { + ctx.restore(); + return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i}; + } + } + ctx.restore(); + } + } + + return null; + } + + function onMouseMove(e) + { + triggerClickHoverEvent('plothover', e); + } + + function onClick(e) + { + triggerClickHoverEvent('plotclick', e); + } + + // trigger click or hover event (they send the same parameters so we share their code) + function triggerClickHoverEvent(eventname, e) + { + var offset = plot.offset(), + canvasX = parseInt(e.pageX - offset.left), + canvasY = parseInt(e.pageY - offset.top), + item = findNearbySlice(canvasX, canvasY); + + if (options.grid.autoHighlight) + { + // clear auto-highlights + for (var i = 0; i < highlights.length; ++i) + { + var h = highlights[i]; + if (h.auto == eventname && !(item && h.series == item.series)) + unhighlight(h.series); + } + } + + // highlight the slice + if (item) + highlight(item.series, eventname); + + // trigger any hover bind events + var pos = { pageX: e.pageX, pageY: e.pageY }; + target.trigger(eventname, [ pos, item ]); + } + + function highlight(s, auto) + { + if (typeof s == "number") + s = series[s]; + + var i = indexOfHighlight(s); + if (i == -1) + { + highlights.push({ series: s, auto: auto }); + plot.triggerRedrawOverlay(); + } + else if (!auto) + highlights[i].auto = false; + } + + function unhighlight(s) + { + if (s == null) + { + highlights = []; + plot.triggerRedrawOverlay(); + } + + if (typeof s == "number") + s = series[s]; + + var i = indexOfHighlight(s); + if (i != -1) + { + highlights.splice(i, 1); + plot.triggerRedrawOverlay(); + } + } + + function indexOfHighlight(s) + { + for (var i = 0; i < highlights.length; ++i) + { + var h = highlights[i]; + if (h.series == s) + return i; + } + return -1; + } + + function drawOverlay(plot, octx) + { + //alert(options.series.pie.radius); + var options = plot.getOptions(); + //alert(options.series.pie.radius); + + var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; + + octx.save(); + octx.translate(centerLeft, centerTop); + octx.scale(1, options.series.pie.tilt); + + for (i = 0; i < highlights.length; ++i) + drawHighlight(highlights[i].series); + + drawDonutHole(octx); + + octx.restore(); + + function drawHighlight(series) + { + if (series.angle < 0) return; + + //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); + octx.fillStyle = "rgba(255, 255, 255, "+options.series.pie.highlight.opacity+")"; // this is temporary until we have access to parseColor + + octx.beginPath(); + if (Math.abs(series.angle - Math.PI*2) > 0.000000001) + octx.moveTo(0,0); // Center of the pie + octx.arc(0,0,radius,series.startAngle,series.startAngle+series.angle,false); + octx.closePath(); + octx.fill(); + } + + } + + } // end init (plugin body) + + // define pie specific options and their default values + var options = { + series: { + pie: { + show: false, + radius: 'auto', // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value) + innerRadius:0, /* for donut */ + startAngle: 3/2, + tilt: 1, + offset: { + top: 0, + left: 'auto' + }, + stroke: { + color: '#FFF', + width: 1 + }, + label: { + show: 'auto', + formatter: function(label, slice){ + return '
'+label+'
'+Math.round(slice.percent)+'%
'; + }, // formatter function + radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value) + background: { + color: null, + opacity: 0 + }, + threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow) + }, + combine: { + threshold: -1, // percentage at which to combine little slices into one larger slice + color: null, // color to give the new slice (auto-generated if null) + label: 'Other' // label to give the new slice + }, + highlight: { + //color: '#FFF', // will add this functionality once parseColor is available + opacity: 0.5 + } + } + } + }; + + $.plot.plugins.push({ + init: init, + options: options, + name: "pie", + version: "1.0" + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.resize.js b/airtime_mvc/public/js/flot/jquery.flot.resize.js new file mode 100644 index 000000000..69dfb24f3 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.resize.js @@ -0,0 +1,60 @@ +/* +Flot plugin for automatically redrawing plots when the placeholder +size changes, e.g. on window resizes. + +It works by listening for changes on the placeholder div (through the +jQuery resize event plugin) - if the size changes, it will redraw the +plot. + +There are no options. If you need to disable the plugin for some +plots, you can just fix the size of their placeholders. +*/ + + +/* Inline dependency: + * jQuery resize event - v1.1 - 3/14/2010 + * http://benalman.com/projects/jquery-resize-plugin/ + * + * Copyright (c) 2010 "Cowboy" Ben Alman + * Dual licensed under the MIT and GPL licenses. + * http://benalman.com/about/license/ + */ +(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this); + + +(function ($) { + var options = { }; // no options + + function init(plot) { + function onResize() { + var placeholder = plot.getPlaceholder(); + + // somebody might have hidden us and we can't plot + // when we don't have the dimensions + if (placeholder.width() == 0 || placeholder.height() == 0) + return; + + plot.resize(); + plot.setupGrid(); + plot.draw(); + } + + function bindEvents(plot, eventHolder) { + plot.getPlaceholder().resize(onResize); + } + + function shutdown(plot, eventHolder) { + plot.getPlaceholder().unbind("resize", onResize); + } + + plot.hooks.bindEvents.push(bindEvents); + plot.hooks.shutdown.push(shutdown); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'resize', + version: '1.0' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.selection.js b/airtime_mvc/public/js/flot/jquery.flot.selection.js new file mode 100644 index 000000000..7f7b32694 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.selection.js @@ -0,0 +1,344 @@ +/* +Flot plugin for selecting regions. + +The plugin defines the following options: + + selection: { + mode: null or "x" or "y" or "xy", + color: color + } + +Selection support is enabled by setting the mode to one of "x", "y" or +"xy". In "x" mode, the user will only be able to specify the x range, +similarly for "y" mode. For "xy", the selection becomes a rectangle +where both ranges can be specified. "color" is color of the selection +(if you need to change the color later on, you can get to it with +plot.getOptions().selection.color). + +When selection support is enabled, a "plotselected" event will be +emitted on the DOM element you passed into the plot function. The +event handler gets a parameter with the ranges selected on the axes, +like this: + + placeholder.bind("plotselected", function(event, ranges) { + alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to) + // similar for yaxis - with multiple axes, the extra ones are in + // x2axis, x3axis, ... + }); + +The "plotselected" event is only fired when the user has finished +making the selection. A "plotselecting" event is fired during the +process with the same parameters as the "plotselected" event, in case +you want to know what's happening while it's happening, + +A "plotunselected" event with no arguments is emitted when the user +clicks the mouse to remove the selection. + +The plugin allso adds the following methods to the plot object: + +- setSelection(ranges, preventEvent) + + Set the selection rectangle. The passed in ranges is on the same + form as returned in the "plotselected" event. If the selection mode + is "x", you should put in either an xaxis range, if the mode is "y" + you need to put in an yaxis range and both xaxis and yaxis if the + selection mode is "xy", like this: + + setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } }); + + setSelection will trigger the "plotselected" event when called. If + you don't want that to happen, e.g. if you're inside a + "plotselected" handler, pass true as the second parameter. If you + are using multiple axes, you can specify the ranges on any of those, + e.g. as x2axis/x3axis/... instead of xaxis, the plugin picks the + first one it sees. + +- clearSelection(preventEvent) + + Clear the selection rectangle. Pass in true to avoid getting a + "plotunselected" event. + +- getSelection() + + Returns the current selection in the same format as the + "plotselected" event. If there's currently no selection, the + function returns null. + +*/ + +(function ($) { + function init(plot) { + var selection = { + first: { x: -1, y: -1}, second: { x: -1, y: -1}, + show: false, + active: false + }; + + // FIXME: The drag handling implemented here should be + // abstracted out, there's some similar code from a library in + // the navigation plugin, this should be massaged a bit to fit + // the Flot cases here better and reused. Doing this would + // make this plugin much slimmer. + var savedhandlers = {}; + + var mouseUpHandler = null; + + function onMouseMove(e) { + if (selection.active) { + updateSelection(e); + + plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]); + } + } + + function onMouseDown(e) { + if (e.which != 1) // only accept left-click + return; + + // cancel out any text selections + document.body.focus(); + + // prevent text selection and drag in old-school browsers + if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) { + savedhandlers.onselectstart = document.onselectstart; + document.onselectstart = function () { return false; }; + } + if (document.ondrag !== undefined && savedhandlers.ondrag == null) { + savedhandlers.ondrag = document.ondrag; + document.ondrag = function () { return false; }; + } + + setSelectionPos(selection.first, e); + + selection.active = true; + + // this is a bit silly, but we have to use a closure to be + // able to whack the same handler again + mouseUpHandler = function (e) { onMouseUp(e); }; + + $(document).one("mouseup", mouseUpHandler); + } + + function onMouseUp(e) { + mouseUpHandler = null; + + // revert drag stuff for old-school browsers + if (document.onselectstart !== undefined) + document.onselectstart = savedhandlers.onselectstart; + if (document.ondrag !== undefined) + document.ondrag = savedhandlers.ondrag; + + // no more dragging + selection.active = false; + updateSelection(e); + + if (selectionIsSane()) + triggerSelectedEvent(); + else { + // this counts as a clear + plot.getPlaceholder().trigger("plotunselected", [ ]); + plot.getPlaceholder().trigger("plotselecting", [ null ]); + } + + return false; + } + + function getSelection() { + if (!selectionIsSane()) + return null; + + var r = {}, c1 = selection.first, c2 = selection.second; + $.each(plot.getAxes(), function (name, axis) { + if (axis.used) { + var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); + r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) }; + } + }); + return r; + } + + function triggerSelectedEvent() { + var r = getSelection(); + + plot.getPlaceholder().trigger("plotselected", [ r ]); + + // backwards-compat stuff, to be removed in future + if (r.xaxis && r.yaxis) + plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); + } + + function clamp(min, value, max) { + return value < min ? min: (value > max ? max: value); + } + + function setSelectionPos(pos, e) { + var o = plot.getOptions(); + var offset = plot.getPlaceholder().offset(); + var plotOffset = plot.getPlotOffset(); + pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width()); + pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height()); + + if (o.selection.mode == "y") + pos.x = pos == selection.first ? 0 : plot.width(); + + if (o.selection.mode == "x") + pos.y = pos == selection.first ? 0 : plot.height(); + } + + function updateSelection(pos) { + if (pos.pageX == null) + return; + + setSelectionPos(selection.second, pos); + if (selectionIsSane()) { + selection.show = true; + plot.triggerRedrawOverlay(); + } + else + clearSelection(true); + } + + function clearSelection(preventEvent) { + if (selection.show) { + selection.show = false; + plot.triggerRedrawOverlay(); + if (!preventEvent) + plot.getPlaceholder().trigger("plotunselected", [ ]); + } + } + + // function taken from markings support in Flot + function extractRange(ranges, coord) { + var axis, from, to, key, axes = plot.getAxes(); + + for (var k in axes) { + axis = axes[k]; + if (axis.direction == coord) { + key = coord + axis.n + "axis"; + if (!ranges[key] && axis.n == 1) + key = coord + "axis"; // support x1axis as xaxis + if (ranges[key]) { + from = ranges[key].from; + to = ranges[key].to; + break; + } + } + } + + // backwards-compat stuff - to be removed in future + if (!ranges[key]) { + axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; + from = ranges[coord + "1"]; + to = ranges[coord + "2"]; + } + + // auto-reverse as an added bonus + if (from != null && to != null && from > to) { + var tmp = from; + from = to; + to = tmp; + } + + return { from: from, to: to, axis: axis }; + } + + function setSelection(ranges, preventEvent) { + var axis, range, o = plot.getOptions(); + + if (o.selection.mode == "y") { + selection.first.x = 0; + selection.second.x = plot.width(); + } + else { + range = extractRange(ranges, "x"); + + selection.first.x = range.axis.p2c(range.from); + selection.second.x = range.axis.p2c(range.to); + } + + if (o.selection.mode == "x") { + selection.first.y = 0; + selection.second.y = plot.height(); + } + else { + range = extractRange(ranges, "y"); + + selection.first.y = range.axis.p2c(range.from); + selection.second.y = range.axis.p2c(range.to); + } + + selection.show = true; + plot.triggerRedrawOverlay(); + if (!preventEvent && selectionIsSane()) + triggerSelectedEvent(); + } + + function selectionIsSane() { + var minSize = 5; + return Math.abs(selection.second.x - selection.first.x) >= minSize && + Math.abs(selection.second.y - selection.first.y) >= minSize; + } + + plot.clearSelection = clearSelection; + plot.setSelection = setSelection; + plot.getSelection = getSelection; + + plot.hooks.bindEvents.push(function(plot, eventHolder) { + var o = plot.getOptions(); + if (o.selection.mode != null) { + eventHolder.mousemove(onMouseMove); + eventHolder.mousedown(onMouseDown); + } + }); + + + plot.hooks.drawOverlay.push(function (plot, ctx) { + // draw selection + if (selection.show && selectionIsSane()) { + var plotOffset = plot.getPlotOffset(); + var o = plot.getOptions(); + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + var c = $.color.parse(o.selection.color); + + ctx.strokeStyle = c.scale('a', 0.8).toString(); + ctx.lineWidth = 1; + ctx.lineJoin = "round"; + ctx.fillStyle = c.scale('a', 0.4).toString(); + + var x = Math.min(selection.first.x, selection.second.x), + y = Math.min(selection.first.y, selection.second.y), + w = Math.abs(selection.second.x - selection.first.x), + h = Math.abs(selection.second.y - selection.first.y); + + ctx.fillRect(x, y, w, h); + ctx.strokeRect(x, y, w, h); + + ctx.restore(); + } + }); + + plot.hooks.shutdown.push(function (plot, eventHolder) { + eventHolder.unbind("mousemove", onMouseMove); + eventHolder.unbind("mousedown", onMouseDown); + + if (mouseUpHandler) + $(document).unbind("mouseup", mouseUpHandler); + }); + + } + + $.plot.plugins.push({ + init: init, + options: { + selection: { + mode: null, // one of null, "x", "y" or "xy" + color: "#e8cfac" + } + }, + name: 'selection', + version: '1.1' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.stack.js b/airtime_mvc/public/js/flot/jquery.flot.stack.js new file mode 100644 index 000000000..a31d5dc9b --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.stack.js @@ -0,0 +1,184 @@ +/* +Flot plugin for stacking data sets, i.e. putting them on top of each +other, for accumulative graphs. + +The plugin assumes the data is sorted on x (or y if stacking +horizontally). For line charts, it is assumed that if a line has an +undefined gap (from a null point), then the line above it should have +the same gap - insert zeros instead of "null" if you want another +behaviour. This also holds for the start and end of the chart. Note +that stacking a mix of positive and negative values in most instances +doesn't make sense (so it looks weird). + +Two or more series are stacked when their "stack" attribute is set to +the same key (which can be any number or string or just "true"). To +specify the default stack, you can set + + series: { + stack: null or true or key (number/string) + } + +or specify it for a specific series + + $.plot($("#placeholder"), [{ data: [ ... ], stack: true }]) + +The stacking order is determined by the order of the data series in +the array (later series end up on top of the previous). + +Internally, the plugin modifies the datapoints in each series, adding +an offset to the y value. For line series, extra data points are +inserted through interpolation. If there's a second y value, it's also +adjusted (e.g for bar charts or filled areas). +*/ + +(function ($) { + var options = { + series: { stack: null } // or number/string + }; + + function init(plot) { + function findMatchingSeries(s, allseries) { + var res = null + for (var i = 0; i < allseries.length; ++i) { + if (s == allseries[i]) + break; + + if (allseries[i].stack == s.stack) + res = allseries[i]; + } + + return res; + } + + function stackData(plot, s, datapoints) { + if (s.stack == null) + return; + + var other = findMatchingSeries(s, plot.getData()); + if (!other) + return; + + var ps = datapoints.pointsize, + points = datapoints.points, + otherps = other.datapoints.pointsize, + otherpoints = other.datapoints.points, + newpoints = [], + px, py, intery, qx, qy, bottom, + withlines = s.lines.show, + horizontal = s.bars.horizontal, + withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y), + withsteps = withlines && s.lines.steps, + fromgap = true, + keyOffset = horizontal ? 1 : 0, + accumulateOffset = horizontal ? 0 : 1, + i = 0, j = 0, l; + + while (true) { + if (i >= points.length) + break; + + l = newpoints.length; + + if (points[i] == null) { + // copy gaps + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + i += ps; + } + else if (j >= otherpoints.length) { + // for lines, we can't use the rest of the points + if (!withlines) { + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + } + i += ps; + } + else if (otherpoints[j] == null) { + // oops, got a gap + for (m = 0; m < ps; ++m) + newpoints.push(null); + fromgap = true; + j += otherps; + } + else { + // cases where we actually got two points + px = points[i + keyOffset]; + py = points[i + accumulateOffset]; + qx = otherpoints[j + keyOffset]; + qy = otherpoints[j + accumulateOffset]; + bottom = 0; + + if (px == qx) { + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + + newpoints[l + accumulateOffset] += qy; + bottom = qy; + + i += ps; + j += otherps; + } + else if (px > qx) { + // we got past point below, might need to + // insert interpolated extra point + if (withlines && i > 0 && points[i - ps] != null) { + intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px); + newpoints.push(qx); + newpoints.push(intery + qy); + for (m = 2; m < ps; ++m) + newpoints.push(points[i + m]); + bottom = qy; + } + + j += otherps; + } + else { // px < qx + if (fromgap && withlines) { + // if we come from a gap, we just skip this point + i += ps; + continue; + } + + for (m = 0; m < ps; ++m) + newpoints.push(points[i + m]); + + // we might be able to interpolate a point below, + // this can give us a better y + if (withlines && j > 0 && otherpoints[j - otherps] != null) + bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx); + + newpoints[l + accumulateOffset] += bottom; + + i += ps; + } + + fromgap = false; + + if (l != newpoints.length && withbottom) + newpoints[l + 2] += bottom; + } + + // maintain the line steps invariant + if (withsteps && l != newpoints.length && l > 0 + && newpoints[l] != null + && newpoints[l] != newpoints[l - ps] + && newpoints[l + 1] != newpoints[l - ps + 1]) { + for (m = 0; m < ps; ++m) + newpoints[l + ps + m] = newpoints[l + m]; + newpoints[l + 1] = newpoints[l - ps + 1]; + } + } + + datapoints.points = newpoints; + } + + plot.hooks.processDatapoints.push(stackData); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'stack', + version: '1.2' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.symbol.js b/airtime_mvc/public/js/flot/jquery.flot.symbol.js new file mode 100644 index 000000000..a32fe3185 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.symbol.js @@ -0,0 +1,70 @@ +/* +Flot plugin that adds some extra symbols for plotting points. + +The symbols are accessed as strings through the standard symbol +choice: + + series: { + points: { + symbol: "square" // or "diamond", "triangle", "cross" + } + } + +*/ + +(function ($) { + function processRawData(plot, series, datapoints) { + // we normalize the area of each symbol so it is approximately the + // same as a circle of the given radius + + var handlers = { + square: function (ctx, x, y, radius, shadow) { + // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 + var size = radius * Math.sqrt(Math.PI) / 2; + ctx.rect(x - size, y - size, size + size, size + size); + }, + diamond: function (ctx, x, y, radius, shadow) { + // pi * r^2 = 2s^2 => s = r * sqrt(pi/2) + var size = radius * Math.sqrt(Math.PI / 2); + ctx.moveTo(x - size, y); + ctx.lineTo(x, y - size); + ctx.lineTo(x + size, y); + ctx.lineTo(x, y + size); + ctx.lineTo(x - size, y); + }, + triangle: function (ctx, x, y, radius, shadow) { + // pi * r^2 = 1/2 * s^2 * sin (pi / 3) => s = r * sqrt(2 * pi / sin(pi / 3)) + var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3)); + var height = size * Math.sin(Math.PI / 3); + ctx.moveTo(x - size/2, y + height/2); + ctx.lineTo(x + size/2, y + height/2); + if (!shadow) { + ctx.lineTo(x, y - height/2); + ctx.lineTo(x - size/2, y + height/2); + } + }, + cross: function (ctx, x, y, radius, shadow) { + // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 + var size = radius * Math.sqrt(Math.PI) / 2; + ctx.moveTo(x - size, y - size); + ctx.lineTo(x + size, y + size); + ctx.moveTo(x - size, y + size); + ctx.lineTo(x + size, y - size); + } + } + + var s = series.points.symbol; + if (handlers[s]) + series.points.symbol = handlers[s]; + } + + function init(plot) { + plot.hooks.processDatapoints.push(processRawData); + } + + $.plot.plugins.push({ + init: init, + name: 'symbols', + version: '1.0' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.flot.threshold.js b/airtime_mvc/public/js/flot/jquery.flot.threshold.js new file mode 100644 index 000000000..0b2e7ac82 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.flot.threshold.js @@ -0,0 +1,103 @@ +/* +Flot plugin for thresholding data. Controlled through the option +"threshold" in either the global series options + + series: { + threshold: { + below: number + color: colorspec + } + } + +or in a specific series + + $.plot($("#placeholder"), [{ data: [ ... ], threshold: { ... }}]) + +The data points below "below" are drawn with the specified color. This +makes it easy to mark points below 0, e.g. for budget data. + +Internally, the plugin works by splitting the data into two series, +above and below the threshold. The extra series below the threshold +will have its label cleared and the special "originSeries" attribute +set to the original series. You may need to check for this in hover +events. +*/ + +(function ($) { + var options = { + series: { threshold: null } // or { below: number, color: color spec} + }; + + function init(plot) { + function thresholdData(plot, s, datapoints) { + if (!s.threshold) + return; + + var ps = datapoints.pointsize, i, x, y, p, prevp, + thresholded = $.extend({}, s); // note: shallow copy + + thresholded.datapoints = { points: [], pointsize: ps }; + thresholded.label = null; + thresholded.color = s.threshold.color; + thresholded.threshold = null; + thresholded.originSeries = s; + thresholded.data = []; + + var below = s.threshold.below, + origpoints = datapoints.points, + addCrossingPoints = s.lines.show; + + threspoints = []; + newpoints = []; + + for (i = 0; i < origpoints.length; i += ps) { + x = origpoints[i] + y = origpoints[i + 1]; + + prevp = p; + if (y < below) + p = threspoints; + else + p = newpoints; + + if (addCrossingPoints && prevp != p && x != null + && i > 0 && origpoints[i - ps] != null) { + var interx = (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]) * (below - y) + x; + prevp.push(interx); + prevp.push(below); + for (m = 2; m < ps; ++m) + prevp.push(origpoints[i + m]); + + p.push(null); // start new segment + p.push(null); + for (m = 2; m < ps; ++m) + p.push(origpoints[i + m]); + p.push(interx); + p.push(below); + for (m = 2; m < ps; ++m) + p.push(origpoints[i + m]); + } + + p.push(x); + p.push(y); + } + + datapoints.points = newpoints; + thresholded.datapoints.points = threspoints; + + if (thresholded.datapoints.points.length > 0) + plot.getData().push(thresholded); + + // FIXME: there are probably some edge cases left in bars + } + + plot.hooks.processDatapoints.push(thresholdData); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'threshold', + version: '1.0' + }); +})(jQuery); diff --git a/airtime_mvc/public/js/flot/jquery.js b/airtime_mvc/public/js/flot/jquery.js new file mode 100644 index 000000000..78fcfa469 --- /dev/null +++ b/airtime_mvc/public/js/flot/jquery.js @@ -0,0 +1,8316 @@ +/*! + * jQuery JavaScript Library v1.5.1 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Wed Feb 23 13:55:29 2011 -0500 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // (both of which we optimize for) + quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Check for digits + rdigit = /\d/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // Has the ready events already been bound? + readyBound = false, + + // The deferred used on DOM ready + readyList, + + // Promise methods + promiseMethods = "then done fail isResolved isRejected promise".split( " " ), + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = "body"; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + match = quickExpr.exec( selector ); + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = (context ? context.ownerDocument || context : document); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return (context || rootjQuery).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if (selector.selector !== undefined) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.5.1", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + (this.selector ? " " : "") + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.done( fn ); + + return this; + }, + + eq: function( i ) { + return i === -1 ? + this.slice( i ) : + this.slice( i, +i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + window.$ = _$; + + if ( deep ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + // A third-party is pushing the ready event forwards + if ( wait === true ) { + jQuery.readyWait--; + } + + // Make sure that the DOM is not already loaded + if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).unbind( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyBound ) { + return; + } + + readyBound = true; + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent("onreadystatechange", DOMContentLoaded); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNaN: function( obj ) { + return obj == null || !rdigit.test( obj ) || isNaN( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw msg; + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test(data.replace(rvalidescape, "@") + .replace(rvalidtokens, "]") + .replace(rvalidbraces, "")) ) { + + // Try to use the native JSON parser first + return window.JSON && window.JSON.parse ? + window.JSON.parse( data ) : + (new Function("return " + data))(); + + } else { + jQuery.error( "Invalid JSON: " + data ); + } + }, + + // Cross-browser xml parsing + // (xml & tmp used internally) + parseXML: function( data , xml , tmp ) { + + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + + tmp = xml.documentElement; + + if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { + jQuery.error( "Invalid XML: " + data ); + } + + return xml; + }, + + noop: function() {}, + + // Evalulates a script in a global context + globalEval: function( data ) { + if ( data && rnotwhite.test(data) ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement, + script = document.createElement( "script" ); + + if ( jQuery.support.scriptEval() ) { + script.appendChild( document.createTextNode( data ) ); + } else { + script.text = data; + } + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction(object); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // The extra typeof function check is to prevent crashes + // in Safari 2 (See: #3039) + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type(array); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var ret = [], value; + + // Go through the array, translating each of the items to their + // new value (or values). + for ( var i = 0, length = elems.length; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + proxy: function( fn, proxy, thisObject ) { + if ( arguments.length === 2 ) { + if ( typeof proxy === "string" ) { + thisObject = fn; + fn = thisObject[ proxy ]; + proxy = undefined; + + } else if ( proxy && !jQuery.isFunction( proxy ) ) { + thisObject = proxy; + proxy = undefined; + } + } + + if ( !proxy && fn ) { + proxy = function() { + return fn.apply( thisObject || this, arguments ); + }; + } + + // Set the guid of unique handler to the same of original handler, so it can be removed + if ( fn ) { + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + } + + // So proxy can be declared as an argument + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can be optionally by executed if its a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return (new Date()).getTime(); + }, + + // Create a simple deferred (one callbacks list) + _Deferred: function() { + var // callbacks list + callbacks = [], + // stored [ context , args ] + fired, + // to avoid firing when already doing so + firing, + // flag to know if the deferred has been cancelled + cancelled, + // the deferred itself + deferred = { + + // done( f1, f2, ...) + done: function() { + if ( !cancelled ) { + var args = arguments, + i, + length, + elem, + type, + _fired; + if ( fired ) { + _fired = fired; + fired = 0; + } + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + deferred.done.apply( deferred, elem ); + } else if ( type === "function" ) { + callbacks.push( elem ); + } + } + if ( _fired ) { + deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); + } + } + return this; + }, + + // resolve with given context and args + resolveWith: function( context, args ) { + if ( !cancelled && !fired && !firing ) { + firing = 1; + try { + while( callbacks[ 0 ] ) { + callbacks.shift().apply( context, args ); + } + } + // We have to add a catch block for + // IE prior to 8 or else the finally + // block will never get executed + catch (e) { + throw e; + } + finally { + fired = [ context, args ]; + firing = 0; + } + } + return this; + }, + + // resolve with this as context and given arguments + resolve: function() { + deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments ); + return this; + }, + + // Has this deferred been resolved? + isResolved: function() { + return !!( firing || fired ); + }, + + // Cancel + cancel: function() { + cancelled = 1; + callbacks = []; + return this; + } + }; + + return deferred; + }, + + // Full fledged deferred (two callbacks list) + Deferred: function( func ) { + var deferred = jQuery._Deferred(), + failDeferred = jQuery._Deferred(), + promise; + // Add errorDeferred methods, then and promise + jQuery.extend( deferred, { + then: function( doneCallbacks, failCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ); + return this; + }, + fail: failDeferred.done, + rejectWith: failDeferred.resolveWith, + reject: failDeferred.resolve, + isRejected: failDeferred.isResolved, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + if ( promise ) { + return promise; + } + promise = obj = {}; + } + var i = promiseMethods.length; + while( i-- ) { + obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; + } + return obj; + } + } ); + // Make sure only one callback list will be used + deferred.done( failDeferred.cancel ).fail( deferred.cancel ); + // Unexpose cancel + delete deferred.cancel; + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + return deferred; + }, + + // Deferred helper + when: function( object ) { + var lastIndex = arguments.length, + deferred = lastIndex <= 1 && object && jQuery.isFunction( object.promise ) ? + object : + jQuery.Deferred(), + promise = deferred.promise(); + + if ( lastIndex > 1 ) { + var array = slice.call( arguments, 0 ), + count = lastIndex, + iCallback = function( index ) { + return function( value ) { + array[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( promise, array ); + } + }; + }; + while( ( lastIndex-- ) ) { + object = array[ lastIndex ]; + if ( object && jQuery.isFunction( object.promise ) ) { + object.promise().then( iCallback(lastIndex), deferred.reject ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( promise, array ); + } + } else if ( deferred !== object ) { + deferred.resolve( object ); + } + return promise; + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySubclass( selector, context ) { + return new jQuerySubclass.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySubclass, this ); + jQuerySubclass.superclass = this; + jQuerySubclass.fn = jQuerySubclass.prototype = this(); + jQuerySubclass.fn.constructor = jQuerySubclass; + jQuerySubclass.subclass = this.subclass; + jQuerySubclass.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) { + context = jQuerySubclass(context); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass ); + }; + jQuerySubclass.fn.init.prototype = jQuerySubclass.fn; + var rootjQuerySubclass = jQuerySubclass(document); + return jQuerySubclass; + }, + + browser: {} +}); + +// Create readyList deferred +readyList = jQuery._Deferred(); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +if ( indexOf ) { + jQuery.inArray = function( elem, array ) { + return indexOf.call( array, elem ); + }; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +// Expose jQuery to the global object +return jQuery; + +})(); + + +(function() { + + jQuery.support = {}; + + var div = document.createElement("div"); + + div.style.display = "none"; + div.innerHTML = "
a"; + + var all = div.getElementsByTagName("*"), + a = div.getElementsByTagName("a")[0], + select = document.createElement("select"), + opt = select.appendChild( document.createElement("option") ), + input = div.getElementsByTagName("input")[0]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return; + } + + jQuery.support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: div.firstChild.nodeType === 3, + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText insted) + style: /red/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: a.getAttribute("href") === "/a", + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55$/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: input.value === "on", + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Will be defined later + deleteExpando: true, + optDisabled: false, + checkClone: false, + noCloneEvent: true, + noCloneChecked: true, + boxModel: null, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableHiddenOffsets: true + }; + + input.checked = true; + jQuery.support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as diabled) + select.disabled = true; + jQuery.support.optDisabled = !opt.disabled; + + var _scriptEval = null; + jQuery.support.scriptEval = function() { + if ( _scriptEval === null ) { + var root = document.documentElement, + script = document.createElement("script"), + id = "script" + jQuery.now(); + + try { + script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); + } catch(e) {} + + root.insertBefore( script, root.firstChild ); + + // Make sure that the execution of code works by injecting a script + // tag with appendChild/createTextNode + // (IE doesn't support this, fails, and uses .text instead) + if ( window[ id ] ) { + _scriptEval = true; + delete window[ id ]; + } else { + _scriptEval = false; + } + + root.removeChild( script ); + // release memory in IE + root = script = id = null; + } + + return _scriptEval; + }; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + + } catch(e) { + jQuery.support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent("onclick", function click() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + jQuery.support.noCloneEvent = false; + div.detachEvent("onclick", click); + }); + div.cloneNode(true).fireEvent("onclick"); + } + + div = document.createElement("div"); + div.innerHTML = ""; + + var fragment = document.createDocumentFragment(); + fragment.appendChild( div.firstChild ); + + // WebKit doesn't clone checked state correctly in fragments + jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; + + // Figure out if the W3C box model works as expected + // document.body must exist before we can do this + jQuery(function() { + var div = document.createElement("div"), + body = document.getElementsByTagName("body")[0]; + + // Frameset documents with no body should not run this code + if ( !body ) { + return; + } + + div.style.width = div.style.paddingLeft = "1px"; + body.appendChild( div ); + jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; + + if ( "zoom" in div.style ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2; + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "
"; + jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; + } + + div.innerHTML = "
t
"; + var tds = div.getElementsByTagName("td"); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0; + + tds[0].style.display = ""; + tds[1].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE < 8 fail this test) + jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; + div.innerHTML = ""; + + body.removeChild( div ).style.display = "none"; + div = tds = null; + }); + + // Technique from Juriy Zaytsev + // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ + var eventSupported = function( eventName ) { + var el = document.createElement("div"); + eventName = "on" + eventName; + + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( !el.attachEvent ) { + return true; + } + + var isSupported = (eventName in el); + if ( !isSupported ) { + el.setAttribute(eventName, "return;"); + isSupported = typeof el[eventName] === "function"; + } + el = null; + + return isSupported; + }; + + jQuery.support.submitBubbles = eventSupported("submit"); + jQuery.support.changeBubbles = eventSupported("change"); + + // release memory in IE + div = all = a = null; +})(); + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ jQuery.expando ] = id = ++jQuery.uuid; + } else { + id = jQuery.expando; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery + // metadata on plain JS objects when the object is serialized using + // JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); + } else { + cache[ id ] = jQuery.extend(cache[ id ], name); + } + } + + thisCache = cache[ id ]; + + // Internal jQuery data is stored in a separate object inside the object's data + // cache in order to avoid key collisions between internal data and user-defined + // data + if ( pvt ) { + if ( !thisCache[ internalKey ] ) { + thisCache[ internalKey ] = {}; + } + + thisCache = thisCache[ internalKey ]; + } + + if ( data !== undefined ) { + thisCache[ name ] = data; + } + + // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should + // not attempt to inspect the internal events object using jQuery.data, as this + // internal data object is undocumented and subject to change. + if ( name === "events" && !thisCache[name] ) { + return thisCache[ internalKey ] && thisCache[ internalKey ].events; + } + + return getByName ? thisCache[ name ] : thisCache; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var internalKey = jQuery.expando, isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; + + if ( thisCache ) { + delete thisCache[ name ]; + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !isEmptyDataObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( pvt ) { + delete cache[ id ][ internalKey ]; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + var internalCache = cache[ id ][ internalKey ]; + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + if ( jQuery.support.deleteExpando || cache != window ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the entire user cache at once because it's faster than + // iterating through each key, but we need to continue to persist internal + // data if it existed + if ( internalCache ) { + cache[ id ] = {}; + // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery + // metadata on plain JS objects when the object is serialized using + // JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + + cache[ id ][ internalKey ] = internalCache; + + // Otherwise, we need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + } else if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ jQuery.expando ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } else { + elem[ jQuery.expando ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 ) { + var attr = this[0].attributes, name; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = name.substr( 5 ); + dataAttr( this[0], name, data[ name ] ); + } + } + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + var parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var $this = jQuery( this ), + args = [ parts[0], value ]; + + $this.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + $this.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + data = elem.getAttribute( "data-" + key ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + !jQuery.isNaN( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON +// property to be considered empty objects; this property always exists in +// order to make sure JSON.stringify does not expose internal metadata +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +jQuery.extend({ + queue: function( elem, type, data ) { + if ( !elem ) { + return; + } + + type = (type || "fx") + "queue"; + var q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( !data ) { + return q || []; + } + + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + + } else { + q.push( data ); + } + + return q; + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(); + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift("inprogress"); + } + + fn.call(elem, function() { + jQuery.dequeue(elem, type); + }); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue", true ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function( i ) { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; + type = type || "fx"; + + return this.queue( type, function() { + var elem = this; + setTimeout(function() { + jQuery.dequeue( elem, type ); + }, time ); + }); + }, + + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspaces = /\s+/, + rreturn = /\r/g, + rspecialurl = /^(?:href|src|style)$/, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rradiocheck = /^(?:radio|checkbox)$/i; + +jQuery.props = { + "for": "htmlFor", + "class": "className", + readonly: "readOnly", + maxlength: "maxLength", + cellspacing: "cellSpacing", + rowspan: "rowSpan", + colspan: "colSpan", + tabindex: "tabIndex", + usemap: "useMap", + frameborder: "frameBorder" +}; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name, fn ) { + return this.each(function(){ + jQuery.attr( this, name, "" ); + if ( this.nodeType === 1 ) { + this.removeAttribute( name ); + } + }); + }, + + addClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.addClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( value && typeof value === "string" ) { + var classNames = (value || "").split( rspaces ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className ) { + elem.className = value; + + } else { + var className = " " + elem.className + " ", + setClass = elem.className; + + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { + setClass += " " + classNames[c]; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.removeClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + var classNames = (value || "").split( rspaces ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + var className = (" " + elem.className + " ").replace(rclass, " "); + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[c] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this); + self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspaces ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " "; + for ( var i = 0, l = this.length; i < l; i++ ) { + if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + if ( !arguments.length ) { + var elem = this[0]; + + if ( elem ) { + if ( jQuery.nodeName( elem, "option" ) ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery(option).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + } + + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { + return elem.getAttribute("value") === null ? "on" : elem.value; + } + + // Everything else, we just grab the value + return (elem.value || "").replace(rreturn, ""); + + } + + return undefined; + } + + var isFunction = jQuery.isFunction(value); + + return this.each(function(i) { + var self = jQuery(this), val = value; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call(this, i, self.val()); + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray(val) ) { + val = jQuery.map(val, function (value) { + return value == null ? "" : value + ""; + }); + } + + if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { + this.checked = jQuery.inArray( self.val(), val ) >= 0; + + } else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(val); + + jQuery( "option", this ).each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + this.selectedIndex = -1; + } + + } else { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) { + return undefined; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery(elem)[name](value); + } + + var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), + // Whether we are setting (or getting) + set = value !== undefined; + + // Try to normalize/fix the name + name = notxml && jQuery.props[ name ] || name; + + // Only do all the following if this is a node (faster for style) + if ( elem.nodeType === 1 ) { + // These attributes require special treatment + var special = rspecialurl.test( name ); + + // Safari mis-reports the default selected property of an option + // Accessing the parent's selectedIndex property fixes it + if ( name === "selected" && !jQuery.support.optSelected ) { + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + + // If applicable, access the attribute via the DOM 0 way + // 'in' checks fail in Blackberry 4.7 #6931 + if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { + if ( set ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } + + if ( value === null ) { + if ( elem.nodeType === 1 ) { + elem.removeAttribute( name ); + } + + } else { + elem[ name ] = value; + } + } + + // browsers index elements by id/name on forms, give priority to attributes. + if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { + return elem.getAttributeNode( name ).nodeValue; + } + + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + if ( name === "tabIndex" ) { + var attributeNode = elem.getAttributeNode( "tabIndex" ); + + return attributeNode && attributeNode.specified ? + attributeNode.value : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + + return elem[ name ]; + } + + if ( !jQuery.support.style && notxml && name === "style" ) { + if ( set ) { + elem.style.cssText = "" + value; + } + + return elem.style.cssText; + } + + if ( set ) { + // convert the value to a string (all browsers do this but IE) see #1070 + elem.setAttribute( name, "" + value ); + } + + // Ensure that missing attributes return undefined + // Blackberry 4.7 returns "" from getAttribute #6938 + if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { + return undefined; + } + + var attr = !jQuery.support.hrefNormalized && notxml && special ? + // Some attributes require a special call on IE + elem.getAttribute( name, 2 ) : + elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return attr === null ? undefined : attr; + } + // Handle everything which isn't a DOM element node + if ( set ) { + elem[ name ] = value; + } + return elem[ name ]; + } +}); + + + + +var rnamespaces = /\.(.*)$/, + rformElems = /^(?:textarea|input|select)$/i, + rperiod = /\./g, + rspace = / /g, + rescape = /[^\w\s.|`]/g, + fcleanup = function( nm ) { + return nm.replace(rescape, "\\$&"); + }; + +/* + * A number of helper functions used for managing events. + * Many of the ideas behind this code originated from + * Dean Edwards' addEvent library. + */ +jQuery.event = { + + // Bind an event to an element + // Original by Dean Edwards + add: function( elem, types, handler, data ) { + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // TODO :: Use a try/catch until it's safe to pull this out (likely 1.6) + // Minor release fix for bug #8018 + try { + // For whatever reason, IE has trouble passing the window object + // around, causing it to be cloned in the process + if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { + elem = window; + } + } + catch ( e ) {} + + if ( handler === false ) { + handler = returnFalse; + } else if ( !handler ) { + // Fixes bug #7229. Fix recommended by jdalton + return; + } + + var handleObjIn, handleObj; + + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the function being executed has a unique ID + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure + var elemData = jQuery._data( elem ); + + // If no elemData is found then we must be trying to bind to one of the + // banned noData elements + if ( !elemData ) { + return; + } + + var events = elemData.events, + eventHandle = elemData.handle; + + if ( !events ) { + elemData.events = events = {}; + } + + if ( !eventHandle ) { + elemData.handle = eventHandle = function() { + // Handle the second event of a trigger and when + // an event is called after a page has unloaded + return typeof jQuery !== "undefined" && !jQuery.event.triggered ? + jQuery.event.handle.apply( eventHandle.elem, arguments ) : + undefined; + }; + } + + // Add elem as a property of the handle function + // This is to prevent a memory leak with non-native events in IE. + eventHandle.elem = elem; + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = types.split(" "); + + var type, i = 0, namespaces; + + while ( (type = types[ i++ ]) ) { + handleObj = handleObjIn ? + jQuery.extend({}, handleObjIn) : + { handler: handler, data: data }; + + // Namespaced event handlers + if ( type.indexOf(".") > -1 ) { + namespaces = type.split("."); + type = namespaces.shift(); + handleObj.namespace = namespaces.slice(0).sort().join("."); + + } else { + namespaces = []; + handleObj.namespace = ""; + } + + handleObj.type = type; + if ( !handleObj.guid ) { + handleObj.guid = handler.guid; + } + + // Get the current list of functions bound to this event + var handlers = events[ type ], + special = jQuery.event.special[ type ] || {}; + + // Init the event handler queue + if ( !handlers ) { + handlers = events[ type ] = []; + + // Check for a special event handler + // Only use addEventListener/attachEvent if the special + // events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add the function to the element's handler list + handlers.push( handleObj ); + + // Keep track of which events have been used, for global triggering + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, pos ) { + // don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + if ( handler === false ) { + handler = returnFalse; + } + + var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + events = elemData && elemData.events; + + if ( !elemData || !events ) { + return; + } + + // types is actually an event object here + if ( types && types.type ) { + handler = types.handler; + types = types.type; + } + + // Unbind all events for the element + if ( !types || typeof types === "string" && types.charAt(0) === "." ) { + types = types || ""; + + for ( type in events ) { + jQuery.event.remove( elem, type + types ); + } + + return; + } + + // Handle multiple events separated by a space + // jQuery(...).unbind("mouseover mouseout", fn); + types = types.split(" "); + + while ( (type = types[ i++ ]) ) { + origType = type; + handleObj = null; + all = type.indexOf(".") < 0; + namespaces = []; + + if ( !all ) { + // Namespaced event handlers + namespaces = type.split("."); + type = namespaces.shift(); + + namespace = new RegExp("(^|\\.)" + + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + eventType = events[ type ]; + + if ( !eventType ) { + continue; + } + + if ( !handler ) { + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( all || namespace.test( handleObj.namespace ) ) { + jQuery.event.remove( elem, origType, handleObj.handler, j ); + eventType.splice( j--, 1 ); + } + } + + continue; + } + + special = jQuery.event.special[ type ] || {}; + + for ( j = pos || 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( handler.guid === handleObj.guid ) { + // remove the given handler for the given type + if ( all || namespace.test( handleObj.namespace ) ) { + if ( pos == null ) { + eventType.splice( j--, 1 ); + } + + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + + if ( pos != null ) { + break; + } + } + } + + // remove generic event handler if no more handlers exist + if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + ret = null; + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + var handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + delete elemData.events; + delete elemData.handle; + + if ( jQuery.isEmptyObject( elemData ) ) { + jQuery.removeData( elem, undefined, true ); + } + } + }, + + // bubbling is internal + trigger: function( event, data, elem /*, bubbling */ ) { + // Event object or event type + var type = event.type || event, + bubbling = arguments[3]; + + if ( !bubbling ) { + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + jQuery.extend( jQuery.Event(type), event ) : + // Just the event type (string) + jQuery.Event(type); + + if ( type.indexOf("!") >= 0 ) { + event.type = type = type.slice(0, -1); + event.exclusive = true; + } + + // Handle a global trigger + if ( !elem ) { + // Don't bubble custom events when global (to avoid too much overhead) + event.stopPropagation(); + + // Only trigger if we've ever bound an event for it + if ( jQuery.event.global[ type ] ) { + // XXX This code smells terrible. event.js should not be directly + // inspecting the data cache + jQuery.each( jQuery.cache, function() { + // internalKey variable is just used to make it easier to find + // and potentially change this stuff later; currently it just + // points to jQuery.expando + var internalKey = jQuery.expando, + internalCache = this[ internalKey ]; + if ( internalCache && internalCache.events && internalCache.events[ type ] ) { + jQuery.event.trigger( event, data, internalCache.handle.elem ); + } + }); + } + } + + // Handle triggering a single element + + // don't do events on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + // Clean up in case it is reused + event.result = undefined; + event.target = elem; + + // Clone the incoming data, if any + data = jQuery.makeArray( data ); + data.unshift( event ); + } + + event.currentTarget = elem; + + // Trigger the event, it is assumed that "handle" is a function + var handle = jQuery._data( elem, "handle" ); + + if ( handle ) { + handle.apply( elem, data ); + } + + var parent = elem.parentNode || elem.ownerDocument; + + // Trigger an inline bound script + try { + if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { + if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { + event.result = false; + event.preventDefault(); + } + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (inlineError) {} + + if ( !event.isPropagationStopped() && parent ) { + jQuery.event.trigger( event, data, parent, true ); + + } else if ( !event.isDefaultPrevented() ) { + var old, + target = event.target, + targetType = type.replace( rnamespaces, "" ), + isClick = jQuery.nodeName( target, "a" ) && targetType === "click", + special = jQuery.event.special[ targetType ] || {}; + + if ( (!special._default || special._default.call( elem, event ) === false) && + !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { + + try { + if ( target[ targetType ] ) { + // Make sure that we don't accidentally re-trigger the onFOO events + old = target[ "on" + targetType ]; + + if ( old ) { + target[ "on" + targetType ] = null; + } + + jQuery.event.triggered = true; + target[ targetType ](); + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (triggerError) {} + + if ( old ) { + target[ "on" + targetType ] = old; + } + + jQuery.event.triggered = false; + } + } + }, + + handle: function( event ) { + var all, handlers, namespaces, namespace_re, events, + namespace_sort = [], + args = jQuery.makeArray( arguments ); + + event = args[0] = jQuery.event.fix( event || window.event ); + event.currentTarget = this; + + // Namespaced event handlers + all = event.type.indexOf(".") < 0 && !event.exclusive; + + if ( !all ) { + namespaces = event.type.split("."); + event.type = namespaces.shift(); + namespace_sort = namespaces.slice(0).sort(); + namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + event.namespace = event.namespace || namespace_sort.join("."); + + events = jQuery._data(this, "events"); + + handlers = (events || {})[ event.type ]; + + if ( events && handlers ) { + // Clone the handlers to prevent manipulation + handlers = handlers.slice(0); + + for ( var j = 0, l = handlers.length; j < l; j++ ) { + var handleObj = handlers[ j ]; + + // Filter the functions by class + if ( all || namespace_re.test( handleObj.namespace ) ) { + // Pass in a reference to the handler function itself + // So that we can later remove it + event.handler = handleObj.handler; + event.data = handleObj.data; + event.handleObj = handleObj; + + var ret = handleObj.handler.apply( this, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + + if ( event.isImmediatePropagationStopped() ) { + break; + } + } + } + } + + return event.result; + }, + + props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // store a copy of the original event object + // and "clone" to set read-only properties + var originalEvent = event; + event = jQuery.Event( originalEvent ); + + for ( var i = this.props.length, prop; i; ) { + prop = this.props[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary + if ( !event.target ) { + // Fixes #1925 where srcElement might not be defined either + event.target = event.srcElement || document; + } + + // check if target is a textnode (safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && event.fromElement ) { + event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; + } + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && event.clientX != null ) { + var doc = document.documentElement, + body = document.body; + + event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); + event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); + } + + // Add which for key events + if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { + event.which = event.charCode != null ? event.charCode : event.keyCode; + } + + // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) + if ( !event.metaKey && event.ctrlKey ) { + event.metaKey = event.ctrlKey; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && event.button !== undefined ) { + event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); + } + + return event; + }, + + // Deprecated, use jQuery.guid instead + guid: 1E8, + + // Deprecated, use jQuery.proxy instead + proxy: jQuery.proxy, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady, + teardown: jQuery.noop + }, + + live: { + add: function( handleObj ) { + jQuery.event.add( this, + liveConvert( handleObj.origType, handleObj.selector ), + jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); + }, + + remove: function( handleObj ) { + jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); + } + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src ) { + // Allow instantiation without the 'new' keyword + if ( !this.preventDefault ) { + return new jQuery.Event( src ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // timeStamp is buggy for some events on Firefox(#3843) + // So we won't rely on the native value + this.timeStamp = jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Checks if an event happened on an element within another element +// Used in jQuery.event.special.mouseenter and mouseleave handlers +var withinElement = function( event ) { + // Check if mouse(over|out) are still within the same parent element + var parent = event.relatedTarget; + + // Firefox sometimes assigns relatedTarget a XUL element + // which we cannot access the parentNode property of + try { + + // Chrome does something similar, the parentNode property + // can be accessed but is null. + if ( parent !== document && !parent.parentNode ) { + return; + } + // Traverse up the tree + while ( parent && parent !== this ) { + parent = parent.parentNode; + } + + if ( parent !== this ) { + // set the correct event type + event.type = event.data; + + // handle event if we actually just moused on to a non sub-element + jQuery.event.handle.apply( this, arguments ); + } + + // assuming we've left the element since we most likely mousedover a xul element + } catch(e) { } +}, + +// In case of event delegation, we only need to rename the event.type, +// liveHandler will take care of the rest. +delegate = function( event ) { + event.type = event.data; + jQuery.event.handle.apply( this, arguments ); +}; + +// Create mouseenter and mouseleave events +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + setup: function( data ) { + jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); + }, + teardown: function( data ) { + jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); + } + }; +}); + +// submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function( data, namespaces ) { + if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) { + jQuery.event.add(this, "click.specialSubmit", function( e ) { + var elem = e.target, + type = elem.type; + + if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { + trigger( "submit", this, arguments ); + } + }); + + jQuery.event.add(this, "keypress.specialSubmit", function( e ) { + var elem = e.target, + type = elem.type; + + if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { + trigger( "submit", this, arguments ); + } + }); + + } else { + return false; + } + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialSubmit" ); + } + }; + +} + +// change delegation, happens here so we have bind. +if ( !jQuery.support.changeBubbles ) { + + var changeFilters, + + getVal = function( elem ) { + var type = elem.type, val = elem.value; + + if ( type === "radio" || type === "checkbox" ) { + val = elem.checked; + + } else if ( type === "select-multiple" ) { + val = elem.selectedIndex > -1 ? + jQuery.map( elem.options, function( elem ) { + return elem.selected; + }).join("-") : + ""; + + } else if ( elem.nodeName.toLowerCase() === "select" ) { + val = elem.selectedIndex; + } + + return val; + }, + + testChange = function testChange( e ) { + var elem = e.target, data, val; + + if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { + return; + } + + data = jQuery._data( elem, "_change_data" ); + val = getVal(elem); + + // the current data will be also retrieved by beforeactivate + if ( e.type !== "focusout" || elem.type !== "radio" ) { + jQuery._data( elem, "_change_data", val ); + } + + if ( data === undefined || val === data ) { + return; + } + + if ( data != null || val ) { + e.type = "change"; + e.liveFired = undefined; + jQuery.event.trigger( e, arguments[1], elem ); + } + }; + + jQuery.event.special.change = { + filters: { + focusout: testChange, + + beforedeactivate: testChange, + + click: function( e ) { + var elem = e.target, type = elem.type; + + if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { + testChange.call( this, e ); + } + }, + + // Change has to be called before submit + // Keydown will be called before keypress, which is used in submit-event delegation + keydown: function( e ) { + var elem = e.target, type = elem.type; + + if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || + (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || + type === "select-multiple" ) { + testChange.call( this, e ); + } + }, + + // Beforeactivate happens also before the previous element is blurred + // with this event you can't trigger a change event, but you can store + // information + beforeactivate: function( e ) { + var elem = e.target; + jQuery._data( elem, "_change_data", getVal(elem) ); + } + }, + + setup: function( data, namespaces ) { + if ( this.type === "file" ) { + return false; + } + + for ( var type in changeFilters ) { + jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); + } + + return rformElems.test( this.nodeName ); + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialChange" ); + + return rformElems.test( this.nodeName ); + } + }; + + changeFilters = jQuery.event.special.change.filters; + + // Handle when the input is .focus()'d + changeFilters.focus = changeFilters.beforeactivate; +} + +function trigger( type, elem, args ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + // Don't pass args or remember liveFired; they apply to the donor event. + var event = jQuery.extend( {}, args[ 0 ] ); + event.type = type; + event.originalEvent = {}; + event.liveFired = undefined; + jQuery.event.handle.call( elem, event ); + if ( event.isDefaultPrevented() ) { + args[ 0 ].preventDefault(); + } +} + +// Create "bubbling" focus and blur events +if ( document.addEventListener ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + jQuery.event.special[ fix ] = { + setup: function() { + this.addEventListener( orig, handler, true ); + }, + teardown: function() { + this.removeEventListener( orig, handler, true ); + } + }; + + function handler( e ) { + e = jQuery.event.fix( e ); + e.type = fix; + return jQuery.event.handle.call( this, e ); + } + }); +} + +jQuery.each(["bind", "one"], function( i, name ) { + jQuery.fn[ name ] = function( type, data, fn ) { + // Handle object literals + if ( typeof type === "object" ) { + for ( var key in type ) { + this[ name ](key, data, type[key], fn); + } + return this; + } + + if ( jQuery.isFunction( data ) || data === false ) { + fn = data; + data = undefined; + } + + var handler = name === "one" ? jQuery.proxy( fn, function( event ) { + jQuery( this ).unbind( event, handler ); + return fn.apply( this, arguments ); + }) : fn; + + if ( type === "unload" && name !== "one" ) { + this.one( type, data, fn ); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.add( this[i], type, handler, data ); + } + } + + return this; + }; +}); + +jQuery.fn.extend({ + unbind: function( type, fn ) { + // Handle object literals + if ( typeof type === "object" && !type.preventDefault ) { + for ( var key in type ) { + this.unbind(key, type[key]); + } + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.remove( this[i], type, fn ); + } + } + + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.live( types, data, fn, selector ); + }, + + undelegate: function( selector, types, fn ) { + if ( arguments.length === 0 ) { + return this.unbind( "live" ); + + } else { + return this.die( types, null, fn, selector ); + } + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + + triggerHandler: function( type, data ) { + if ( this[0] ) { + var event = jQuery.Event( type ); + event.preventDefault(); + event.stopPropagation(); + jQuery.event.trigger( event, data, this[0] ); + return event.result; + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + i = 1; + + // link all the functions, so any of them can unbind this click handler + while ( i < args.length ) { + jQuery.proxy( fn, args[ i++ ] ); + } + + return this.click( jQuery.proxy( fn, function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + })); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +var liveMap = { + focus: "focusin", + blur: "focusout", + mouseenter: "mouseover", + mouseleave: "mouseout" +}; + +jQuery.each(["live", "die"], function( i, name ) { + jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { + var type, i = 0, match, namespaces, preType, + selector = origSelector || this.selector, + context = origSelector ? this : jQuery( this.context ); + + if ( typeof types === "object" && !types.preventDefault ) { + for ( var key in types ) { + context[ name ]( key, data, types[key], selector ); + } + + return this; + } + + if ( jQuery.isFunction( data ) ) { + fn = data; + data = undefined; + } + + types = (types || "").split(" "); + + while ( (type = types[ i++ ]) != null ) { + match = rnamespaces.exec( type ); + namespaces = ""; + + if ( match ) { + namespaces = match[0]; + type = type.replace( rnamespaces, "" ); + } + + if ( type === "hover" ) { + types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); + continue; + } + + preType = type; + + if ( type === "focus" || type === "blur" ) { + types.push( liveMap[ type ] + namespaces ); + type = type + namespaces; + + } else { + type = (liveMap[ type ] || type) + namespaces; + } + + if ( name === "live" ) { + // bind live handler + for ( var j = 0, l = context.length; j < l; j++ ) { + jQuery.event.add( context[j], "live." + liveConvert( type, selector ), + { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); + } + + } else { + // unbind live handler + context.unbind( "live." + liveConvert( type, selector ), fn ); + } + } + + return this; + }; +}); + +function liveHandler( event ) { + var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, + elems = [], + selectors = [], + events = jQuery._data( this, "events" ); + + // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) + if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { + return; + } + + if ( event.namespace ) { + namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + event.liveFired = this; + + var live = events.live.slice(0); + + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { + selectors.push( handleObj.selector ); + + } else { + live.splice( j--, 1 ); + } + } + + match = jQuery( event.target ).closest( selectors, event.currentTarget ); + + for ( i = 0, l = match.length; i < l; i++ ) { + close = match[i]; + + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { + elem = close.elem; + related = null; + + // Those two events require additional checking + if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { + event.type = handleObj.preType; + related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; + } + + if ( !related || related !== elem ) { + elems.push({ elem: elem, handleObj: handleObj, level: close.level }); + } + } + } + } + + for ( i = 0, l = elems.length; i < l; i++ ) { + match = elems[i]; + + if ( maxLevel && match.level > maxLevel ) { + break; + } + + event.currentTarget = match.elem; + event.data = match.handleObj.data; + event.handleObj = match.handleObj; + + ret = match.handleObj.origHandler.apply( match.elem, arguments ); + + if ( ret === false || event.isPropagationStopped() ) { + maxLevel = match.level; + + if ( ret === false ) { + stop = false; + } + if ( event.isImmediatePropagationStopped() ) { + break; + } + } + } + + return stop; +} + +function liveConvert( type, selector ) { + return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&"); +} + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.bind( name, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } +}); + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set; + + if ( !expr ) { + return []; + } + + for ( var i = 0, l = Expr.order.length; i < l; i++ ) { + var match, + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + var left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( var type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + var found, item, + filter = Expr.filter[ type ], + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( var i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + var pass = not ^ !!found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw "Syntax error, unrecognized expression: " + msg; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return "text" === elem.getAttribute( 'type' ); + }, + radio: function( elem ) { + return "radio" === elem.type; + }, + + checkbox: function( elem ) { + return "checkbox" === elem.type; + }, + + file: function( elem ) { + return "file" === elem.type; + }, + password: function( elem ) { + return "password" === elem.type; + }, + + submit: function( elem ) { + return "submit" === elem.type; + }, + + image: function( elem ) { + return "image" === elem.type; + }, + + reset: function( elem ) { + return "reset" === elem.type; + }, + + button: function( elem ) { + return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + var first = match[2], + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + var doneName = match[0], + parent = elem.parentNode; + + if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { + var count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent.sizcache = doneName; + } + + var diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // If the nodes are siblings (or identical) we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Utility function for retreiving the text value of an array of DOM nodes +Sizzle.getText = function( elems ) { + var ret = "", elem; + + for ( var i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += Sizzle.getText( elem.childNodes ); + } + } + + return ret; +}; + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "

"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector, + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + if ( matches ) { + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + return matches.call( node, expr ); + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var ret = this.pushStack( "", "find", selector ), + length = 0; + + for ( var i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( var n = length; n < ret.length; n++ ) { + for ( var r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && jQuery.filter( selector, this ).length > 0; + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + if ( jQuery.isArray( selectors ) ) { + var match, selector, + matches = {}, + level = 1; + + if ( cur && selectors.length ) { + for ( i = 0, l = selectors.length; i < l; i++ ) { + selector = selectors[i]; + + if ( !matches[selector] ) { + matches[selector] = jQuery.expr.match.POS.test( selector ) ? + jQuery( selector, context || this.context ) : + selector; + } + } + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( selector in matches ) { + match = matches[selector]; + + if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { + ret.push({ selector: selector, elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + } + + return ret; + } + + var pos = POS.test( selectors ) ? + jQuery( selectors, context || this.context ) : null; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique(ret) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + if ( !elem || typeof elem === "string" ) { + return jQuery.inArray( this[0], + // If it receives a string, the selector is used + // If it receives nothing, the siblings are used + elem ? jQuery( elem ) : this.parent().children() ); + } + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ), + // The variable 'args' was introduced in + // https://github.com/jquery/jquery/commit/52a0238 + // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. + // http://code.google.com/p/v8/issues/detail?id=1050 + args = slice.call(arguments); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, args.join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return (elem === qualifier) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return (jQuery.inArray( elem, qualifier ) >= 0) === keep; + }); +} + + + + +var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /", "" ], + legend: [ 1, "
", "
" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + col: [ 2, "", "
" ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }; + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize and