diff --git a/about.php b/about.php index d61f199..08bff5d 100644 --- a/about.php +++ b/about.php @@ -1,7 +1,7 @@ , Jam Warehouse (Pty) Ltd, South Africa */ diff --git a/plugins/ktcore/KTColumns.inc.php b/plugins/ktcore/KTColumns.inc.php index 7601419..8c1c194 100644 --- a/plugins/ktcore/KTColumns.inc.php +++ b/plugins/ktcore/KTColumns.inc.php @@ -1,6 +1,6 @@ 0){ - $pages = floor($items/10)+1; -}else{ - $pages = ($items/10); -} -if($pageNum == 1){ - $listStart = 0; - $listEnd = 9; -}elseif($pageNum == $pages){ - $listStart = (10*($pageNum-1)); - $listEnd = count($aDocuments)-1; -}else{ - $listStart = (10*($pageNum-1)); - $listEnd = $listStart+9; -} -for($i = $listStart; $i <= $listEnd; $i++){ - $output .= " - - ".$aDocuments[$i]->getName()." - ".$aDocuments[$i]->getLastModifiedDate()." - ".$aDocuments[$i]->getLastDeletionComment()." - "; -} -echo $output; -?> + 0){ + $pages = floor($items/10)+1; +}else{ + $pages = ($items/10); +} +if($pageNum == 1){ + $listStart = 0; + $listEnd = 9; +}elseif($pageNum == $pages){ + $listStart = (10*($pageNum-1)); + $listEnd = count($aDocuments)-1; +}else{ + $listStart = (10*($pageNum-1)); + $listEnd = $listStart+9; +} +for($i = $listStart; $i <= $listEnd; $i++){ + $output .= " + + ".$aDocuments[$i]->getName()." + ".$aDocuments[$i]->getLastModifiedDate()." + ".$aDocuments[$i]->getLastDeletionComment()." + "; +} +echo $output; +?> diff --git a/plugins/ktcore/admin/fieldsets/basic.inc.php b/plugins/ktcore/admin/fieldsets/basic.inc.php index 2003389..6f4c558 100644 --- a/plugins/ktcore/admin/fieldsets/basic.inc.php +++ b/plugins/ktcore/admin/fieldsets/basic.inc.php @@ -1,7 +1,7 @@ 'id',)); - $id = $user[$_SERVER['PHP_AUTH_USER']]['id']; - - - if(KTUtil::arrayGet($_REQUEST, 'docId')){ // if a docId parameter is passed - // get document id from http request object - $iDocumentId = KTUtil::arrayGet($_REQUEST, 'docId'); - - if(KTrss::validateDocumentPermissions($id, $iDocumentId)){ // if document passes validation check - // get document info - $aDocumentInfo[] = KTrss::getOneDocument($iDocumentId, $id); - - if($aDocumentInfo){ - // create rss xml for document - $documentFeed = KTrss::arrayToXML($aDocumentInfo); - }else{ - // create rss xml for the error - $error = KTrss::errorToXML(_kt('This document has returned a empty response')); - } - }else{ - // create rss xml for error - $error = KTrss::errorToXML(_kt('You are either not authorised to view details on this document or it does not exist.' . - ' Please visit http://' .$_SERVER['HTTP_HOST'].'/'.$GLOBALS['KTRootUrl'].'/ to browse for a valid document.')); - } - if(isset($error)){ // if an error exist, output...else out the result - echo $error; - }else{ - echo $documentFeed; - } - }elseif(KTUtil::arrayGet($_REQUEST, 'folderId')){ // if a folderId parameter is passed - // get folder id from http request object - $iFolderId = KTUtil::arrayGet($_REQUEST, 'folderId'); - - if(KTrss::validateFolderPermissions($id, $iFolderId)){ // if folder passes validation check - // get folder info - $aFolderInfo[] = KTrss::getOneFolder($iFolderId); - - if($aFolderInfo){ - // create rss xml for folder - $folderFeed = KTrss::arrayToXML($aFolderInfo); - }else{ - // create rss xml for error - $error = KTrss::errorToXML(_kt('This document has returned a empty response')); - } - }else{ - // create rss xml for error - $error = KTrss::errorToXML(_kt('You are either not authorised to view details on this folder or it does not exist.' . - ' Please visit http://' .$_SERVER['HTTP_HOST'].'/'.$GLOBALS['KTRootUrl'].'/ to browse for a valid folder.')); - } - if(isset($error)){ // if an error exist, output...else out the result - echo $error; - }else{ - echo $folderFeed; - } - }else{ // else do normal rss parsing - // get full list of subscribed documents and folders - $aFullList = array_merge(KTrss::getDocuments($id), KTrss::getFolders($id)); - $internalFeed = KTrss::arrayToXML($aFullList); - echo $internalFeed; - } -} - -// Validate user credentials -function validateUser($username, $password){ - return DBAuthenticator::checkPassword($username, $password); -} -?> +'id',)); + $id = $user[$_SERVER['PHP_AUTH_USER']]['id']; + + + if(KTUtil::arrayGet($_REQUEST, 'docId')){ // if a docId parameter is passed + // get document id from http request object + $iDocumentId = KTUtil::arrayGet($_REQUEST, 'docId'); + + if(KTrss::validateDocumentPermissions($id, $iDocumentId)){ // if document passes validation check + // get document info + $aDocumentInfo[] = KTrss::getOneDocument($iDocumentId, $id); + + if($aDocumentInfo){ + // create rss xml for document + $documentFeed = KTrss::arrayToXML($aDocumentInfo); + }else{ + // create rss xml for the error + $error = KTrss::errorToXML(_kt('This document has returned a empty response')); + } + }else{ + // create rss xml for error + $error = KTrss::errorToXML(_kt('You are either not authorised to view details on this document or it does not exist.' . + ' Please visit http://' .$_SERVER['HTTP_HOST'].'/'.$GLOBALS['KTRootUrl'].'/ to browse for a valid document.')); + } + if(isset($error)){ // if an error exist, output...else out the result + echo $error; + }else{ + echo $documentFeed; + } + }elseif(KTUtil::arrayGet($_REQUEST, 'folderId')){ // if a folderId parameter is passed + // get folder id from http request object + $iFolderId = KTUtil::arrayGet($_REQUEST, 'folderId'); + + if(KTrss::validateFolderPermissions($id, $iFolderId)){ // if folder passes validation check + // get folder info + $aFolderInfo[] = KTrss::getOneFolder($iFolderId); + + if($aFolderInfo){ + // create rss xml for folder + $folderFeed = KTrss::arrayToXML($aFolderInfo); + }else{ + // create rss xml for error + $error = KTrss::errorToXML(_kt('This document has returned a empty response')); + } + }else{ + // create rss xml for error + $error = KTrss::errorToXML(_kt('You are either not authorised to view details on this folder or it does not exist.' . + ' Please visit http://' .$_SERVER['HTTP_HOST'].'/'.$GLOBALS['KTRootUrl'].'/ to browse for a valid folder.')); + } + if(isset($error)){ // if an error exist, output...else out the result + echo $error; + }else{ + echo $folderFeed; + } + }else{ // else do normal rss parsing + // get full list of subscribed documents and folders + $aFullList = array_merge(KTrss::getDocuments($id), KTrss::getFolders($id)); + $internalFeed = KTrss::arrayToXML($aFullList); + echo $internalFeed; + } +} + +// Validate user credentials +function validateUser($username, $password){ + return DBAuthenticator::checkPassword($username, $password); +} +?> diff --git a/sql/mysql/install/rebuild.bat b/sql/mysql/install/rebuild.bat index 961155d..bf56b25 100644 --- a/sql/mysql/install/rebuild.bat +++ b/sql/mysql/install/rebuild.bat @@ -1,21 +1,21 @@ -@ECHO OFF -CLS -ECHO. -FOR /F "tokens=5* delims= " %%A IN ('VOL C: ^| FIND "drive C"') DO SET OLDLABEL=%%B -ECHO Enter name of database (default is dms): -FOR /F "TOKENS=*" %%? IN ('LABEL C: 2^>NUL') DO SET INPUT=%%? -SET INPUT -CLS -LABEL C: %OLDLABEL% -PAUSE -CLS -ECHO ---- Dropping database %INPUT% ---- -mysqladmin -u root -p -f drop %INPUT% -ECHO ---- Creating database %INPUT% ---- -mysqladmin -u root -p create %INPUT% -ECHO ---- Creating structure for database %INPUT% ---- -mysql -u root %INPUT%NUL') DO SET INPUT=%%? +SET INPUT +CLS +LABEL C: %OLDLABEL% +PAUSE +CLS +ECHO ---- Dropping database %INPUT% ---- +mysqladmin -u root -p -f drop %INPUT% +ECHO ---- Creating database %INPUT% ---- +mysqladmin -u root -p create %INPUT% +ECHO ---- Creating structure for database %INPUT% ---- +mysql -u root %INPUT%get("ui/morphTo")}/title_bullet.png{else}{$rootUrl}/resources/graphics/title_bullet.png{/if}"/>{i18n}Generate PDF of{/i18n}:
{$context->oDocument->getName()} - -{$form->render()} +

get("ui/morphTo")}/title_bullet.png{else}{$rootUrl}/resources/graphics/title_bullet.png{/if}"/>{i18n}Generate PDF of{/i18n}:
{$context->oDocument->getName()}

+ +{$form->render()} diff --git a/templates/ktstandard/ktwebdavdashlet/dashlet.smarty b/templates/ktstandard/ktwebdavdashlet/dashlet.smarty index 25a74ba..16c86c9 100644 --- a/templates/ktstandard/ktwebdavdashlet/dashlet.smarty +++ b/templates/ktstandard/ktwebdavdashlet/dashlet.smarty @@ -1,8 +1,8 @@ -
-

{i18n arg_appname="$appname"}To connect to #appname# via a third-party WebDAV client, please use the following address{/i18n}:
-{$url}ktwebdav/ktwebdav.php

-{i18n arg_appname="$appname"}To connect with the #appname# Tools Suite, use this address{/i18n}:
-{$url}

-

-
- +
+

{i18n arg_appname="$appname"}To connect to #appname# via a third-party WebDAV client, please use the following address{/i18n}:
+{$url}ktwebdav/ktwebdav.php

+{i18n arg_appname="$appname"}To connect with the #appname# Tools Suite, use this address{/i18n}:
+{$url}

+

+
+ diff --git a/thirdparty/pear/Console/Getopt.php b/thirdparty/pear/Console/Getopt.php index 7966d1a..52b2dea 100644 --- a/thirdparty/pear/Console/Getopt.php +++ b/thirdparty/pear/Console/Getopt.php @@ -16,7 +16,7 @@ // | Author: Andrei Zmievski | // +----------------------------------------------------------------------+ // -// $Id: Getopt.php,v 1.21.4.7 2003/12/05 21:57:01 andrei Exp $ +// $Id$ require_once 'PEAR.php'; diff --git a/thirdparty/pear/GraphViz.php b/thirdparty/pear/GraphViz.php index b439ad4..5224018 100644 --- a/thirdparty/pear/GraphViz.php +++ b/thirdparty/pear/GraphViz.php @@ -21,7 +21,7 @@ * @author Michael Lively Jr. * @copyright 2001-2006 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id: GraphViz.php,v 1.25 2006/05/16 15:49:19 sebastian Exp $ + * @version CVS: $Id$ * @link http://pear.php.net/package/Image_GraphViz * @since File available since Release 0.1 */ diff --git a/thirdparty/pear/HTTP/Client.php b/thirdparty/pear/HTTP/Client.php index 5708cc3..dc6bfac 100644 --- a/thirdparty/pear/HTTP/Client.php +++ b/thirdparty/pear/HTTP/Client.php @@ -16,7 +16,7 @@ // | Author: Alexey Borzov | // +----------------------------------------------------------------------+ // -// $Id: Client.php,v 1.4 2004/03/23 13:35:37 avb Exp $ +// $Id$ require_once 'HTTP/Request.php'; require_once 'HTTP/Client/CookieManager.php'; @@ -29,7 +29,7 @@ require_once 'HTTP/Client/CookieManager.php'; * * @package HTTP_Client * @author Alexey Borzov - * @version $Revision: 1.4 $ + * @version $Revision$ */ class HTTP_Client { diff --git a/thirdparty/pear/HTTP/Client/CookieManager.php b/thirdparty/pear/HTTP/Client/CookieManager.php index 3b9abb2..407bdca 100644 --- a/thirdparty/pear/HTTP/Client/CookieManager.php +++ b/thirdparty/pear/HTTP/Client/CookieManager.php @@ -16,14 +16,14 @@ // | Author: Alexey Borzov | // +----------------------------------------------------------------------+ // -// $Id: CookieManager.php,v 1.3 2004/04/10 10:04:52 avb Exp $ +// $Id$ /** * This class is used to store cookies and pass them between HTTP requests. * * @package HTTP_Client * @author Alexey Borzov - * @version $Revision: 1.3 $ + * @version $Revision$ */ class HTTP_Client_CookieManager { diff --git a/thirdparty/pear/HTTP/Download.php b/thirdparty/pear/HTTP/Download.php index 51d496a..04e8c8d 100644 --- a/thirdparty/pear/HTTP/Download.php +++ b/thirdparty/pear/HTTP/Download.php @@ -1,1031 +1,1031 @@ - - * @copyright 2003-2005 Michael Wallner - * @license BSD, revised - * @version CVS: $Id: Download.php,v 1.75 2005/11/13 19:18:53 mike Exp $ - * @link http://pear.php.net/package/HTTP_Download - */ - -// {{{ includes -/** - * Requires PEAR - */ -require_once 'PEAR.php'; - -/** - * Requires HTTP_Header - */ -require_once 'HTTP/Header.php'; -// }}} - -// {{{ constants -/**#@+ Use with HTTP_Download::setContentDisposition() **/ -/** - * Send data as attachment - */ -define('HTTP_DOWNLOAD_ATTACHMENT', 'attachment'); -/** - * Send data inline - */ -define('HTTP_DOWNLOAD_INLINE', 'inline'); -/**#@-**/ - -/**#@+ Use with HTTP_Download::sendArchive() **/ -/** - * Send as uncompressed tar archive - */ -define('HTTP_DOWNLOAD_TAR', 'TAR'); -/** - * Send as gzipped tar archive - */ -define('HTTP_DOWNLOAD_TGZ', 'TGZ'); -/** - * Send as bzip2 compressed tar archive - */ -define('HTTP_DOWNLOAD_BZ2', 'BZ2'); -/** - * Send as zip archive - */ -define('HTTP_DOWNLOAD_ZIP', 'ZIP'); -/**#@-**/ - -/**#@+ - * Error constants - */ -define('HTTP_DOWNLOAD_E_HEADERS_SENT', -1); -define('HTTP_DOWNLOAD_E_NO_EXT_ZLIB', -2); -define('HTTP_DOWNLOAD_E_NO_EXT_MMAGIC', -3); -define('HTTP_DOWNLOAD_E_INVALID_FILE', -4); -define('HTTP_DOWNLOAD_E_INVALID_PARAM', -5); -define('HTTP_DOWNLOAD_E_INVALID_RESOURCE', -6); -define('HTTP_DOWNLOAD_E_INVALID_REQUEST', -7); -define('HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE', -8); -define('HTTP_DOWNLOAD_E_INVALID_ARCHIVE_TYPE', -9); -/**#@-**/ -// }}} - -/** - * Send HTTP Downloads/Responses. - * - * With this package you can handle (hidden) downloads. - * It supports partial downloads, resuming and sending - * raw data ie. from database BLOBs. - * - * ATTENTION: - * You shouldn't use this package together with ob_gzhandler or - * zlib.output_compression enabled in your php.ini, especially - * if you want to send already gzipped data! - * - * @access public - * @version $Revision: 1.75 $ - */ -class HTTP_Download -{ - // {{{ protected member variables - /** - * Path to file for download - * - * @see HTTP_Download::setFile() - * @access protected - * @var string - */ - var $file = ''; - - /** - * Data for download - * - * @see HTTP_Download::setData() - * @access protected - * @var string - */ - var $data = null; - - /** - * Resource handle for download - * - * @see HTTP_Download::setResource() - * @access protected - * @var int - */ - var $handle = null; - - /** - * Whether to gzip the download - * - * @access protected - * @var bool - */ - var $gzip = false; - - /** - * Whether to allow caching of the download on the clients side - * - * @access protected - * @var bool - */ - var $cache = true; - - /** - * Size of download - * - * @access protected - * @var int - */ - var $size = 0; - - /** - * Last modified - * - * @access protected - * @var int - */ - var $lastModified = 0; - - /** - * HTTP headers - * - * @access protected - * @var array - */ - var $headers = array( - 'Content-Type' => 'application/x-octetstream', - 'Pragma' => 'cache', - 'Cache-Control' => 'public, must-revalidate, max-age=0', - 'Accept-Ranges' => 'bytes', - 'X-Sent-By' => 'PEAR::HTTP::Download' - ); - - /** - * HTTP_Header - * - * @access protected - * @var object - */ - var $HTTP = null; - - /** - * ETag - * - * @access protected - * @var string - */ - var $etag = ''; - - /** - * Buffer Size - * - * @access protected - * @var int - */ - var $bufferSize = 2097152; - - /** - * Throttle Delay - * - * @access protected - * @var float - */ - var $throttleDelay = 0; - - /** - * Sent Bytes - * - * @access public - * @var int - */ - var $sentBytes = 0; - // }}} - - // {{{ constructor - /** - * Constructor - * - * Set supplied parameters. - * - * @access public - * @param array $params associative array of parameters - * - * one of: - * o 'file' => path to file for download - * o 'data' => raw data for download - * o 'resource' => resource handle for download - *
- * and any of: - * o 'cache' => whether to allow cs caching - * o 'gzip' => whether to gzip the download - * o 'lastmodified' => unix timestamp - * o 'contenttype' => content type of download - * o 'contentdisposition' => content disposition - * o 'buffersize' => amount of bytes to buffer - * o 'throttledelay' => amount of secs to sleep - * o 'cachecontrol' => cache privacy and validity - * - *
- * 'Content-Disposition' is not HTTP compliant, but most browsers - * follow this header, so it was borrowed from MIME standard. - * - * It looks like this:
- * "Content-Disposition: attachment; filename=example.tgz". - * - * @see HTTP_Download::setContentDisposition() - */ - function HTTP_Download($params = array()) - { - $this->HTTP = &new HTTP_Header; - $this->setParams($params); - } - // }}} - - // {{{ public methods - /** - * Set parameters - * - * Set supplied parameters through its accessor methods. - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param array $params associative array of parameters - * - * @see HTTP_Download::HTTP_Download() - */ - function setParams($params) - { - foreach((array) $params as $param => $value){ - $method = 'set'. $param; - - if (!method_exists($this, $method)) { - return PEAR::raiseError( - "Method '$method' doesn't exist.", - HTTP_DOWNLOAD_E_INVALID_PARAM - ); - } - - $e = call_user_func_array(array(&$this, $method), (array) $value); - - if (PEAR::isError($e)) { - return $e; - } - } - return true; - } - - /** - * Set path to file for download - * - * The Last-Modified header will be set to files filemtime(), actually. - * Returns PEAR_Error (HTTP_DOWNLOAD_E_INVALID_FILE) if file doesn't exist. - * Sends HTTP 404 status if $send_404 is set to true. - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param string $file path to file for download - * @param bool $send_404 whether to send HTTP/404 if - * the file wasn't found - */ - function setFile($file, $send_404 = true) - { - $file = realpath($file); - if (!is_file($file)) { - if ($send_404) { - $this->HTTP->sendStatusCode(404); - } - return PEAR::raiseError( - "File '$file' not found.", - HTTP_DOWNLOAD_E_INVALID_FILE - ); - } - $this->setLastModified(filemtime($file)); - $this->file = $file; - $this->size = filesize($file); - return true; - } - - /** - * Set data for download - * - * Set $data to null if you want to unset this. - * - * @access public - * @return void - * @param $data raw data to send - */ - function setData($data = null) - { - $this->data = $data; - $this->size = strlen($data); - } - - /** - * Set resource for download - * - * The resource handle supplied will be closed after sending the download. - * Returns a PEAR_Error (HTTP_DOWNLOAD_E_INVALID_RESOURCE) if $handle - * is no valid resource. Set $handle to null if you want to unset this. - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param int $handle resource handle - */ - function setResource($handle = null) - { - if (!isset($handle)) { - $this->handle = null; - $this->size = 0; - return true; - } - - if (is_resource($handle)) { - $this->handle = $handle; - $filestats = fstat($handle); - $this->size = $filestats['size']; - return true; - } - - return PEAR::raiseError( - "Handle '$handle' is no valid resource.", - HTTP_DOWNLOAD_E_INVALID_RESOURCE - ); - } - - /** - * Whether to gzip the download - * - * Returns a PEAR_Error (HTTP_DOWNLOAD_E_NO_EXT_ZLIB) - * if ext/zlib is not available/loadable. - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param bool $gzip whether to gzip the download - */ - function setGzip($gzip = false) - { - if ($gzip && !PEAR::loadExtension('zlib')){ - return PEAR::raiseError( - 'GZIP compression (ext/zlib) not available.', - HTTP_DOWNLOAD_E_NO_EXT_ZLIB - ); - } - $this->gzip = (bool) $gzip; - return true; - } - - /** - * Whether to allow caching - * - * If set to true (default) we'll send some headers that are commonly - * used for caching purposes like ETag, Cache-Control and Last-Modified. - * - * If caching is disabled, we'll send the download no matter if it - * would actually be cached at the client side. - * - * @access public - * @return void - * @param bool $cache whether to allow caching - */ - function setCache($cache = true) - { - $this->cache = (bool) $cache; - } - - /** - * Whether to allow proxies to cache - * - * If set to 'private' proxies shouldn't cache the response. - * This setting defaults to 'public' and affects only cached responses. - * - * @access public - * @return bool - * @param string $cache private or public - * @param int $maxage maximum age of the client cache entry - */ - function setCacheControl($cache = 'public', $maxage = 0) - { - switch ($cache = strToLower($cache)) - { - case 'private': - case 'public': - $this->headers['Cache-Control'] = - $cache .', must-revalidate, max-age='. abs($maxage); - return true; - break; - } - return false; - } - - /** - * Set ETag - * - * Sets a user-defined ETag for cache-validation. The ETag is usually - * generated by HTTP_Download through its payload information. - * - * @access public - * @return void - * @param string $etag Entity tag used for strong cache validation. - */ - function setETag($etag = null) - { - $this->etag = (string) $etag; - } - - /** - * Set Size of Buffer - * - * The amount of bytes specified as buffer size is the maximum amount - * of data read at once from resources or files. The default size is 2M - * (2097152 bytes). Be aware that if you enable gzip compression and - * you set a very low buffer size that the actual file size may grow - * due to added gzip headers for each sent chunk of the specified size. - * - * Returns PEAR_Error (HTTP_DOWNLOAD_E_INVALID_PARAM) if $size is not - * greater than 0 bytes. - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param int $bytes Amount of bytes to use as buffer. - */ - function setBufferSize($bytes = 2097152) - { - if (0 >= $bytes) { - return PEAR::raiseError( - 'Buffer size must be greater than 0 bytes ('. $bytes .' given)', - HTTP_DOWNLOAD_E_INVALID_PARAM); - } - $this->bufferSize = abs($bytes); - return true; - } - - /** - * Set Throttle Delay - * - * Set the amount of seconds to sleep after each chunck that has been - * sent. One can implement some sort of throttle through adjusting the - * buffer size and the throttle delay. With the following settings - * HTTP_Download will sleep a second after each 25 K of data sent. - * - * - * Array( - * 'throttledelay' => 1, - * 'buffersize' => 1024 * 25, - * ) - * - * - * Just be aware that if gzipp'ing is enabled, decreasing the chunk size - * too much leads to proportionally increased network traffic due to added - * gzip header and bottom bytes around each chunk. - * - * @access public - * @return void - * @param float $seconds Amount of seconds to sleep after each - * chunk that has been sent. - */ - function setThrottleDelay($seconds = 0) - { - $this->throttleDelay = abs($seconds) * 1000; - } - - /** - * Set "Last-Modified" - * - * This is usually determined by filemtime() in HTTP_Download::setFile() - * If you set raw data for download with HTTP_Download::setData() and you - * want do send an appropiate "Last-Modified" header, you should call this - * method. - * - * @access public - * @return void - * @param int unix timestamp - */ - function setLastModified($last_modified) - { - $this->lastModified = $this->headers['Last-Modified'] = (int) $last_modified; - } - - /** - * Set Content-Disposition header - * - * @see HTTP_Download::HTTP_Download - * - * @access public - * @return void - * @param string $disposition whether to send the download - * inline or as attachment - * @param string $file_name the filename to display in - * the browser's download window - * - * Example: - * - * $HTTP_Download->setContentDisposition( - * HTTP_DOWNLOAD_ATTACHMENT, - * 'download.tgz' - * ); - * - */ - function setContentDisposition( $disposition = HTTP_DOWNLOAD_ATTACHMENT, - $file_name = null) - { - $cd = $disposition; - if (isset($file_name)) { - $cd .= '; filename="' . $file_name . '"'; - } elseif ($this->file) { - $cd .= '; filename="' . basename($this->file) . '"'; - } - $this->headers['Content-Disposition'] = $cd; - } - - /** - * Set content type of the download - * - * Default content type of the download will be 'application/x-octetstream'. - * Returns PEAR_Error (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE) if - * $content_type doesn't seem to be valid. - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param string $content_type content type of file for download - */ - function setContentType($content_type = 'application/x-octetstream') - { - if (!preg_match('/^[a-z]+\w*\/[a-z]+[\w.;= -]*$/', $content_type)) { - return PEAR::raiseError( - "Invalid content type '$content_type' supplied.", - HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE - ); - } - $this->headers['Content-Type'] = $content_type; - return true; - } - - /** - * Guess content type of file - * - * First we try to use PEAR::MIME_Type, if installed, to detect the content - * type, else we check if ext/mime_magic is loaded and properly configured. - * - * Returns PEAR_Error if: - * o if PEAR::MIME_Type failed to detect a proper content type - * (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE) - * o ext/magic.mime is not installed, or not properly configured - * (HTTP_DOWNLOAD_E_NO_EXT_MMAGIC) - * o mime_content_type() couldn't guess content type or returned - * a content type considered to be bogus by setContentType() - * (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE) - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - */ - function guessContentType() - { - if (class_exists('MIME_Type') || @include_once 'MIME/Type.php') { - if (PEAR::isError($mime_type = MIME_Type::autoDetect($this->file))) { - return PEAR::raiseError($mime_type->getMessage(), - HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE); - } - return $this->setContentType($mime_type); - } - if (!function_exists('mime_content_type')) { - return PEAR::raiseError( - 'This feature requires ext/mime_magic!', - HTTP_DOWNLOAD_E_NO_EXT_MMAGIC - ); - } - if (!is_file(ini_get('mime_magic.magicfile'))) { - return PEAR::raiseError( - 'ext/mime_magic is loaded but not properly configured!', - HTTP_DOWNLOAD_E_NO_EXT_MMAGIC - ); - } - if (!$content_type = @mime_content_type($this->file)) { - return PEAR::raiseError( - 'Couldn\'t guess content type with mime_content_type().', - HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE - ); - } - return $this->setContentType($content_type); - } - - /** - * Send - * - * Returns PEAR_Error if: - * o HTTP headers were already sent (HTTP_DOWNLOAD_E_HEADERS_SENT) - * o HTTP Range was invalid (HTTP_DOWNLOAD_E_INVALID_REQUEST) - * - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param bool $autoSetContentDisposition Whether to set the - * Content-Disposition header if it isn't already. - */ - function send($autoSetContentDisposition = true) - { - if (headers_sent()) { - return PEAR::raiseError( - 'Headers already sent.', - HTTP_DOWNLOAD_E_HEADERS_SENT - ); - } - - if (!ini_get('safe_mode')) { - @set_time_limit(0); - } - - if ($autoSetContentDisposition && - !isset($this->headers['Content-Disposition'])) { - $this->setContentDisposition(); - } - - if ($this->cache) { - $this->headers['ETag'] = $this->generateETag(); - if ($this->isCached()) { - $this->HTTP->sendStatusCode(304); - $this->sendHeaders(); - return true; - } - } else { - unset($this->headers['Last-Modified']); - } - - while (@ob_end_clean()); - - if ($this->gzip) { - @ob_start('ob_gzhandler'); - } else { - ob_start(); - } - - $this->sentBytes = 0; - - if ($this->isRangeRequest()) { - $this->HTTP->sendStatusCode(206); - $chunks = $this->getChunks(); - } else { - $this->HTTP->sendStatusCode(200); - $chunks = array(array(0, $this->size)); - if (!$this->gzip && count(ob_list_handlers()) < 2) { - $this->headers['Content-Length'] = $this->size; - } - } - - if (PEAR::isError($e = $this->sendChunks($chunks))) { - ob_end_clean(); - $this->HTTP->sendStatusCode(416); - return $e; - } - - ob_end_flush(); - flush(); - return true; - } - - /** - * Static send - * - * @see HTTP_Download::HTTP_Download() - * @see HTTP_Download::send() - * - * @static - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param array $params associative array of parameters - * @param bool $guess whether HTTP_Download::guessContentType() - * should be called - */ - function staticSend($params, $guess = false) - { - $d = &new HTTP_Download(); - $e = $d->setParams($params); - if (PEAR::isError($e)) { - return $e; - } - if ($guess) { - $e = $d->guessContentType(); - if (PEAR::isError($e)) { - return $e; - } - } - return $d->send(); - } - - /** - * Send a bunch of files or directories as an archive - * - * Example: - * - * require_once 'HTTP/Download.php'; - * HTTP_Download::sendArchive( - * 'myArchive.tgz', - * '/var/ftp/pub/mike', - * HTTP_DOWNLOAD_TGZ, - * '', - * '/var/ftp/pub' - * ); - * - * - * @see Archive_Tar::createModify() - * @deprecated use HTTP_Download_Archive::send() - * @static - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param string $name name the sent archive should have - * @param mixed $files files/directories - * @param string $type archive type - * @param string $add_path path that should be prepended to the files - * @param string $strip_path path that should be stripped from the files - */ - function sendArchive( $name, - $files, - $type = HTTP_DOWNLOAD_TGZ, - $add_path = '', - $strip_path = '') - { - require_once 'HTTP/Download/Archive.php'; - return HTTP_Download_Archive::send($name, $files, $type, - $add_path, $strip_path); - } - // }}} - - // {{{ protected methods - /** - * Generate ETag - * - * @access protected - * @return string - */ - function generateETag() - { - if (!$this->etag) { - if ($this->data) { - $md5 = md5($this->data); - } else { - $fst = is_resource($this->handle) ? - fstat($this->handle) : stat($this->file); - $md5 = md5($fst['mtime'] .'='. $fst['ino'] .'='. $fst['size']); - } - $this->etag = '"' . $md5 . '-' . crc32($md5) . '"'; - } - return $this->etag; - } - - /** - * Send multiple chunks - * - * @access protected - * @return mixed Returns true on success or PEAR_Error on failure. - * @param array $chunks - */ - function sendChunks($chunks) - { - if (count($chunks) == 1) { - return $this->sendChunk(array_shift($chunks)); - } - - $bound = uniqid('HTTP_DOWNLOAD-', true); - $cType = $this->headers['Content-Type']; - $this->headers['Content-Type'] = - 'multipart/byteranges; boundary=' . $bound; - $this->sendHeaders(); - foreach ($chunks as $chunk){ - if (PEAR::isError($e = $this->sendChunk($chunk, $cType, $bound))) { - return $e; - } - } - #echo "\r\n--$bound--\r\n"; - return true; - } - - /** - * Send chunk of data - * - * @access protected - * @return mixed Returns true on success or PEAR_Error on failure. - * @param array $chunk start and end offset of the chunk to send - * @param string $cType actual content type - * @param string $bound boundary for multipart/byteranges - */ - function sendChunk($chunk, $cType = null, $bound = null) - { - list($offset, $lastbyte) = $chunk; - $length = ($lastbyte - $offset) + 1; - - if ($length < 1) { - return PEAR::raiseError( - "Error processing range request: $offset-$lastbyte/$length", - HTTP_DOWNLOAD_E_INVALID_REQUEST - ); - } - - $range = $offset . '-' . $lastbyte . '/' . $this->size; - - if (isset($cType, $bound)) { - echo "\r\n--$bound\r\n", - "Content-Type: $cType\r\n", - "Content-Range: bytes $range\r\n\r\n"; - } else { - if ($this->isRangeRequest()) { - $this->headers['Content-Range'] = 'bytes '. $range; - } - $this->sendHeaders(); - } - - if ($this->data) { - while (($length -= $this->bufferSize) > 0) { - $this->flush(substr($this->data, $offset, $this->bufferSize)); - $this->throttleDelay and $this->sleep(); - $offset += $this->bufferSize; - } - if ($length) { - $this->flush(substr($this->data, $offset, $this->bufferSize + $length)); - } - } else { - if (!is_resource($this->handle)) { - $this->handle = fopen($this->file, 'rb'); - } - fseek($this->handle, $offset); - while (($length -= $this->bufferSize) > 0) { - $this->flush(fread($this->handle, $this->bufferSize)); - $this->throttleDelay and $this->sleep(); - } - if ($length) { - $this->flush(fread($this->handle, $this->bufferSize + $length)); - } - } - return true; - } - - /** - * Get chunks to send - * - * @access protected - * @return array - */ - function getChunks() - { - $parts = array(); - foreach (explode(',', $this->getRanges()) as $chunk){ - list($o, $e) = explode('-', $chunk); - if ($e >= $this->size || (empty($e) && $e !== 0 && $e !== '0')) { - $e = $this->size - 1; - } - if (empty($o) && $o !== 0 && $o !== '0') { - $o = $this->size - $e; - $e = $this->size - 1; - } - $parts[] = array($o, $e); - } - return $parts; - } - - /** - * Check if range is requested - * - * @access protected - * @return bool - */ - function isRangeRequest() - { - if (!isset($_SERVER['HTTP_RANGE'])) { - return false; - } - return $this->isValidRange(); - } - - /** - * Get range request - * - * @access protected - * @return array - */ - function getRanges() - { - return preg_match('/^bytes=((\d*-\d*,? ?)+)$/', - @$_SERVER['HTTP_RANGE'], $matches) ? $matches[1] : array(); - } - - /** - * Check if entity is cached - * - * @access protected - * @return bool - */ - function isCached() - { - return ( - (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && - $this->lastModified == strtotime(current($a = explode( - ';', $_SERVER['HTTP_IF_MODIFIED_SINCE'])))) || - (isset($_SERVER['HTTP_IF_NONE_MATCH']) && - $this->compareAsterisk('HTTP_IF_NONE_MATCH', $this->etag)) - ); - } - - /** - * Check if entity hasn't changed - * - * @access protected - * @return bool - */ - function isValidRange() - { - if (isset($_SERVER['HTTP_IF_MATCH']) && - !$this->compareAsterisk('HTTP_IF_MATCH', $this->etag)) { - return false; - } - if (isset($_SERVER['HTTP_IF_RANGE']) && - $_SERVER['HTTP_IF_RANGE'] !== $this->etag && - strtotime($_SERVER['HTTP_IF_RANGE']) !== $this->lastModified) { - return false; - } - if (isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE'])) { - $lm = array_shift(explode(';', $_SERVER['HTTP_IF_UNMODIFIED_SINCE'])); - if (strtotime($lm) !== $this->lastModified) { - return false; - } - } - if (isset($_SERVER['HTTP_UNLESS_MODIFIED_SINCE'])) { - $lm = array_shift(explode(';', $_SERVER['HTTP_UNLESS_MODIFIED_SINCE'])); - if (strtotime($lm) !== $this->lastModified) { - return false; - } - } - return true; - } - - /** - * Compare against an asterisk or check for equality - * - * @access protected - * @return bool - * @param string key for the $_SERVER array - * @param string string to compare - */ - function compareAsterisk($svar, $compare) - { - foreach (array_map('trim', explode(',', $_SERVER[$svar])) as $request) { - if ($request === '*' || $request === $compare) { - return true; - } - } - return false; - } - - /** - * Send HTTP headers - * - * @access protected - * @return void - */ - function sendHeaders() - { - foreach ($this->headers as $header => $value) { - $this->HTTP->setHeader($header, $value); - } - $this->HTTP->sendHeaders(); - /* NSAPI won't output anything if we did this */ - if (strncasecmp(PHP_SAPI, 'nsapi', 5)) { - ob_flush(); - flush(); - } - } - - /** - * Flush - * - * @access protected - * @return void - * @param string $data - */ - function flush($data = '') - { - if ($dlen = strlen($data)) { - $this->sentBytes += $dlen; - echo $data; - } - ob_flush(); - flush(); - } - - /** - * Sleep - * - * @access protected - * @return void - */ - function sleep() - { - if (OS_WINDOWS) { - com_message_pump($this->throttleDelay); - } else { - usleep($this->throttleDelay * 1000); - } - } - // }}} -} -?> + + * @copyright 2003-2005 Michael Wallner + * @license BSD, revised + * @version CVS: $Id$ + * @link http://pear.php.net/package/HTTP_Download + */ + +// {{{ includes +/** + * Requires PEAR + */ +require_once 'PEAR.php'; + +/** + * Requires HTTP_Header + */ +require_once 'HTTP/Header.php'; +// }}} + +// {{{ constants +/**#@+ Use with HTTP_Download::setContentDisposition() **/ +/** + * Send data as attachment + */ +define('HTTP_DOWNLOAD_ATTACHMENT', 'attachment'); +/** + * Send data inline + */ +define('HTTP_DOWNLOAD_INLINE', 'inline'); +/**#@-**/ + +/**#@+ Use with HTTP_Download::sendArchive() **/ +/** + * Send as uncompressed tar archive + */ +define('HTTP_DOWNLOAD_TAR', 'TAR'); +/** + * Send as gzipped tar archive + */ +define('HTTP_DOWNLOAD_TGZ', 'TGZ'); +/** + * Send as bzip2 compressed tar archive + */ +define('HTTP_DOWNLOAD_BZ2', 'BZ2'); +/** + * Send as zip archive + */ +define('HTTP_DOWNLOAD_ZIP', 'ZIP'); +/**#@-**/ + +/**#@+ + * Error constants + */ +define('HTTP_DOWNLOAD_E_HEADERS_SENT', -1); +define('HTTP_DOWNLOAD_E_NO_EXT_ZLIB', -2); +define('HTTP_DOWNLOAD_E_NO_EXT_MMAGIC', -3); +define('HTTP_DOWNLOAD_E_INVALID_FILE', -4); +define('HTTP_DOWNLOAD_E_INVALID_PARAM', -5); +define('HTTP_DOWNLOAD_E_INVALID_RESOURCE', -6); +define('HTTP_DOWNLOAD_E_INVALID_REQUEST', -7); +define('HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE', -8); +define('HTTP_DOWNLOAD_E_INVALID_ARCHIVE_TYPE', -9); +/**#@-**/ +// }}} + +/** + * Send HTTP Downloads/Responses. + * + * With this package you can handle (hidden) downloads. + * It supports partial downloads, resuming and sending + * raw data ie. from database BLOBs. + * + * ATTENTION: + * You shouldn't use this package together with ob_gzhandler or + * zlib.output_compression enabled in your php.ini, especially + * if you want to send already gzipped data! + * + * @access public + * @version $Revision$ + */ +class HTTP_Download +{ + // {{{ protected member variables + /** + * Path to file for download + * + * @see HTTP_Download::setFile() + * @access protected + * @var string + */ + var $file = ''; + + /** + * Data for download + * + * @see HTTP_Download::setData() + * @access protected + * @var string + */ + var $data = null; + + /** + * Resource handle for download + * + * @see HTTP_Download::setResource() + * @access protected + * @var int + */ + var $handle = null; + + /** + * Whether to gzip the download + * + * @access protected + * @var bool + */ + var $gzip = false; + + /** + * Whether to allow caching of the download on the clients side + * + * @access protected + * @var bool + */ + var $cache = true; + + /** + * Size of download + * + * @access protected + * @var int + */ + var $size = 0; + + /** + * Last modified + * + * @access protected + * @var int + */ + var $lastModified = 0; + + /** + * HTTP headers + * + * @access protected + * @var array + */ + var $headers = array( + 'Content-Type' => 'application/x-octetstream', + 'Pragma' => 'cache', + 'Cache-Control' => 'public, must-revalidate, max-age=0', + 'Accept-Ranges' => 'bytes', + 'X-Sent-By' => 'PEAR::HTTP::Download' + ); + + /** + * HTTP_Header + * + * @access protected + * @var object + */ + var $HTTP = null; + + /** + * ETag + * + * @access protected + * @var string + */ + var $etag = ''; + + /** + * Buffer Size + * + * @access protected + * @var int + */ + var $bufferSize = 2097152; + + /** + * Throttle Delay + * + * @access protected + * @var float + */ + var $throttleDelay = 0; + + /** + * Sent Bytes + * + * @access public + * @var int + */ + var $sentBytes = 0; + // }}} + + // {{{ constructor + /** + * Constructor + * + * Set supplied parameters. + * + * @access public + * @param array $params associative array of parameters + * + * one of: + * o 'file' => path to file for download + * o 'data' => raw data for download + * o 'resource' => resource handle for download + *
+ * and any of: + * o 'cache' => whether to allow cs caching + * o 'gzip' => whether to gzip the download + * o 'lastmodified' => unix timestamp + * o 'contenttype' => content type of download + * o 'contentdisposition' => content disposition + * o 'buffersize' => amount of bytes to buffer + * o 'throttledelay' => amount of secs to sleep + * o 'cachecontrol' => cache privacy and validity + * + *
+ * 'Content-Disposition' is not HTTP compliant, but most browsers + * follow this header, so it was borrowed from MIME standard. + * + * It looks like this:
+ * "Content-Disposition: attachment; filename=example.tgz". + * + * @see HTTP_Download::setContentDisposition() + */ + function HTTP_Download($params = array()) + { + $this->HTTP = &new HTTP_Header; + $this->setParams($params); + } + // }}} + + // {{{ public methods + /** + * Set parameters + * + * Set supplied parameters through its accessor methods. + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param array $params associative array of parameters + * + * @see HTTP_Download::HTTP_Download() + */ + function setParams($params) + { + foreach((array) $params as $param => $value){ + $method = 'set'. $param; + + if (!method_exists($this, $method)) { + return PEAR::raiseError( + "Method '$method' doesn't exist.", + HTTP_DOWNLOAD_E_INVALID_PARAM + ); + } + + $e = call_user_func_array(array(&$this, $method), (array) $value); + + if (PEAR::isError($e)) { + return $e; + } + } + return true; + } + + /** + * Set path to file for download + * + * The Last-Modified header will be set to files filemtime(), actually. + * Returns PEAR_Error (HTTP_DOWNLOAD_E_INVALID_FILE) if file doesn't exist. + * Sends HTTP 404 status if $send_404 is set to true. + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param string $file path to file for download + * @param bool $send_404 whether to send HTTP/404 if + * the file wasn't found + */ + function setFile($file, $send_404 = true) + { + $file = realpath($file); + if (!is_file($file)) { + if ($send_404) { + $this->HTTP->sendStatusCode(404); + } + return PEAR::raiseError( + "File '$file' not found.", + HTTP_DOWNLOAD_E_INVALID_FILE + ); + } + $this->setLastModified(filemtime($file)); + $this->file = $file; + $this->size = filesize($file); + return true; + } + + /** + * Set data for download + * + * Set $data to null if you want to unset this. + * + * @access public + * @return void + * @param $data raw data to send + */ + function setData($data = null) + { + $this->data = $data; + $this->size = strlen($data); + } + + /** + * Set resource for download + * + * The resource handle supplied will be closed after sending the download. + * Returns a PEAR_Error (HTTP_DOWNLOAD_E_INVALID_RESOURCE) if $handle + * is no valid resource. Set $handle to null if you want to unset this. + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param int $handle resource handle + */ + function setResource($handle = null) + { + if (!isset($handle)) { + $this->handle = null; + $this->size = 0; + return true; + } + + if (is_resource($handle)) { + $this->handle = $handle; + $filestats = fstat($handle); + $this->size = $filestats['size']; + return true; + } + + return PEAR::raiseError( + "Handle '$handle' is no valid resource.", + HTTP_DOWNLOAD_E_INVALID_RESOURCE + ); + } + + /** + * Whether to gzip the download + * + * Returns a PEAR_Error (HTTP_DOWNLOAD_E_NO_EXT_ZLIB) + * if ext/zlib is not available/loadable. + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param bool $gzip whether to gzip the download + */ + function setGzip($gzip = false) + { + if ($gzip && !PEAR::loadExtension('zlib')){ + return PEAR::raiseError( + 'GZIP compression (ext/zlib) not available.', + HTTP_DOWNLOAD_E_NO_EXT_ZLIB + ); + } + $this->gzip = (bool) $gzip; + return true; + } + + /** + * Whether to allow caching + * + * If set to true (default) we'll send some headers that are commonly + * used for caching purposes like ETag, Cache-Control and Last-Modified. + * + * If caching is disabled, we'll send the download no matter if it + * would actually be cached at the client side. + * + * @access public + * @return void + * @param bool $cache whether to allow caching + */ + function setCache($cache = true) + { + $this->cache = (bool) $cache; + } + + /** + * Whether to allow proxies to cache + * + * If set to 'private' proxies shouldn't cache the response. + * This setting defaults to 'public' and affects only cached responses. + * + * @access public + * @return bool + * @param string $cache private or public + * @param int $maxage maximum age of the client cache entry + */ + function setCacheControl($cache = 'public', $maxage = 0) + { + switch ($cache = strToLower($cache)) + { + case 'private': + case 'public': + $this->headers['Cache-Control'] = + $cache .', must-revalidate, max-age='. abs($maxage); + return true; + break; + } + return false; + } + + /** + * Set ETag + * + * Sets a user-defined ETag for cache-validation. The ETag is usually + * generated by HTTP_Download through its payload information. + * + * @access public + * @return void + * @param string $etag Entity tag used for strong cache validation. + */ + function setETag($etag = null) + { + $this->etag = (string) $etag; + } + + /** + * Set Size of Buffer + * + * The amount of bytes specified as buffer size is the maximum amount + * of data read at once from resources or files. The default size is 2M + * (2097152 bytes). Be aware that if you enable gzip compression and + * you set a very low buffer size that the actual file size may grow + * due to added gzip headers for each sent chunk of the specified size. + * + * Returns PEAR_Error (HTTP_DOWNLOAD_E_INVALID_PARAM) if $size is not + * greater than 0 bytes. + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param int $bytes Amount of bytes to use as buffer. + */ + function setBufferSize($bytes = 2097152) + { + if (0 >= $bytes) { + return PEAR::raiseError( + 'Buffer size must be greater than 0 bytes ('. $bytes .' given)', + HTTP_DOWNLOAD_E_INVALID_PARAM); + } + $this->bufferSize = abs($bytes); + return true; + } + + /** + * Set Throttle Delay + * + * Set the amount of seconds to sleep after each chunck that has been + * sent. One can implement some sort of throttle through adjusting the + * buffer size and the throttle delay. With the following settings + * HTTP_Download will sleep a second after each 25 K of data sent. + * + * + * Array( + * 'throttledelay' => 1, + * 'buffersize' => 1024 * 25, + * ) + * + * + * Just be aware that if gzipp'ing is enabled, decreasing the chunk size + * too much leads to proportionally increased network traffic due to added + * gzip header and bottom bytes around each chunk. + * + * @access public + * @return void + * @param float $seconds Amount of seconds to sleep after each + * chunk that has been sent. + */ + function setThrottleDelay($seconds = 0) + { + $this->throttleDelay = abs($seconds) * 1000; + } + + /** + * Set "Last-Modified" + * + * This is usually determined by filemtime() in HTTP_Download::setFile() + * If you set raw data for download with HTTP_Download::setData() and you + * want do send an appropiate "Last-Modified" header, you should call this + * method. + * + * @access public + * @return void + * @param int unix timestamp + */ + function setLastModified($last_modified) + { + $this->lastModified = $this->headers['Last-Modified'] = (int) $last_modified; + } + + /** + * Set Content-Disposition header + * + * @see HTTP_Download::HTTP_Download + * + * @access public + * @return void + * @param string $disposition whether to send the download + * inline or as attachment + * @param string $file_name the filename to display in + * the browser's download window + * + * Example: + * + * $HTTP_Download->setContentDisposition( + * HTTP_DOWNLOAD_ATTACHMENT, + * 'download.tgz' + * ); + * + */ + function setContentDisposition( $disposition = HTTP_DOWNLOAD_ATTACHMENT, + $file_name = null) + { + $cd = $disposition; + if (isset($file_name)) { + $cd .= '; filename="' . $file_name . '"'; + } elseif ($this->file) { + $cd .= '; filename="' . basename($this->file) . '"'; + } + $this->headers['Content-Disposition'] = $cd; + } + + /** + * Set content type of the download + * + * Default content type of the download will be 'application/x-octetstream'. + * Returns PEAR_Error (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE) if + * $content_type doesn't seem to be valid. + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param string $content_type content type of file for download + */ + function setContentType($content_type = 'application/x-octetstream') + { + if (!preg_match('/^[a-z]+\w*\/[a-z]+[\w.;= -]*$/', $content_type)) { + return PEAR::raiseError( + "Invalid content type '$content_type' supplied.", + HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE + ); + } + $this->headers['Content-Type'] = $content_type; + return true; + } + + /** + * Guess content type of file + * + * First we try to use PEAR::MIME_Type, if installed, to detect the content + * type, else we check if ext/mime_magic is loaded and properly configured. + * + * Returns PEAR_Error if: + * o if PEAR::MIME_Type failed to detect a proper content type + * (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE) + * o ext/magic.mime is not installed, or not properly configured + * (HTTP_DOWNLOAD_E_NO_EXT_MMAGIC) + * o mime_content_type() couldn't guess content type or returned + * a content type considered to be bogus by setContentType() + * (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE) + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + */ + function guessContentType() + { + if (class_exists('MIME_Type') || @include_once 'MIME/Type.php') { + if (PEAR::isError($mime_type = MIME_Type::autoDetect($this->file))) { + return PEAR::raiseError($mime_type->getMessage(), + HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE); + } + return $this->setContentType($mime_type); + } + if (!function_exists('mime_content_type')) { + return PEAR::raiseError( + 'This feature requires ext/mime_magic!', + HTTP_DOWNLOAD_E_NO_EXT_MMAGIC + ); + } + if (!is_file(ini_get('mime_magic.magicfile'))) { + return PEAR::raiseError( + 'ext/mime_magic is loaded but not properly configured!', + HTTP_DOWNLOAD_E_NO_EXT_MMAGIC + ); + } + if (!$content_type = @mime_content_type($this->file)) { + return PEAR::raiseError( + 'Couldn\'t guess content type with mime_content_type().', + HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE + ); + } + return $this->setContentType($content_type); + } + + /** + * Send + * + * Returns PEAR_Error if: + * o HTTP headers were already sent (HTTP_DOWNLOAD_E_HEADERS_SENT) + * o HTTP Range was invalid (HTTP_DOWNLOAD_E_INVALID_REQUEST) + * + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param bool $autoSetContentDisposition Whether to set the + * Content-Disposition header if it isn't already. + */ + function send($autoSetContentDisposition = true) + { + if (headers_sent()) { + return PEAR::raiseError( + 'Headers already sent.', + HTTP_DOWNLOAD_E_HEADERS_SENT + ); + } + + if (!ini_get('safe_mode')) { + @set_time_limit(0); + } + + if ($autoSetContentDisposition && + !isset($this->headers['Content-Disposition'])) { + $this->setContentDisposition(); + } + + if ($this->cache) { + $this->headers['ETag'] = $this->generateETag(); + if ($this->isCached()) { + $this->HTTP->sendStatusCode(304); + $this->sendHeaders(); + return true; + } + } else { + unset($this->headers['Last-Modified']); + } + + while (@ob_end_clean()); + + if ($this->gzip) { + @ob_start('ob_gzhandler'); + } else { + ob_start(); + } + + $this->sentBytes = 0; + + if ($this->isRangeRequest()) { + $this->HTTP->sendStatusCode(206); + $chunks = $this->getChunks(); + } else { + $this->HTTP->sendStatusCode(200); + $chunks = array(array(0, $this->size)); + if (!$this->gzip && count(ob_list_handlers()) < 2) { + $this->headers['Content-Length'] = $this->size; + } + } + + if (PEAR::isError($e = $this->sendChunks($chunks))) { + ob_end_clean(); + $this->HTTP->sendStatusCode(416); + return $e; + } + + ob_end_flush(); + flush(); + return true; + } + + /** + * Static send + * + * @see HTTP_Download::HTTP_Download() + * @see HTTP_Download::send() + * + * @static + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param array $params associative array of parameters + * @param bool $guess whether HTTP_Download::guessContentType() + * should be called + */ + function staticSend($params, $guess = false) + { + $d = &new HTTP_Download(); + $e = $d->setParams($params); + if (PEAR::isError($e)) { + return $e; + } + if ($guess) { + $e = $d->guessContentType(); + if (PEAR::isError($e)) { + return $e; + } + } + return $d->send(); + } + + /** + * Send a bunch of files or directories as an archive + * + * Example: + * + * require_once 'HTTP/Download.php'; + * HTTP_Download::sendArchive( + * 'myArchive.tgz', + * '/var/ftp/pub/mike', + * HTTP_DOWNLOAD_TGZ, + * '', + * '/var/ftp/pub' + * ); + * + * + * @see Archive_Tar::createModify() + * @deprecated use HTTP_Download_Archive::send() + * @static + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param string $name name the sent archive should have + * @param mixed $files files/directories + * @param string $type archive type + * @param string $add_path path that should be prepended to the files + * @param string $strip_path path that should be stripped from the files + */ + function sendArchive( $name, + $files, + $type = HTTP_DOWNLOAD_TGZ, + $add_path = '', + $strip_path = '') + { + require_once 'HTTP/Download/Archive.php'; + return HTTP_Download_Archive::send($name, $files, $type, + $add_path, $strip_path); + } + // }}} + + // {{{ protected methods + /** + * Generate ETag + * + * @access protected + * @return string + */ + function generateETag() + { + if (!$this->etag) { + if ($this->data) { + $md5 = md5($this->data); + } else { + $fst = is_resource($this->handle) ? + fstat($this->handle) : stat($this->file); + $md5 = md5($fst['mtime'] .'='. $fst['ino'] .'='. $fst['size']); + } + $this->etag = '"' . $md5 . '-' . crc32($md5) . '"'; + } + return $this->etag; + } + + /** + * Send multiple chunks + * + * @access protected + * @return mixed Returns true on success or PEAR_Error on failure. + * @param array $chunks + */ + function sendChunks($chunks) + { + if (count($chunks) == 1) { + return $this->sendChunk(array_shift($chunks)); + } + + $bound = uniqid('HTTP_DOWNLOAD-', true); + $cType = $this->headers['Content-Type']; + $this->headers['Content-Type'] = + 'multipart/byteranges; boundary=' . $bound; + $this->sendHeaders(); + foreach ($chunks as $chunk){ + if (PEAR::isError($e = $this->sendChunk($chunk, $cType, $bound))) { + return $e; + } + } + #echo "\r\n--$bound--\r\n"; + return true; + } + + /** + * Send chunk of data + * + * @access protected + * @return mixed Returns true on success or PEAR_Error on failure. + * @param array $chunk start and end offset of the chunk to send + * @param string $cType actual content type + * @param string $bound boundary for multipart/byteranges + */ + function sendChunk($chunk, $cType = null, $bound = null) + { + list($offset, $lastbyte) = $chunk; + $length = ($lastbyte - $offset) + 1; + + if ($length < 1) { + return PEAR::raiseError( + "Error processing range request: $offset-$lastbyte/$length", + HTTP_DOWNLOAD_E_INVALID_REQUEST + ); + } + + $range = $offset . '-' . $lastbyte . '/' . $this->size; + + if (isset($cType, $bound)) { + echo "\r\n--$bound\r\n", + "Content-Type: $cType\r\n", + "Content-Range: bytes $range\r\n\r\n"; + } else { + if ($this->isRangeRequest()) { + $this->headers['Content-Range'] = 'bytes '. $range; + } + $this->sendHeaders(); + } + + if ($this->data) { + while (($length -= $this->bufferSize) > 0) { + $this->flush(substr($this->data, $offset, $this->bufferSize)); + $this->throttleDelay and $this->sleep(); + $offset += $this->bufferSize; + } + if ($length) { + $this->flush(substr($this->data, $offset, $this->bufferSize + $length)); + } + } else { + if (!is_resource($this->handle)) { + $this->handle = fopen($this->file, 'rb'); + } + fseek($this->handle, $offset); + while (($length -= $this->bufferSize) > 0) { + $this->flush(fread($this->handle, $this->bufferSize)); + $this->throttleDelay and $this->sleep(); + } + if ($length) { + $this->flush(fread($this->handle, $this->bufferSize + $length)); + } + } + return true; + } + + /** + * Get chunks to send + * + * @access protected + * @return array + */ + function getChunks() + { + $parts = array(); + foreach (explode(',', $this->getRanges()) as $chunk){ + list($o, $e) = explode('-', $chunk); + if ($e >= $this->size || (empty($e) && $e !== 0 && $e !== '0')) { + $e = $this->size - 1; + } + if (empty($o) && $o !== 0 && $o !== '0') { + $o = $this->size - $e; + $e = $this->size - 1; + } + $parts[] = array($o, $e); + } + return $parts; + } + + /** + * Check if range is requested + * + * @access protected + * @return bool + */ + function isRangeRequest() + { + if (!isset($_SERVER['HTTP_RANGE'])) { + return false; + } + return $this->isValidRange(); + } + + /** + * Get range request + * + * @access protected + * @return array + */ + function getRanges() + { + return preg_match('/^bytes=((\d*-\d*,? ?)+)$/', + @$_SERVER['HTTP_RANGE'], $matches) ? $matches[1] : array(); + } + + /** + * Check if entity is cached + * + * @access protected + * @return bool + */ + function isCached() + { + return ( + (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && + $this->lastModified == strtotime(current($a = explode( + ';', $_SERVER['HTTP_IF_MODIFIED_SINCE'])))) || + (isset($_SERVER['HTTP_IF_NONE_MATCH']) && + $this->compareAsterisk('HTTP_IF_NONE_MATCH', $this->etag)) + ); + } + + /** + * Check if entity hasn't changed + * + * @access protected + * @return bool + */ + function isValidRange() + { + if (isset($_SERVER['HTTP_IF_MATCH']) && + !$this->compareAsterisk('HTTP_IF_MATCH', $this->etag)) { + return false; + } + if (isset($_SERVER['HTTP_IF_RANGE']) && + $_SERVER['HTTP_IF_RANGE'] !== $this->etag && + strtotime($_SERVER['HTTP_IF_RANGE']) !== $this->lastModified) { + return false; + } + if (isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE'])) { + $lm = array_shift(explode(';', $_SERVER['HTTP_IF_UNMODIFIED_SINCE'])); + if (strtotime($lm) !== $this->lastModified) { + return false; + } + } + if (isset($_SERVER['HTTP_UNLESS_MODIFIED_SINCE'])) { + $lm = array_shift(explode(';', $_SERVER['HTTP_UNLESS_MODIFIED_SINCE'])); + if (strtotime($lm) !== $this->lastModified) { + return false; + } + } + return true; + } + + /** + * Compare against an asterisk or check for equality + * + * @access protected + * @return bool + * @param string key for the $_SERVER array + * @param string string to compare + */ + function compareAsterisk($svar, $compare) + { + foreach (array_map('trim', explode(',', $_SERVER[$svar])) as $request) { + if ($request === '*' || $request === $compare) { + return true; + } + } + return false; + } + + /** + * Send HTTP headers + * + * @access protected + * @return void + */ + function sendHeaders() + { + foreach ($this->headers as $header => $value) { + $this->HTTP->setHeader($header, $value); + } + $this->HTTP->sendHeaders(); + /* NSAPI won't output anything if we did this */ + if (strncasecmp(PHP_SAPI, 'nsapi', 5)) { + ob_flush(); + flush(); + } + } + + /** + * Flush + * + * @access protected + * @return void + * @param string $data + */ + function flush($data = '') + { + if ($dlen = strlen($data)) { + $this->sentBytes += $dlen; + echo $data; + } + ob_flush(); + flush(); + } + + /** + * Sleep + * + * @access protected + * @return void + */ + function sleep() + { + if (OS_WINDOWS) { + com_message_pump($this->throttleDelay); + } else { + usleep($this->throttleDelay * 1000); + } + } + // }}} +} +?> diff --git a/thirdparty/pear/HTTP/Download/Archive.php b/thirdparty/pear/HTTP/Download/Archive.php index 2aa5b8b..c3745fe 100644 --- a/thirdparty/pear/HTTP/Download/Archive.php +++ b/thirdparty/pear/HTTP/Download/Archive.php @@ -1,122 +1,122 @@ - - * @copyright 2003-2005 Michael Wallner - * @license BSD, revisewd - * @version CVS: $Id: Archive.php,v 1.4 2005/11/13 19:18:55 mike Exp $ - * @link http://pear.php.net/package/HTTP_Download - */ - -/** - * Requires HTTP_Download - */ -require_once 'HTTP/Download.php'; - -/** - * Requires System - */ -require_once 'System.php'; - -/** - * HTTP_Download_Archive - * - * Helper class for sending Archives. - * - * @access public - * @version $Revision: 1.4 $ - */ -class HTTP_Download_Archive -{ - /** - * Send a bunch of files or directories as an archive - * - * Example: - * - * require_once 'HTTP/Download/Archive.php'; - * HTTP_Download_Archive::send( - * 'myArchive.tgz', - * '/var/ftp/pub/mike', - * HTTP_DOWNLOAD_BZ2, - * '', - * '/var/ftp/pub' - * ); - * - * - * @see Archive_Tar::createModify() - * @static - * @access public - * @return mixed Returns true on success or PEAR_Error on failure. - * @param string $name name the sent archive should have - * @param mixed $files files/directories - * @param string $type archive type - * @param string $add_path path that should be prepended to the files - * @param string $strip_path path that should be stripped from the files - */ - function send($name, $files, $type = HTTP_DOWNLOAD_TGZ, $add_path = '', $strip_path = '') - { - $tmp = System::mktemp(); - - switch ($type = strToUpper($type)) - { - case HTTP_DOWNLOAD_TAR: - include_once 'Archive/Tar.php'; - $arc = &new Archive_Tar($tmp); - $content_type = 'x-tar'; - break; - - case HTTP_DOWNLOAD_TGZ: - include_once 'Archive/Tar.php'; - $arc = &new Archive_Tar($tmp, 'gz'); - $content_type = 'x-gzip'; - break; - - case HTTP_DOWNLOAD_BZ2: - include_once 'Archive/Tar.php'; - $arc = &new Archive_Tar($tmp, 'bz2'); - $content_type = 'x-bzip2'; - break; - - case HTTP_DOWNLOAD_ZIP: - include_once 'Archive/Zip.php'; - $arc = &new Archive_Zip($tmp); - $content_type = 'x-zip'; - break; - - default: - return PEAR::raiseError( - 'Archive type not supported: ' . $type, - HTTP_DOWNLOAD_E_INVALID_ARCHIVE_TYPE - ); - } - - if ($type == HTTP_DOWNLOAD_ZIP) { - $options = array( 'add_path' => $add_path, - 'remove_path' => $strip_path); - if (!$arc->create($files, $options)) { - return PEAR::raiseError('Archive creation failed.'); - } - } else { - if (!$e = $arc->createModify($files, $add_path, $strip_path)) { - return PEAR::raiseError('Archive creation failed.'); - } - if (PEAR::isError($e)) { - return $e; - } - } - unset($arc); - - $dl = &new HTTP_Download(array('file' => $tmp)); - $dl->setContentType('application/' . $content_type); - $dl->setContentDisposition(HTTP_DOWNLOAD_ATTACHMENT, $name); - return $dl->send(); - } -} -?> + + * @copyright 2003-2005 Michael Wallner + * @license BSD, revisewd + * @version CVS: $Id$ + * @link http://pear.php.net/package/HTTP_Download + */ + +/** + * Requires HTTP_Download + */ +require_once 'HTTP/Download.php'; + +/** + * Requires System + */ +require_once 'System.php'; + +/** + * HTTP_Download_Archive + * + * Helper class for sending Archives. + * + * @access public + * @version $Revision$ + */ +class HTTP_Download_Archive +{ + /** + * Send a bunch of files or directories as an archive + * + * Example: + * + * require_once 'HTTP/Download/Archive.php'; + * HTTP_Download_Archive::send( + * 'myArchive.tgz', + * '/var/ftp/pub/mike', + * HTTP_DOWNLOAD_BZ2, + * '', + * '/var/ftp/pub' + * ); + * + * + * @see Archive_Tar::createModify() + * @static + * @access public + * @return mixed Returns true on success or PEAR_Error on failure. + * @param string $name name the sent archive should have + * @param mixed $files files/directories + * @param string $type archive type + * @param string $add_path path that should be prepended to the files + * @param string $strip_path path that should be stripped from the files + */ + function send($name, $files, $type = HTTP_DOWNLOAD_TGZ, $add_path = '', $strip_path = '') + { + $tmp = System::mktemp(); + + switch ($type = strToUpper($type)) + { + case HTTP_DOWNLOAD_TAR: + include_once 'Archive/Tar.php'; + $arc = &new Archive_Tar($tmp); + $content_type = 'x-tar'; + break; + + case HTTP_DOWNLOAD_TGZ: + include_once 'Archive/Tar.php'; + $arc = &new Archive_Tar($tmp, 'gz'); + $content_type = 'x-gzip'; + break; + + case HTTP_DOWNLOAD_BZ2: + include_once 'Archive/Tar.php'; + $arc = &new Archive_Tar($tmp, 'bz2'); + $content_type = 'x-bzip2'; + break; + + case HTTP_DOWNLOAD_ZIP: + include_once 'Archive/Zip.php'; + $arc = &new Archive_Zip($tmp); + $content_type = 'x-zip'; + break; + + default: + return PEAR::raiseError( + 'Archive type not supported: ' . $type, + HTTP_DOWNLOAD_E_INVALID_ARCHIVE_TYPE + ); + } + + if ($type == HTTP_DOWNLOAD_ZIP) { + $options = array( 'add_path' => $add_path, + 'remove_path' => $strip_path); + if (!$arc->create($files, $options)) { + return PEAR::raiseError('Archive creation failed.'); + } + } else { + if (!$e = $arc->createModify($files, $add_path, $strip_path)) { + return PEAR::raiseError('Archive creation failed.'); + } + if (PEAR::isError($e)) { + return $e; + } + } + unset($arc); + + $dl = &new HTTP_Download(array('file' => $tmp)); + $dl->setContentType('application/' . $content_type); + $dl->setContentDisposition(HTTP_DOWNLOAD_ATTACHMENT, $name); + return $dl->send(); + } +} +?> diff --git a/thirdparty/pear/HTTP/Download/PgLOB.php b/thirdparty/pear/HTTP/Download/PgLOB.php index 19de2bc..bb97bf3 100644 --- a/thirdparty/pear/HTTP/Download/PgLOB.php +++ b/thirdparty/pear/HTTP/Download/PgLOB.php @@ -1,177 +1,177 @@ - - * @copyright 2003-2005 Michael Wallner - * @license BSD, revised - * @version CVS: $Id: PgLOB.php,v 1.14 2005/11/13 19:18:55 mike Exp $ - * @link http://pear.php.net/package/HTTP_Download - */ - -$GLOBALS['_HTTP_Download_PgLOB_Connection'] = null; -stream_register_wrapper('pglob', 'HTTP_Download_PgLOB'); - -/** - * PgSQL large object stream interface for HTTP_Download - * - * Usage: - * - * require_once 'HTTP/Download.php'; - * require_once 'HTTP/Download/PgLOB.php'; - * $db = &DB::connect('pgsql://user:pass@host/db'); - * // or $db = pg_connect(...); - * $lo = HTTP_Download_PgLOB::open($db, 12345); - * $dl = &new HTTP_Download; - * $dl->setResource($lo); - * $dl->send() - * - * - * @access public - * @version $Revision: 1.14 $ - */ -class HTTP_Download_PgLOB -{ - /** - * Set Connection - * - * @static - * @access public - * @return bool - * @param mixed $conn - */ - function setConnection($conn) - { - if (is_a($conn, 'DB_Common')) { - $conn = $conn->dbh; - } elseif ( is_a($conn, 'MDB_Common') || - is_a($conn, 'MDB2_Driver_Common')) { - $conn = $conn->connection; - } - if ($isResource = is_resource($conn)) { - $GLOBALS['_HTTP_Download_PgLOB_Connection'] = $conn; - } - return $isResource; - } - - /** - * Get Connection - * - * @static - * @access public - * @return resource - */ - function getConnection() - { - if (is_resource($GLOBALS['_HTTP_Download_PgLOB_Connection'])) { - return $GLOBALS['_HTTP_Download_PgLOB_Connection']; - } - return null; - } - - /** - * Open - * - * @static - * @access public - * @return resource - * @param mixed $conn - * @param int $loid - * @param string $mode - */ - function open($conn, $loid, $mode = 'rb') - { - HTTP_Download_PgLOB::setConnection($conn); - return fopen('pglob:///'. $loid, $mode); - } - - /**#@+ - * Stream Interface Implementation - * @internal - */ - var $ID = 0; - var $size = 0; - var $conn = null; - var $handle = null; - - function stream_open($path, $mode) - { - if (!$this->conn = HTTP_Download_PgLOB::getConnection()) { - return false; - } - if (!preg_match('/(\d+)/', $path, $matches)) { - return false; - } - $this->ID = $matches[1]; - - if (!pg_query($this->conn, 'BEGIN')) { - return false; - } - - $this->handle = pg_lo_open($this->conn, $this->ID, $mode); - if (!is_resource($this->handle)) { - return false; - } - - // fetch size of lob - pg_lo_seek($this->handle, 0, PGSQL_SEEK_END); - $this->size = (int) pg_lo_tell($this->handle); - pg_lo_seek($this->handle, 0, PGSQL_SEEK_SET); - - return true; - } - - function stream_read($length) - { - return pg_lo_read($this->handle, $length); - } - - function stream_seek($offset, $whence = SEEK_SET) - { - return pg_lo_seek($this->handle, $offset, $whence); - } - - function stream_tell() - { - return pg_lo_tell($this->handle); - } - - function stream_eof() - { - return pg_lo_tell($this->handle) >= $this->size; - } - - function stream_flush() - { - return true; - } - - function stream_stat() - { - return array('size' => $this->size, 'ino' => $this->ID); - } - - function stream_write($data) - { - return pg_lo_write($this->handle, $data); - } - - function stream_close() - { - if (pg_lo_close($this->handle)) { - return pg_query($this->conn, 'COMMIT'); - } else { - pg_query($this->conn ,'ROLLBACK'); - return false; - } - } - /**#@-*/ -} - -?> + + * @copyright 2003-2005 Michael Wallner + * @license BSD, revised + * @version CVS: $Id$ + * @link http://pear.php.net/package/HTTP_Download + */ + +$GLOBALS['_HTTP_Download_PgLOB_Connection'] = null; +stream_register_wrapper('pglob', 'HTTP_Download_PgLOB'); + +/** + * PgSQL large object stream interface for HTTP_Download + * + * Usage: + * + * require_once 'HTTP/Download.php'; + * require_once 'HTTP/Download/PgLOB.php'; + * $db = &DB::connect('pgsql://user:pass@host/db'); + * // or $db = pg_connect(...); + * $lo = HTTP_Download_PgLOB::open($db, 12345); + * $dl = &new HTTP_Download; + * $dl->setResource($lo); + * $dl->send() + * + * + * @access public + * @version $Revision$ + */ +class HTTP_Download_PgLOB +{ + /** + * Set Connection + * + * @static + * @access public + * @return bool + * @param mixed $conn + */ + function setConnection($conn) + { + if (is_a($conn, 'DB_Common')) { + $conn = $conn->dbh; + } elseif ( is_a($conn, 'MDB_Common') || + is_a($conn, 'MDB2_Driver_Common')) { + $conn = $conn->connection; + } + if ($isResource = is_resource($conn)) { + $GLOBALS['_HTTP_Download_PgLOB_Connection'] = $conn; + } + return $isResource; + } + + /** + * Get Connection + * + * @static + * @access public + * @return resource + */ + function getConnection() + { + if (is_resource($GLOBALS['_HTTP_Download_PgLOB_Connection'])) { + return $GLOBALS['_HTTP_Download_PgLOB_Connection']; + } + return null; + } + + /** + * Open + * + * @static + * @access public + * @return resource + * @param mixed $conn + * @param int $loid + * @param string $mode + */ + function open($conn, $loid, $mode = 'rb') + { + HTTP_Download_PgLOB::setConnection($conn); + return fopen('pglob:///'. $loid, $mode); + } + + /**#@+ + * Stream Interface Implementation + * @internal + */ + var $ID = 0; + var $size = 0; + var $conn = null; + var $handle = null; + + function stream_open($path, $mode) + { + if (!$this->conn = HTTP_Download_PgLOB::getConnection()) { + return false; + } + if (!preg_match('/(\d+)/', $path, $matches)) { + return false; + } + $this->ID = $matches[1]; + + if (!pg_query($this->conn, 'BEGIN')) { + return false; + } + + $this->handle = pg_lo_open($this->conn, $this->ID, $mode); + if (!is_resource($this->handle)) { + return false; + } + + // fetch size of lob + pg_lo_seek($this->handle, 0, PGSQL_SEEK_END); + $this->size = (int) pg_lo_tell($this->handle); + pg_lo_seek($this->handle, 0, PGSQL_SEEK_SET); + + return true; + } + + function stream_read($length) + { + return pg_lo_read($this->handle, $length); + } + + function stream_seek($offset, $whence = SEEK_SET) + { + return pg_lo_seek($this->handle, $offset, $whence); + } + + function stream_tell() + { + return pg_lo_tell($this->handle); + } + + function stream_eof() + { + return pg_lo_tell($this->handle) >= $this->size; + } + + function stream_flush() + { + return true; + } + + function stream_stat() + { + return array('size' => $this->size, 'ino' => $this->ID); + } + + function stream_write($data) + { + return pg_lo_write($this->handle, $data); + } + + function stream_close() + { + if (pg_lo_close($this->handle)) { + return pg_query($this->conn, 'COMMIT'); + } else { + pg_query($this->conn ,'ROLLBACK'); + return false; + } + } + /**#@-*/ +} + +?> diff --git a/thirdparty/pear/HTTP/Header.php b/thirdparty/pear/HTTP/Header.php index fd6c497..7ba3419 100644 --- a/thirdparty/pear/HTTP/Header.php +++ b/thirdparty/pear/HTTP/Header.php @@ -1,531 +1,531 @@ - - * @author Davey Shafik - * @author Michael Wallner - * @copyright 2003-2005 The Authors - * @license BSD, revised - * @version CVS: $Id: Header.php,v 1.32 2005/11/08 19:06:10 mike Exp $ - * @link http://pear.php.net/package/HTTP_Header - */ - -/** - * Requires HTTP - */ -require_once 'HTTP.php'; - -/**#@+ - * Information Codes - */ -define('HTTP_HEADER_STATUS_100', '100 Continue'); -define('HTTP_HEADER_STATUS_101', '101 Switching Protocols'); -define('HTTP_HEADER_STATUS_102', '102 Processing'); -define('HTTP_HEADER_STATUS_INFORMATIONAL',1); -/**#@-*/ - -/**#+ - * Success Codes - */ -define('HTTP_HEADER_STATUS_200', '200 OK'); -define('HTTP_HEADER_STATUS_201', '201 Created'); -define('HTTP_HEADER_STATUS_202', '202 Accepted'); -define('HTTP_HEADER_STATUS_203', '203 Non-Authoritative Information'); -define('HTTP_HEADER_STATUS_204', '204 No Content'); -define('HTTP_HEADER_STATUS_205', '205 Reset Content'); -define('HTTP_HEADER_STATUS_206', '206 Partial Content'); -define('HTTP_HEADER_STATUS_207', '207 Multi-Status'); -define('HTTP_HEADER_STATUS_SUCCESSFUL',2); -/**#@-*/ - -/**#@+ - * Redirection Codes - */ -define('HTTP_HEADER_STATUS_300', '300 Multiple Choices'); -define('HTTP_HEADER_STATUS_301', '301 Moved Permanently'); -define('HTTP_HEADER_STATUS_302', '302 Found'); -define('HTTP_HEADER_STATUS_303', '303 See Other'); -define('HTTP_HEADER_STATUS_304', '304 Not Modified'); -define('HTTP_HEADER_STATUS_305', '305 Use Proxy'); -define('HTTP_HEADER_STATUS_306', '306 (Unused)'); -define('HTTP_HEADER_STATUS_307', '307 Temporary Redirect'); -define('HTTP_HEADER_STATUS_REDIRECT',3); -/**#@-*/ - -/**#@+ - * Error Codes - */ -define('HTTP_HEADER_STATUS_400', '400 Bad Request'); -define('HTTP_HEADER_STATUS_401', '401 Unauthorized'); -define('HTTP_HEADER_STATUS_402', '402 Payment Granted'); -define('HTTP_HEADER_STATUS_403', '403 Forbidden'); -define('HTTP_HEADER_STATUS_404', '404 File Not Found'); -define('HTTP_HEADER_STATUS_405', '405 Method Not Allowed'); -define('HTTP_HEADER_STATUS_406', '406 Not Acceptable'); -define('HTTP_HEADER_STATUS_407', '407 Proxy Authentication Required'); -define('HTTP_HEADER_STATUS_408', '408 Request Time-out'); -define('HTTP_HEADER_STATUS_409', '409 Conflict'); -define('HTTP_HEADER_STATUS_410', '410 Gone'); -define('HTTP_HEADER_STATUS_411', '411 Length Required'); -define('HTTP_HEADER_STATUS_412', '412 Precondition Failed'); -define('HTTP_HEADER_STATUS_413', '413 Request Entity Too Large'); -define('HTTP_HEADER_STATUS_414', '414 Request-URI Too Large'); -define('HTTP_HEADER_STATUS_415', '415 Unsupported Media Type'); -define('HTTP_HEADER_STATUS_416', '416 Requested range not satisfiable'); -define('HTTP_HEADER_STATUS_417', '417 Expectation Failed'); -define('HTTP_HEADER_STATUS_422', '422 Unprocessable Entity'); -define('HTTP_HEADER_STATUS_423', '423 Locked'); -define('HTTP_HEADER_STATUS_424', '424 Failed Dependency'); -define('HTTP_HEADER_STATUS_CLIENT_ERROR',4); -/**#@-*/ - -/**#@+ - * Server Errors - */ -define('HTTP_HEADER_STATUS_500', '500 Internal Server Error'); -define('HTTP_HEADER_STATUS_501', '501 Not Implemented'); -define('HTTP_HEADER_STATUS_502', '502 Bad Gateway'); -define('HTTP_HEADER_STATUS_503', '503 Service Unavailable'); -define('HTTP_HEADER_STATUS_504', '504 Gateway Time-out'); -define('HTTP_HEADER_STATUS_505', '505 HTTP Version not supported'); -define('HTTP_HEADER_STATUS_507', '507 Insufficient Storage'); -define('HTTP_HEADER_STATUS_SERVER_ERROR',5); -/**#@-*/ - -/** - * HTTP_Header - * - * @package HTTP_Header - * @category HTTP - * @access public - * @version $Revision: 1.32 $ - */ -class HTTP_Header extends HTTP -{ - /** - * Default Headers - * - * The values that are set as default, are the same as PHP sends by default. - * - * @var array - * @access private - */ - var $_headers = array( - 'content-type' => 'text/html', - 'pragma' => 'no-cache', - 'cache-control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0' - ); - - /** - * HTTP version - * - * @var string - * @access private - */ - var $_httpVersion = '1.0'; - - /** - * Constructor - * - * Sets HTTP version. - * - * @access public - * @return object HTTP_Header - */ - function HTTP_Header() - { - if (isset($_SERVER['SERVER_PROTOCOL'])) { - $this->setHttpVersion(substr($_SERVER['SERVER_PROTOCOL'], -3)); - } - } - - /** - * Set HTTP version - * - * @access public - * @return bool Returns true on success or false if version doesn't - * match 1.0 or 1.1 (note: 1 will result in 1.0) - * @param mixed $version HTTP version, either 1.0 or 1.1 - */ - function setHttpVersion($version) - { - $version = round((float) $version, 1); - if ($version < 1.0 || $version > 1.1) { - return false; - } - $this->_httpVersion = sprintf('%0.1f', $version); - return true; - } - - /** - * Get HTTP version - * - * @access public - * @return string - */ - function getHttpVersion() - { - return $this->_httpVersion; - } - - /** - * Set Header - * - * The default value for the Last-Modified header will be current - * date and atime if $value is omitted. - * - * @access public - * @return bool Returns true on success or false if $key was empty or - * $value was not of an scalar type. - * @param string $key The name of the header. - * @param string $value The value of the header. (NULL to unset header) - */ - function setHeader($key, $value = null) - { - if (empty($key) || (isset($value) && !is_scalar($value))) { - return false; - } - - $key = strToLower($key); - if ($key == 'last-modified') { - if (!isset($value)) { - $value = HTTP::Date(time()); - } elseif (is_numeric($value)) { - $value = HTTP::Date($value); - } - } - - if (isset($value)) { - $this->_headers[$key] = $value; - } else { - unset($this->_headers[$key]); - } - - return true; - } - - /** - * Get Header - * - * If $key is omitted, all stored headers will be returned. - * - * @access public - * @return mixed Returns string value of the requested header, - * array values of all headers or false if header $key - * is not set. - * @param string $key The name of the header to fetch. - */ - function getHeader($key = null) - { - if (!isset($key)) { - return $this->_headers; - } - - $key = strToLower($key); - - if (!isset($this->_headers[$key])) { - return false; - } - - return $this->_headers[$key]; - } - - /** - * Send Headers - * - * Send out the header that you set via setHeader(). - * - * @access public - * @return bool Returns true on success or false if headers are already - * sent. - * @param array $keys Headers to (not) send, see $include. - * @param array $include If true only $keys matching headers will be - * sent, if false only header not matching $keys will be - * sent. - */ - function sendHeaders($keys = array(), $include = true) - { - if (headers_sent()) { - return false; - } - - if (count($keys)) { - array_change_key_case($keys, CASE_LOWER); - foreach ($this->_headers as $key => $value) { - if ($include ? in_array($key, $keys) : !in_array($key, $keys)) { - header($key .': '. $value); - } - } - } else { - foreach ($this->_headers as $header => $value) { - header($header .': '. $value); - } - } - return true; - } - - /** - * Send Satus Code - * - * Send out the given HTTP-Status code. Use this for example when you - * want to tell the client this page is cached, then you would call - * sendStatusCode(304). - * - * @see HTTP_Header_Cache::exitIfCached() - * - * @access public - * @return bool Returns true on success or false if headers are already - * sent. - * @param int $code The status code to send, i.e. 404, 304, 200, etc. - */ - function sendStatusCode($code) - { - if (headers_sent()) { - return false; - } - - if ($code == (int) $code && defined('HTTP_HEADER_STATUS_'. $code)) { - $code = constant('HTTP_HEADER_STATUS_'. $code); - } - - if (strncasecmp(PHP_SAPI, 'cgi', 3)) { - header('HTTP/'. $this->_httpVersion .' '. $code); - } else { - header('Status: '. $code); - } - return true; - } - - /** - * Date to Timestamp - * - * Converts dates like - * Mon, 31 Mar 2003 15:26:34 GMT - * Tue, 15 Nov 1994 12:45:26 GMT - * into a timestamp, strtotime() didn't do it in older versions. - * - * @deprecated Use PHPs strtotime() instead. - * @access public - * @return mixed Returns int unix timestamp or false if the date doesn't - * seem to be a valid GMT date. - * @param string $date The GMT date. - */ - function dateToTimestamp($date) - { - static $months = array( - null => 0, 'Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4, - 'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8, 'Sep' => 9, - 'Oct' => 10, 'Nov' => 11, 'Dec' => 12 - ); - - if (-1 < $timestamp = strToTime($date)) { - return $timestamp; - } - - if (!preg_match('~[^,]*,\s(\d+)\s(\w+)\s(\d+)\s(\d+):(\d+):(\d+).*~', - $date, $m)) { - return false; - } - - // [0] => Mon, 31 Mar 2003 15:42:55 GMT - // [1] => 31 [2] => Mar [3] => 2003 [4] => 15 [5] => 42 [6] => 55 - return mktime($m[4], $m[5], $m[6], $months[$m[2]], $m[1], $m[3]); - } - - /** - * Redirect - * - * This function redirects the client. This is done by issuing a Location - * header and exiting. Additionally to HTTP::redirect() you can also add - * parameters to the url. - * - * If you dont need parameters to be added, simply use HTTP::redirect() - * otherwise use HTTP_Header::redirect(). - * - * @see HTTP::redirect() - * @author Wolfram Kriesing - * @access public - * @return void - * @param string $url The URL to redirect to, if none is given it - * redirects to the current page. - * @param array $param Array of query string parameters to add; usually - * a set of key => value pairs; if an array entry consists - * only of an value it is used as key and the respective - * value is fetched from $GLOBALS[$value] - * @param bool $session Whether the session name/id should be added - */ - function redirect($url = null, $param = array(), $session = false) - { - if (!isset($url)) { - $url = $_SERVER['PHP_SELF']; - } - - $qs = array(); - - if ($session) { - $qs[] = session_name() .'='. session_id(); - } - - if (is_array($param) && count($param)) { - if (count($param)) { - foreach ($param as $key => $val) { - if (is_string($key)) { - $qs[] = urlencode($key) .'='. urlencode($val); - } else { - $qs[] = urlencode($val) .'='. urlencode(@$GLOBALS[$val]); - } - } - } - } - - if ($qstr = implode('&', $qs)) { - $purl = parse_url($url); - $url .= (isset($purl['query']) ? '&' : '?') . $qstr; - } - - parent::redirect($url); - } - - /**#@+ - * @author Davey Shafik - * @param int $http_code HTTP Code to check - * @access public - */ - - /** - * Return HTTP Status Code Type - * - * @return int|false - */ - function getStatusType($http_code) - { - if(is_int($http_code) && defined('HTTP_HEADER_STATUS_' .$http_code) || defined($http_code)) { - $type = substr($http_code,0,1); - switch ($type) { - case HTTP_HEADER_STATUS_INFORMATIONAL: - case HTTP_HEADER_STATUS_SUCCESSFUL: - case HTTP_HEADER_STATUS_REDIRECT: - case HTTP_HEADER_STATUS_CLIENT_ERROR: - case HTTP_HEADER_STATUS_SERVER_ERROR: - return $type; - break; - default: - return false; - break; - } - } else { - return false; - } - } - - /** - * Return Status Code Message - * - * @return string|false - */ - function getStatusText($http_code) - { - if ($this->getStatusType($http_code)) { - if (is_int($http_code) && defined('HTTP_HEADER_STATUS_' .$http_code)) { - return substr(constant('HTTP_HEADER_STATUS_' .$http_code),4); - } else { - return substr($http_code,4); - } - } else { - return false; - } - } - - /** - * Checks if HTTP Status code is Information (1xx) - * - * @return boolean - */ - function isInformational($http_code) - { - if ($status_type = $this->getStatusType($http_code)) { - return $status_type{0} == HTTP_HEADER_STATUS_INFORMATIONAL; - } else { - return false; - } - } - - /** - * Checks if HTTP Status code is Successful (2xx) - * - * @return boolean - */ - function isSuccessful($http_code) - { - if ($status_type = $this->getStatusType($http_code)) { - return $status_type{0} == HTTP_HEADER_STATUS_SUCCESSFUL; - } else { - return false; - } - } - - /** - * Checks if HTTP Status code is a Redirect (3xx) - * - * @return boolean - */ - function isRedirect($http_code) - { - if ($status_type = $this->getStatusType($http_code)) { - return $status_type{0} == HTTP_HEADER_STATUS_REDIRECT; - } else { - return false; - } - } - - /** - * Checks if HTTP Status code is a Client Error (4xx) - * - * @return boolean - */ - function isClientError($http_code) - { - if ($status_type = $this->getStatusType($http_code)) { - return $status_type{0} == HTTP_HEADER_STATUS_CLIENT_ERROR; - } else { - return false; - } - } - - /** - * Checks if HTTP Status code is Server Error (5xx) - * - * @return boolean - */ - function isServerError($http_code) - { - if ($status_type = $this->getStatusType($http_code)) { - return $status_type{0} == HTTP_HEADER_STATUS_SERVER_ERROR; - } else { - return false; - } - } - - /** - * Checks if HTTP Status code is Server OR Client Error (4xx or 5xx) - * - * @return boolean - */ - function isError($http_code) - { - if ($status_type = $this->getStatusType($http_code)) { - return (($status_type == HTTP_HEADER_STATUS_CLIENT_ERROR) || ($status_type == HTTP_HEADER_STATUS_SERVER_ERROR)) ? true : false; - } else { - return false; - } - } - /**#@-*/ -} -?> + + * @author Davey Shafik + * @author Michael Wallner + * @copyright 2003-2005 The Authors + * @license BSD, revised + * @version CVS: $Id$ + * @link http://pear.php.net/package/HTTP_Header + */ + +/** + * Requires HTTP + */ +require_once 'HTTP.php'; + +/**#@+ + * Information Codes + */ +define('HTTP_HEADER_STATUS_100', '100 Continue'); +define('HTTP_HEADER_STATUS_101', '101 Switching Protocols'); +define('HTTP_HEADER_STATUS_102', '102 Processing'); +define('HTTP_HEADER_STATUS_INFORMATIONAL',1); +/**#@-*/ + +/**#+ + * Success Codes + */ +define('HTTP_HEADER_STATUS_200', '200 OK'); +define('HTTP_HEADER_STATUS_201', '201 Created'); +define('HTTP_HEADER_STATUS_202', '202 Accepted'); +define('HTTP_HEADER_STATUS_203', '203 Non-Authoritative Information'); +define('HTTP_HEADER_STATUS_204', '204 No Content'); +define('HTTP_HEADER_STATUS_205', '205 Reset Content'); +define('HTTP_HEADER_STATUS_206', '206 Partial Content'); +define('HTTP_HEADER_STATUS_207', '207 Multi-Status'); +define('HTTP_HEADER_STATUS_SUCCESSFUL',2); +/**#@-*/ + +/**#@+ + * Redirection Codes + */ +define('HTTP_HEADER_STATUS_300', '300 Multiple Choices'); +define('HTTP_HEADER_STATUS_301', '301 Moved Permanently'); +define('HTTP_HEADER_STATUS_302', '302 Found'); +define('HTTP_HEADER_STATUS_303', '303 See Other'); +define('HTTP_HEADER_STATUS_304', '304 Not Modified'); +define('HTTP_HEADER_STATUS_305', '305 Use Proxy'); +define('HTTP_HEADER_STATUS_306', '306 (Unused)'); +define('HTTP_HEADER_STATUS_307', '307 Temporary Redirect'); +define('HTTP_HEADER_STATUS_REDIRECT',3); +/**#@-*/ + +/**#@+ + * Error Codes + */ +define('HTTP_HEADER_STATUS_400', '400 Bad Request'); +define('HTTP_HEADER_STATUS_401', '401 Unauthorized'); +define('HTTP_HEADER_STATUS_402', '402 Payment Granted'); +define('HTTP_HEADER_STATUS_403', '403 Forbidden'); +define('HTTP_HEADER_STATUS_404', '404 File Not Found'); +define('HTTP_HEADER_STATUS_405', '405 Method Not Allowed'); +define('HTTP_HEADER_STATUS_406', '406 Not Acceptable'); +define('HTTP_HEADER_STATUS_407', '407 Proxy Authentication Required'); +define('HTTP_HEADER_STATUS_408', '408 Request Time-out'); +define('HTTP_HEADER_STATUS_409', '409 Conflict'); +define('HTTP_HEADER_STATUS_410', '410 Gone'); +define('HTTP_HEADER_STATUS_411', '411 Length Required'); +define('HTTP_HEADER_STATUS_412', '412 Precondition Failed'); +define('HTTP_HEADER_STATUS_413', '413 Request Entity Too Large'); +define('HTTP_HEADER_STATUS_414', '414 Request-URI Too Large'); +define('HTTP_HEADER_STATUS_415', '415 Unsupported Media Type'); +define('HTTP_HEADER_STATUS_416', '416 Requested range not satisfiable'); +define('HTTP_HEADER_STATUS_417', '417 Expectation Failed'); +define('HTTP_HEADER_STATUS_422', '422 Unprocessable Entity'); +define('HTTP_HEADER_STATUS_423', '423 Locked'); +define('HTTP_HEADER_STATUS_424', '424 Failed Dependency'); +define('HTTP_HEADER_STATUS_CLIENT_ERROR',4); +/**#@-*/ + +/**#@+ + * Server Errors + */ +define('HTTP_HEADER_STATUS_500', '500 Internal Server Error'); +define('HTTP_HEADER_STATUS_501', '501 Not Implemented'); +define('HTTP_HEADER_STATUS_502', '502 Bad Gateway'); +define('HTTP_HEADER_STATUS_503', '503 Service Unavailable'); +define('HTTP_HEADER_STATUS_504', '504 Gateway Time-out'); +define('HTTP_HEADER_STATUS_505', '505 HTTP Version not supported'); +define('HTTP_HEADER_STATUS_507', '507 Insufficient Storage'); +define('HTTP_HEADER_STATUS_SERVER_ERROR',5); +/**#@-*/ + +/** + * HTTP_Header + * + * @package HTTP_Header + * @category HTTP + * @access public + * @version $Revision$ + */ +class HTTP_Header extends HTTP +{ + /** + * Default Headers + * + * The values that are set as default, are the same as PHP sends by default. + * + * @var array + * @access private + */ + var $_headers = array( + 'content-type' => 'text/html', + 'pragma' => 'no-cache', + 'cache-control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0' + ); + + /** + * HTTP version + * + * @var string + * @access private + */ + var $_httpVersion = '1.0'; + + /** + * Constructor + * + * Sets HTTP version. + * + * @access public + * @return object HTTP_Header + */ + function HTTP_Header() + { + if (isset($_SERVER['SERVER_PROTOCOL'])) { + $this->setHttpVersion(substr($_SERVER['SERVER_PROTOCOL'], -3)); + } + } + + /** + * Set HTTP version + * + * @access public + * @return bool Returns true on success or false if version doesn't + * match 1.0 or 1.1 (note: 1 will result in 1.0) + * @param mixed $version HTTP version, either 1.0 or 1.1 + */ + function setHttpVersion($version) + { + $version = round((float) $version, 1); + if ($version < 1.0 || $version > 1.1) { + return false; + } + $this->_httpVersion = sprintf('%0.1f', $version); + return true; + } + + /** + * Get HTTP version + * + * @access public + * @return string + */ + function getHttpVersion() + { + return $this->_httpVersion; + } + + /** + * Set Header + * + * The default value for the Last-Modified header will be current + * date and atime if $value is omitted. + * + * @access public + * @return bool Returns true on success or false if $key was empty or + * $value was not of an scalar type. + * @param string $key The name of the header. + * @param string $value The value of the header. (NULL to unset header) + */ + function setHeader($key, $value = null) + { + if (empty($key) || (isset($value) && !is_scalar($value))) { + return false; + } + + $key = strToLower($key); + if ($key == 'last-modified') { + if (!isset($value)) { + $value = HTTP::Date(time()); + } elseif (is_numeric($value)) { + $value = HTTP::Date($value); + } + } + + if (isset($value)) { + $this->_headers[$key] = $value; + } else { + unset($this->_headers[$key]); + } + + return true; + } + + /** + * Get Header + * + * If $key is omitted, all stored headers will be returned. + * + * @access public + * @return mixed Returns string value of the requested header, + * array values of all headers or false if header $key + * is not set. + * @param string $key The name of the header to fetch. + */ + function getHeader($key = null) + { + if (!isset($key)) { + return $this->_headers; + } + + $key = strToLower($key); + + if (!isset($this->_headers[$key])) { + return false; + } + + return $this->_headers[$key]; + } + + /** + * Send Headers + * + * Send out the header that you set via setHeader(). + * + * @access public + * @return bool Returns true on success or false if headers are already + * sent. + * @param array $keys Headers to (not) send, see $include. + * @param array $include If true only $keys matching headers will be + * sent, if false only header not matching $keys will be + * sent. + */ + function sendHeaders($keys = array(), $include = true) + { + if (headers_sent()) { + return false; + } + + if (count($keys)) { + array_change_key_case($keys, CASE_LOWER); + foreach ($this->_headers as $key => $value) { + if ($include ? in_array($key, $keys) : !in_array($key, $keys)) { + header($key .': '. $value); + } + } + } else { + foreach ($this->_headers as $header => $value) { + header($header .': '. $value); + } + } + return true; + } + + /** + * Send Satus Code + * + * Send out the given HTTP-Status code. Use this for example when you + * want to tell the client this page is cached, then you would call + * sendStatusCode(304). + * + * @see HTTP_Header_Cache::exitIfCached() + * + * @access public + * @return bool Returns true on success or false if headers are already + * sent. + * @param int $code The status code to send, i.e. 404, 304, 200, etc. + */ + function sendStatusCode($code) + { + if (headers_sent()) { + return false; + } + + if ($code == (int) $code && defined('HTTP_HEADER_STATUS_'. $code)) { + $code = constant('HTTP_HEADER_STATUS_'. $code); + } + + if (strncasecmp(PHP_SAPI, 'cgi', 3)) { + header('HTTP/'. $this->_httpVersion .' '. $code); + } else { + header('Status: '. $code); + } + return true; + } + + /** + * Date to Timestamp + * + * Converts dates like + * Mon, 31 Mar 2003 15:26:34 GMT + * Tue, 15 Nov 1994 12:45:26 GMT + * into a timestamp, strtotime() didn't do it in older versions. + * + * @deprecated Use PHPs strtotime() instead. + * @access public + * @return mixed Returns int unix timestamp or false if the date doesn't + * seem to be a valid GMT date. + * @param string $date The GMT date. + */ + function dateToTimestamp($date) + { + static $months = array( + null => 0, 'Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4, + 'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8, 'Sep' => 9, + 'Oct' => 10, 'Nov' => 11, 'Dec' => 12 + ); + + if (-1 < $timestamp = strToTime($date)) { + return $timestamp; + } + + if (!preg_match('~[^,]*,\s(\d+)\s(\w+)\s(\d+)\s(\d+):(\d+):(\d+).*~', + $date, $m)) { + return false; + } + + // [0] => Mon, 31 Mar 2003 15:42:55 GMT + // [1] => 31 [2] => Mar [3] => 2003 [4] => 15 [5] => 42 [6] => 55 + return mktime($m[4], $m[5], $m[6], $months[$m[2]], $m[1], $m[3]); + } + + /** + * Redirect + * + * This function redirects the client. This is done by issuing a Location + * header and exiting. Additionally to HTTP::redirect() you can also add + * parameters to the url. + * + * If you dont need parameters to be added, simply use HTTP::redirect() + * otherwise use HTTP_Header::redirect(). + * + * @see HTTP::redirect() + * @author Wolfram Kriesing + * @access public + * @return void + * @param string $url The URL to redirect to, if none is given it + * redirects to the current page. + * @param array $param Array of query string parameters to add; usually + * a set of key => value pairs; if an array entry consists + * only of an value it is used as key and the respective + * value is fetched from $GLOBALS[$value] + * @param bool $session Whether the session name/id should be added + */ + function redirect($url = null, $param = array(), $session = false) + { + if (!isset($url)) { + $url = $_SERVER['PHP_SELF']; + } + + $qs = array(); + + if ($session) { + $qs[] = session_name() .'='. session_id(); + } + + if (is_array($param) && count($param)) { + if (count($param)) { + foreach ($param as $key => $val) { + if (is_string($key)) { + $qs[] = urlencode($key) .'='. urlencode($val); + } else { + $qs[] = urlencode($val) .'='. urlencode(@$GLOBALS[$val]); + } + } + } + } + + if ($qstr = implode('&', $qs)) { + $purl = parse_url($url); + $url .= (isset($purl['query']) ? '&' : '?') . $qstr; + } + + parent::redirect($url); + } + + /**#@+ + * @author Davey Shafik + * @param int $http_code HTTP Code to check + * @access public + */ + + /** + * Return HTTP Status Code Type + * + * @return int|false + */ + function getStatusType($http_code) + { + if(is_int($http_code) && defined('HTTP_HEADER_STATUS_' .$http_code) || defined($http_code)) { + $type = substr($http_code,0,1); + switch ($type) { + case HTTP_HEADER_STATUS_INFORMATIONAL: + case HTTP_HEADER_STATUS_SUCCESSFUL: + case HTTP_HEADER_STATUS_REDIRECT: + case HTTP_HEADER_STATUS_CLIENT_ERROR: + case HTTP_HEADER_STATUS_SERVER_ERROR: + return $type; + break; + default: + return false; + break; + } + } else { + return false; + } + } + + /** + * Return Status Code Message + * + * @return string|false + */ + function getStatusText($http_code) + { + if ($this->getStatusType($http_code)) { + if (is_int($http_code) && defined('HTTP_HEADER_STATUS_' .$http_code)) { + return substr(constant('HTTP_HEADER_STATUS_' .$http_code),4); + } else { + return substr($http_code,4); + } + } else { + return false; + } + } + + /** + * Checks if HTTP Status code is Information (1xx) + * + * @return boolean + */ + function isInformational($http_code) + { + if ($status_type = $this->getStatusType($http_code)) { + return $status_type{0} == HTTP_HEADER_STATUS_INFORMATIONAL; + } else { + return false; + } + } + + /** + * Checks if HTTP Status code is Successful (2xx) + * + * @return boolean + */ + function isSuccessful($http_code) + { + if ($status_type = $this->getStatusType($http_code)) { + return $status_type{0} == HTTP_HEADER_STATUS_SUCCESSFUL; + } else { + return false; + } + } + + /** + * Checks if HTTP Status code is a Redirect (3xx) + * + * @return boolean + */ + function isRedirect($http_code) + { + if ($status_type = $this->getStatusType($http_code)) { + return $status_type{0} == HTTP_HEADER_STATUS_REDIRECT; + } else { + return false; + } + } + + /** + * Checks if HTTP Status code is a Client Error (4xx) + * + * @return boolean + */ + function isClientError($http_code) + { + if ($status_type = $this->getStatusType($http_code)) { + return $status_type{0} == HTTP_HEADER_STATUS_CLIENT_ERROR; + } else { + return false; + } + } + + /** + * Checks if HTTP Status code is Server Error (5xx) + * + * @return boolean + */ + function isServerError($http_code) + { + if ($status_type = $this->getStatusType($http_code)) { + return $status_type{0} == HTTP_HEADER_STATUS_SERVER_ERROR; + } else { + return false; + } + } + + /** + * Checks if HTTP Status code is Server OR Client Error (4xx or 5xx) + * + * @return boolean + */ + function isError($http_code) + { + if ($status_type = $this->getStatusType($http_code)) { + return (($status_type == HTTP_HEADER_STATUS_CLIENT_ERROR) || ($status_type == HTTP_HEADER_STATUS_SERVER_ERROR)) ? true : false; + } else { + return false; + } + } + /**#@-*/ +} +?> diff --git a/thirdparty/pear/HTTP/Header/Cache.php b/thirdparty/pear/HTTP/Header/Cache.php index af26b76..58fb44a 100644 --- a/thirdparty/pear/HTTP/Header/Cache.php +++ b/thirdparty/pear/HTTP/Header/Cache.php @@ -1,238 +1,238 @@ - - * @author Michael Wallner - * @copyright 2003-2005 The Authors - * @license BSD, revised - * @version CVS: $Id: Cache.php,v 1.24 2005/11/08 19:06:14 mike Exp $ - * @link http://pear.php.net/package/HTTP_Header - */ - -/** - * Requires HTTP_Header - */ -require_once 'HTTP/Header.php'; - -/** - * HTTP_Header_Cache - * - * This package provides methods to easier handle caching of HTTP pages. That - * means that the pages can be cached at the client (user agent or browser) and - * your application only needs to send "hey client you already have the pages". - * - * Which is done by sending the HTTP-Status "304 Not Modified", so that your - * application load and the network traffic can be reduced, since you only need - * to send the complete page once. This is really an advantage e.g. for - * generated style sheets, or simply pages that do only change rarely. - * - * Usage: - * - * require_once 'HTTP/Header/Cache.php'; - * $httpCache = new HTTP_Header_Cache(4, 'weeks'); - * $httpCache->sendHeaders(); - * // your code goes here - * - * - * @package HTTP_Header - * @category HTTP - * @access public - * @version $Revision: 1.24 $ - */ -class HTTP_Header_Cache extends HTTP_Header -{ - /** - * Constructor - * - * Set the amount of time to cache. - * - * @access public - * @return object HTTP_Header_Cache - * @param int $expires - * @param string $unit - */ - function HTTP_Header_Cache($expires = 0, $unit = 'seconds') - { - parent::HTTP_Header(); - $this->setHeader('Pragma', 'cache'); - $this->setHeader('Last-Modified', $this->getCacheStart()); - $this->setHeader('Cache-Control', 'private, must-revalidate, max-age=0'); - - if ($expires) { - if (!$this->isOlderThan($expires, $unit)) { - $this->exitCached(); - } - $this->setHeader('Last-Modified', time()); - } - } - - /** - * Get Cache Start - * - * Returns the unix timestamp of the If-Modified-Since HTTP header or the - * current time if the header was not sent by the client. - * - * @access public - * @return int unix timestamp - */ - function getCacheStart() - { - if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && !$this->isPost()) { - return strtotime(current($array = explode(';', - $_SERVER['HTTP_IF_MODIFIED_SINCE']))); - } - return time(); - } - - /** - * Is Older Than - * - * You can call it like this: - * - * $httpCache->isOlderThan(1, 'day'); - * $httpCache->isOlderThan(47, 'days'); - * - * $httpCache->isOlderThan(1, 'week'); - * $httpCache->isOlderThan(3, 'weeks'); - * - * $httpCache->isOlderThan(1, 'hour'); - * $httpCache->isOlderThan(5, 'hours'); - * - * $httpCache->isOlderThan(1, 'minute'); - * $httpCache->isOlderThan(15, 'minutes'); - * - * $httpCache->isOlderThan(1, 'second'); - * $httpCache->isOlderThan(15); - * - * - * If you specify something greater than "weeks" as time untit, it just - * works approximatly, because a month is taken to consist of 4.3 weeks. - * - * @access public - * @return bool Returns true if requested page is older than specified. - * @param int $time The amount of time. - * @param string $unit The unit of the time amount - (year[s], month[s], - * week[s], day[s], hour[s], minute[s], second[s]). - */ - function isOlderThan($time = 0, $unit = 'seconds') - { - if (!isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || $this->isPost()) { - return true; - } - if (!$time) { - return false; - } - - switch (strtolower($unit)) - { - case 'year': - case 'years': - $time *= 12; - case 'month': - case 'months': - $time *= 4.3; - case 'week': - case 'weeks': - $time *= 7; - case 'day': - case 'days': - $time *= 24; - case 'hour': - case 'hours': - $time *= 60; - case 'minute': - case 'minutes': - $time *= 60; - } - - return (time() - $this->getCacheStart()) > $time; - } - - /** - * Is Cached - * - * Check whether we can consider to be cached on the client side. - * - * @access public - * @return bool Whether the page/resource is considered to be cached. - * @param int $lastModified Unix timestamp of last modification. - */ - function isCached($lastModified = 0) - { - if ($this->isPost()) { - return false; - } - if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && !$lastModified) { - return true; - } - if (!$seconds = time() - $lastModified) { - return false; - } - return !$this->isOlderThan($seconds); - } - - /** - * Is Post - * - * Check if request method is "POST". - * - * @access public - * @return bool - */ - function isPost() - { - return isset($_SERVER['REQUEST_METHOD']) and - 'POST' == $_SERVER['REQUEST_METHOD']; - } - - /** - * Exit If Cached - * - * Exit with "HTTP 304 Not Modified" if we consider to be cached. - * - * @access public - * @return void - * @param int $lastModified Unix timestamp of last modification. - */ - function exitIfCached($lastModified = 0) - { - if ($this->isCached($lastModified)) { - $this->exitCached(); - } - } - - /** - * Exit Cached - * - * Exit with "HTTP 304 Not Modified". - * - * @access public - * @return void - */ - function exitCached() - { - $this->sendHeaders(); - $this->sendStatusCode(304); - exit; - } - - /** - * Set Last Modified - * - * @access public - * @return void - * @param int $lastModified The unix timestamp of last modification. - */ - function setLastModified($lastModified = null) - { - $this->setHeader('Last-Modified', $lastModified); - } -} -?> + + * @author Michael Wallner + * @copyright 2003-2005 The Authors + * @license BSD, revised + * @version CVS: $Id$ + * @link http://pear.php.net/package/HTTP_Header + */ + +/** + * Requires HTTP_Header + */ +require_once 'HTTP/Header.php'; + +/** + * HTTP_Header_Cache + * + * This package provides methods to easier handle caching of HTTP pages. That + * means that the pages can be cached at the client (user agent or browser) and + * your application only needs to send "hey client you already have the pages". + * + * Which is done by sending the HTTP-Status "304 Not Modified", so that your + * application load and the network traffic can be reduced, since you only need + * to send the complete page once. This is really an advantage e.g. for + * generated style sheets, or simply pages that do only change rarely. + * + * Usage: + * + * require_once 'HTTP/Header/Cache.php'; + * $httpCache = new HTTP_Header_Cache(4, 'weeks'); + * $httpCache->sendHeaders(); + * // your code goes here + * + * + * @package HTTP_Header + * @category HTTP + * @access public + * @version $Revision$ + */ +class HTTP_Header_Cache extends HTTP_Header +{ + /** + * Constructor + * + * Set the amount of time to cache. + * + * @access public + * @return object HTTP_Header_Cache + * @param int $expires + * @param string $unit + */ + function HTTP_Header_Cache($expires = 0, $unit = 'seconds') + { + parent::HTTP_Header(); + $this->setHeader('Pragma', 'cache'); + $this->setHeader('Last-Modified', $this->getCacheStart()); + $this->setHeader('Cache-Control', 'private, must-revalidate, max-age=0'); + + if ($expires) { + if (!$this->isOlderThan($expires, $unit)) { + $this->exitCached(); + } + $this->setHeader('Last-Modified', time()); + } + } + + /** + * Get Cache Start + * + * Returns the unix timestamp of the If-Modified-Since HTTP header or the + * current time if the header was not sent by the client. + * + * @access public + * @return int unix timestamp + */ + function getCacheStart() + { + if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && !$this->isPost()) { + return strtotime(current($array = explode(';', + $_SERVER['HTTP_IF_MODIFIED_SINCE']))); + } + return time(); + } + + /** + * Is Older Than + * + * You can call it like this: + * + * $httpCache->isOlderThan(1, 'day'); + * $httpCache->isOlderThan(47, 'days'); + * + * $httpCache->isOlderThan(1, 'week'); + * $httpCache->isOlderThan(3, 'weeks'); + * + * $httpCache->isOlderThan(1, 'hour'); + * $httpCache->isOlderThan(5, 'hours'); + * + * $httpCache->isOlderThan(1, 'minute'); + * $httpCache->isOlderThan(15, 'minutes'); + * + * $httpCache->isOlderThan(1, 'second'); + * $httpCache->isOlderThan(15); + * + * + * If you specify something greater than "weeks" as time untit, it just + * works approximatly, because a month is taken to consist of 4.3 weeks. + * + * @access public + * @return bool Returns true if requested page is older than specified. + * @param int $time The amount of time. + * @param string $unit The unit of the time amount - (year[s], month[s], + * week[s], day[s], hour[s], minute[s], second[s]). + */ + function isOlderThan($time = 0, $unit = 'seconds') + { + if (!isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || $this->isPost()) { + return true; + } + if (!$time) { + return false; + } + + switch (strtolower($unit)) + { + case 'year': + case 'years': + $time *= 12; + case 'month': + case 'months': + $time *= 4.3; + case 'week': + case 'weeks': + $time *= 7; + case 'day': + case 'days': + $time *= 24; + case 'hour': + case 'hours': + $time *= 60; + case 'minute': + case 'minutes': + $time *= 60; + } + + return (time() - $this->getCacheStart()) > $time; + } + + /** + * Is Cached + * + * Check whether we can consider to be cached on the client side. + * + * @access public + * @return bool Whether the page/resource is considered to be cached. + * @param int $lastModified Unix timestamp of last modification. + */ + function isCached($lastModified = 0) + { + if ($this->isPost()) { + return false; + } + if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && !$lastModified) { + return true; + } + if (!$seconds = time() - $lastModified) { + return false; + } + return !$this->isOlderThan($seconds); + } + + /** + * Is Post + * + * Check if request method is "POST". + * + * @access public + * @return bool + */ + function isPost() + { + return isset($_SERVER['REQUEST_METHOD']) and + 'POST' == $_SERVER['REQUEST_METHOD']; + } + + /** + * Exit If Cached + * + * Exit with "HTTP 304 Not Modified" if we consider to be cached. + * + * @access public + * @return void + * @param int $lastModified Unix timestamp of last modification. + */ + function exitIfCached($lastModified = 0) + { + if ($this->isCached($lastModified)) { + $this->exitCached(); + } + } + + /** + * Exit Cached + * + * Exit with "HTTP 304 Not Modified". + * + * @access public + * @return void + */ + function exitCached() + { + $this->sendHeaders(); + $this->sendStatusCode(304); + exit; + } + + /** + * Set Last Modified + * + * @access public + * @return void + * @param int $lastModified The unix timestamp of last modification. + */ + function setLastModified($lastModified = null) + { + $this->setHeader('Last-Modified', $lastModified); + } +} +?> diff --git a/thirdparty/pear/HTTP/Request.php b/thirdparty/pear/HTTP/Request.php index f7fa93e..5d48b39 100644 --- a/thirdparty/pear/HTTP/Request.php +++ b/thirdparty/pear/HTTP/Request.php @@ -32,7 +32,7 @@ // | Author: Richard Heyes | // +-----------------------------------------------------------------------+ // -// $Id: Request.php,v 1.43 2005/11/06 18:29:14 avb Exp $ +// $Id$ // // HTTP_Request Class // diff --git a/thirdparty/pear/HTTP/Request/Listener.php b/thirdparty/pear/HTTP/Request/Listener.php index 38b115a..4923419 100644 --- a/thirdparty/pear/HTTP/Request/Listener.php +++ b/thirdparty/pear/HTTP/Request/Listener.php @@ -32,7 +32,7 @@ // | Author: Alexey Borzov | // +-----------------------------------------------------------------------+ // -// $Id: Listener.php,v 1.2 2003/10/26 10:28:29 avb Exp $ +// $Id$ // /** @@ -42,7 +42,7 @@ * * @package HTTP_Request * @author Alexey Borzov - * @version $Revision: 1.2 $ + * @version $Revision$ */ class HTTP_Request_Listener { diff --git a/thirdparty/pear/HTTP/Upload.php b/thirdparty/pear/HTTP/Upload.php index 2737d39..d2390e0 100644 --- a/thirdparty/pear/HTTP/Upload.php +++ b/thirdparty/pear/HTTP/Upload.php @@ -1,856 +1,856 @@ - http://www.gnu.org/copyleft/lesser.txt -// (c) 2001-2004 by Tomas Von Veschler Cox -// -// ********************************************** -// -// $Id: Upload.php,v 1.42 2004/08/08 09:37:50 wenz Exp $ - -/* - * Pear File Uploader class. Easy and secure managment of files - * submitted via HTML Forms. - * - * Leyend: - * - you can add error msgs in your language in the HTTP_Upload_Error class - * - * TODO: - * - try to think a way of having all the Error system in other - * file and only include it when an error ocurrs - * - * -- Notes for users HTTP_Upload >= 0.9.0 -- - * - * Error detection was enhanced, so you no longer need to - * check for PEAR::isError() in $upload->getFiles() or call - * $upload->isMissing(). Instead you'll - * get the error when do a check for $file->isError(). - * - * Example: - * - * $upload = new HTTP_Upload('en'); - * $file = $upload->getFiles('i_dont_exist_in_form_definition'); - * if ($file->isError()) { - * die($file->getMessage()); - * } - * - * -- - * - */ - -require_once 'PEAR.php'; - -/** - * defines default chmod - */ -define('HTTP_UPLOAD_DEFAULT_CHMOD', 0660); - -/** - * Error Class for HTTP_Upload - * - * @author Tomas V.V.Cox - * @see http://vulcanonet.com/soft/index.php?pack=uploader - * @package HTTP_Upload - * @category HTTP - * @access public - */ -class HTTP_Upload_Error extends PEAR -{ - /** - * Selected language for error messages - * @var string - */ - var $lang = 'en'; - - /** - * Whether HTML entities shall be encoded automatically - * @var boolean - */ - var $html = false; - - /** - * Constructor - * - * Creates a new PEAR_Error - * - * @param string $lang The language selected for error code messages - * @access public - */ - function HTTP_Upload_Error($lang = null, $html = false) - { - $this->lang = ($lang !== null) ? $lang : $this->lang; - $this->html = ($html !== false) ? $html : $this->html; - $ini_size = preg_replace('/m/i', '000000', ini_get('upload_max_filesize')); - - if (function_exists('version_compare') && - version_compare(phpversion(), '4.1', 'ge')) { - $maxsize = (isset($_POST['MAX_FILE_SIZE'])) ? - $_POST['MAX_FILE_SIZE'] : null; - } else { - global $HTTP_POST_VARS; - $maxsize = (isset($HTTP_POST_VARS['MAX_FILE_SIZE'])) ? - $HTTP_POST_VARS['MAX_FILE_SIZE'] : null; - } - - if (empty($maxsize) || ($maxsize > $ini_size)) { - $maxsize = $ini_size; - } - // XXXXX Add here error messages in your language - $this->error_codes = array( - 'TOO_LARGE' => array( - 'es' => "Fichero demasiado largo. El maximo permitido es: $maxsize bytes.", - 'en' => "File size too large. The maximum permitted size is: $maxsize bytes.", - 'de' => "Datei zu groß. Die zulässige Maximalgröße ist: $maxsize Bytes.", - 'nl' => "Het bestand is te groot, de maximale grootte is: $maxsize bytes.", - 'fr' => "Le fichier est trop gros. La taille maximum autorisée est: $maxsize bytes.", - 'it' => "Il file é troppo grande. Il massimo permesso é: $maxsize bytes.", - 'pt_BR' => "Arquivo muito grande. O tamanho máximo permitido é $maxsize bytes." - ), - 'MISSING_DIR' => array( - 'es' => 'Falta directorio destino.', - 'en' => 'Missing destination directory.', - 'de' => 'Kein Zielverzeichnis definiert.', - 'nl' => 'Geen bestemmings directory.', - 'fr' => 'Le répertoire de destination n\'est pas défini.', - 'it' => 'Manca la directory di destinazione.', - 'pt_BR' => 'Ausência de diretório de destino.' - ), - 'IS_NOT_DIR' => array( - 'es' => 'El directorio destino no existe o es un fichero regular.', - 'en' => 'The destination directory doesn\'t exist or is a regular file.', - 'de' => 'Das angebene Zielverzeichnis existiert nicht oder ist eine Datei.', - 'nl' => 'De doeldirectory bestaat niet, of is een gewoon bestand.', - 'fr' => 'Le répertoire de destination n\'existe pas ou il s\'agit d\'un fichier régulier.', - 'it' => 'La directory di destinazione non esiste o é un file.', - 'pt_BR' => 'O diretório de destino não existe ou é um arquivo.' - ), - 'NO_WRITE_PERMS' => array( - 'es' => 'El directorio destino no tiene permisos de escritura.', - 'en' => 'The destination directory doesn\'t have write perms.', - 'de' => 'Fehlende Schreibrechte für das Zielverzeichnis.', - 'nl' => 'Geen toestemming om te schrijven in de doeldirectory.', - 'fr' => 'Le répertoire de destination n\'a pas les droits en écriture.', - 'it' => 'Non si hanno i permessi di scrittura sulla directory di destinazione.', - 'pt_BR' => 'O diretório de destino não possui permissão para escrita.' - ), - 'NO_USER_FILE' => array( - 'es' => 'No se ha escogido fichero para el upload.', - 'en' => 'You haven\'t selected any file for uploading.', - 'de' => 'Es wurde keine Datei für den Upload ausgewählt.', - 'nl' => 'Er is geen bestand opgegeven om te uploaden.', - 'fr' => 'Vous n\'avez pas sélectionné de fichier à envoyer.', - 'it' => 'Nessun file selezionato per l\'upload.', - 'pt_BR' => 'Nenhum arquivo selecionado para upload.' - ), - 'BAD_FORM' => array( - 'es' => 'El formulario no contiene method="post" enctype="multipart/form-data" requerido.', - 'en' => 'The html form doesn\'t contain the required method="post" enctype="multipart/form-data".', - 'de' => 'Das HTML-Formular enthält nicht die Angabe method="post" enctype="multipart/form-data" '. - 'im >form<-Tag.', - 'nl' => 'Het HTML-formulier bevat niet de volgende benodigde '. - 'eigenschappen: method="post" enctype="multipart/form-data".', - 'fr' => 'Le formulaire HTML ne contient pas les attributs requis : '. - ' method="post" enctype="multipart/form-data".', - 'it' => 'Il modulo HTML non contiene gli attributi richiesti: "'. - ' method="post" enctype="multipart/form-data".', - 'pt_BR' => 'O formulário HTML não possui o method="post" enctype="multipart/form-data" requerido.' - ), - 'E_FAIL_COPY' => array( - 'es' => 'Fallo al copiar el fichero temporal.', - 'en' => 'Failed to copy the temporary file.', - 'de' => 'Temporäre Datei konnte nicht kopiert werden.', - 'nl' => 'Het tijdelijke bestand kon niet gekopieerd worden.', - 'fr' => 'L\'enregistrement du fichier temporaire a échoué.', - 'it' => 'Copia del file temporaneo fallita.', - 'pt_BR' => 'Falha ao copiar o arquivo temporário.' - ), - 'E_FAIL_MOVE' => array( - 'es' => 'No puedo mover el fichero.', - 'en' => 'Impossible to move the file.', - 'de' => 'Datei kann nicht verschoben werden.', - 'nl' => 'Het bestand kon niet verplaatst worden.', - 'fr' => 'Impossible de déplacer le fichier.', - 'pt_BR' => 'Não foi possível mover o arquivo.' - ), - 'FILE_EXISTS' => array( - 'es' => 'El fichero destino ya existe.', - 'en' => 'The destination file already exists.', - 'de' => 'Die zu erzeugende Datei existiert bereits.', - 'nl' => 'Het doelbestand bestaat al.', - 'fr' => 'Le fichier de destination existe déjà.', - 'it' => 'File destinazione già esistente.', - 'pt_BR' => 'O arquivo de destino já existe.' - ), - 'CANNOT_OVERWRITE' => array( - 'es' => 'El fichero destino ya existe y no se puede sobreescribir.', - 'en' => 'The destination file already exists and could not be overwritten.', - 'de' => 'Die zu erzeugende Datei existiert bereits und konnte nicht überschrieben werden.', - 'nl' => 'Het doelbestand bestaat al, en kon niet worden overschreven.', - 'fr' => 'Le fichier de destination existe déjà et ne peux pas être remplacé.', - 'it' => 'File destinazione già esistente e non si può sovrascrivere.', - 'pt_BR' => 'O arquivo de destino já existe e não pôde ser sobrescrito.' - ), - 'NOT_ALLOWED_EXTENSION' => array( - 'es' => 'Extension de fichero no permitida.', - 'en' => 'File extension not permitted.', - 'de' => 'Unerlaubte Dateiendung.', - 'nl' => 'Niet toegestane bestands-extensie.', - 'fr' => 'Le fichier a une extension non autorisée.', - 'it' => 'Estensione del File non permessa.', - 'pt_BR' => 'Extensão de arquivo não permitida.' - ), - 'PARTIAL' => array( - 'es' => 'El fichero fue parcialmente subido', - 'en' => 'The file was only partially uploaded.', - 'de' => 'Die Datei wurde unvollständig übertragen.', - 'nl' => 'Het bestand is slechts gedeeltelijk geupload.', - 'pt_BR' => 'O arquivo não foi enviado por completo.' - ), - 'ERROR' => array( - 'es' => 'Error en subida:', - 'en' => 'Upload error:', - 'de' => 'Fehler beim Upload:', - 'nl' => 'Upload fout:', - 'pt_BR' => 'Erro de upload:' - ), - 'DEV_NO_DEF_FILE' => array( - 'es' => 'No está definido en el formulario este nombre de fichero como <input type="file" name=?>.', - 'en' => 'This filename is not defined in the form as <input type="file" name=?>.', - 'de' => 'Dieser Dateiname ist im Formular nicht als <input type="file" name=?> definiert.', - 'nl' => 'Deze bestandsnaam is niett gedefineerd in het formulier als <input type="file" name=?>.' - ) - ); - } - - /** - * returns the error code - * - * @param string $e_code type of error - * @return string Error message - */ - function errorCode($e_code) - { - if (!empty($this->error_codes[$e_code][$this->lang])) { - $msg = $this->html ? - html_entity_decode($this->error_codes[$e_code][$this->lang]) : - $this->error_codes[$e_code][$this->lang]; - } else { - $msg = $e_code; - } - - if (!empty($this->error_codes['ERROR'][$this->lang])) { - $error = $this->error_codes['ERROR'][$this->lang]; - } else { - $error = $this->error_codes['ERROR']['en']; - } - return $error.' '.$msg; - } - - /** - * Overwrites the PEAR::raiseError method - * - * @param string $e_code type of error - * @return object PEAR_Error a PEAR-Error object - * @access public - */ - function raiseError($e_code) - { - return PEAR::raiseError($this->errorCode($e_code), $e_code); - } -} - -/** - * This class provides an advanced file uploader system - * for file uploads made from html forms - - * - * @author Tomas V.V.Cox - * @see http://vulcanonet.com/soft/index.php?pack=uploader - * @package HTTP_Upload - * @category HTTP - * @access public - */ -class HTTP_Upload extends HTTP_Upload_Error -{ - /** - * Contains an array of "uploaded files" objects - * @var array - */ - var $files = array(); - - /** - * Contains the desired chmod for uploaded files - * @var int - * @access private - */ - var $_chmod = HTTP_UPLOAD_DEFAULT_CHMOD; - - /** - * Constructor - * - * @param string $lang Language to use for reporting errors - * @see Upload_Error::error_codes - * @access public - */ - function HTTP_Upload($lang = null) - { - $this->HTTP_Upload_Error($lang); - if (function_exists('version_compare') && - version_compare(phpversion(), '4.1', 'ge')) - { - $this->post_files = $_FILES; - if (isset($_SERVER['CONTENT_TYPE'])) { - $this->content_type = $_SERVER['CONTENT_TYPE']; - } - } else { - global $HTTP_POST_FILES, $HTTP_SERVER_VARS; - $this->post_files = $HTTP_POST_FILES; - if (isset($HTTP_SERVER_VARS['CONTENT_TYPE'])) { - $this->content_type = $HTTP_SERVER_VARS['CONTENT_TYPE']; - } - } - } - - /** - * Get files - * - * @param mixed $file If: - * - not given, function will return array of upload_file objects - * - is int, will return the $file position in upload_file objects array - * - is string, will return the upload_file object corresponding - * to $file name of the form. For ex: - * if form is - * to get this file use: $upload->getFiles('userfile') - * - * @return mixed array or object (see @param $file above) or Pear_Error - * @access public - */ - function &getFiles($file = null) - { - static $is_built = false; - //build only once for multiple calls - if (!$is_built) { - $files = &$this->_buildFiles(); - if (PEAR::isError($files)) { - // there was an error with the form. - // Create a faked upload embedding the error - $this->files['_error'] = &new HTTP_Upload_File( - '_error', null, - null, null, - null, $files->getCode(), - $this->lang, $this->_chmod); - } else { - $this->files = $files; - } - $is_built = true; - } - if ($file !== null) { - if (is_int($file)) { - $pos = 0; - foreach ($this->files as $obj) { - if ($pos == $file) { - return $obj; - } - $pos++; - } - } elseif (is_string($file) && isset($this->files[$file])) { - return $this->files[$file]; - } - if (isset($this->files['_error'])) { - return $this->files['_error']; - } else { - // developer didn't specify this name in the form - // warn him about it with a faked upload - return new HTTP_Upload_File( - '_error', null, - null, null, - null, 'DEV_NO_DEF_FILE', - $this->lang); - } - } - return $this->files; - } - - /** - * Creates the list of the uploaded file - * - * @return array of HTTP_Upload_File objects for every file - */ - function &_buildFiles() - { - // Form method check - if (!isset($this->content_type) || - strpos($this->content_type, 'multipart/form-data') !== 0) - { - return $this->raiseError('BAD_FORM'); - } - // In 4.1 $_FILES isn't initialized when no uploads - // XXX (cox) afaik, in >= 4.1 and <= 4.3 only - if (function_exists('version_compare') && - version_compare(phpversion(), '4.1', 'ge')) - { - $error = $this->isMissing(); - if (PEAR::isError($error)) { - return $error; - } - } - - // map error codes from 4.2.0 $_FILES['userfile']['error'] - if (function_exists('version_compare') && - version_compare(phpversion(), '4.2.0', 'ge')) { - $uploadError = array( - 1 => 'TOO_LARGE', - 2 => 'TOO_LARGE', - 3 => 'PARTIAL', - 4 => 'NO_USER_FILE' - ); - } - - - // Parse $_FILES (or $HTTP_POST_FILES) - $files = array(); - foreach ($this->post_files as $userfile => $value) { - if (is_array($value['name'])) { - foreach ($value['name'] as $key => $val) { - $err = $value['error'][$key]; - if (isset($err) && $err !== 0 && isset($uploadError[$err])) { - $error = $uploadError[$err]; - } else { - $error = null; - } - $name = basename($value['name'][$key]); - $tmp_name = $value['tmp_name'][$key]; - $size = $value['size'][$key]; - $type = $value['type'][$key]; - $formname = $userfile . "[$key]"; - $files[$formname] = new HTTP_Upload_File($name, $tmp_name, - $formname, $type, $size, $error, $this->lang, $this->_chmod); - } - // One file - } else { - $err = $value['error']; - if (isset($err) && $err !== 0 && isset($uploadError[$err])) { - $error = $uploadError[$err]; - } else { - $error = null; - } - $name = basename($value['name']); - $tmp_name = $value['tmp_name']; - $size = $value['size']; - $type = $value['type']; - $formname = $userfile; - $files[$formname] = new HTTP_Upload_File($name, $tmp_name, - $formname, $type, $size, $error, $this->lang, $this->_chmod); - } - } - return $files; - } - - /** - * Checks if the user submited or not some file - * - * @return mixed False when are files or PEAR_Error when no files - * @access public - * @see Read the note in the source code about this function - */ - function isMissing() - { - if (count($this->post_files) < 1) { - return $this->raiseError('NO_USER_FILE'); - } - //we also check if at least one file has more than 0 bytes :) - $files = array(); - $size = 0; - foreach ($this->post_files as $userfile => $value) { - if (is_array($value['name'])) { - foreach ($value['name'] as $key => $val) { - $size += $value['size'][$key]; - } - } else { //one file - $size = $value['size']; - } - } - if ($size == 0) { - $this->raiseError('NO_USER_FILE'); - } - return false; - } - - /** - * Sets the chmod to be used for uploaded files - * - * @param int Desired mode - */ - function setChmod($mode) - { - $this->_chmod = $mode; - } -} - -/** - * This class provides functions to work with the uploaded file - * - * @author Tomas V.V.Cox - * @see http://vulcanonet.com/soft/index.php?pack=uploader - * @package HTTP_Upload - * @category HTTP - * @access public - */ -class HTTP_Upload_File extends HTTP_Upload_Error -{ - /** - * If the random seed was initialized before or not - * @var boolean; - */ - var $_seeded = 0; - - /** - * Assoc array with file properties - * @var array - */ - var $upload = array(); - - /** - * If user haven't selected a mode, by default 'safe' will be used - * @var boolean - */ - var $mode_name_selected = false; - - /** - * It's a common security risk in pages who has the upload dir - * under the document root (remember the hack of the Apache web?) - * - * @var array - * @access private - * @see HTTP_Upload_File::setValidExtensions() - */ - var $_extensions_check = array('php', 'phtm', 'phtml', 'php3', 'inc'); - - /** - * @see HTTP_Upload_File::setValidExtensions() - * @var string - * @access private - */ - var $_extensions_mode = 'deny'; - - /** - * Contains the desired chmod for uploaded files - * @var int - * @access private - */ - var $_chmod = HTTP_UPLOAD_DEFAULT_CHMOD; - - /** - * Constructor - * - * @param string $name destination file name - * @param string $tmp temp file name - * @param string $formname name of the form - * @param string $type Mime type of the file - * @param string $size size of the file - * @param string $error error on upload - * @param string $lang used language for errormessages - * @access public - */ - function HTTP_Upload_File($name = null, $tmp = null, $formname = null, - $type = null, $size = null, $error = null, - $lang = null, $chmod = HTTP_UPLOAD_DEFAULT_CHMOD) - { - $this->HTTP_Upload_Error($lang); - $ext = null; - - if (empty($name) || $size == 0) { - $error = 'NO_USER_FILE'; - } elseif ($tmp == 'none') { - $error = 'TOO_LARGE'; - } else { - // strpos needed to detect files without extension - if (($pos = strrpos($name, '.')) !== false) { - $ext = substr($name, $pos + 1); - } - } - - if (function_exists('version_compare') && - version_compare(phpversion(), '4.1', 'ge')) { - if (isset($_POST['MAX_FILE_SIZE']) && - $size > $_POST['MAX_FILE_SIZE']) { - $error = 'TOO_LARGE'; - } - } else { - global $HTTP_POST_VARS; - if (isset($HTTP_POST_VARS['MAX_FILE_SIZE']) && - $size > $HTTP_POST_VARS['MAX_FILE_SIZE']) { - $error = 'TOO_LARGE'; - } - } - - $this->upload = array( - 'real' => $name, - 'name' => $name, - 'form_name' => $formname, - 'ext' => $ext, - 'tmp_name' => $tmp, - 'size' => $size, - 'type' => $type, - 'error' => $error - ); - - $this->_chmod = $chmod; - } - - /** - * Sets the name of the destination file - * - * @param string $mode A valid mode: 'uniq', 'safe' or 'real' or a file name - * @param string $prepend A string to prepend to the name - * @param string $append A string to append to the name - * - * @return string The modified name of the destination file - * @access public - */ - function setName($mode, $prepend = null, $append = null) - { - switch ($mode) { - case 'uniq': - $name = $this->nameToUniq(); - $this->upload['ext'] = $this->nameToSafe($this->upload['ext'], 10); - $name .= '.' . $this->upload['ext']; - break; - case 'safe': - $name = $this->nameToSafe($this->upload['real']); - if (($pos = strrpos($name, '.')) !== false) { - $this->upload['ext'] = substr($name, $pos + 1); - } else { - $this->upload['ext'] = ''; - } - break; - case 'real': - $name = $this->upload['real']; - break; - default: - $name = $mode; - } - $this->upload['name'] = $prepend . $name . $append; - $this->mode_name_selected = true; - return $this->upload['name']; - } - - /** - * Unique file names in the form: 9022210413b75410c28bef.html - * @see HTTP_Upload_File::setName() - */ - function nameToUniq() - { - if (! $this->_seeded) { - srand((double) microtime() * 1000000); - $this->_seeded = 1; - } - $uniq = uniqid(rand()); - return $uniq; - } - - /** - * Format a file name to be safe - * - * @param string $file The string file name - * @param int $maxlen Maximun permited string lenght - * @return string Formatted file name - * @see HTTP_Upload_File::setName() - */ - function nameToSafe($name, $maxlen=250) - { - $noalpha = 'ÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÀÈÌÒÙàèìòùÄËÏÖÜäëïöüÿÃãÕõÅåÑñÇç@°ºª'; - $alpha = 'AEIOUYaeiouyAEIOUaeiouAEIOUaeiouAEIOUaeiouyAaOoAaNnCcaooa'; - - $name = substr($name, 0, $maxlen); - $name = strtr($name, $noalpha, $alpha); - // not permitted chars are replaced with "_" - return preg_replace('/[^a-zA-Z0-9,._\+\()\-]/', '_', $name); - } - - /** - * The upload was valid - * - * @return bool If the file was submitted correctly - * @access public - */ - function isValid() - { - if ($this->upload['error'] === null) { - return true; - } - return false; - } - - /** - * User haven't submit a file - * - * @return bool If the user submitted a file or not - * @access public - */ - function isMissing() - { - if ($this->upload['error'] == 'NO_USER_FILE') { - return true; - } - return false; - } - - /** - * Some error occured during upload (most common due a file size problem, - * like max size exceeded or 0 bytes long). - * @return bool If there were errors submitting the file (probably - * because the file excess the max permitted file size) - * @access public - */ - function isError() - { - if (in_array($this->upload['error'], array('TOO_LARGE', 'BAD_FORM','DEV_NO_DEF_FILE'))) { - return true; - } - return false; - } - - /** - * Moves the uploaded file to its destination directory. - * - * @param string $dir_dest Destination directory - * @param bool $overwrite Overwrite if destination file exists? - * @return mixed True on success or Pear_Error object on error - * @access public - */ - function moveTo($dir_dest, $overwrite = true) - { - if (!$this->isValid()) { - return $this->raiseError($this->upload['error']); - } - - //Valid extensions check - if (!$this->_evalValidExtensions()) { - return $this->raiseError('NOT_ALLOWED_EXTENSION'); - } - - $err_code = $this->_chk_dir_dest($dir_dest); - if ($err_code !== false) { - return $this->raiseError($err_code); - } - // Use 'safe' mode by default if no other was selected - if (!$this->mode_name_selected) { - $this->setName('safe'); - } - - $name_dest = $dir_dest . DIRECTORY_SEPARATOR . $this->upload['name']; - - if (@is_file($name_dest)) { - if ($overwrite !== true) { - return $this->raiseError('FILE_EXISTS'); - } elseif (!is_writable($name_dest)) { - return $this->raiseError('CANNOT_OVERWRITE'); - } - } - - // copy the file and let php clean the tmp - if (!@move_uploaded_file($this->upload['tmp_name'], $name_dest)) { - return $this->raiseError('E_FAIL_MOVE'); - } - @chmod($name_dest, $this->_chmod); - return $this->getProp('name'); - } - - /** - * Check for a valid destination dir - * - * @param string $dir_dest Destination dir - * @return mixed False on no errors or error code on error - */ - function _chk_dir_dest($dir_dest) - { - if (!$dir_dest) { - return 'MISSING_DIR'; - } - if (!@is_dir ($dir_dest)) { - return 'IS_NOT_DIR'; - } - if (!is_writeable ($dir_dest)) { - return 'NO_WRITE_PERMS'; - } - return false; - } - /** - * Retrive properties of the uploaded file - * @param string $name The property name. When null an assoc array with - * all the properties will be returned - * @return mixed A string or array - * @see HTTP_Upload_File::HTTP_Upload_File() - * @access public - */ - function getProp($name = null) - { - if ($name === null) { - return $this->upload; - } - return $this->upload[$name]; - } - - /** - * Returns a error message, if a error occured - * (deprecated) Use getMessage() instead - * @return string a Error message - * @access public - */ - function errorMsg() - { - return $this->errorCode($this->upload['error']); - } - - /** - * Returns a error message, if a error occured - * @return string a Error message - * @access public - */ - function getMessage() - { - return $this->errorCode($this->upload['error']); - } - - /** - * Function to restrict the valid extensions on file uploads - * - * @param array $exts File extensions to validate - * @param string $mode The type of validation: - * 1) 'deny' Will deny only the supplied extensions - * 2) 'accept' Will accept only the supplied extensions - * as valid - * @access public - */ - function setValidExtensions($exts, $mode = 'deny') - { - $this->_extensions_check = $exts; - $this->_extensions_mode = $mode; - } - - /** - * Evaluates the validity of the extensions set by setValidExtensions - * - * @return bool False on non valid extension, true if they are valid - * @access private - */ - function _evalValidExtensions() - { - $exts = $this->_extensions_check; - settype($exts, 'array'); - if ($this->_extensions_mode == 'deny') { - if (in_array($this->getProp('ext'), $exts)) { - return false; - } - // mode == 'accept' - } else { - if (!in_array($this->getProp('ext'), $exts)) { - return false; - } - } - return true; - } -} + http://www.gnu.org/copyleft/lesser.txt +// (c) 2001-2004 by Tomas Von Veschler Cox +// +// ********************************************** +// +// $Id$ + +/* + * Pear File Uploader class. Easy and secure managment of files + * submitted via HTML Forms. + * + * Leyend: + * - you can add error msgs in your language in the HTTP_Upload_Error class + * + * TODO: + * - try to think a way of having all the Error system in other + * file and only include it when an error ocurrs + * + * -- Notes for users HTTP_Upload >= 0.9.0 -- + * + * Error detection was enhanced, so you no longer need to + * check for PEAR::isError() in $upload->getFiles() or call + * $upload->isMissing(). Instead you'll + * get the error when do a check for $file->isError(). + * + * Example: + * + * $upload = new HTTP_Upload('en'); + * $file = $upload->getFiles('i_dont_exist_in_form_definition'); + * if ($file->isError()) { + * die($file->getMessage()); + * } + * + * -- + * + */ + +require_once 'PEAR.php'; + +/** + * defines default chmod + */ +define('HTTP_UPLOAD_DEFAULT_CHMOD', 0660); + +/** + * Error Class for HTTP_Upload + * + * @author Tomas V.V.Cox + * @see http://vulcanonet.com/soft/index.php?pack=uploader + * @package HTTP_Upload + * @category HTTP + * @access public + */ +class HTTP_Upload_Error extends PEAR +{ + /** + * Selected language for error messages + * @var string + */ + var $lang = 'en'; + + /** + * Whether HTML entities shall be encoded automatically + * @var boolean + */ + var $html = false; + + /** + * Constructor + * + * Creates a new PEAR_Error + * + * @param string $lang The language selected for error code messages + * @access public + */ + function HTTP_Upload_Error($lang = null, $html = false) + { + $this->lang = ($lang !== null) ? $lang : $this->lang; + $this->html = ($html !== false) ? $html : $this->html; + $ini_size = preg_replace('/m/i', '000000', ini_get('upload_max_filesize')); + + if (function_exists('version_compare') && + version_compare(phpversion(), '4.1', 'ge')) { + $maxsize = (isset($_POST['MAX_FILE_SIZE'])) ? + $_POST['MAX_FILE_SIZE'] : null; + } else { + global $HTTP_POST_VARS; + $maxsize = (isset($HTTP_POST_VARS['MAX_FILE_SIZE'])) ? + $HTTP_POST_VARS['MAX_FILE_SIZE'] : null; + } + + if (empty($maxsize) || ($maxsize > $ini_size)) { + $maxsize = $ini_size; + } + // XXXXX Add here error messages in your language + $this->error_codes = array( + 'TOO_LARGE' => array( + 'es' => "Fichero demasiado largo. El maximo permitido es: $maxsize bytes.", + 'en' => "File size too large. The maximum permitted size is: $maxsize bytes.", + 'de' => "Datei zu groß. Die zulässige Maximalgröße ist: $maxsize Bytes.", + 'nl' => "Het bestand is te groot, de maximale grootte is: $maxsize bytes.", + 'fr' => "Le fichier est trop gros. La taille maximum autorisée est: $maxsize bytes.", + 'it' => "Il file é troppo grande. Il massimo permesso é: $maxsize bytes.", + 'pt_BR' => "Arquivo muito grande. O tamanho máximo permitido é $maxsize bytes." + ), + 'MISSING_DIR' => array( + 'es' => 'Falta directorio destino.', + 'en' => 'Missing destination directory.', + 'de' => 'Kein Zielverzeichnis definiert.', + 'nl' => 'Geen bestemmings directory.', + 'fr' => 'Le répertoire de destination n\'est pas défini.', + 'it' => 'Manca la directory di destinazione.', + 'pt_BR' => 'Ausência de diretório de destino.' + ), + 'IS_NOT_DIR' => array( + 'es' => 'El directorio destino no existe o es un fichero regular.', + 'en' => 'The destination directory doesn\'t exist or is a regular file.', + 'de' => 'Das angebene Zielverzeichnis existiert nicht oder ist eine Datei.', + 'nl' => 'De doeldirectory bestaat niet, of is een gewoon bestand.', + 'fr' => 'Le répertoire de destination n\'existe pas ou il s\'agit d\'un fichier régulier.', + 'it' => 'La directory di destinazione non esiste o é un file.', + 'pt_BR' => 'O diretório de destino não existe ou é um arquivo.' + ), + 'NO_WRITE_PERMS' => array( + 'es' => 'El directorio destino no tiene permisos de escritura.', + 'en' => 'The destination directory doesn\'t have write perms.', + 'de' => 'Fehlende Schreibrechte für das Zielverzeichnis.', + 'nl' => 'Geen toestemming om te schrijven in de doeldirectory.', + 'fr' => 'Le répertoire de destination n\'a pas les droits en écriture.', + 'it' => 'Non si hanno i permessi di scrittura sulla directory di destinazione.', + 'pt_BR' => 'O diretório de destino não possui permissão para escrita.' + ), + 'NO_USER_FILE' => array( + 'es' => 'No se ha escogido fichero para el upload.', + 'en' => 'You haven\'t selected any file for uploading.', + 'de' => 'Es wurde keine Datei für den Upload ausgewählt.', + 'nl' => 'Er is geen bestand opgegeven om te uploaden.', + 'fr' => 'Vous n\'avez pas sélectionné de fichier à envoyer.', + 'it' => 'Nessun file selezionato per l\'upload.', + 'pt_BR' => 'Nenhum arquivo selecionado para upload.' + ), + 'BAD_FORM' => array( + 'es' => 'El formulario no contiene method="post" enctype="multipart/form-data" requerido.', + 'en' => 'The html form doesn\'t contain the required method="post" enctype="multipart/form-data".', + 'de' => 'Das HTML-Formular enthält nicht die Angabe method="post" enctype="multipart/form-data" '. + 'im >form<-Tag.', + 'nl' => 'Het HTML-formulier bevat niet de volgende benodigde '. + 'eigenschappen: method="post" enctype="multipart/form-data".', + 'fr' => 'Le formulaire HTML ne contient pas les attributs requis : '. + ' method="post" enctype="multipart/form-data".', + 'it' => 'Il modulo HTML non contiene gli attributi richiesti: "'. + ' method="post" enctype="multipart/form-data".', + 'pt_BR' => 'O formulário HTML não possui o method="post" enctype="multipart/form-data" requerido.' + ), + 'E_FAIL_COPY' => array( + 'es' => 'Fallo al copiar el fichero temporal.', + 'en' => 'Failed to copy the temporary file.', + 'de' => 'Temporäre Datei konnte nicht kopiert werden.', + 'nl' => 'Het tijdelijke bestand kon niet gekopieerd worden.', + 'fr' => 'L\'enregistrement du fichier temporaire a échoué.', + 'it' => 'Copia del file temporaneo fallita.', + 'pt_BR' => 'Falha ao copiar o arquivo temporário.' + ), + 'E_FAIL_MOVE' => array( + 'es' => 'No puedo mover el fichero.', + 'en' => 'Impossible to move the file.', + 'de' => 'Datei kann nicht verschoben werden.', + 'nl' => 'Het bestand kon niet verplaatst worden.', + 'fr' => 'Impossible de déplacer le fichier.', + 'pt_BR' => 'Não foi possível mover o arquivo.' + ), + 'FILE_EXISTS' => array( + 'es' => 'El fichero destino ya existe.', + 'en' => 'The destination file already exists.', + 'de' => 'Die zu erzeugende Datei existiert bereits.', + 'nl' => 'Het doelbestand bestaat al.', + 'fr' => 'Le fichier de destination existe déjà.', + 'it' => 'File destinazione già esistente.', + 'pt_BR' => 'O arquivo de destino já existe.' + ), + 'CANNOT_OVERWRITE' => array( + 'es' => 'El fichero destino ya existe y no se puede sobreescribir.', + 'en' => 'The destination file already exists and could not be overwritten.', + 'de' => 'Die zu erzeugende Datei existiert bereits und konnte nicht überschrieben werden.', + 'nl' => 'Het doelbestand bestaat al, en kon niet worden overschreven.', + 'fr' => 'Le fichier de destination existe déjà et ne peux pas être remplacé.', + 'it' => 'File destinazione già esistente e non si può sovrascrivere.', + 'pt_BR' => 'O arquivo de destino já existe e não pôde ser sobrescrito.' + ), + 'NOT_ALLOWED_EXTENSION' => array( + 'es' => 'Extension de fichero no permitida.', + 'en' => 'File extension not permitted.', + 'de' => 'Unerlaubte Dateiendung.', + 'nl' => 'Niet toegestane bestands-extensie.', + 'fr' => 'Le fichier a une extension non autorisée.', + 'it' => 'Estensione del File non permessa.', + 'pt_BR' => 'Extensão de arquivo não permitida.' + ), + 'PARTIAL' => array( + 'es' => 'El fichero fue parcialmente subido', + 'en' => 'The file was only partially uploaded.', + 'de' => 'Die Datei wurde unvollständig übertragen.', + 'nl' => 'Het bestand is slechts gedeeltelijk geupload.', + 'pt_BR' => 'O arquivo não foi enviado por completo.' + ), + 'ERROR' => array( + 'es' => 'Error en subida:', + 'en' => 'Upload error:', + 'de' => 'Fehler beim Upload:', + 'nl' => 'Upload fout:', + 'pt_BR' => 'Erro de upload:' + ), + 'DEV_NO_DEF_FILE' => array( + 'es' => 'No está definido en el formulario este nombre de fichero como <input type="file" name=?>.', + 'en' => 'This filename is not defined in the form as <input type="file" name=?>.', + 'de' => 'Dieser Dateiname ist im Formular nicht als <input type="file" name=?> definiert.', + 'nl' => 'Deze bestandsnaam is niett gedefineerd in het formulier als <input type="file" name=?>.' + ) + ); + } + + /** + * returns the error code + * + * @param string $e_code type of error + * @return string Error message + */ + function errorCode($e_code) + { + if (!empty($this->error_codes[$e_code][$this->lang])) { + $msg = $this->html ? + html_entity_decode($this->error_codes[$e_code][$this->lang]) : + $this->error_codes[$e_code][$this->lang]; + } else { + $msg = $e_code; + } + + if (!empty($this->error_codes['ERROR'][$this->lang])) { + $error = $this->error_codes['ERROR'][$this->lang]; + } else { + $error = $this->error_codes['ERROR']['en']; + } + return $error.' '.$msg; + } + + /** + * Overwrites the PEAR::raiseError method + * + * @param string $e_code type of error + * @return object PEAR_Error a PEAR-Error object + * @access public + */ + function raiseError($e_code) + { + return PEAR::raiseError($this->errorCode($e_code), $e_code); + } +} + +/** + * This class provides an advanced file uploader system + * for file uploads made from html forms + + * + * @author Tomas V.V.Cox + * @see http://vulcanonet.com/soft/index.php?pack=uploader + * @package HTTP_Upload + * @category HTTP + * @access public + */ +class HTTP_Upload extends HTTP_Upload_Error +{ + /** + * Contains an array of "uploaded files" objects + * @var array + */ + var $files = array(); + + /** + * Contains the desired chmod for uploaded files + * @var int + * @access private + */ + var $_chmod = HTTP_UPLOAD_DEFAULT_CHMOD; + + /** + * Constructor + * + * @param string $lang Language to use for reporting errors + * @see Upload_Error::error_codes + * @access public + */ + function HTTP_Upload($lang = null) + { + $this->HTTP_Upload_Error($lang); + if (function_exists('version_compare') && + version_compare(phpversion(), '4.1', 'ge')) + { + $this->post_files = $_FILES; + if (isset($_SERVER['CONTENT_TYPE'])) { + $this->content_type = $_SERVER['CONTENT_TYPE']; + } + } else { + global $HTTP_POST_FILES, $HTTP_SERVER_VARS; + $this->post_files = $HTTP_POST_FILES; + if (isset($HTTP_SERVER_VARS['CONTENT_TYPE'])) { + $this->content_type = $HTTP_SERVER_VARS['CONTENT_TYPE']; + } + } + } + + /** + * Get files + * + * @param mixed $file If: + * - not given, function will return array of upload_file objects + * - is int, will return the $file position in upload_file objects array + * - is string, will return the upload_file object corresponding + * to $file name of the form. For ex: + * if form is + * to get this file use: $upload->getFiles('userfile') + * + * @return mixed array or object (see @param $file above) or Pear_Error + * @access public + */ + function &getFiles($file = null) + { + static $is_built = false; + //build only once for multiple calls + if (!$is_built) { + $files = &$this->_buildFiles(); + if (PEAR::isError($files)) { + // there was an error with the form. + // Create a faked upload embedding the error + $this->files['_error'] = &new HTTP_Upload_File( + '_error', null, + null, null, + null, $files->getCode(), + $this->lang, $this->_chmod); + } else { + $this->files = $files; + } + $is_built = true; + } + if ($file !== null) { + if (is_int($file)) { + $pos = 0; + foreach ($this->files as $obj) { + if ($pos == $file) { + return $obj; + } + $pos++; + } + } elseif (is_string($file) && isset($this->files[$file])) { + return $this->files[$file]; + } + if (isset($this->files['_error'])) { + return $this->files['_error']; + } else { + // developer didn't specify this name in the form + // warn him about it with a faked upload + return new HTTP_Upload_File( + '_error', null, + null, null, + null, 'DEV_NO_DEF_FILE', + $this->lang); + } + } + return $this->files; + } + + /** + * Creates the list of the uploaded file + * + * @return array of HTTP_Upload_File objects for every file + */ + function &_buildFiles() + { + // Form method check + if (!isset($this->content_type) || + strpos($this->content_type, 'multipart/form-data') !== 0) + { + return $this->raiseError('BAD_FORM'); + } + // In 4.1 $_FILES isn't initialized when no uploads + // XXX (cox) afaik, in >= 4.1 and <= 4.3 only + if (function_exists('version_compare') && + version_compare(phpversion(), '4.1', 'ge')) + { + $error = $this->isMissing(); + if (PEAR::isError($error)) { + return $error; + } + } + + // map error codes from 4.2.0 $_FILES['userfile']['error'] + if (function_exists('version_compare') && + version_compare(phpversion(), '4.2.0', 'ge')) { + $uploadError = array( + 1 => 'TOO_LARGE', + 2 => 'TOO_LARGE', + 3 => 'PARTIAL', + 4 => 'NO_USER_FILE' + ); + } + + + // Parse $_FILES (or $HTTP_POST_FILES) + $files = array(); + foreach ($this->post_files as $userfile => $value) { + if (is_array($value['name'])) { + foreach ($value['name'] as $key => $val) { + $err = $value['error'][$key]; + if (isset($err) && $err !== 0 && isset($uploadError[$err])) { + $error = $uploadError[$err]; + } else { + $error = null; + } + $name = basename($value['name'][$key]); + $tmp_name = $value['tmp_name'][$key]; + $size = $value['size'][$key]; + $type = $value['type'][$key]; + $formname = $userfile . "[$key]"; + $files[$formname] = new HTTP_Upload_File($name, $tmp_name, + $formname, $type, $size, $error, $this->lang, $this->_chmod); + } + // One file + } else { + $err = $value['error']; + if (isset($err) && $err !== 0 && isset($uploadError[$err])) { + $error = $uploadError[$err]; + } else { + $error = null; + } + $name = basename($value['name']); + $tmp_name = $value['tmp_name']; + $size = $value['size']; + $type = $value['type']; + $formname = $userfile; + $files[$formname] = new HTTP_Upload_File($name, $tmp_name, + $formname, $type, $size, $error, $this->lang, $this->_chmod); + } + } + return $files; + } + + /** + * Checks if the user submited or not some file + * + * @return mixed False when are files or PEAR_Error when no files + * @access public + * @see Read the note in the source code about this function + */ + function isMissing() + { + if (count($this->post_files) < 1) { + return $this->raiseError('NO_USER_FILE'); + } + //we also check if at least one file has more than 0 bytes :) + $files = array(); + $size = 0; + foreach ($this->post_files as $userfile => $value) { + if (is_array($value['name'])) { + foreach ($value['name'] as $key => $val) { + $size += $value['size'][$key]; + } + } else { //one file + $size = $value['size']; + } + } + if ($size == 0) { + $this->raiseError('NO_USER_FILE'); + } + return false; + } + + /** + * Sets the chmod to be used for uploaded files + * + * @param int Desired mode + */ + function setChmod($mode) + { + $this->_chmod = $mode; + } +} + +/** + * This class provides functions to work with the uploaded file + * + * @author Tomas V.V.Cox + * @see http://vulcanonet.com/soft/index.php?pack=uploader + * @package HTTP_Upload + * @category HTTP + * @access public + */ +class HTTP_Upload_File extends HTTP_Upload_Error +{ + /** + * If the random seed was initialized before or not + * @var boolean; + */ + var $_seeded = 0; + + /** + * Assoc array with file properties + * @var array + */ + var $upload = array(); + + /** + * If user haven't selected a mode, by default 'safe' will be used + * @var boolean + */ + var $mode_name_selected = false; + + /** + * It's a common security risk in pages who has the upload dir + * under the document root (remember the hack of the Apache web?) + * + * @var array + * @access private + * @see HTTP_Upload_File::setValidExtensions() + */ + var $_extensions_check = array('php', 'phtm', 'phtml', 'php3', 'inc'); + + /** + * @see HTTP_Upload_File::setValidExtensions() + * @var string + * @access private + */ + var $_extensions_mode = 'deny'; + + /** + * Contains the desired chmod for uploaded files + * @var int + * @access private + */ + var $_chmod = HTTP_UPLOAD_DEFAULT_CHMOD; + + /** + * Constructor + * + * @param string $name destination file name + * @param string $tmp temp file name + * @param string $formname name of the form + * @param string $type Mime type of the file + * @param string $size size of the file + * @param string $error error on upload + * @param string $lang used language for errormessages + * @access public + */ + function HTTP_Upload_File($name = null, $tmp = null, $formname = null, + $type = null, $size = null, $error = null, + $lang = null, $chmod = HTTP_UPLOAD_DEFAULT_CHMOD) + { + $this->HTTP_Upload_Error($lang); + $ext = null; + + if (empty($name) || $size == 0) { + $error = 'NO_USER_FILE'; + } elseif ($tmp == 'none') { + $error = 'TOO_LARGE'; + } else { + // strpos needed to detect files without extension + if (($pos = strrpos($name, '.')) !== false) { + $ext = substr($name, $pos + 1); + } + } + + if (function_exists('version_compare') && + version_compare(phpversion(), '4.1', 'ge')) { + if (isset($_POST['MAX_FILE_SIZE']) && + $size > $_POST['MAX_FILE_SIZE']) { + $error = 'TOO_LARGE'; + } + } else { + global $HTTP_POST_VARS; + if (isset($HTTP_POST_VARS['MAX_FILE_SIZE']) && + $size > $HTTP_POST_VARS['MAX_FILE_SIZE']) { + $error = 'TOO_LARGE'; + } + } + + $this->upload = array( + 'real' => $name, + 'name' => $name, + 'form_name' => $formname, + 'ext' => $ext, + 'tmp_name' => $tmp, + 'size' => $size, + 'type' => $type, + 'error' => $error + ); + + $this->_chmod = $chmod; + } + + /** + * Sets the name of the destination file + * + * @param string $mode A valid mode: 'uniq', 'safe' or 'real' or a file name + * @param string $prepend A string to prepend to the name + * @param string $append A string to append to the name + * + * @return string The modified name of the destination file + * @access public + */ + function setName($mode, $prepend = null, $append = null) + { + switch ($mode) { + case 'uniq': + $name = $this->nameToUniq(); + $this->upload['ext'] = $this->nameToSafe($this->upload['ext'], 10); + $name .= '.' . $this->upload['ext']; + break; + case 'safe': + $name = $this->nameToSafe($this->upload['real']); + if (($pos = strrpos($name, '.')) !== false) { + $this->upload['ext'] = substr($name, $pos + 1); + } else { + $this->upload['ext'] = ''; + } + break; + case 'real': + $name = $this->upload['real']; + break; + default: + $name = $mode; + } + $this->upload['name'] = $prepend . $name . $append; + $this->mode_name_selected = true; + return $this->upload['name']; + } + + /** + * Unique file names in the form: 9022210413b75410c28bef.html + * @see HTTP_Upload_File::setName() + */ + function nameToUniq() + { + if (! $this->_seeded) { + srand((double) microtime() * 1000000); + $this->_seeded = 1; + } + $uniq = uniqid(rand()); + return $uniq; + } + + /** + * Format a file name to be safe + * + * @param string $file The string file name + * @param int $maxlen Maximun permited string lenght + * @return string Formatted file name + * @see HTTP_Upload_File::setName() + */ + function nameToSafe($name, $maxlen=250) + { + $noalpha = 'ÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÀÈÌÒÙàèìòùÄËÏÖÜäëïöüÿÃãÕõÅåÑñÇç@°ºª'; + $alpha = 'AEIOUYaeiouyAEIOUaeiouAEIOUaeiouAEIOUaeiouyAaOoAaNnCcaooa'; + + $name = substr($name, 0, $maxlen); + $name = strtr($name, $noalpha, $alpha); + // not permitted chars are replaced with "_" + return preg_replace('/[^a-zA-Z0-9,._\+\()\-]/', '_', $name); + } + + /** + * The upload was valid + * + * @return bool If the file was submitted correctly + * @access public + */ + function isValid() + { + if ($this->upload['error'] === null) { + return true; + } + return false; + } + + /** + * User haven't submit a file + * + * @return bool If the user submitted a file or not + * @access public + */ + function isMissing() + { + if ($this->upload['error'] == 'NO_USER_FILE') { + return true; + } + return false; + } + + /** + * Some error occured during upload (most common due a file size problem, + * like max size exceeded or 0 bytes long). + * @return bool If there were errors submitting the file (probably + * because the file excess the max permitted file size) + * @access public + */ + function isError() + { + if (in_array($this->upload['error'], array('TOO_LARGE', 'BAD_FORM','DEV_NO_DEF_FILE'))) { + return true; + } + return false; + } + + /** + * Moves the uploaded file to its destination directory. + * + * @param string $dir_dest Destination directory + * @param bool $overwrite Overwrite if destination file exists? + * @return mixed True on success or Pear_Error object on error + * @access public + */ + function moveTo($dir_dest, $overwrite = true) + { + if (!$this->isValid()) { + return $this->raiseError($this->upload['error']); + } + + //Valid extensions check + if (!$this->_evalValidExtensions()) { + return $this->raiseError('NOT_ALLOWED_EXTENSION'); + } + + $err_code = $this->_chk_dir_dest($dir_dest); + if ($err_code !== false) { + return $this->raiseError($err_code); + } + // Use 'safe' mode by default if no other was selected + if (!$this->mode_name_selected) { + $this->setName('safe'); + } + + $name_dest = $dir_dest . DIRECTORY_SEPARATOR . $this->upload['name']; + + if (@is_file($name_dest)) { + if ($overwrite !== true) { + return $this->raiseError('FILE_EXISTS'); + } elseif (!is_writable($name_dest)) { + return $this->raiseError('CANNOT_OVERWRITE'); + } + } + + // copy the file and let php clean the tmp + if (!@move_uploaded_file($this->upload['tmp_name'], $name_dest)) { + return $this->raiseError('E_FAIL_MOVE'); + } + @chmod($name_dest, $this->_chmod); + return $this->getProp('name'); + } + + /** + * Check for a valid destination dir + * + * @param string $dir_dest Destination dir + * @return mixed False on no errors or error code on error + */ + function _chk_dir_dest($dir_dest) + { + if (!$dir_dest) { + return 'MISSING_DIR'; + } + if (!@is_dir ($dir_dest)) { + return 'IS_NOT_DIR'; + } + if (!is_writeable ($dir_dest)) { + return 'NO_WRITE_PERMS'; + } + return false; + } + /** + * Retrive properties of the uploaded file + * @param string $name The property name. When null an assoc array with + * all the properties will be returned + * @return mixed A string or array + * @see HTTP_Upload_File::HTTP_Upload_File() + * @access public + */ + function getProp($name = null) + { + if ($name === null) { + return $this->upload; + } + return $this->upload[$name]; + } + + /** + * Returns a error message, if a error occured + * (deprecated) Use getMessage() instead + * @return string a Error message + * @access public + */ + function errorMsg() + { + return $this->errorCode($this->upload['error']); + } + + /** + * Returns a error message, if a error occured + * @return string a Error message + * @access public + */ + function getMessage() + { + return $this->errorCode($this->upload['error']); + } + + /** + * Function to restrict the valid extensions on file uploads + * + * @param array $exts File extensions to validate + * @param string $mode The type of validation: + * 1) 'deny' Will deny only the supplied extensions + * 2) 'accept' Will accept only the supplied extensions + * as valid + * @access public + */ + function setValidExtensions($exts, $mode = 'deny') + { + $this->_extensions_check = $exts; + $this->_extensions_mode = $mode; + } + + /** + * Evaluates the validity of the extensions set by setValidExtensions + * + * @return bool False on non valid extension, true if they are valid + * @access private + */ + function _evalValidExtensions() + { + $exts = $this->_extensions_check; + settype($exts, 'array'); + if ($this->_extensions_mode == 'deny') { + if (in_array($this->getProp('ext'), $exts)) { + return false; + } + // mode == 'accept' + } else { + if (!in_array($this->getProp('ext'), $exts)) { + return false; + } + } + return true; + } +} ?> \ No newline at end of file diff --git a/thirdparty/pear/HTTP/WebDAV/Server.php b/thirdparty/pear/HTTP/WebDAV/Server.php index 258120e..8e200c9 100755 --- a/thirdparty/pear/HTTP/WebDAV/Server.php +++ b/thirdparty/pear/HTTP/WebDAV/Server.php @@ -17,7 +17,7 @@ // | Christian Stocker | // +----------------------------------------------------------------------+ // -// $Id: Server.php,v 1.36 2005/09/24 20:08:57 hholzgra Exp $ +// $Id$ // require_once "HTTP/WebDAV/Tools/_parse_propfind.php"; require_once "HTTP/WebDAV/Tools/_parse_proppatch.php"; diff --git a/thirdparty/pear/HTTP/WebDAV/Tools/_parse_lockinfo.php b/thirdparty/pear/HTTP/WebDAV/Tools/_parse_lockinfo.php index 3b32e2f..4a08100 100644 --- a/thirdparty/pear/HTTP/WebDAV/Tools/_parse_lockinfo.php +++ b/thirdparty/pear/HTTP/WebDAV/Tools/_parse_lockinfo.php @@ -17,7 +17,7 @@ // | Christian Stocker | // +----------------------------------------------------------------------+ // -// $Id: _parse_lockinfo.php,v 1.2 2004/01/05 12:32:40 hholzgra Exp $ +// $Id$ // /** diff --git a/thirdparty/pear/HTTP/WebDAV/Tools/_parse_propfind.php b/thirdparty/pear/HTTP/WebDAV/Tools/_parse_propfind.php index 15234cb..ea16cd7 100644 --- a/thirdparty/pear/HTTP/WebDAV/Tools/_parse_propfind.php +++ b/thirdparty/pear/HTTP/WebDAV/Tools/_parse_propfind.php @@ -17,7 +17,7 @@ // | Christian Stocker | // +----------------------------------------------------------------------+ // -// $Id: _parse_propfind.php,v 1.2 2004/01/05 12:33:22 hholzgra Exp $ +// $Id$ // /** diff --git a/thirdparty/pear/HTTP/WebDAV/Tools/_parse_proppatch.php b/thirdparty/pear/HTTP/WebDAV/Tools/_parse_proppatch.php index 9836ab2..006efb5 100644 --- a/thirdparty/pear/HTTP/WebDAV/Tools/_parse_proppatch.php +++ b/thirdparty/pear/HTTP/WebDAV/Tools/_parse_proppatch.php @@ -17,7 +17,7 @@ // | Christian Stocker | // +----------------------------------------------------------------------+ // -// $Id: _parse_proppatch.php,v 1.3 2004/01/05 12:41:34 hholzgra Exp $ +// $Id$ // /** diff --git a/thirdparty/pear/JSON.php b/thirdparty/pear/JSON.php index 0cddbdd..8283e7e 100644 --- a/thirdparty/pear/JSON.php +++ b/thirdparty/pear/JSON.php @@ -51,7 +51,7 @@ * @author Matt Knapp * @author Brett Stimmerman * @copyright 2005 Michal Migurski - * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ + * @version CVS: $Id$ * @license http://www.opensource.org/licenses/bsd-license.php * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 */ diff --git a/thirdparty/pear/Net/CheckIP.php b/thirdparty/pear/Net/CheckIP.php index b0fbc73..99e348b 100644 --- a/thirdparty/pear/Net/CheckIP.php +++ b/thirdparty/pear/Net/CheckIP.php @@ -17,7 +17,7 @@ // | Guido Haeger | // +----------------------------------------------------------------------+ // -// $Id: CheckIP.php,v 1.5 2002/08/17 09:41:24 mj Exp $ +// $Id$ /** * Class to validate the syntax of IPv4 adresses diff --git a/thirdparty/pear/Net/Curl.php b/thirdparty/pear/Net/Curl.php index d8c65d0..2aa0240 100644 --- a/thirdparty/pear/Net/Curl.php +++ b/thirdparty/pear/Net/Curl.php @@ -18,7 +18,7 @@ * @author Joe Stump * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Revision: 1.11 $ + * @version CVS: $Revision$ * @link http://pear.php.net/package/Net_Curl */ diff --git a/thirdparty/pear/Net/DIME.php b/thirdparty/pear/Net/DIME.php index 6c54208..fc69af5 100644 --- a/thirdparty/pear/Net/DIME.php +++ b/thirdparty/pear/Net/DIME.php @@ -1,629 +1,629 @@ - | -// | Ralf Hofmann | -// +----------------------------------------------------------------------+ -// -// $Id: DIME.php,v 1.5 2002/09/29 01:55:16 shane Exp $ -// - -require_once 'PEAR.php'; -/** - * - * DIME Encoding/Decoding - * - * What is it? - * This class enables you to manipulate and build - * a DIME encapsulated message. - * - * http://www.ietf.org/internet-drafts/draft-nielsen-dime-02.txt - * - * 09/18/02 Ralf - A huge number of changes to be compliant - * with the DIME Specification Release 17 June 2002 - * - * TODO: lots of stuff needs to be tested. - * Definitily have to go through DIME spec and - * make things work right, most importantly, sec 3.3 - * make examples, document - * - * see test/dime_mesage_test.php for example of usage - * - * @author Shane Caraveo , - * Ralf Hofmann - * @version $Revision: 1.5 $ - * @package Net_DIME - */ -define('NET_DIME_TYPE_UNCHANGED',0x00); -define('NET_DIME_TYPE_MEDIA',0x01); -define('NET_DIME_TYPE_URI',0x02); -define('NET_DIME_TYPE_UNKNOWN',0x03); -define('NET_DIME_TYPE_NONE',0x04); - -define('NET_DIME_VERSION',0x0001); - -define('NET_DIME_RECORD_HEADER',12); - -define('NET_DIME_FLAGS', 0); -define('NET_DIME_OPTS_LEN', 1); -define('NET_DIME_ID_LEN', 2); -define('NET_DIME_TYPE_LEN', 3); -define('NET_DIME_DATA_LEN', 4); -define('NET_DIME_OPTS', 5); -define('NET_DIME_ID', 6); -define('NET_DIME_TYPE', 7); -define('NET_DIME_DATA', 8); - -class Net_DIME_Record extends PEAR -{ - // these are used to hold the padded length - var $OPTS_LENGTH = 0; - var $ID_LENGTH = 0; - var $TYPE_LENGTH = 0; - var $DATA_LENGTH = 0; - var $_haveOpts = FALSE; - var $_haveID = FALSE; - var $_haveType = FALSE; - var $_haveData = FALSE; - var $debug = FALSE; - var $padstr = "\0"; - /** - * Elements - * [NET_DIME_FLAGS], 16 bits: VERSION:MB:ME:CF:TYPE_T - * [NET_DIME_OPTS_LEN], 16 bits: OPTIONS_LENGTH - * [NET_DIME_ID_LEN], 16 bits: ID_LENGTH - * [NET_DIME_TYPE_LEN], 16 bits: TYPE_LENGTH - * [NET_DIME_DATA_LEN], 32 bits: DATA_LENGTH - * [NET_DIME_OPTS] : OPTIONS - * [NET_DIME_ID] : ID - * [NET_DIME_TYPE] : TYPE - * [NET_DIME_DATA] : DATA - */ - var $Elements = array(NET_DIME_FLAGS => 0, NET_DIME_OPTS_LEN => 0, - NET_DIME_ID_LEN => 0, NET_DIME_TYPE_LEN => 0, - NET_DIME_DATA_LEN => 0, - NET_DIME_OPTS => '', - NET_DIME_ID => '', - NET_DIME_TYPE => '', - NET_DIME_DATA => ''); - - function Net_DIME_Record($debug = FALSE) - { - $this->debug = $debug; - if ($debug) $this->padstr = '*'; - } - - function setMB() - { - $this->Elements[NET_DIME_FLAGS] |= 0x0400; - } - - function setME() - { - $this->Elements[NET_DIME_FLAGS] |= 0x0200; - } - - function setCF() - { - $this->Elements[NET_DIME_FLAGS] |= 0x0100; - } - - function isChunk() - { - return $this->Elements[NET_DIME_FLAGS] & 0x0100; - } - - function isEnd() - { - return $this->Elements[NET_DIME_FLAGS] & 0x0200; - } - - function isStart() - { - return $this->Elements[NET_DIME_FLAGS] & 0x0400; - } - - function getID() - { - return $this->Elements[NET_DIME_ID]; - } - - function getType() - { - return $this->Elements[NET_DIME_TYPE]; - } - - function getData() - { - return $this->Elements[NET_DIME_DATA]; - } - - function getDataLength() - { - return $this->Elements[NET_DIME_DATA_LEN]; - } - - function setType($typestring, $type=NET_DIME_TYPE_UNKNOWN) - { - $typelen = strlen($typestring) & 0xFFFF; - $type = $type << 4; - $this->Elements[NET_DIME_FLAGS] = ($this->Elements[NET_DIME_FLAGS] & 0xFF0F) | $type; - $this->Elements[NET_DIME_TYPE_LEN] = $typelen; - $this->TYPE_LENGTH = $this->_getPadLength($typelen); - $this->Elements[NET_DIME_TYPE] = $typestring; - } - - function generateID() - { - $id = md5(time()); - $this->setID($id); - return $id; - } - - function setID($id) - { - $idlen = strlen($id) & 0xFFFF; - $this->Elements[NET_DIME_ID_LEN] = $idlen; - $this->ID_LENGTH = $this->_getPadLength($idlen); - $this->Elements[NET_DIME_ID] = $id; - } - - function setData($data, $size=0) - { - $datalen = $size?$size:strlen($data); - $this->Elements[NET_DIME_DATA_LEN] = $datalen; - $this->DATA_LENGTH = $this->_getPadLength($datalen); - $this->Elements[NET_DIME_DATA] = $data; - } - - function encode() - { - // insert version - $this->Elements[NET_DIME_FLAGS] = ($this->Elements[NET_DIME_FLAGS] & 0x07FF) | (NET_DIME_VERSION << 11); - - // the real dime encoding - $format = '%c%c%c%c%c%c%c%c%c%c%c%c'. - '%'.$this->OPTS_LENGTH.'s'. - '%'.$this->ID_LENGTH.'s'. - '%'.$this->TYPE_LENGTH.'s'. - '%'.$this->DATA_LENGTH.'s'; - return sprintf($format, - ($this->Elements[NET_DIME_FLAGS]&0x0000FF00)>>8, - ($this->Elements[NET_DIME_FLAGS]&0x000000FF), - ($this->Elements[NET_DIME_OPTS_LEN]&0x0000FF00)>>8, - ($this->Elements[NET_DIME_OPTS_LEN]&0x000000FF), - ($this->Elements[NET_DIME_ID_LEN]&0x0000FF00)>>8, - ($this->Elements[NET_DIME_ID_LEN]&0x000000FF), - ($this->Elements[NET_DIME_TYPE_LEN]&0x0000FF00)>>8, - ($this->Elements[NET_DIME_TYPE_LEN]&0x000000FF), - ($this->Elements[NET_DIME_DATA_LEN]&0xFF000000)>>24, - ($this->Elements[NET_DIME_DATA_LEN]&0x00FF0000)>>16, - ($this->Elements[NET_DIME_DATA_LEN]&0x0000FF00)>>8, - ($this->Elements[NET_DIME_DATA_LEN]&0x000000FF), - str_pad($this->Elements[NET_DIME_OPTS], $this->OPTS_LENGTH, $this->padstr), - str_pad($this->Elements[NET_DIME_ID], $this->ID_LENGTH, $this->padstr), - str_pad($this->Elements[NET_DIME_TYPE], $this->TYPE_LENGTH, $this->padstr), - str_pad($this->Elements[NET_DIME_DATA], $this->DATA_LENGTH, $this->padstr)); - } - - function _getPadLength($len) - { - $pad = 0; - if ($len) { - $pad = $len % 4; - if ($pad) $pad = 4 - $pad; - } - return $len + $pad; - } - - function decode(&$data) - { - // REAL DIME decoding - $this->Elements[NET_DIME_FLAGS] = (hexdec(bin2hex($data[0]))<<8) + hexdec(bin2hex($data[1])); - $this->Elements[NET_DIME_OPTS_LEN] = (hexdec(bin2hex($data[2]))<<8) + hexdec(bin2hex($data[3])); - $this->Elements[NET_DIME_ID_LEN] = (hexdec(bin2hex($data[4]))<<8) + hexdec(bin2hex($data[5])); - $this->Elements[NET_DIME_TYPE_LEN] = (hexdec(bin2hex($data[6]))<<8) + hexdec(bin2hex($data[7])); - $this->Elements[NET_DIME_DATA_LEN] = (hexdec(bin2hex($data[8]))<<24) + - (hexdec(bin2hex($data[9]))<<16) + - (hexdec(bin2hex($data[10]))<<8) + - hexdec(bin2hex($data[11])); - $p = 12; - - $version = (($this->Elements[NET_DIME_FLAGS]>>11) & 0x001F); - - if ($version == NET_DIME_VERSION) - { - $this->OPTS_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_OPTS_LEN]); - $this->ID_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_ID_LEN]); - $this->TYPE_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_TYPE_LEN]); - $this->DATA_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_DATA_LEN]); - - $datalen = strlen($data); - $this->Elements[NET_DIME_OPTS] = substr($data,$p,$this->Elements[NET_DIME_OPTS_LEN]); - $this->_haveOpts = (strlen($this->Elements[NET_DIME_OPTS]) == $this->Elements[NET_DIME_OPTS_LEN]); - if ($this->_haveOpts) { - $p += $this->OPTS_LENGTH; - $this->Elements[NET_DIME_ID] = substr($data,$p,$this->Elements[NET_DIME_ID_LEN]); - $this->_haveID = (strlen($this->Elements[NET_DIME_ID]) == $this->Elements[NET_DIME_ID_LEN]); - if ($this->_haveID) { - $p += $this->ID_LENGTH; - $this->Elements[NET_DIME_TYPE] = substr($data,$p,$this->Elements[NET_DIME_TYPE_LEN]); - $this->_haveType = (strlen($this->Elements[NET_DIME_TYPE]) == $this->Elements[NET_DIME_TYPE_LEN]); - if ($this->_haveType) { - $p += $this->TYPE_LENGTH; - $this->Elements[NET_DIME_DATA] = substr($data,$p,$this->Elements[NET_DIME_DATA_LEN]); - $this->_haveData = (strlen($this->Elements[NET_DIME_DATA]) == $this->Elements[NET_DIME_DATA_LEN]); - if ($this->_haveData) { - $p += $this->DATA_LENGTH; - } else { - $p += strlen($this->Elements[NET_DIME_DATA]); - } - } else { - $p += strlen($this->Elements[NET_DIME_TYPE]); - } - } else { - $p += strlen($this->Elements[NET_DIME_ID]); - } - } else { - $p += strlen($this->Elements[NET_DIME_OPTS]); - } - } - return substr($data, $p); - } - - function addData(&$data) - { - $datalen = strlen($data); - $p = 0; - if (!$this->_haveOpts) { - $have = strlen($this->Elements[NET_DIME_OPTS]); - $this->Elements[NET_DIME_OPTS] .= substr($data,$p,$this->Elements[NET_DIME_OPTS_LEN]-$have); - $this->_haveOpts = (strlen($this->Elements[NET_DIME_OPTS]) == $this->Elements[DIME_OTPS_LEN]); - if (!$this->_haveOpts) return NULL; - $p += $this->OPTS_LENGTH-$have; - } - if (!$this->_haveID) { - $have = strlen($this->Elements[NET_DIME_ID]); - $this->Elements[NET_DIME_ID] .= substr($data,$p,$this->Elements[NET_DIME_ID_LEN]-$have); - $this->_haveID = (strlen($this->Elements[NET_DIME_ID]) == $this->Elements[NET_DIME_ID_LEN]); - if (!$this->_haveID) return NULL; - $p += $this->ID_LENGTH-$have; - } - if (!$this->_haveType && $p < $datalen) { - $have = strlen($this->Elements[NET_DIME_TYPE]); - $this->Elements[NET_DIME_TYPE] .= substr($data,$p,$this->Elements[NET_DIME_TYPE_LEN]-$have); - $this->_haveType = (strlen($this->Elements[NET_DIME_TYPE]) == $this->Elements[NET_DIME_TYPE_LEN]); - if (!$this->_haveType) return NULL; - $p += $this->TYPE_LENGTH-$have; - } - if (!$this->_haveData && $p < $datalen) { - $have = strlen($this->Elements[NET_DIME_DATA]); - $this->Elements[NET_DIME_DATA] .= substr($data,$p,$this->Elements[NET_DIME_DATA_LEN]-$have); - $this->_haveData = (strlen($this->Elements[NET_DIME_DATA]) == $this->Elements[NET_DIME_DATA_LEN]); - if (!$this->_haveData) return NULL; - $p += $this->DATA_LENGTH-$have; - } - return substr($data,$p); - } -} - - -class Net_DIME_Message extends PEAR -{ - - var $record_size = 4096; - #var $records =array(); - var $parts = array(); - var $currentPart = -1; - var $stream = NULL; - var $_currentRecord; - var $_proc = array(); - var $type; - var $typestr; - var $mb = 1; - var $me = 0; - var $cf = 0; - var $id = NULL; - var $debug = FALSE; - /** - * constructor - * - * this currently takes a file pointer as provided - * by fopen - * - * TODO: integrate with the php streams stuff - */ - function Net_DIME_Message($stream=NULL, $record_size = 4096, $debug = FALSE) - { - $this->stream = $stream; - $this->record_size = $record_size; - $this->debug = $debug; - } - - function _makeRecord(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) - { - $record = new Net_DIME_Record($this->debug); - if ($this->mb) { - $record->setMB(); - // all subsequent records are not message begin! - $this->mb = 0; - } - if ($this->me) $record->setME(); - if ($this->cf) $record->setCF(); - $record->setData($data); - $record->setType($typestr,$type); - if ($id) $record->setID($id); - #if ($this->debug) { - # print str_replace('\0','*',$record->encode()); - #} - return $record->encode(); - } - - function startChunk(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) - { - $this->me = 0; - $this->cf = 1; - $this->type = $type; - $this->typestr = $typestr; - if ($id) { - $this->id = $id; - } else { - $this->id = md5(time()); - } - return $this->_makeRecord($data, $this->typestr, $this->id, $this->type); - } - - function doChunk(&$data) - { - $this->me = 0; - $this->cf = 1; - return $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_UNCHANGED); - } - - function endChunk() - { - $this->cf = 0; - $data = NULL; - $rec = $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_UNCHANGED); - $this->id = 0; - $this->cf = 0; - $this->id = 0; - $this->type = NET_DIME_TYPE_UNKNOWN; - $this->typestr = NULL; - return $rec; - } - - function endMessage() - { - $this->me = 1; - $data = NULL; - $rec = $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_NONE); - $this->me = 0; - $this->mb = 1; - $this->id = 0; - return $rec; - } - - /** - * sendRecord - * - * given a chunk of data, it creates DIME records - * and writes them to the stream - * - */ - function sendData(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) - { - $len = strlen($data); - if ($len > $this->record_size) { - $chunk = substr($data, 0, $this->record_size); - $p = $this->record_size; - $rec = $this->startChunk($chunk,$typestr,$id,$type); - fwrite($this->stream, $rec); - while ($p < $len) { - $chunk = substr($data, $p, $this->record_size); - $p += $this->record_size; - $rec = $this->doChunk($chunk); - fwrite($this->stream, $rec); - } - $rec = $this->endChunk(); - fwrite($this->stream, $rec); - return; - } - $rec = $this->_makeRecord($data, $typestr,$id,$type); - fwrite($this->stream, $rec); - } - - function sendEndMessage() - { - $rec = $this->endMessage(); - fwrite($this->stream, $rec); - } - - /** - * sendFile - * - * given a filename, it reads the file, - * creates records and writes them to the stream - * - */ - function sendFile($filename, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) - { - $f = fopen($filename, "rb"); - if ($f) { - if ($data = fread($f, $this->record_size)) { - $this->startChunk($data,$typestr,$id,$type); - } - while ($data = fread($f, $this->record_size)) { - $this->doChunk($data,$typestr,$id,$type); - } - $this->endChunk(); - fclose($f); - } - } - - /** - * encodeData - * - * given data, encode it in DIME - * - */ - function encodeData($data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) - { - $len = strlen($data); - $resp = ''; - if ($len > $this->record_size) { - $chunk = substr($data, 0, $this->record_size); - $p = $this->record_size; - $resp .= $this->startChunk($chunk,$typestr,$id,$type); - while ($p < $len) { - $chunk = substr($data, $p, $this->record_size); - $p += $this->record_size; - $resp .= $this->doChunk($chunk); - } - $resp .= $this->endChunk(); - } else { - $resp .= $this->_makeRecord($data, $typestr,$id,$type); - } - return $resp; - } - - /** - * sendFile - * - * given a filename, it reads the file, - * creates records and writes them to the stream - * - */ - function encodeFile($filename, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) - { - $f = fopen($filename, "rb"); - if ($f) { - if ($data = fread($f, $this->record_size)) { - $resp = $this->startChunk($data,$typestr,$id,$type); - } - while ($data = fread($f, $this->record_size)) { - $resp = $this->doChunk($data,$typestr,$id,$type); - } - $resp = $this->endChunk(); - fclose($f); - } - return $resp; - } - - /** - * _processData - * - * creates Net_DIME_Records from provided data - * - */ - function _processData(&$data) - { - $leftover = NULL; - if (!$this->_currentRecord) { - $this->_currentRecord = new Net_DIME_Record($this->debug); - $data = $this->_currentRecord->decode($data); - } else { - $data = $this->_currentRecord->addData($data); - } - - if ($this->_currentRecord->_haveData) { - if (count($this->parts)==0 && !$this->_currentRecord->isStart()) { - // raise an error! - return PEAR::raiseError('First Message is not a DIME begin record!'); - } - - if ($this->_currentRecord->isEnd() && $this->_currentRecord->getDataLength()==0) { - return NULL; - } - - if ($this->currentPart < 0 && !$this->_currentRecord->isChunk()) { - $this->parts[] = array(); - $this->currentPart = count($this->parts)-1; - $this->parts[$this->currentPart]['id'] = $this->_currentRecord->getID(); - $this->parts[$this->currentPart]['type'] = $this->_currentRecord->getType(); - $this->parts[$this->currentPart]['data'] = $this->_currentRecord->getData(); - $this->currentPart = -1; - } else { - if ($this->currentPart < 0) { - $this->parts[] = array(); - $this->currentPart = count($this->parts)-1; - $this->parts[$this->currentPart]['id'] = $this->_currentRecord->getID(); - $this->parts[$this->currentPart]['type'] = $this->_currentRecord->getType(); - $this->parts[$this->currentPart]['data'] = $this->_currentRecord->getData(); - } else { - $this->parts[$this->currentPart]['data'] .= $this->_currentRecord->getData(); - if (!$this->_currentRecord->isChunk()) { - // we reached the end of the chunk - $this->currentPart = -1; - } - } - } - #$this->records[] = $this->_currentRecord; - if (!$this->_currentRecord->isEnd()) $this->_currentRecord = NULL; - } - return NULL; - } - - /** - * decodeData - * - * decodes a DIME encrypted string of data - * - */ - function decodeData(&$data) { - while (strlen($data) >= NET_DIME_RECORD_HEADER) { - $err = $this->_processData($data); - if (PEAR::isError($err)) { - return $err; - } - } - } - - /** - * read - * - * reads the stream and creates - * an array of records - * - * it can accept the start of a previously read buffer - * this is usefull in situations where you need to read - * headers before discovering that the data is DIME encoded - * such as in the case of reading an HTTP response. - */ - function read($buf=NULL) - { - while ($data = fread($this->stream, 8192)) { - if ($buf) { - $data = $buf.$data; - $buf = NULL; - } - if ($this->debug) - echo "read: ".strlen($data)." bytes\n"; - $err = $this->decodeData($data); - if (PEAR::isError($err)) { - return $err; - } - - // store any leftover data to be used again - // should be < NET_DIME_RECORD_HEADER bytes - $buf = $data; - } - if (!$this->_currentRecord || !$this->_currentRecord->isEnd()) { - return PEAR::raiseError('reached stream end without end record'); - } - return NULL; - } -} + | +// | Ralf Hofmann | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'PEAR.php'; +/** + * + * DIME Encoding/Decoding + * + * What is it? + * This class enables you to manipulate and build + * a DIME encapsulated message. + * + * http://www.ietf.org/internet-drafts/draft-nielsen-dime-02.txt + * + * 09/18/02 Ralf - A huge number of changes to be compliant + * with the DIME Specification Release 17 June 2002 + * + * TODO: lots of stuff needs to be tested. + * Definitily have to go through DIME spec and + * make things work right, most importantly, sec 3.3 + * make examples, document + * + * see test/dime_mesage_test.php for example of usage + * + * @author Shane Caraveo , + * Ralf Hofmann + * @version $Revision$ + * @package Net_DIME + */ +define('NET_DIME_TYPE_UNCHANGED',0x00); +define('NET_DIME_TYPE_MEDIA',0x01); +define('NET_DIME_TYPE_URI',0x02); +define('NET_DIME_TYPE_UNKNOWN',0x03); +define('NET_DIME_TYPE_NONE',0x04); + +define('NET_DIME_VERSION',0x0001); + +define('NET_DIME_RECORD_HEADER',12); + +define('NET_DIME_FLAGS', 0); +define('NET_DIME_OPTS_LEN', 1); +define('NET_DIME_ID_LEN', 2); +define('NET_DIME_TYPE_LEN', 3); +define('NET_DIME_DATA_LEN', 4); +define('NET_DIME_OPTS', 5); +define('NET_DIME_ID', 6); +define('NET_DIME_TYPE', 7); +define('NET_DIME_DATA', 8); + +class Net_DIME_Record extends PEAR +{ + // these are used to hold the padded length + var $OPTS_LENGTH = 0; + var $ID_LENGTH = 0; + var $TYPE_LENGTH = 0; + var $DATA_LENGTH = 0; + var $_haveOpts = FALSE; + var $_haveID = FALSE; + var $_haveType = FALSE; + var $_haveData = FALSE; + var $debug = FALSE; + var $padstr = "\0"; + /** + * Elements + * [NET_DIME_FLAGS], 16 bits: VERSION:MB:ME:CF:TYPE_T + * [NET_DIME_OPTS_LEN], 16 bits: OPTIONS_LENGTH + * [NET_DIME_ID_LEN], 16 bits: ID_LENGTH + * [NET_DIME_TYPE_LEN], 16 bits: TYPE_LENGTH + * [NET_DIME_DATA_LEN], 32 bits: DATA_LENGTH + * [NET_DIME_OPTS] : OPTIONS + * [NET_DIME_ID] : ID + * [NET_DIME_TYPE] : TYPE + * [NET_DIME_DATA] : DATA + */ + var $Elements = array(NET_DIME_FLAGS => 0, NET_DIME_OPTS_LEN => 0, + NET_DIME_ID_LEN => 0, NET_DIME_TYPE_LEN => 0, + NET_DIME_DATA_LEN => 0, + NET_DIME_OPTS => '', + NET_DIME_ID => '', + NET_DIME_TYPE => '', + NET_DIME_DATA => ''); + + function Net_DIME_Record($debug = FALSE) + { + $this->debug = $debug; + if ($debug) $this->padstr = '*'; + } + + function setMB() + { + $this->Elements[NET_DIME_FLAGS] |= 0x0400; + } + + function setME() + { + $this->Elements[NET_DIME_FLAGS] |= 0x0200; + } + + function setCF() + { + $this->Elements[NET_DIME_FLAGS] |= 0x0100; + } + + function isChunk() + { + return $this->Elements[NET_DIME_FLAGS] & 0x0100; + } + + function isEnd() + { + return $this->Elements[NET_DIME_FLAGS] & 0x0200; + } + + function isStart() + { + return $this->Elements[NET_DIME_FLAGS] & 0x0400; + } + + function getID() + { + return $this->Elements[NET_DIME_ID]; + } + + function getType() + { + return $this->Elements[NET_DIME_TYPE]; + } + + function getData() + { + return $this->Elements[NET_DIME_DATA]; + } + + function getDataLength() + { + return $this->Elements[NET_DIME_DATA_LEN]; + } + + function setType($typestring, $type=NET_DIME_TYPE_UNKNOWN) + { + $typelen = strlen($typestring) & 0xFFFF; + $type = $type << 4; + $this->Elements[NET_DIME_FLAGS] = ($this->Elements[NET_DIME_FLAGS] & 0xFF0F) | $type; + $this->Elements[NET_DIME_TYPE_LEN] = $typelen; + $this->TYPE_LENGTH = $this->_getPadLength($typelen); + $this->Elements[NET_DIME_TYPE] = $typestring; + } + + function generateID() + { + $id = md5(time()); + $this->setID($id); + return $id; + } + + function setID($id) + { + $idlen = strlen($id) & 0xFFFF; + $this->Elements[NET_DIME_ID_LEN] = $idlen; + $this->ID_LENGTH = $this->_getPadLength($idlen); + $this->Elements[NET_DIME_ID] = $id; + } + + function setData($data, $size=0) + { + $datalen = $size?$size:strlen($data); + $this->Elements[NET_DIME_DATA_LEN] = $datalen; + $this->DATA_LENGTH = $this->_getPadLength($datalen); + $this->Elements[NET_DIME_DATA] = $data; + } + + function encode() + { + // insert version + $this->Elements[NET_DIME_FLAGS] = ($this->Elements[NET_DIME_FLAGS] & 0x07FF) | (NET_DIME_VERSION << 11); + + // the real dime encoding + $format = '%c%c%c%c%c%c%c%c%c%c%c%c'. + '%'.$this->OPTS_LENGTH.'s'. + '%'.$this->ID_LENGTH.'s'. + '%'.$this->TYPE_LENGTH.'s'. + '%'.$this->DATA_LENGTH.'s'; + return sprintf($format, + ($this->Elements[NET_DIME_FLAGS]&0x0000FF00)>>8, + ($this->Elements[NET_DIME_FLAGS]&0x000000FF), + ($this->Elements[NET_DIME_OPTS_LEN]&0x0000FF00)>>8, + ($this->Elements[NET_DIME_OPTS_LEN]&0x000000FF), + ($this->Elements[NET_DIME_ID_LEN]&0x0000FF00)>>8, + ($this->Elements[NET_DIME_ID_LEN]&0x000000FF), + ($this->Elements[NET_DIME_TYPE_LEN]&0x0000FF00)>>8, + ($this->Elements[NET_DIME_TYPE_LEN]&0x000000FF), + ($this->Elements[NET_DIME_DATA_LEN]&0xFF000000)>>24, + ($this->Elements[NET_DIME_DATA_LEN]&0x00FF0000)>>16, + ($this->Elements[NET_DIME_DATA_LEN]&0x0000FF00)>>8, + ($this->Elements[NET_DIME_DATA_LEN]&0x000000FF), + str_pad($this->Elements[NET_DIME_OPTS], $this->OPTS_LENGTH, $this->padstr), + str_pad($this->Elements[NET_DIME_ID], $this->ID_LENGTH, $this->padstr), + str_pad($this->Elements[NET_DIME_TYPE], $this->TYPE_LENGTH, $this->padstr), + str_pad($this->Elements[NET_DIME_DATA], $this->DATA_LENGTH, $this->padstr)); + } + + function _getPadLength($len) + { + $pad = 0; + if ($len) { + $pad = $len % 4; + if ($pad) $pad = 4 - $pad; + } + return $len + $pad; + } + + function decode(&$data) + { + // REAL DIME decoding + $this->Elements[NET_DIME_FLAGS] = (hexdec(bin2hex($data[0]))<<8) + hexdec(bin2hex($data[1])); + $this->Elements[NET_DIME_OPTS_LEN] = (hexdec(bin2hex($data[2]))<<8) + hexdec(bin2hex($data[3])); + $this->Elements[NET_DIME_ID_LEN] = (hexdec(bin2hex($data[4]))<<8) + hexdec(bin2hex($data[5])); + $this->Elements[NET_DIME_TYPE_LEN] = (hexdec(bin2hex($data[6]))<<8) + hexdec(bin2hex($data[7])); + $this->Elements[NET_DIME_DATA_LEN] = (hexdec(bin2hex($data[8]))<<24) + + (hexdec(bin2hex($data[9]))<<16) + + (hexdec(bin2hex($data[10]))<<8) + + hexdec(bin2hex($data[11])); + $p = 12; + + $version = (($this->Elements[NET_DIME_FLAGS]>>11) & 0x001F); + + if ($version == NET_DIME_VERSION) + { + $this->OPTS_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_OPTS_LEN]); + $this->ID_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_ID_LEN]); + $this->TYPE_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_TYPE_LEN]); + $this->DATA_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_DATA_LEN]); + + $datalen = strlen($data); + $this->Elements[NET_DIME_OPTS] = substr($data,$p,$this->Elements[NET_DIME_OPTS_LEN]); + $this->_haveOpts = (strlen($this->Elements[NET_DIME_OPTS]) == $this->Elements[NET_DIME_OPTS_LEN]); + if ($this->_haveOpts) { + $p += $this->OPTS_LENGTH; + $this->Elements[NET_DIME_ID] = substr($data,$p,$this->Elements[NET_DIME_ID_LEN]); + $this->_haveID = (strlen($this->Elements[NET_DIME_ID]) == $this->Elements[NET_DIME_ID_LEN]); + if ($this->_haveID) { + $p += $this->ID_LENGTH; + $this->Elements[NET_DIME_TYPE] = substr($data,$p,$this->Elements[NET_DIME_TYPE_LEN]); + $this->_haveType = (strlen($this->Elements[NET_DIME_TYPE]) == $this->Elements[NET_DIME_TYPE_LEN]); + if ($this->_haveType) { + $p += $this->TYPE_LENGTH; + $this->Elements[NET_DIME_DATA] = substr($data,$p,$this->Elements[NET_DIME_DATA_LEN]); + $this->_haveData = (strlen($this->Elements[NET_DIME_DATA]) == $this->Elements[NET_DIME_DATA_LEN]); + if ($this->_haveData) { + $p += $this->DATA_LENGTH; + } else { + $p += strlen($this->Elements[NET_DIME_DATA]); + } + } else { + $p += strlen($this->Elements[NET_DIME_TYPE]); + } + } else { + $p += strlen($this->Elements[NET_DIME_ID]); + } + } else { + $p += strlen($this->Elements[NET_DIME_OPTS]); + } + } + return substr($data, $p); + } + + function addData(&$data) + { + $datalen = strlen($data); + $p = 0; + if (!$this->_haveOpts) { + $have = strlen($this->Elements[NET_DIME_OPTS]); + $this->Elements[NET_DIME_OPTS] .= substr($data,$p,$this->Elements[NET_DIME_OPTS_LEN]-$have); + $this->_haveOpts = (strlen($this->Elements[NET_DIME_OPTS]) == $this->Elements[DIME_OTPS_LEN]); + if (!$this->_haveOpts) return NULL; + $p += $this->OPTS_LENGTH-$have; + } + if (!$this->_haveID) { + $have = strlen($this->Elements[NET_DIME_ID]); + $this->Elements[NET_DIME_ID] .= substr($data,$p,$this->Elements[NET_DIME_ID_LEN]-$have); + $this->_haveID = (strlen($this->Elements[NET_DIME_ID]) == $this->Elements[NET_DIME_ID_LEN]); + if (!$this->_haveID) return NULL; + $p += $this->ID_LENGTH-$have; + } + if (!$this->_haveType && $p < $datalen) { + $have = strlen($this->Elements[NET_DIME_TYPE]); + $this->Elements[NET_DIME_TYPE] .= substr($data,$p,$this->Elements[NET_DIME_TYPE_LEN]-$have); + $this->_haveType = (strlen($this->Elements[NET_DIME_TYPE]) == $this->Elements[NET_DIME_TYPE_LEN]); + if (!$this->_haveType) return NULL; + $p += $this->TYPE_LENGTH-$have; + } + if (!$this->_haveData && $p < $datalen) { + $have = strlen($this->Elements[NET_DIME_DATA]); + $this->Elements[NET_DIME_DATA] .= substr($data,$p,$this->Elements[NET_DIME_DATA_LEN]-$have); + $this->_haveData = (strlen($this->Elements[NET_DIME_DATA]) == $this->Elements[NET_DIME_DATA_LEN]); + if (!$this->_haveData) return NULL; + $p += $this->DATA_LENGTH-$have; + } + return substr($data,$p); + } +} + + +class Net_DIME_Message extends PEAR +{ + + var $record_size = 4096; + #var $records =array(); + var $parts = array(); + var $currentPart = -1; + var $stream = NULL; + var $_currentRecord; + var $_proc = array(); + var $type; + var $typestr; + var $mb = 1; + var $me = 0; + var $cf = 0; + var $id = NULL; + var $debug = FALSE; + /** + * constructor + * + * this currently takes a file pointer as provided + * by fopen + * + * TODO: integrate with the php streams stuff + */ + function Net_DIME_Message($stream=NULL, $record_size = 4096, $debug = FALSE) + { + $this->stream = $stream; + $this->record_size = $record_size; + $this->debug = $debug; + } + + function _makeRecord(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) + { + $record = new Net_DIME_Record($this->debug); + if ($this->mb) { + $record->setMB(); + // all subsequent records are not message begin! + $this->mb = 0; + } + if ($this->me) $record->setME(); + if ($this->cf) $record->setCF(); + $record->setData($data); + $record->setType($typestr,$type); + if ($id) $record->setID($id); + #if ($this->debug) { + # print str_replace('\0','*',$record->encode()); + #} + return $record->encode(); + } + + function startChunk(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) + { + $this->me = 0; + $this->cf = 1; + $this->type = $type; + $this->typestr = $typestr; + if ($id) { + $this->id = $id; + } else { + $this->id = md5(time()); + } + return $this->_makeRecord($data, $this->typestr, $this->id, $this->type); + } + + function doChunk(&$data) + { + $this->me = 0; + $this->cf = 1; + return $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_UNCHANGED); + } + + function endChunk() + { + $this->cf = 0; + $data = NULL; + $rec = $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_UNCHANGED); + $this->id = 0; + $this->cf = 0; + $this->id = 0; + $this->type = NET_DIME_TYPE_UNKNOWN; + $this->typestr = NULL; + return $rec; + } + + function endMessage() + { + $this->me = 1; + $data = NULL; + $rec = $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_NONE); + $this->me = 0; + $this->mb = 1; + $this->id = 0; + return $rec; + } + + /** + * sendRecord + * + * given a chunk of data, it creates DIME records + * and writes them to the stream + * + */ + function sendData(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) + { + $len = strlen($data); + if ($len > $this->record_size) { + $chunk = substr($data, 0, $this->record_size); + $p = $this->record_size; + $rec = $this->startChunk($chunk,$typestr,$id,$type); + fwrite($this->stream, $rec); + while ($p < $len) { + $chunk = substr($data, $p, $this->record_size); + $p += $this->record_size; + $rec = $this->doChunk($chunk); + fwrite($this->stream, $rec); + } + $rec = $this->endChunk(); + fwrite($this->stream, $rec); + return; + } + $rec = $this->_makeRecord($data, $typestr,$id,$type); + fwrite($this->stream, $rec); + } + + function sendEndMessage() + { + $rec = $this->endMessage(); + fwrite($this->stream, $rec); + } + + /** + * sendFile + * + * given a filename, it reads the file, + * creates records and writes them to the stream + * + */ + function sendFile($filename, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) + { + $f = fopen($filename, "rb"); + if ($f) { + if ($data = fread($f, $this->record_size)) { + $this->startChunk($data,$typestr,$id,$type); + } + while ($data = fread($f, $this->record_size)) { + $this->doChunk($data,$typestr,$id,$type); + } + $this->endChunk(); + fclose($f); + } + } + + /** + * encodeData + * + * given data, encode it in DIME + * + */ + function encodeData($data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) + { + $len = strlen($data); + $resp = ''; + if ($len > $this->record_size) { + $chunk = substr($data, 0, $this->record_size); + $p = $this->record_size; + $resp .= $this->startChunk($chunk,$typestr,$id,$type); + while ($p < $len) { + $chunk = substr($data, $p, $this->record_size); + $p += $this->record_size; + $resp .= $this->doChunk($chunk); + } + $resp .= $this->endChunk(); + } else { + $resp .= $this->_makeRecord($data, $typestr,$id,$type); + } + return $resp; + } + + /** + * sendFile + * + * given a filename, it reads the file, + * creates records and writes them to the stream + * + */ + function encodeFile($filename, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN) + { + $f = fopen($filename, "rb"); + if ($f) { + if ($data = fread($f, $this->record_size)) { + $resp = $this->startChunk($data,$typestr,$id,$type); + } + while ($data = fread($f, $this->record_size)) { + $resp = $this->doChunk($data,$typestr,$id,$type); + } + $resp = $this->endChunk(); + fclose($f); + } + return $resp; + } + + /** + * _processData + * + * creates Net_DIME_Records from provided data + * + */ + function _processData(&$data) + { + $leftover = NULL; + if (!$this->_currentRecord) { + $this->_currentRecord = new Net_DIME_Record($this->debug); + $data = $this->_currentRecord->decode($data); + } else { + $data = $this->_currentRecord->addData($data); + } + + if ($this->_currentRecord->_haveData) { + if (count($this->parts)==0 && !$this->_currentRecord->isStart()) { + // raise an error! + return PEAR::raiseError('First Message is not a DIME begin record!'); + } + + if ($this->_currentRecord->isEnd() && $this->_currentRecord->getDataLength()==0) { + return NULL; + } + + if ($this->currentPart < 0 && !$this->_currentRecord->isChunk()) { + $this->parts[] = array(); + $this->currentPart = count($this->parts)-1; + $this->parts[$this->currentPart]['id'] = $this->_currentRecord->getID(); + $this->parts[$this->currentPart]['type'] = $this->_currentRecord->getType(); + $this->parts[$this->currentPart]['data'] = $this->_currentRecord->getData(); + $this->currentPart = -1; + } else { + if ($this->currentPart < 0) { + $this->parts[] = array(); + $this->currentPart = count($this->parts)-1; + $this->parts[$this->currentPart]['id'] = $this->_currentRecord->getID(); + $this->parts[$this->currentPart]['type'] = $this->_currentRecord->getType(); + $this->parts[$this->currentPart]['data'] = $this->_currentRecord->getData(); + } else { + $this->parts[$this->currentPart]['data'] .= $this->_currentRecord->getData(); + if (!$this->_currentRecord->isChunk()) { + // we reached the end of the chunk + $this->currentPart = -1; + } + } + } + #$this->records[] = $this->_currentRecord; + if (!$this->_currentRecord->isEnd()) $this->_currentRecord = NULL; + } + return NULL; + } + + /** + * decodeData + * + * decodes a DIME encrypted string of data + * + */ + function decodeData(&$data) { + while (strlen($data) >= NET_DIME_RECORD_HEADER) { + $err = $this->_processData($data); + if (PEAR::isError($err)) { + return $err; + } + } + } + + /** + * read + * + * reads the stream and creates + * an array of records + * + * it can accept the start of a previously read buffer + * this is usefull in situations where you need to read + * headers before discovering that the data is DIME encoded + * such as in the case of reading an HTTP response. + */ + function read($buf=NULL) + { + while ($data = fread($this->stream, 8192)) { + if ($buf) { + $data = $buf.$data; + $buf = NULL; + } + if ($this->debug) + echo "read: ".strlen($data)." bytes\n"; + $err = $this->decodeData($data); + if (PEAR::isError($err)) { + return $err; + } + + // store any leftover data to be used again + // should be < NET_DIME_RECORD_HEADER bytes + $buf = $data; + } + if (!$this->_currentRecord || !$this->_currentRecord->isEnd()) { + return PEAR::raiseError('reached stream end without end record'); + } + return NULL; + } +} ?> \ No newline at end of file diff --git a/thirdparty/pear/Net/Dict.php b/thirdparty/pear/Net/Dict.php index 0acc797..cf7c4ce 100644 --- a/thirdparty/pear/Net/Dict.php +++ b/thirdparty/pear/Net/Dict.php @@ -20,7 +20,7 @@ // | Authors: Chandrashekhar Bhosle | // +----------------------------------------------------------------------+ // -// $Id: Dict.php,v 1.3 2002/10/06 04:55:33 cnb Exp $ +// $Id$ // }}} // {{{ includes diff --git a/thirdparty/pear/Net/Dig.php b/thirdparty/pear/Net/Dig.php index 662399b..2721b8d 100644 --- a/thirdparty/pear/Net/Dig.php +++ b/thirdparty/pear/Net/Dig.php @@ -16,7 +16,7 @@ // | Author: Colin Viebrock | // +----------------------------------------------------------------------+ // -// $Id: Dig.php,v 1.1 2002/04/25 14:57:23 cmv Exp $ +// $Id$ // // A nice friendly OO interface to dig // diff --git a/thirdparty/pear/Net/Finger.php b/thirdparty/pear/Net/Finger.php index fd6f365..ea61dd9 100644 --- a/thirdparty/pear/Net/Finger.php +++ b/thirdparty/pear/Net/Finger.php @@ -16,7 +16,7 @@ // | Authors: Sebastian Nohn | // +----------------------------------------------------------------------+ // -// $Id: Finger.php,v 1.5 2003/01/04 11:55:46 mj Exp $ +// $Id$ // require_once 'PEAR.php'; @@ -27,7 +27,7 @@ require_once 'Net/Socket.php'; * * Provides functions useful for Finger-Queries. * - * @version $Revision: 1.5 $ + * @version $Revision$ * @author Sebastian Nohn * @package Net */ diff --git a/thirdparty/pear/Net/Geo.php b/thirdparty/pear/Net/Geo.php index 1bc3bad..6d19a7c 100644 --- a/thirdparty/pear/Net/Geo.php +++ b/thirdparty/pear/Net/Geo.php @@ -17,7 +17,7 @@ // | | // +----------------------------------------------------------------------+ // -// $Id: Geo.php,v 1.7 2004/02/18 22:59:20 lsmith Exp $ +// $Id$ require_once 'PEAR.php'; require_once 'Cache/Function.php'; diff --git a/thirdparty/pear/Net/IPv4.php b/thirdparty/pear/Net/IPv4.php index 68de17e..ba62a8d 100644 --- a/thirdparty/pear/Net/IPv4.php +++ b/thirdparty/pear/Net/IPv4.php @@ -17,7 +17,7 @@ * @author Florian Anderiasch * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_01.txt PHP License 3.01 -* @version CVS: $Id: IPv4.php,v 1.11 2005/11/29 12:56:35 fa Exp $ +* @version CVS: $Id$ * @link http://pear.php.net/package/Net_IPv4 */ diff --git a/thirdparty/pear/Net/IPv6.php b/thirdparty/pear/Net/IPv6.php index 296abe6..c624028 100644 --- a/thirdparty/pear/Net/IPv6.php +++ b/thirdparty/pear/Net/IPv6.php @@ -1,218 +1,218 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: IPv6.php,v 1.12 2005/09/01 12:42:00 alexmerz Exp $ - -/** -* Class to validate and to work with IPv6 -* -* @author Alexander Merz -* @author elfrink at introweb dot nl -* @package Net_IPv6 -* @version $Id: IPv6.php,v 1.12 2005/09/01 12:42:00 alexmerz Exp $ -* @access public -*/ -class Net_IPv6 { - - // {{{ Uncompress() - - /** - * Uncompresses an IPv6 adress - * - * RFC 2373 allows you to compress zeros in an adress to '::'. This - * function expects an valid IPv6 adress and expands the '::' to - * the required zeros. - * - * Example: FF01::101 -> FF01:0:0:0:0:0:0:101 - * ::1 -> 0:0:0:0:0:0:0:1 - * - * @access public - * @see Compress() - * @static - * @param string $ip a valid IPv6-adress (hex format) - * @return string the uncompressed IPv6-adress (hex format) - */ - function Uncompress($ip) { - $uip = $ip; - $c1 = -1; - $c2 = -1; - if (false !== strpos($ip, '::') ) { - list($ip1, $ip2) = explode('::', $ip); - if(""==$ip1) { - $c1 = -1; - } else { - $pos = 0; - if(0 < ($pos = substr_count($ip1, ':'))) { - $c1 = $pos; - } else { - $c1 = 0; - } - } - if(""==$ip2) { - $c2 = -1; - } else { - $pos = 0; - if(0 < ($pos = substr_count($ip2, ':'))) { - $c2 = $pos; - } else { - $c2 = 0; - } - } - if(strstr($ip2, '.')) { - $c2++; - } - if(-1 == $c1 && -1 == $c2) { // :: - $uip = "0:0:0:0:0:0:0:0"; - } else if(-1==$c1) { // ::xxx - $fill = str_repeat('0:', 7-$c2); - $uip = str_replace('::', $fill, $uip); - } else if(-1==$c2) { // xxx:: - $fill = str_repeat(':0', 7-$c1); - $uip = str_replace('::', $fill, $uip); - } else { // xxx::xxx - $fill = str_repeat(':0:', 6-$c2-$c1); - $uip = str_replace('::', $fill, $uip); - $uip = str_replace('::', ':', $uip); - } - } - return $uip; - } - - // }}} - // {{{ Compress() - - /** - * Compresses an IPv6 adress - * - * RFC 2373 allows you to compress zeros in an adress to '::'. This - * function expects an valid IPv6 adress and compresses successive zeros - * to '::' - * - * Example: FF01:0:0:0:0:0:0:101 -> FF01::101 - * 0:0:0:0:0:0:0:1 -> ::1 - * - * @access public - * @see Uncompress() - * @static - * @param string $ip a valid IPv6-adress (hex format) - * @return string the compressed IPv6-adress (hex format) - * @author elfrink at introweb dot nl - */ - function Compress($ip) { - $cip = $ip; - - if (!strstr($ip, '::')) { - $ipp = explode(':',$ip); - for($i=0; $i0) { - $match = ''; - foreach($zeros[0] as $zero) { - if (strlen($zero) > strlen($match)) - $match = $zero; - } - $cip = preg_replace('/' . $match . '/', ':', $cip, 1); - } - $cip = preg_replace('/((^:)|(:$))/', '' ,$cip); - $cip = preg_replace('/((^:)|(:$))/', '::' ,$cip); - } - return $cip; - } - - // }}} - // {{{ SplitV64() - - /** - * Splits an IPv6 adress into the IPv6 and a possible IPv4 part - * - * RFC 2373 allows you to note the last two parts of an IPv6 adress as - * an IPv4 compatible adress - * - * Example: 0:0:0:0:0:0:13.1.68.3 - * 0:0:0:0:0:FFFF:129.144.52.38 - * - * @access public - * @static - * @param string $ip a valid IPv6-adress (hex format) - * @return array [0] contains the IPv6 part, [1] the IPv4 part (hex format) - */ - function SplitV64($ip) { - $ip = Net_IPv6::Uncompress($ip); - if (strstr($ip, '.')) { - $pos = strrpos($ip, ':'); - $ip{$pos} = '_'; - $ipPart = explode('_', $ip); - return $ipPart; - } else { - return array($ip, ""); - } - } - - // }}} - // {{{ checkIPv6 - - /** - * Checks an IPv6 adress - * - * Checks if the given IP is IPv6-compatible - * - * @access public - * @static - * @param string $ip a valid IPv6-adress - * @return boolean true if $ip is an IPv6 adress - */ - function checkIPv6($ip) { - - $ipPart = Net_IPv6::SplitV64($ip); - $count = 0; - if (!empty($ipPart[0])) { - $ipv6 =explode(':', $ipPart[0]); - for ($i = 0; $i < count($ipv6); $i++) { - $dec = hexdec($ipv6[$i]); - $hex = strtoupper(preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/", "\\1", $ipv6[$i])); - if ($ipv6[$i] >= 0 && $dec <= 65535 && $hex == strtoupper(dechex($dec))) { - $count++; - } - } - if (8 == $count) { - return true; - } elseif (6 == $count and !empty($ipPart[1])) { - $ipv4 = explode('.',$ipPart[1]); - $count = 0; - for ($i = 0; $i < count($ipv4); $i++) { - if ($ipv4[$i] >= 0 && (integer)$ipv4[$i] <= 255 && preg_match("/^\d{1,3}$/", $ipv4[$i])) { - $count++; - } - } - if (4 == $count) { - return true; - } - } else { - return false; - } - - } else { - return false; - } - } - // }}} -} -?> + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +/** +* Class to validate and to work with IPv6 +* +* @author Alexander Merz +* @author elfrink at introweb dot nl +* @package Net_IPv6 +* @version $Id$ +* @access public +*/ +class Net_IPv6 { + + // {{{ Uncompress() + + /** + * Uncompresses an IPv6 adress + * + * RFC 2373 allows you to compress zeros in an adress to '::'. This + * function expects an valid IPv6 adress and expands the '::' to + * the required zeros. + * + * Example: FF01::101 -> FF01:0:0:0:0:0:0:101 + * ::1 -> 0:0:0:0:0:0:0:1 + * + * @access public + * @see Compress() + * @static + * @param string $ip a valid IPv6-adress (hex format) + * @return string the uncompressed IPv6-adress (hex format) + */ + function Uncompress($ip) { + $uip = $ip; + $c1 = -1; + $c2 = -1; + if (false !== strpos($ip, '::') ) { + list($ip1, $ip2) = explode('::', $ip); + if(""==$ip1) { + $c1 = -1; + } else { + $pos = 0; + if(0 < ($pos = substr_count($ip1, ':'))) { + $c1 = $pos; + } else { + $c1 = 0; + } + } + if(""==$ip2) { + $c2 = -1; + } else { + $pos = 0; + if(0 < ($pos = substr_count($ip2, ':'))) { + $c2 = $pos; + } else { + $c2 = 0; + } + } + if(strstr($ip2, '.')) { + $c2++; + } + if(-1 == $c1 && -1 == $c2) { // :: + $uip = "0:0:0:0:0:0:0:0"; + } else if(-1==$c1) { // ::xxx + $fill = str_repeat('0:', 7-$c2); + $uip = str_replace('::', $fill, $uip); + } else if(-1==$c2) { // xxx:: + $fill = str_repeat(':0', 7-$c1); + $uip = str_replace('::', $fill, $uip); + } else { // xxx::xxx + $fill = str_repeat(':0:', 6-$c2-$c1); + $uip = str_replace('::', $fill, $uip); + $uip = str_replace('::', ':', $uip); + } + } + return $uip; + } + + // }}} + // {{{ Compress() + + /** + * Compresses an IPv6 adress + * + * RFC 2373 allows you to compress zeros in an adress to '::'. This + * function expects an valid IPv6 adress and compresses successive zeros + * to '::' + * + * Example: FF01:0:0:0:0:0:0:101 -> FF01::101 + * 0:0:0:0:0:0:0:1 -> ::1 + * + * @access public + * @see Uncompress() + * @static + * @param string $ip a valid IPv6-adress (hex format) + * @return string the compressed IPv6-adress (hex format) + * @author elfrink at introweb dot nl + */ + function Compress($ip) { + $cip = $ip; + + if (!strstr($ip, '::')) { + $ipp = explode(':',$ip); + for($i=0; $i0) { + $match = ''; + foreach($zeros[0] as $zero) { + if (strlen($zero) > strlen($match)) + $match = $zero; + } + $cip = preg_replace('/' . $match . '/', ':', $cip, 1); + } + $cip = preg_replace('/((^:)|(:$))/', '' ,$cip); + $cip = preg_replace('/((^:)|(:$))/', '::' ,$cip); + } + return $cip; + } + + // }}} + // {{{ SplitV64() + + /** + * Splits an IPv6 adress into the IPv6 and a possible IPv4 part + * + * RFC 2373 allows you to note the last two parts of an IPv6 adress as + * an IPv4 compatible adress + * + * Example: 0:0:0:0:0:0:13.1.68.3 + * 0:0:0:0:0:FFFF:129.144.52.38 + * + * @access public + * @static + * @param string $ip a valid IPv6-adress (hex format) + * @return array [0] contains the IPv6 part, [1] the IPv4 part (hex format) + */ + function SplitV64($ip) { + $ip = Net_IPv6::Uncompress($ip); + if (strstr($ip, '.')) { + $pos = strrpos($ip, ':'); + $ip{$pos} = '_'; + $ipPart = explode('_', $ip); + return $ipPart; + } else { + return array($ip, ""); + } + } + + // }}} + // {{{ checkIPv6 + + /** + * Checks an IPv6 adress + * + * Checks if the given IP is IPv6-compatible + * + * @access public + * @static + * @param string $ip a valid IPv6-adress + * @return boolean true if $ip is an IPv6 adress + */ + function checkIPv6($ip) { + + $ipPart = Net_IPv6::SplitV64($ip); + $count = 0; + if (!empty($ipPart[0])) { + $ipv6 =explode(':', $ipPart[0]); + for ($i = 0; $i < count($ipv6); $i++) { + $dec = hexdec($ipv6[$i]); + $hex = strtoupper(preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/", "\\1", $ipv6[$i])); + if ($ipv6[$i] >= 0 && $dec <= 65535 && $hex == strtoupper(dechex($dec))) { + $count++; + } + } + if (8 == $count) { + return true; + } elseif (6 == $count and !empty($ipPart[1])) { + $ipv4 = explode('.',$ipPart[1]); + $count = 0; + for ($i = 0; $i < count($ipv4); $i++) { + if ($ipv4[$i] >= 0 && (integer)$ipv4[$i] <= 255 && preg_match("/^\d{1,3}$/", $ipv4[$i])) { + $count++; + } + } + if (4 == $count) { + return true; + } + } else { + return false; + } + + } else { + return false; + } + } + // }}} +} +?> diff --git a/thirdparty/pear/Net/Ident.php b/thirdparty/pear/Net/Ident.php index df5c4f5..c5dc283 100644 --- a/thirdparty/pear/Net/Ident.php +++ b/thirdparty/pear/Net/Ident.php @@ -18,7 +18,7 @@ // | Original author: Gavin Brown | // +----------------------------------------------------------------------+ // -// $Id: Ident.php,v 1.7 2005/03/07 11:23:26 nepto Exp $ +// $Id$ // // Identification Protocol implementation // diff --git a/thirdparty/pear/Net/POP3.php b/thirdparty/pear/Net/POP3.php index 316a142..b73f842 100644 --- a/thirdparty/pear/Net/POP3.php +++ b/thirdparty/pear/Net/POP3.php @@ -33,7 +33,7 @@ // | Co-Author: Damian Fernandez Sosa | // +-----------------------------------------------------------------------+ // -// $Id: POP3.php,v 1.2 2004/12/05 16:34:39 damian Exp $ +// $Id$ require_once('Net/Socket.php'); diff --git a/thirdparty/pear/Net/Ping.php b/thirdparty/pear/Net/Ping.php index 21f9fda..8446cf5 100644 --- a/thirdparty/pear/Net/Ping.php +++ b/thirdparty/pear/Net/Ping.php @@ -19,7 +19,7 @@ // | Kai Schröder | // +----------------------------------------------------------------------+ // -// $Id: Ping.php,v 1.36 2004/02/08 23:17:22 jan Exp $ +// $Id$ require_once "PEAR.php"; require_once "OS/Guess.php"; @@ -65,7 +65,7 @@ define('NET_PING_RESULT_UNSUPPORTED_BACKEND', 4); * ?> * * @author Jan Lehnardt -* @version $Revision: 1.36 $ +* @version $Revision$ * @package Net * @access public */ @@ -524,7 +524,7 @@ class Net_Ping * Container class for Net_Ping results * * @author Jan Lehnardt -* @version $Revision: 1.36 $ +* @version $Revision$ * @package Net * @access private */ diff --git a/thirdparty/pear/Net/SMTP.php b/thirdparty/pear/Net/SMTP.php index 049a92f..4a29f4d 100644 --- a/thirdparty/pear/Net/SMTP.php +++ b/thirdparty/pear/Net/SMTP.php @@ -18,7 +18,7 @@ // | Damian Alejandro Fernandez Sosa | // +----------------------------------------------------------------------+ // -// $Id: SMTP.php,v 1.54 2005/08/16 03:44:15 jon Exp $ +// $Id$ require_once 'PEAR.php'; require_once 'Net/Socket.php'; diff --git a/thirdparty/pear/Net/SmartIRC.php b/thirdparty/pear/Net/SmartIRC.php index e0167a8..95e2b50 100644 --- a/thirdparty/pear/Net/SmartIRC.php +++ b/thirdparty/pear/Net/SmartIRC.php @@ -1,9 +1,9 @@ | // +----------------------------------------------------------------------+ // -// $Id: Socket.php,v 1.24 2005/02/03 20:40:16 chagenbu Exp $ +// $Id$ require_once 'PEAR.php'; diff --git a/thirdparty/pear/Net/Whois.php b/thirdparty/pear/Net/Whois.php index aac9997..5550f91 100644 --- a/thirdparty/pear/Net/Whois.php +++ b/thirdparty/pear/Net/Whois.php @@ -18,7 +18,7 @@ // | Author: Seamus Venasse | // +----------------------------------------------------------------------+ // -// $Id: Whois.php,v 1.11 2003/01/04 11:55:54 mj Exp $ +// $Id$ // // Whois Class // diff --git a/thirdparty/pear/SOAP/Type/hexBinary.php b/thirdparty/pear/SOAP/Type/hexBinary.php index 150e45d..6acdc21 100644 --- a/thirdparty/pear/SOAP/Type/hexBinary.php +++ b/thirdparty/pear/SOAP/Type/hexBinary.php @@ -17,7 +17,7 @@ // | Authors: Dietrich Ayala Original Author | // +----------------------------------------------------------------------+ // -// $Id: hexBinary.php,v 1.6 2005/03/10 23:16:39 yunosh Exp $ +// $Id$ // class SOAP_Type_hexBinary { diff --git a/thirdparty/pear/SOAP/example/com_client.php b/thirdparty/pear/SOAP/example/com_client.php index d511f0a..3f33daf 100644 --- a/thirdparty/pear/SOAP/example/com_client.php +++ b/thirdparty/pear/SOAP/example/com_client.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo | // +----------------------------------------------------------------------+ // -// $Id: com_client.php,v 1.3 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // // SOAPStruct is defined in the following file require_once 'example_types.php'; diff --git a/thirdparty/pear/SOAP/example/disco_server.php b/thirdparty/pear/SOAP/example/disco_server.php index 6dc8581..21a9018 100644 --- a/thirdparty/pear/SOAP/example/disco_server.php +++ b/thirdparty/pear/SOAP/example/disco_server.php @@ -16,7 +16,7 @@ // | Author: Dmitri Vinogradov | // +----------------------------------------------------------------------+ // -// $Id: disco_server.php,v 1.5 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ /* This example shows how to mark up a server object so that diff --git a/thirdparty/pear/SOAP/example/email_client.php b/thirdparty/pear/SOAP/example/email_client.php index 40d0d18..797906f 100644 --- a/thirdparty/pear/SOAP/example/email_client.php +++ b/thirdparty/pear/SOAP/example/email_client.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo Port to PEAR and more | // +----------------------------------------------------------------------+ // -// $Id: email_client.php,v 1.4 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // /* diff --git a/thirdparty/pear/SOAP/example/email_gateway.php b/thirdparty/pear/SOAP/example/email_gateway.php index 2e14a85..42701ed 100644 --- a/thirdparty/pear/SOAP/example/email_gateway.php +++ b/thirdparty/pear/SOAP/example/email_gateway.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo Port to PEAR and more | // +----------------------------------------------------------------------+ // -// $Id: email_gateway.php,v 1.5 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // /* diff --git a/thirdparty/pear/SOAP/example/email_pop_gateway.php b/thirdparty/pear/SOAP/example/email_pop_gateway.php index a998466..bd9ff38 100644 --- a/thirdparty/pear/SOAP/example/email_pop_gateway.php +++ b/thirdparty/pear/SOAP/example/email_pop_gateway.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo Port to PEAR and more | // +----------------------------------------------------------------------+ // -// $Id: email_pop_gateway.php,v 1.6 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // /* include the Email server class, which knows how to diff --git a/thirdparty/pear/SOAP/example/email_pop_server.php b/thirdparty/pear/SOAP/example/email_pop_server.php index 2a12b56..be47873 100644 --- a/thirdparty/pear/SOAP/example/email_pop_server.php +++ b/thirdparty/pear/SOAP/example/email_pop_server.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo Port to PEAR and more | // +----------------------------------------------------------------------+ // -// $Id: email_pop_server.php,v 1.6 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // /* include the Email server class, which knows how to diff --git a/thirdparty/pear/SOAP/example/email_server.php b/thirdparty/pear/SOAP/example/email_server.php index f4477c4..cad3dea 100644 --- a/thirdparty/pear/SOAP/example/email_server.php +++ b/thirdparty/pear/SOAP/example/email_server.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo Port to PEAR and more | // +----------------------------------------------------------------------+ // -// $Id: email_server.php,v 1.5 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // /* diff --git a/thirdparty/pear/SOAP/example/example_server.php b/thirdparty/pear/SOAP/example/example_server.php index 7e59d49..376b324 100644 --- a/thirdparty/pear/SOAP/example/example_server.php +++ b/thirdparty/pear/SOAP/example/example_server.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo | // +----------------------------------------------------------------------+ // -// $Id: example_server.php,v 1.5 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // // first, include the SOAP/Server class diff --git a/thirdparty/pear/SOAP/example/server.php b/thirdparty/pear/SOAP/example/server.php index 1990072..543bff3 100644 --- a/thirdparty/pear/SOAP/example/server.php +++ b/thirdparty/pear/SOAP/example/server.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo | // +----------------------------------------------------------------------+ // -// $Id: server.php,v 1.10 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // // first, include the SOAP/Server class diff --git a/thirdparty/pear/SOAP/example/server2.php b/thirdparty/pear/SOAP/example/server2.php index 2d64446..3d945b5 100644 --- a/thirdparty/pear/SOAP/example/server2.php +++ b/thirdparty/pear/SOAP/example/server2.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo | // +----------------------------------------------------------------------+ // -// $Id: server2.php,v 1.3 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // // first, include the SOAP/Server class diff --git a/thirdparty/pear/SOAP/example/smtp.php b/thirdparty/pear/SOAP/example/smtp.php index a7814da..7a2695e 100644 --- a/thirdparty/pear/SOAP/example/smtp.php +++ b/thirdparty/pear/SOAP/example/smtp.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo | // +----------------------------------------------------------------------+ // -// $Id: smtp.php,v 1.5 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // // include soap client class include("SOAP/Client.php"); diff --git a/thirdparty/pear/SOAP/example/stockquote.php b/thirdparty/pear/SOAP/example/stockquote.php index 0305032..04749bc 100644 --- a/thirdparty/pear/SOAP/example/stockquote.php +++ b/thirdparty/pear/SOAP/example/stockquote.php @@ -18,7 +18,7 @@ // | Authors: Dietrich Ayala Original Author | // +----------------------------------------------------------------------+ // -// $Id: stockquote.php,v 1.7 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // // include soap client class include("SOAP/Client.php"); diff --git a/thirdparty/pear/SOAP/example/tcp_client.php b/thirdparty/pear/SOAP/example/tcp_client.php index b3f04d7..f583f7f 100644 --- a/thirdparty/pear/SOAP/example/tcp_client.php +++ b/thirdparty/pear/SOAP/example/tcp_client.php @@ -16,7 +16,7 @@ // | Authors: Shane Hanna | // +----------------------------------------------------------------------+ // -// $Id: tcp_client.php,v 1.3 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // require_once('SOAP/Client.php'); diff --git a/thirdparty/pear/SOAP/example/tcp_server.php b/thirdparty/pear/SOAP/example/tcp_server.php index 41c8468..e1ceda9 100644 --- a/thirdparty/pear/SOAP/example/tcp_server.php +++ b/thirdparty/pear/SOAP/example/tcp_server.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo | // +----------------------------------------------------------------------+ // -// $Id: tcp_server.php,v 1.4 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // // first, include the SOAP/Server class diff --git a/thirdparty/pear/SOAP/example/wsdl_client.php b/thirdparty/pear/SOAP/example/wsdl_client.php index dc63a76..4af4bf4 100644 --- a/thirdparty/pear/SOAP/example/wsdl_client.php +++ b/thirdparty/pear/SOAP/example/wsdl_client.php @@ -16,7 +16,7 @@ // | Authors: Shane Caraveo | // +----------------------------------------------------------------------+ // -// $Id: wsdl_client.php,v 1.3 2005/03/10 23:16:40 yunosh Exp $ +// $Id$ // include("SOAP/Client.php"); diff --git a/thirdparty/pear/System.php b/thirdparty/pear/System.php index dc3acee..7289016 100644 --- a/thirdparty/pear/System.php +++ b/thirdparty/pear/System.php @@ -16,7 +16,7 @@ // | Authors: Tomas V.V.Cox | // +----------------------------------------------------------------------+ // -// $Id: System.php,v 1.36 2004/06/15 16:33:46 pajoye Exp $ +// $Id$ // require_once 'PEAR.php'; @@ -48,7 +48,7 @@ $GLOBALS['_System_temp_files'] = array(); * * @package System * @author Tomas V.V.Cox -* @version $Revision: 1.36 $ +* @version $Revision$ * @access public * @see http://pear.php.net/manual/ */ diff --git a/thirdparty/simpletest/simpletest/exceptions.php b/thirdparty/simpletest/simpletest/exceptions.php index 2cde258..a2bf0af 100644 --- a/thirdparty/simpletest/simpletest/exceptions.php +++ b/thirdparty/simpletest/simpletest/exceptions.php @@ -3,7 +3,7 @@ * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester - * @version $Id: exceptions.php,v 1.12 2006/11/09 23:14:48 lastcraft Exp $ + * @version $Id$ */ /**#@+ diff --git a/thirdpartyjs/curvycorners/lgpl.txt b/thirdpartyjs/curvycorners/lgpl.txt index 259cffb..f8e41e9 100644 --- a/thirdpartyjs/curvycorners/lgpl.txt +++ b/thirdpartyjs/curvycorners/lgpl.txt @@ -1,502 +1,502 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + That's all there is to it! \ No newline at end of file diff --git a/thirdpartyjs/yui/animation/README b/thirdpartyjs/yui/animation/README index e0f9951..22cc72b 100644 --- a/thirdpartyjs/yui/animation/README +++ b/thirdpartyjs/yui/animation/README @@ -1,34 +1,34 @@ -Animation Release Notes - -*** version 0.12.0 *** - -* added boolean finish argument to Anim.stop() - -*** version 0.11.3 *** - -* no changes - -*** version 0.11.1 *** - -* changed "prototype" shorthand to "proto" (workaround firefox < 1.5 scoping -bug) - -*** version 0.11.0 *** - -* ColorAnim subclass added -* Motion and Scroll now inherit from ColorAnim -* getDefaultUnit method added -* defaultUnit and defaultUnits deprecated -* getDefault and setDefault methods deprecated - -*** version 0.10.0 *** - -* Scroll now handles relative ("by") animation correctly - -* Now converts "auto" values of "from" to appropriate initial values - -*** version 0.9.0 *** - -* Initial release - - +Animation Release Notes + +*** version 0.12.0 *** + +* added boolean finish argument to Anim.stop() + +*** version 0.11.3 *** + +* no changes + +*** version 0.11.1 *** + +* changed "prototype" shorthand to "proto" (workaround firefox < 1.5 scoping +bug) + +*** version 0.11.0 *** + +* ColorAnim subclass added +* Motion and Scroll now inherit from ColorAnim +* getDefaultUnit method added +* defaultUnit and defaultUnits deprecated +* getDefault and setDefault methods deprecated + +*** version 0.10.0 *** + +* Scroll now handles relative ("by") animation correctly + +* Now converts "auto" values of "from" to appropriate initial values + +*** version 0.9.0 *** + +* Initial release + + diff --git a/thirdpartyjs/yui/animation/animation-debug.js b/thirdpartyjs/yui/animation/animation-debug.js index 1a4c89c..60cd905 100644 --- a/thirdpartyjs/yui/animation/animation-debug.js +++ b/thirdpartyjs/yui/animation/animation-debug.js @@ -1,1276 +1,1276 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 0.12.0 -*/ - -/** - * The animation module provides allows effects to be added to HTMLElements. - * @module animation - */ - -/** - * - * Base animation class that provides the interface for building animated effects. - *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

- * @class Anim - * @namespace YAHOO.util - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - -YAHOO.util.Anim = function(el, attributes, duration, method) { - if (el) { - this.init(el, attributes, duration, method); - } -}; - -YAHOO.util.Anim.prototype = { - /** - * Provides a readable name for the Anim instance. - * @method toString - * @return {String} - */ - toString: function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Anim " + id); - }, - - patterns: { // cached for performance - noNegatives: /width|height|opacity|padding/i, // keep at zero or above - offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default - defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default - offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset - }, - - /** - * Returns the value computed by the animation's "method". - * @method doMethod - * @param {String} attr The name of the attribute. - * @param {Number} start The value this attribute should start from for this animation. - * @param {Number} end The value this attribute should end at for this animation. - * @return {Number} The Value to be applied to the attribute. - */ - doMethod: function(attr, start, end) { - return this.method(this.currentFrame, start, end - start, this.totalFrames); - }, - - /** - * Applies a value to an attribute. - * @method setAttribute - * @param {String} attr The name of the attribute. - * @param {Number} val The value to be applied to the attribute. - * @param {String} unit The unit ('px', '%', etc.) of the value. - */ - setAttribute: function(attr, val, unit) { - if ( this.patterns.noNegatives.test(attr) ) { - val = (val > 0) ? val : 0; - } - - YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); - }, - - /** - * Returns current value of the attribute. - * @method getAttribute - * @param {String} attr The name of the attribute. - * @return {Number} val The current value of the attribute. - */ - getAttribute: function(attr) { - var el = this.getEl(); - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { - return parseFloat(val); - } - - var a = this.patterns.offsetAttribute.exec(attr) || []; - var pos = !!( a[3] ); // top or left - var box = !!( a[2] ); // width or height - - // use offsets for width/height and abs pos top/left - if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { - val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; - } else { // default to zero for other 'auto' - val = 0; - } - - return val; - }, - - /** - * Returns the unit to use when none is supplied. - * @method getDefaultUnit - * @param {attr} attr The name of the attribute. - * @return {String} The default unit to be used. - */ - getDefaultUnit: function(attr) { - if ( this.patterns.defaultUnit.test(attr) ) { - return 'px'; - } - - return ''; - }, - - /** - * Sets the actual values to be used during the animation. - * @method setRuntimeAttribute - * Should only be needed for subclass use. - * @param {Object} attr The attribute object - * @private - */ - setRuntimeAttribute: function(attr) { - var start; - var end; - var attributes = this.attributes; - - this.runtimeAttributes[attr] = {}; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; - - if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { - return false; // note return; nothing to animate to - } - - start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); - - // To beats by, per SMIL 2.1 spec - if ( isset(attributes[attr]['to']) ) { - end = attributes[attr]['to']; - } else if ( isset(attributes[attr]['by']) ) { - if (start.constructor == Array) { - end = []; - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + attributes[attr]['by'][i]; - } - } else { - end = start + attributes[attr]['by']; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - - // set units if needed - this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); - }, - - /** - * Constructor for Anim instance. - * @method init - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - init: function(el, attributes, duration, method) { - /** - * Whether or not the animation is running. - * @property isAnimated - * @private - * @type Boolean - */ - var isAnimated = false; - - /** - * A Date object that is created when the animation begins. - * @property startTime - * @private - * @type Date - */ - var startTime = null; - - /** - * The number of frames this animation was able to execute. - * @property actualFrames - * @private - * @type Int - */ - var actualFrames = 0; - - /** - * The element to be animated. - * @property el - * @private - * @type HTMLElement - */ - el = YAHOO.util.Dom.get(el); - - /** - * The collection of attributes to be animated. - * Each attribute must have at least a "to" or "by" defined in order to animate. - * If "to" is supplied, the animation will end with the attribute at that value. - * If "by" is supplied, the animation will end at that value plus its starting value. - * If both are supplied, "to" is used, and "by" is ignored. - * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). - * @property attributes - * @type Object - */ - this.attributes = attributes || {}; - - /** - * The length of the animation. Defaults to "1" (second). - * @property duration - * @type Number - */ - this.duration = duration || 1; - - /** - * The method that will provide values to the attribute(s) during the animation. - * Defaults to "YAHOO.util.Easing.easeNone". - * @property method - * @type Function - */ - this.method = method || YAHOO.util.Easing.easeNone; - - /** - * Whether or not the duration should be treated as seconds. - * Defaults to true. - * @property useSeconds - * @type Boolean - */ - this.useSeconds = true; // default to seconds - - /** - * The location of the current animation on the timeline. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property currentFrame - * @type Int - */ - this.currentFrame = 0; - - /** - * The total number of frames to be executed. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property totalFrames - * @type Int - */ - this.totalFrames = YAHOO.util.AnimMgr.fps; - - - /** - * Returns a reference to the animated element. - * @method getEl - * @return {HTMLElement} - */ - this.getEl = function() { return el; }; - - /** - * Checks whether the element is currently animated. - * @method isAnimated - * @return {Boolean} current value of isAnimated. - */ - this.isAnimated = function() { - return isAnimated; - }; - - /** - * Returns the animation start time. - * @method getStartTime - * @return {Date} current value of startTime. - */ - this.getStartTime = function() { - return startTime; - }; - - this.runtimeAttributes = {}; - - var logger = {}; - logger.log = function() {YAHOO.log.apply(window, arguments)}; - - logger.log('creating new instance of ' + this); - - /** - * Starts the animation by registering it with the animation manager. - * @method animate - */ - this.animate = function() { - if ( this.isAnimated() ) { return false; } - - this.currentFrame = 0; - - this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; - - YAHOO.util.AnimMgr.registerElement(this); - }; - - /** - * Stops the animation. Normally called by AnimMgr when animation completes. - * @method stop - * @param {Boolean} finish (optional) If true, animation will jump to final frame. - */ - this.stop = function(finish) { - if (finish) { - this.currentFrame = this.totalFrames; - this._onTween.fire(); - } - YAHOO.util.AnimMgr.stop(this); - }; - - var onStart = function() { - this.onStart.fire(); - - this.runtimeAttributes = {}; - for (var attr in this.attributes) { - this.setRuntimeAttribute(attr); - } - - isAnimated = true; - actualFrames = 0; - startTime = new Date(); - }; - - /** - * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). - * @private - */ - - var onTween = function() { - var data = { - duration: new Date() - this.getStartTime(), - currentFrame: this.currentFrame - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', currentFrame: ' + data.currentFrame - ); - }; - - this.onTween.fire(data); - - var runtimeAttributes = this.runtimeAttributes; - - for (var attr in runtimeAttributes) { - this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); - } - - actualFrames += 1; - }; - - var onComplete = function() { - var actual_duration = (new Date() - startTime) / 1000 ; - - var data = { - duration: actual_duration, - frames: actualFrames, - fps: actualFrames / actual_duration - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', frames: ' + data.frames + - ', fps: ' + data.fps - ); - }; - - isAnimated = false; - actualFrames = 0; - this.onComplete.fire(data); - }; - - /** - * Custom event that fires after onStart, useful in subclassing - * @private - */ - this._onStart = new YAHOO.util.CustomEvent('_start', this, true); - - /** - * Custom event that fires when animation begins - * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) - * @event onStart - */ - this.onStart = new YAHOO.util.CustomEvent('start', this); - - /** - * Custom event that fires between each frame - * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) - * @event onTween - */ - this.onTween = new YAHOO.util.CustomEvent('tween', this); - - /** - * Custom event that fires after onTween - * @private - */ - this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); - - /** - * Custom event that fires when animation ends - * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) - * @event onComplete - */ - this.onComplete = new YAHOO.util.CustomEvent('complete', this); - /** - * Custom event that fires after onComplete - * @private - */ - this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); - - this._onStart.subscribe(onStart); - this._onTween.subscribe(onTween); - this._onComplete.subscribe(onComplete); - } -}; - -/** - * Handles animation queueing and threading. - * Used by Anim and subclasses. - * @class AnimMgr - * @namespace YAHOO.util - */ -YAHOO.util.AnimMgr = new function() { - /** - * Reference to the animation Interval. - * @property thread - * @private - * @type Int - */ - var thread = null; - - /** - * The current queue of registered animation objects. - * @property queue - * @private - * @type Array - */ - var queue = []; - - /** - * The number of active animations. - * @property tweenCount - * @private - * @type Int - */ - var tweenCount = 0; - - /** - * Base frame rate (frames per second). - * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). - * @property fps - * @type Int - * - */ - this.fps = 200; - - /** - * Interval delay in milliseconds, defaults to fastest possible. - * @property delay - * @type Int - * - */ - this.delay = 1; - - /** - * Adds an animation instance to the animation queue. - * All animation instances must be registered in order to animate. - * @method registerElement - * @param {object} tween The Anim instance to be be registered - */ - this.registerElement = function(tween) { - queue[queue.length] = tween; - tweenCount += 1; - tween._onStart.fire(); - this.start(); - }; - - /** - * removes an animation instance from the animation queue. - * All animation instances must be registered in order to animate. - * @method unRegister - * @param {object} tween The Anim instance to be be registered - * @param {Int} index The index of the Anim instance - * @private - */ - this.unRegister = function(tween, index) { - tween._onComplete.fire(); - index = index || getIndex(tween); - if (index != -1) { queue.splice(index, 1); } - - tweenCount -= 1; - if (tweenCount <= 0) { this.stop(); } - }; - - /** - * Starts the animation thread. - * Only one thread can run at a time. - * @method start - */ - this.start = function() { - if (thread === null) { thread = setInterval(this.run, this.delay); } - }; - - /** - * Stops the animation thread or a specific animation instance. - * @method stop - * @param {object} tween A specific Anim instance to stop (optional) - * If no instance given, Manager stops thread and all animations. - */ - this.stop = function(tween) { - if (!tween) { - clearInterval(thread); - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i].isAnimated()) { - this.unRegister(tween, i); - } - } - queue = []; - thread = null; - tweenCount = 0; - } - else { - this.unRegister(tween); - } - }; - - /** - * Called per Interval to handle each animation frame. - * @method run - */ - this.run = function() { - for (var i = 0, len = queue.length; i < len; ++i) { - var tween = queue[i]; - if ( !tween || !tween.isAnimated() ) { continue; } - - if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) - { - tween.currentFrame += 1; - - if (tween.useSeconds) { - correctFrame(tween); - } - tween._onTween.fire(); - } - else { YAHOO.util.AnimMgr.stop(tween, i); } - } - }; - - var getIndex = function(anim) { - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i] == anim) { - return i; // note return; - } - } - return -1; - }; - - /** - * On the fly frame correction to keep animation on time. - * @method correctFrame - * @private - * @param {Object} tween The Anim instance being corrected. - */ - var correctFrame = function(tween) { - var frames = tween.totalFrames; - var frame = tween.currentFrame; - var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); - var elapsed = (new Date() - tween.getStartTime()); - var tweak = 0; - - if (elapsed < tween.duration * 1000) { // check if falling behind - tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); - } else { // went over duration, so jump to end - tweak = frames - (frame + 1); - } - if (tweak > 0 && isFinite(tweak)) { // adjust if needed - if (tween.currentFrame + tweak >= frames) {// dont go past last frame - tweak = frames - (frame + 1); - } - - tween.currentFrame += tweak; - } - }; -}; -/** - * Used to calculate Bezier splines for any number of control points. - * @class Bezier - * @namespace YAHOO.util - * - */ -YAHOO.util.Bezier = new function() -{ - /** - * Get the current position of the animated element based on t. - * Each point is an array of "x" and "y" values (0 = x, 1 = y) - * At least 2 points are required (start and end). - * First point is start. Last point is end. - * Additional control points are optional. - * @method getPosition - * @param {Array} points An array containing Bezier points - * @param {Number} t A number between 0 and 1 which is the basis for determining current position - * @return {Array} An array containing int x and y member data - */ - this.getPosition = function(points, t) - { - var n = points.length; - var tmp = []; - - for (var i = 0; i < n; ++i){ - tmp[i] = [points[i][0], points[i][1]]; // save input - } - - for (var j = 1; j < n; ++j) { - for (i = 0; i < n - j; ++i) { - tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; - tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; - } - } - - return [ tmp[0][0], tmp[0][1] ]; - - }; -}; -/** - * Anim subclass for color transitions. - *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, - * [255,255,255], or rgb(255,255,255)

- * @class ColorAnim - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @constructor - * @extends YAHOO.util.Anim - * @param {HTMLElement | String} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ -(function() { - YAHOO.util.ColorAnim = function(el, attributes, duration, method) { - YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); - }; - - YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.ColorAnim.superclass; - var proto = Y.ColorAnim.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("ColorAnim " + id); - }; - - proto.patterns.color = /color$/i; - proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; - proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; - proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; - proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari - - /** - * Attempts to parse the given string and return a 3-tuple. - * @method parseColor - * @param {String} s The string to parse. - * @return {Array} The 3-tuple of rgb values. - */ - proto.parseColor = function(s) { - if (s.length == 3) { return s; } - - var c = this.patterns.hex.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; - } - - c = this.patterns.rgb.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; - } - - c = this.patterns.hex3.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; - } - - return null; - }; - - proto.getAttribute = function(attr) { - var el = this.getEl(); - if ( this.patterns.color.test(attr) ) { - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (this.patterns.transparent.test(val)) { // bgcolor default - var parent = el.parentNode; // try and get from an ancestor - val = Y.Dom.getStyle(parent, attr); - - while (parent && this.patterns.transparent.test(val)) { - parent = parent.parentNode; - val = Y.Dom.getStyle(parent, attr); - if (parent.tagName.toUpperCase() == 'HTML') { - val = '#fff'; - } - } - } - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val; - - if ( this.patterns.color.test(attr) ) { - val = []; - for (var i = 0, len = start.length; i < len; ++i) { - val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); - } - - val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; - } - else { - val = superclass.doMethod.call(this, attr, start, end); - } - - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - superclass.setRuntimeAttribute.call(this, attr); - - if ( this.patterns.color.test(attr) ) { - var attributes = this.attributes; - var start = this.parseColor(this.runtimeAttributes[attr].start); - var end = this.parseColor(this.runtimeAttributes[attr].end); - // fix colors if going "by" - if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { - end = this.parseColor(attributes[attr].by); - - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + end[i]; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - } - }; -})();/* -TERMS OF USE - EASING EQUATIONS -Open source under the BSD License. -Copyright 2001 Robert Penner All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * Singleton that determines how an animation proceeds from start to end. - * @class Easing - * @namespace YAHOO.util -*/ - -YAHOO.util.Easing = { - - /** - * Uniform speed between points. - * @method easeNone - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeNone: function (t, b, c, d) { - return c*t/d + b; - }, - - /** - * Begins slowly and accelerates towards end. (quadratic) - * @method easeIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeIn: function (t, b, c, d) { - return c*(t/=d)*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quadratic) - * @method easeOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOut: function (t, b, c, d) { - return -c *(t/=d)*(t-2) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quadratic) - * @method easeBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBoth: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t + b; - return -c/2 * ((--t)*(t-2) - 1) + b; - }, - - /** - * Begins slowly and accelerates towards end. (quartic) - * @method easeInStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeInStrong: function (t, b, c, d) { - return c*(t/=d)*t*t*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quartic) - * @method easeOutStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOutStrong: function (t, b, c, d) { - return -c * ((t=t/d-1)*t*t*t - 1) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quartic) - * @method easeBothStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBothStrong: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t*t*t + b; - return -c/2 * ((t-=2)*t*t*t - 2) + b; - }, - - /** - * Snap in elastic effect. - * @method elasticIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - - elasticIn: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - }, - - /** - * Snap out elastic effect. - * @method elasticOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticOut: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; - }, - - /** - * Snap both elastic effect. - * @method elasticBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticBoth: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; - }, - - - /** - * Backtracks slightly, then reverses direction and moves to end. - * @method backIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backIn: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*(t/=d)*t*((s+1)*t - s) + b; - }, - - /** - * Overshoots end, then reverses and comes back to end. - * @method backOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backOut: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; - }, - - /** - * Backtracks slightly, then reverses direction, overshoots end, - * then reverses and comes back to end. - * @method backBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backBoth: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; - return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; - }, - - /** - * Bounce off of start. - * @method bounceIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceIn: function (t, b, c, d) { - return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; - }, - - /** - * Bounces off end. - * @method bounceOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceOut: function (t, b, c, d) { - if ((t/=d) < (1/2.75)) { - return c*(7.5625*t*t) + b; - } else if (t < (2/2.75)) { - return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; - } else if (t < (2.5/2.75)) { - return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; - } else { - return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; - } - }, - - /** - * Bounces off start and end. - * @method bounceBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceBoth: function (t, b, c, d) { - if (t < d/2) return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; - return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; - } -}; - -/** - * Anim subclass for moving elements along a path defined by the "points" - * member of "attributes". All "points" are arrays with x, y coordinates. - *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Motion - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @extends YAHOO.util.Anim - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ -(function() { - YAHOO.util.Motion = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Motion.superclass; - var proto = Y.Motion.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Motion " + id); - }; - - proto.patterns.points = /^points$/i; - - proto.setAttribute = function(attr, val, unit) { - if ( this.patterns.points.test(attr) ) { - unit = unit || 'px'; - superclass.setAttribute.call(this, 'left', val[0], unit); - superclass.setAttribute.call(this, 'top', val[1], unit); - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; - - proto.getAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var val = [ - superclass.getAttribute.call(this, 'left'), - superclass.getAttribute.call(this, 'top') - ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if ( this.patterns.points.test(attr) ) { - var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; - val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var el = this.getEl(); - var attributes = this.attributes; - var start; - var control = attributes['points']['control'] || []; - var end; - var i, len; - - if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points - control = [control]; - } else { // break reference to attributes.points.control - var tmp = []; - for (i = 0, len = control.length; i< len; ++i) { - tmp[i] = control[i]; - } - control = tmp; - } - - if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative - Y.Dom.setStyle(el, 'position', 'relative'); - } - - if ( isset(attributes['points']['from']) ) { - Y.Dom.setXY(el, attributes['points']['from']); // set position to from point - } - else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position - - start = this.getAttribute('points'); // get actual top & left - - // TO beats BY, per SMIL 2.1 spec - if ( isset(attributes['points']['to']) ) { - end = translateValues.call(this, attributes['points']['to'], start); - - var pageXY = Y.Dom.getXY(this.getEl()); - for (i = 0, len = control.length; i < len; ++i) { - control[i] = translateValues.call(this, control[i], start); - } - - - } else if ( isset(attributes['points']['by']) ) { - end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; - - for (i = 0, len = control.length; i < len; ++i) { - control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; - } - } - - this.runtimeAttributes[attr] = [start]; - - if (control.length > 0) { - this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); - } - - this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; - } - else { - superclass.setRuntimeAttribute.call(this, attr); - } - }; - - var translateValues = function(val, start) { - var pageXY = Y.Dom.getXY(this.getEl()); - val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; - - return val; - }; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; -})(); -/** - * Anim subclass for scrolling elements to a position defined by the "scroll" - * member of "attributes". All "scroll" members are arrays with x, y scroll positions. - *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Scroll - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @extends YAHOO.util.Anim - * @constructor - * @param {String or HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ -(function() { - YAHOO.util.Scroll = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Scroll.superclass; - var proto = Y.Scroll.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Scroll " + id); - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if (attr == 'scroll') { - val = [ - this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), - this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) - ]; - - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.getAttribute = function(attr) { - var val = null; - var el = this.getEl(); - - if (attr == 'scroll') { - val = [ el.scrollLeft, el.scrollTop ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.setAttribute = function(attr, val, unit) { - var el = this.getEl(); - - if (attr == 'scroll') { - el.scrollLeft = val[0]; - el.scrollTop = val[1]; - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; -})(); +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.0 +*/ + +/** + * The animation module provides allows effects to be added to HTMLElements. + * @module animation + */ + +/** + * + * Base animation class that provides the interface for building animated effects. + *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Anim + * @namespace YAHOO.util + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + +YAHOO.util.Anim = function(el, attributes, duration, method) { + if (el) { + this.init(el, attributes, duration, method); + } +}; + +YAHOO.util.Anim.prototype = { + /** + * Provides a readable name for the Anim instance. + * @method toString + * @return {String} + */ + toString: function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Anim " + id); + }, + + patterns: { // cached for performance + noNegatives: /width|height|opacity|padding/i, // keep at zero or above + offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default + defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default + offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset + }, + + /** + * Returns the value computed by the animation's "method". + * @method doMethod + * @param {String} attr The name of the attribute. + * @param {Number} start The value this attribute should start from for this animation. + * @param {Number} end The value this attribute should end at for this animation. + * @return {Number} The Value to be applied to the attribute. + */ + doMethod: function(attr, start, end) { + return this.method(this.currentFrame, start, end - start, this.totalFrames); + }, + + /** + * Applies a value to an attribute. + * @method setAttribute + * @param {String} attr The name of the attribute. + * @param {Number} val The value to be applied to the attribute. + * @param {String} unit The unit ('px', '%', etc.) of the value. + */ + setAttribute: function(attr, val, unit) { + if ( this.patterns.noNegatives.test(attr) ) { + val = (val > 0) ? val : 0; + } + + YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); + }, + + /** + * Returns current value of the attribute. + * @method getAttribute + * @param {String} attr The name of the attribute. + * @return {Number} val The current value of the attribute. + */ + getAttribute: function(attr) { + var el = this.getEl(); + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { + return parseFloat(val); + } + + var a = this.patterns.offsetAttribute.exec(attr) || []; + var pos = !!( a[3] ); // top or left + var box = !!( a[2] ); // width or height + + // use offsets for width/height and abs pos top/left + if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { + val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; + } else { // default to zero for other 'auto' + val = 0; + } + + return val; + }, + + /** + * Returns the unit to use when none is supplied. + * @method getDefaultUnit + * @param {attr} attr The name of the attribute. + * @return {String} The default unit to be used. + */ + getDefaultUnit: function(attr) { + if ( this.patterns.defaultUnit.test(attr) ) { + return 'px'; + } + + return ''; + }, + + /** + * Sets the actual values to be used during the animation. + * @method setRuntimeAttribute + * Should only be needed for subclass use. + * @param {Object} attr The attribute object + * @private + */ + setRuntimeAttribute: function(attr) { + var start; + var end; + var attributes = this.attributes; + + this.runtimeAttributes[attr] = {}; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; + + if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { + return false; // note return; nothing to animate to + } + + start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); + + // To beats by, per SMIL 2.1 spec + if ( isset(attributes[attr]['to']) ) { + end = attributes[attr]['to']; + } else if ( isset(attributes[attr]['by']) ) { + if (start.constructor == Array) { + end = []; + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + attributes[attr]['by'][i]; + } + } else { + end = start + attributes[attr]['by']; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + + // set units if needed + this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); + }, + + /** + * Constructor for Anim instance. + * @method init + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + init: function(el, attributes, duration, method) { + /** + * Whether or not the animation is running. + * @property isAnimated + * @private + * @type Boolean + */ + var isAnimated = false; + + /** + * A Date object that is created when the animation begins. + * @property startTime + * @private + * @type Date + */ + var startTime = null; + + /** + * The number of frames this animation was able to execute. + * @property actualFrames + * @private + * @type Int + */ + var actualFrames = 0; + + /** + * The element to be animated. + * @property el + * @private + * @type HTMLElement + */ + el = YAHOO.util.Dom.get(el); + + /** + * The collection of attributes to be animated. + * Each attribute must have at least a "to" or "by" defined in order to animate. + * If "to" is supplied, the animation will end with the attribute at that value. + * If "by" is supplied, the animation will end at that value plus its starting value. + * If both are supplied, "to" is used, and "by" is ignored. + * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). + * @property attributes + * @type Object + */ + this.attributes = attributes || {}; + + /** + * The length of the animation. Defaults to "1" (second). + * @property duration + * @type Number + */ + this.duration = duration || 1; + + /** + * The method that will provide values to the attribute(s) during the animation. + * Defaults to "YAHOO.util.Easing.easeNone". + * @property method + * @type Function + */ + this.method = method || YAHOO.util.Easing.easeNone; + + /** + * Whether or not the duration should be treated as seconds. + * Defaults to true. + * @property useSeconds + * @type Boolean + */ + this.useSeconds = true; // default to seconds + + /** + * The location of the current animation on the timeline. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property currentFrame + * @type Int + */ + this.currentFrame = 0; + + /** + * The total number of frames to be executed. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property totalFrames + * @type Int + */ + this.totalFrames = YAHOO.util.AnimMgr.fps; + + + /** + * Returns a reference to the animated element. + * @method getEl + * @return {HTMLElement} + */ + this.getEl = function() { return el; }; + + /** + * Checks whether the element is currently animated. + * @method isAnimated + * @return {Boolean} current value of isAnimated. + */ + this.isAnimated = function() { + return isAnimated; + }; + + /** + * Returns the animation start time. + * @method getStartTime + * @return {Date} current value of startTime. + */ + this.getStartTime = function() { + return startTime; + }; + + this.runtimeAttributes = {}; + + var logger = {}; + logger.log = function() {YAHOO.log.apply(window, arguments)}; + + logger.log('creating new instance of ' + this); + + /** + * Starts the animation by registering it with the animation manager. + * @method animate + */ + this.animate = function() { + if ( this.isAnimated() ) { return false; } + + this.currentFrame = 0; + + this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; + + YAHOO.util.AnimMgr.registerElement(this); + }; + + /** + * Stops the animation. Normally called by AnimMgr when animation completes. + * @method stop + * @param {Boolean} finish (optional) If true, animation will jump to final frame. + */ + this.stop = function(finish) { + if (finish) { + this.currentFrame = this.totalFrames; + this._onTween.fire(); + } + YAHOO.util.AnimMgr.stop(this); + }; + + var onStart = function() { + this.onStart.fire(); + + this.runtimeAttributes = {}; + for (var attr in this.attributes) { + this.setRuntimeAttribute(attr); + } + + isAnimated = true; + actualFrames = 0; + startTime = new Date(); + }; + + /** + * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). + * @private + */ + + var onTween = function() { + var data = { + duration: new Date() - this.getStartTime(), + currentFrame: this.currentFrame + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', currentFrame: ' + data.currentFrame + ); + }; + + this.onTween.fire(data); + + var runtimeAttributes = this.runtimeAttributes; + + for (var attr in runtimeAttributes) { + this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); + } + + actualFrames += 1; + }; + + var onComplete = function() { + var actual_duration = (new Date() - startTime) / 1000 ; + + var data = { + duration: actual_duration, + frames: actualFrames, + fps: actualFrames / actual_duration + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', frames: ' + data.frames + + ', fps: ' + data.fps + ); + }; + + isAnimated = false; + actualFrames = 0; + this.onComplete.fire(data); + }; + + /** + * Custom event that fires after onStart, useful in subclassing + * @private + */ + this._onStart = new YAHOO.util.CustomEvent('_start', this, true); + + /** + * Custom event that fires when animation begins + * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) + * @event onStart + */ + this.onStart = new YAHOO.util.CustomEvent('start', this); + + /** + * Custom event that fires between each frame + * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) + * @event onTween + */ + this.onTween = new YAHOO.util.CustomEvent('tween', this); + + /** + * Custom event that fires after onTween + * @private + */ + this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); + + /** + * Custom event that fires when animation ends + * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) + * @event onComplete + */ + this.onComplete = new YAHOO.util.CustomEvent('complete', this); + /** + * Custom event that fires after onComplete + * @private + */ + this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); + + this._onStart.subscribe(onStart); + this._onTween.subscribe(onTween); + this._onComplete.subscribe(onComplete); + } +}; + +/** + * Handles animation queueing and threading. + * Used by Anim and subclasses. + * @class AnimMgr + * @namespace YAHOO.util + */ +YAHOO.util.AnimMgr = new function() { + /** + * Reference to the animation Interval. + * @property thread + * @private + * @type Int + */ + var thread = null; + + /** + * The current queue of registered animation objects. + * @property queue + * @private + * @type Array + */ + var queue = []; + + /** + * The number of active animations. + * @property tweenCount + * @private + * @type Int + */ + var tweenCount = 0; + + /** + * Base frame rate (frames per second). + * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). + * @property fps + * @type Int + * + */ + this.fps = 200; + + /** + * Interval delay in milliseconds, defaults to fastest possible. + * @property delay + * @type Int + * + */ + this.delay = 1; + + /** + * Adds an animation instance to the animation queue. + * All animation instances must be registered in order to animate. + * @method registerElement + * @param {object} tween The Anim instance to be be registered + */ + this.registerElement = function(tween) { + queue[queue.length] = tween; + tweenCount += 1; + tween._onStart.fire(); + this.start(); + }; + + /** + * removes an animation instance from the animation queue. + * All animation instances must be registered in order to animate. + * @method unRegister + * @param {object} tween The Anim instance to be be registered + * @param {Int} index The index of the Anim instance + * @private + */ + this.unRegister = function(tween, index) { + tween._onComplete.fire(); + index = index || getIndex(tween); + if (index != -1) { queue.splice(index, 1); } + + tweenCount -= 1; + if (tweenCount <= 0) { this.stop(); } + }; + + /** + * Starts the animation thread. + * Only one thread can run at a time. + * @method start + */ + this.start = function() { + if (thread === null) { thread = setInterval(this.run, this.delay); } + }; + + /** + * Stops the animation thread or a specific animation instance. + * @method stop + * @param {object} tween A specific Anim instance to stop (optional) + * If no instance given, Manager stops thread and all animations. + */ + this.stop = function(tween) { + if (!tween) { + clearInterval(thread); + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i].isAnimated()) { + this.unRegister(tween, i); + } + } + queue = []; + thread = null; + tweenCount = 0; + } + else { + this.unRegister(tween); + } + }; + + /** + * Called per Interval to handle each animation frame. + * @method run + */ + this.run = function() { + for (var i = 0, len = queue.length; i < len; ++i) { + var tween = queue[i]; + if ( !tween || !tween.isAnimated() ) { continue; } + + if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) + { + tween.currentFrame += 1; + + if (tween.useSeconds) { + correctFrame(tween); + } + tween._onTween.fire(); + } + else { YAHOO.util.AnimMgr.stop(tween, i); } + } + }; + + var getIndex = function(anim) { + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i] == anim) { + return i; // note return; + } + } + return -1; + }; + + /** + * On the fly frame correction to keep animation on time. + * @method correctFrame + * @private + * @param {Object} tween The Anim instance being corrected. + */ + var correctFrame = function(tween) { + var frames = tween.totalFrames; + var frame = tween.currentFrame; + var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); + var elapsed = (new Date() - tween.getStartTime()); + var tweak = 0; + + if (elapsed < tween.duration * 1000) { // check if falling behind + tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); + } else { // went over duration, so jump to end + tweak = frames - (frame + 1); + } + if (tweak > 0 && isFinite(tweak)) { // adjust if needed + if (tween.currentFrame + tweak >= frames) {// dont go past last frame + tweak = frames - (frame + 1); + } + + tween.currentFrame += tweak; + } + }; +}; +/** + * Used to calculate Bezier splines for any number of control points. + * @class Bezier + * @namespace YAHOO.util + * + */ +YAHOO.util.Bezier = new function() +{ + /** + * Get the current position of the animated element based on t. + * Each point is an array of "x" and "y" values (0 = x, 1 = y) + * At least 2 points are required (start and end). + * First point is start. Last point is end. + * Additional control points are optional. + * @method getPosition + * @param {Array} points An array containing Bezier points + * @param {Number} t A number between 0 and 1 which is the basis for determining current position + * @return {Array} An array containing int x and y member data + */ + this.getPosition = function(points, t) + { + var n = points.length; + var tmp = []; + + for (var i = 0; i < n; ++i){ + tmp[i] = [points[i][0], points[i][1]]; // save input + } + + for (var j = 1; j < n; ++j) { + for (i = 0; i < n - j; ++i) { + tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; + tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; + } + } + + return [ tmp[0][0], tmp[0][1] ]; + + }; +}; +/** + * Anim subclass for color transitions. + *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, + * [255,255,255], or rgb(255,255,255)

+ * @class ColorAnim + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @constructor + * @extends YAHOO.util.Anim + * @param {HTMLElement | String} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ +(function() { + YAHOO.util.ColorAnim = function(el, attributes, duration, method) { + YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); + }; + + YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.ColorAnim.superclass; + var proto = Y.ColorAnim.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("ColorAnim " + id); + }; + + proto.patterns.color = /color$/i; + proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; + proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; + proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; + proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari + + /** + * Attempts to parse the given string and return a 3-tuple. + * @method parseColor + * @param {String} s The string to parse. + * @return {Array} The 3-tuple of rgb values. + */ + proto.parseColor = function(s) { + if (s.length == 3) { return s; } + + var c = this.patterns.hex.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; + } + + c = this.patterns.rgb.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; + } + + c = this.patterns.hex3.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; + } + + return null; + }; + + proto.getAttribute = function(attr) { + var el = this.getEl(); + if ( this.patterns.color.test(attr) ) { + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (this.patterns.transparent.test(val)) { // bgcolor default + var parent = el.parentNode; // try and get from an ancestor + val = Y.Dom.getStyle(parent, attr); + + while (parent && this.patterns.transparent.test(val)) { + parent = parent.parentNode; + val = Y.Dom.getStyle(parent, attr); + if (parent.tagName.toUpperCase() == 'HTML') { + val = '#fff'; + } + } + } + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val; + + if ( this.patterns.color.test(attr) ) { + val = []; + for (var i = 0, len = start.length; i < len; ++i) { + val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); + } + + val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; + } + else { + val = superclass.doMethod.call(this, attr, start, end); + } + + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + superclass.setRuntimeAttribute.call(this, attr); + + if ( this.patterns.color.test(attr) ) { + var attributes = this.attributes; + var start = this.parseColor(this.runtimeAttributes[attr].start); + var end = this.parseColor(this.runtimeAttributes[attr].end); + // fix colors if going "by" + if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { + end = this.parseColor(attributes[attr].by); + + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + end[i]; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + } + }; +})();/* +TERMS OF USE - EASING EQUATIONS +Open source under the BSD License. +Copyright 2001 Robert Penner All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Singleton that determines how an animation proceeds from start to end. + * @class Easing + * @namespace YAHOO.util +*/ + +YAHOO.util.Easing = { + + /** + * Uniform speed between points. + * @method easeNone + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeNone: function (t, b, c, d) { + return c*t/d + b; + }, + + /** + * Begins slowly and accelerates towards end. (quadratic) + * @method easeIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeIn: function (t, b, c, d) { + return c*(t/=d)*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quadratic) + * @method easeOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOut: function (t, b, c, d) { + return -c *(t/=d)*(t-2) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quadratic) + * @method easeBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBoth: function (t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t + b; + return -c/2 * ((--t)*(t-2) - 1) + b; + }, + + /** + * Begins slowly and accelerates towards end. (quartic) + * @method easeInStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeInStrong: function (t, b, c, d) { + return c*(t/=d)*t*t*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quartic) + * @method easeOutStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOutStrong: function (t, b, c, d) { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quartic) + * @method easeBothStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBothStrong: function (t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t*t + b; + return -c/2 * ((t-=2)*t*t*t - 2) + b; + }, + + /** + * Snap in elastic effect. + * @method elasticIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + + elasticIn: function (t, b, c, d, a, p) { + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (!a || a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + }, + + /** + * Snap out elastic effect. + * @method elasticOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticOut: function (t, b, c, d, a, p) { + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (!a || a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; + }, + + /** + * Snap both elastic effect. + * @method elasticBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticBoth: function (t, b, c, d, a, p) { + if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); + if (!a || a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + }, + + + /** + * Backtracks slightly, then reverses direction and moves to end. + * @method backIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backIn: function (t, b, c, d, s) { + if (typeof s == 'undefined') s = 1.70158; + return c*(t/=d)*t*((s+1)*t - s) + b; + }, + + /** + * Overshoots end, then reverses and comes back to end. + * @method backOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backOut: function (t, b, c, d, s) { + if (typeof s == 'undefined') s = 1.70158; + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + }, + + /** + * Backtracks slightly, then reverses direction, overshoots end, + * then reverses and comes back to end. + * @method backBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backBoth: function (t, b, c, d, s) { + if (typeof s == 'undefined') s = 1.70158; + if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + }, + + /** + * Bounce off of start. + * @method bounceIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceIn: function (t, b, c, d) { + return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; + }, + + /** + * Bounces off end. + * @method bounceOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceOut: function (t, b, c, d) { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } else { + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + } + }, + + /** + * Bounces off start and end. + * @method bounceBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceBoth: function (t, b, c, d) { + if (t < d/2) return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; + return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; + } +}; + +/** + * Anim subclass for moving elements along a path defined by the "points" + * member of "attributes". All "points" are arrays with x, y coordinates. + *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Motion + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @extends YAHOO.util.Anim + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ +(function() { + YAHOO.util.Motion = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Motion.superclass; + var proto = Y.Motion.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Motion " + id); + }; + + proto.patterns.points = /^points$/i; + + proto.setAttribute = function(attr, val, unit) { + if ( this.patterns.points.test(attr) ) { + unit = unit || 'px'; + superclass.setAttribute.call(this, 'left', val[0], unit); + superclass.setAttribute.call(this, 'top', val[1], unit); + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; + + proto.getAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var val = [ + superclass.getAttribute.call(this, 'left'), + superclass.getAttribute.call(this, 'top') + ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if ( this.patterns.points.test(attr) ) { + var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; + val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var el = this.getEl(); + var attributes = this.attributes; + var start; + var control = attributes['points']['control'] || []; + var end; + var i, len; + + if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points + control = [control]; + } else { // break reference to attributes.points.control + var tmp = []; + for (i = 0, len = control.length; i< len; ++i) { + tmp[i] = control[i]; + } + control = tmp; + } + + if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative + Y.Dom.setStyle(el, 'position', 'relative'); + } + + if ( isset(attributes['points']['from']) ) { + Y.Dom.setXY(el, attributes['points']['from']); // set position to from point + } + else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position + + start = this.getAttribute('points'); // get actual top & left + + // TO beats BY, per SMIL 2.1 spec + if ( isset(attributes['points']['to']) ) { + end = translateValues.call(this, attributes['points']['to'], start); + + var pageXY = Y.Dom.getXY(this.getEl()); + for (i = 0, len = control.length; i < len; ++i) { + control[i] = translateValues.call(this, control[i], start); + } + + + } else if ( isset(attributes['points']['by']) ) { + end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; + + for (i = 0, len = control.length; i < len; ++i) { + control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; + } + } + + this.runtimeAttributes[attr] = [start]; + + if (control.length > 0) { + this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); + } + + this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; + } + else { + superclass.setRuntimeAttribute.call(this, attr); + } + }; + + var translateValues = function(val, start) { + var pageXY = Y.Dom.getXY(this.getEl()); + val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; + + return val; + }; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; +})(); +/** + * Anim subclass for scrolling elements to a position defined by the "scroll" + * member of "attributes". All "scroll" members are arrays with x, y scroll positions. + *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Scroll + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @extends YAHOO.util.Anim + * @constructor + * @param {String or HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ +(function() { + YAHOO.util.Scroll = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Scroll.superclass; + var proto = Y.Scroll.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Scroll " + id); + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if (attr == 'scroll') { + val = [ + this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), + this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) + ]; + + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.getAttribute = function(attr) { + var val = null; + var el = this.getEl(); + + if (attr == 'scroll') { + val = [ el.scrollLeft, el.scrollTop ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.setAttribute = function(attr, val, unit) { + var el = this.getEl(); + + if (attr == 'scroll') { + el.scrollLeft = val[0]; + el.scrollTop = val[1]; + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; +})(); diff --git a/thirdpartyjs/yui/animation/animation.js b/thirdpartyjs/yui/animation/animation.js index 333f946..7c0165c 100644 --- a/thirdpartyjs/yui/animation/animation.js +++ b/thirdpartyjs/yui/animation/animation.js @@ -1,1272 +1,1272 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 0.12.0 -*/ - -/** - * The animation module provides allows effects to be added to HTMLElements. - * @module animation - */ - -/** - * - * Base animation class that provides the interface for building animated effects. - *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

- * @class Anim - * @namespace YAHOO.util - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - -YAHOO.util.Anim = function(el, attributes, duration, method) { - if (el) { - this.init(el, attributes, duration, method); - } -}; - -YAHOO.util.Anim.prototype = { - /** - * Provides a readable name for the Anim instance. - * @method toString - * @return {String} - */ - toString: function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Anim " + id); - }, - - patterns: { // cached for performance - noNegatives: /width|height|opacity|padding/i, // keep at zero or above - offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default - defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default - offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset - }, - - /** - * Returns the value computed by the animation's "method". - * @method doMethod - * @param {String} attr The name of the attribute. - * @param {Number} start The value this attribute should start from for this animation. - * @param {Number} end The value this attribute should end at for this animation. - * @return {Number} The Value to be applied to the attribute. - */ - doMethod: function(attr, start, end) { - return this.method(this.currentFrame, start, end - start, this.totalFrames); - }, - - /** - * Applies a value to an attribute. - * @method setAttribute - * @param {String} attr The name of the attribute. - * @param {Number} val The value to be applied to the attribute. - * @param {String} unit The unit ('px', '%', etc.) of the value. - */ - setAttribute: function(attr, val, unit) { - if ( this.patterns.noNegatives.test(attr) ) { - val = (val > 0) ? val : 0; - } - - YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); - }, - - /** - * Returns current value of the attribute. - * @method getAttribute - * @param {String} attr The name of the attribute. - * @return {Number} val The current value of the attribute. - */ - getAttribute: function(attr) { - var el = this.getEl(); - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { - return parseFloat(val); - } - - var a = this.patterns.offsetAttribute.exec(attr) || []; - var pos = !!( a[3] ); // top or left - var box = !!( a[2] ); // width or height - - // use offsets for width/height and abs pos top/left - if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { - val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; - } else { // default to zero for other 'auto' - val = 0; - } - - return val; - }, - - /** - * Returns the unit to use when none is supplied. - * @method getDefaultUnit - * @param {attr} attr The name of the attribute. - * @return {String} The default unit to be used. - */ - getDefaultUnit: function(attr) { - if ( this.patterns.defaultUnit.test(attr) ) { - return 'px'; - } - - return ''; - }, - - /** - * Sets the actual values to be used during the animation. - * @method setRuntimeAttribute - * Should only be needed for subclass use. - * @param {Object} attr The attribute object - * @private - */ - setRuntimeAttribute: function(attr) { - var start; - var end; - var attributes = this.attributes; - - this.runtimeAttributes[attr] = {}; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; - - if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { - return false; // note return; nothing to animate to - } - - start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); - - // To beats by, per SMIL 2.1 spec - if ( isset(attributes[attr]['to']) ) { - end = attributes[attr]['to']; - } else if ( isset(attributes[attr]['by']) ) { - if (start.constructor == Array) { - end = []; - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + attributes[attr]['by'][i]; - } - } else { - end = start + attributes[attr]['by']; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - - // set units if needed - this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); - }, - - /** - * Constructor for Anim instance. - * @method init - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ - init: function(el, attributes, duration, method) { - /** - * Whether or not the animation is running. - * @property isAnimated - * @private - * @type Boolean - */ - var isAnimated = false; - - /** - * A Date object that is created when the animation begins. - * @property startTime - * @private - * @type Date - */ - var startTime = null; - - /** - * The number of frames this animation was able to execute. - * @property actualFrames - * @private - * @type Int - */ - var actualFrames = 0; - - /** - * The element to be animated. - * @property el - * @private - * @type HTMLElement - */ - el = YAHOO.util.Dom.get(el); - - /** - * The collection of attributes to be animated. - * Each attribute must have at least a "to" or "by" defined in order to animate. - * If "to" is supplied, the animation will end with the attribute at that value. - * If "by" is supplied, the animation will end at that value plus its starting value. - * If both are supplied, "to" is used, and "by" is ignored. - * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). - * @property attributes - * @type Object - */ - this.attributes = attributes || {}; - - /** - * The length of the animation. Defaults to "1" (second). - * @property duration - * @type Number - */ - this.duration = duration || 1; - - /** - * The method that will provide values to the attribute(s) during the animation. - * Defaults to "YAHOO.util.Easing.easeNone". - * @property method - * @type Function - */ - this.method = method || YAHOO.util.Easing.easeNone; - - /** - * Whether or not the duration should be treated as seconds. - * Defaults to true. - * @property useSeconds - * @type Boolean - */ - this.useSeconds = true; // default to seconds - - /** - * The location of the current animation on the timeline. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property currentFrame - * @type Int - */ - this.currentFrame = 0; - - /** - * The total number of frames to be executed. - * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. - * @property totalFrames - * @type Int - */ - this.totalFrames = YAHOO.util.AnimMgr.fps; - - - /** - * Returns a reference to the animated element. - * @method getEl - * @return {HTMLElement} - */ - this.getEl = function() { return el; }; - - /** - * Checks whether the element is currently animated. - * @method isAnimated - * @return {Boolean} current value of isAnimated. - */ - this.isAnimated = function() { - return isAnimated; - }; - - /** - * Returns the animation start time. - * @method getStartTime - * @return {Date} current value of startTime. - */ - this.getStartTime = function() { - return startTime; - }; - - this.runtimeAttributes = {}; - - - - /** - * Starts the animation by registering it with the animation manager. - * @method animate - */ - this.animate = function() { - if ( this.isAnimated() ) { return false; } - - this.currentFrame = 0; - - this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; - - YAHOO.util.AnimMgr.registerElement(this); - }; - - /** - * Stops the animation. Normally called by AnimMgr when animation completes. - * @method stop - * @param {Boolean} finish (optional) If true, animation will jump to final frame. - */ - this.stop = function(finish) { - if (finish) { - this.currentFrame = this.totalFrames; - this._onTween.fire(); - } - YAHOO.util.AnimMgr.stop(this); - }; - - var onStart = function() { - this.onStart.fire(); - - this.runtimeAttributes = {}; - for (var attr in this.attributes) { - this.setRuntimeAttribute(attr); - } - - isAnimated = true; - actualFrames = 0; - startTime = new Date(); - }; - - /** - * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). - * @private - */ - - var onTween = function() { - var data = { - duration: new Date() - this.getStartTime(), - currentFrame: this.currentFrame - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', currentFrame: ' + data.currentFrame - ); - }; - - this.onTween.fire(data); - - var runtimeAttributes = this.runtimeAttributes; - - for (var attr in runtimeAttributes) { - this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); - } - - actualFrames += 1; - }; - - var onComplete = function() { - var actual_duration = (new Date() - startTime) / 1000 ; - - var data = { - duration: actual_duration, - frames: actualFrames, - fps: actualFrames / actual_duration - }; - - data.toString = function() { - return ( - 'duration: ' + data.duration + - ', frames: ' + data.frames + - ', fps: ' + data.fps - ); - }; - - isAnimated = false; - actualFrames = 0; - this.onComplete.fire(data); - }; - - /** - * Custom event that fires after onStart, useful in subclassing - * @private - */ - this._onStart = new YAHOO.util.CustomEvent('_start', this, true); - - /** - * Custom event that fires when animation begins - * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) - * @event onStart - */ - this.onStart = new YAHOO.util.CustomEvent('start', this); - - /** - * Custom event that fires between each frame - * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) - * @event onTween - */ - this.onTween = new YAHOO.util.CustomEvent('tween', this); - - /** - * Custom event that fires after onTween - * @private - */ - this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); - - /** - * Custom event that fires when animation ends - * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) - * @event onComplete - */ - this.onComplete = new YAHOO.util.CustomEvent('complete', this); - /** - * Custom event that fires after onComplete - * @private - */ - this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); - - this._onStart.subscribe(onStart); - this._onTween.subscribe(onTween); - this._onComplete.subscribe(onComplete); - } -}; - -/** - * Handles animation queueing and threading. - * Used by Anim and subclasses. - * @class AnimMgr - * @namespace YAHOO.util - */ -YAHOO.util.AnimMgr = new function() { - /** - * Reference to the animation Interval. - * @property thread - * @private - * @type Int - */ - var thread = null; - - /** - * The current queue of registered animation objects. - * @property queue - * @private - * @type Array - */ - var queue = []; - - /** - * The number of active animations. - * @property tweenCount - * @private - * @type Int - */ - var tweenCount = 0; - - /** - * Base frame rate (frames per second). - * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). - * @property fps - * @type Int - * - */ - this.fps = 200; - - /** - * Interval delay in milliseconds, defaults to fastest possible. - * @property delay - * @type Int - * - */ - this.delay = 1; - - /** - * Adds an animation instance to the animation queue. - * All animation instances must be registered in order to animate. - * @method registerElement - * @param {object} tween The Anim instance to be be registered - */ - this.registerElement = function(tween) { - queue[queue.length] = tween; - tweenCount += 1; - tween._onStart.fire(); - this.start(); - }; - - /** - * removes an animation instance from the animation queue. - * All animation instances must be registered in order to animate. - * @method unRegister - * @param {object} tween The Anim instance to be be registered - * @param {Int} index The index of the Anim instance - * @private - */ - this.unRegister = function(tween, index) { - tween._onComplete.fire(); - index = index || getIndex(tween); - if (index != -1) { queue.splice(index, 1); } - - tweenCount -= 1; - if (tweenCount <= 0) { this.stop(); } - }; - - /** - * Starts the animation thread. - * Only one thread can run at a time. - * @method start - */ - this.start = function() { - if (thread === null) { thread = setInterval(this.run, this.delay); } - }; - - /** - * Stops the animation thread or a specific animation instance. - * @method stop - * @param {object} tween A specific Anim instance to stop (optional) - * If no instance given, Manager stops thread and all animations. - */ - this.stop = function(tween) { - if (!tween) { - clearInterval(thread); - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i].isAnimated()) { - this.unRegister(tween, i); - } - } - queue = []; - thread = null; - tweenCount = 0; - } - else { - this.unRegister(tween); - } - }; - - /** - * Called per Interval to handle each animation frame. - * @method run - */ - this.run = function() { - for (var i = 0, len = queue.length; i < len; ++i) { - var tween = queue[i]; - if ( !tween || !tween.isAnimated() ) { continue; } - - if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) - { - tween.currentFrame += 1; - - if (tween.useSeconds) { - correctFrame(tween); - } - tween._onTween.fire(); - } - else { YAHOO.util.AnimMgr.stop(tween, i); } - } - }; - - var getIndex = function(anim) { - for (var i = 0, len = queue.length; i < len; ++i) { - if (queue[i] == anim) { - return i; // note return; - } - } - return -1; - }; - - /** - * On the fly frame correction to keep animation on time. - * @method correctFrame - * @private - * @param {Object} tween The Anim instance being corrected. - */ - var correctFrame = function(tween) { - var frames = tween.totalFrames; - var frame = tween.currentFrame; - var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); - var elapsed = (new Date() - tween.getStartTime()); - var tweak = 0; - - if (elapsed < tween.duration * 1000) { // check if falling behind - tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); - } else { // went over duration, so jump to end - tweak = frames - (frame + 1); - } - if (tweak > 0 && isFinite(tweak)) { // adjust if needed - if (tween.currentFrame + tweak >= frames) {// dont go past last frame - tweak = frames - (frame + 1); - } - - tween.currentFrame += tweak; - } - }; -}; -/** - * Used to calculate Bezier splines for any number of control points. - * @class Bezier - * @namespace YAHOO.util - * - */ -YAHOO.util.Bezier = new function() -{ - /** - * Get the current position of the animated element based on t. - * Each point is an array of "x" and "y" values (0 = x, 1 = y) - * At least 2 points are required (start and end). - * First point is start. Last point is end. - * Additional control points are optional. - * @method getPosition - * @param {Array} points An array containing Bezier points - * @param {Number} t A number between 0 and 1 which is the basis for determining current position - * @return {Array} An array containing int x and y member data - */ - this.getPosition = function(points, t) - { - var n = points.length; - var tmp = []; - - for (var i = 0; i < n; ++i){ - tmp[i] = [points[i][0], points[i][1]]; // save input - } - - for (var j = 1; j < n; ++j) { - for (i = 0; i < n - j; ++i) { - tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; - tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; - } - } - - return [ tmp[0][0], tmp[0][1] ]; - - }; -}; -/** - * Anim subclass for color transitions. - *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, - * [255,255,255], or rgb(255,255,255)

- * @class ColorAnim - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @constructor - * @extends YAHOO.util.Anim - * @param {HTMLElement | String} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ -(function() { - YAHOO.util.ColorAnim = function(el, attributes, duration, method) { - YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); - }; - - YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.ColorAnim.superclass; - var proto = Y.ColorAnim.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("ColorAnim " + id); - }; - - proto.patterns.color = /color$/i; - proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; - proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; - proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; - proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari - - /** - * Attempts to parse the given string and return a 3-tuple. - * @method parseColor - * @param {String} s The string to parse. - * @return {Array} The 3-tuple of rgb values. - */ - proto.parseColor = function(s) { - if (s.length == 3) { return s; } - - var c = this.patterns.hex.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; - } - - c = this.patterns.rgb.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; - } - - c = this.patterns.hex3.exec(s); - if (c && c.length == 4) { - return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; - } - - return null; - }; - - proto.getAttribute = function(attr) { - var el = this.getEl(); - if ( this.patterns.color.test(attr) ) { - var val = YAHOO.util.Dom.getStyle(el, attr); - - if (this.patterns.transparent.test(val)) { // bgcolor default - var parent = el.parentNode; // try and get from an ancestor - val = Y.Dom.getStyle(parent, attr); - - while (parent && this.patterns.transparent.test(val)) { - parent = parent.parentNode; - val = Y.Dom.getStyle(parent, attr); - if (parent.tagName.toUpperCase() == 'HTML') { - val = '#fff'; - } - } - } - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val; - - if ( this.patterns.color.test(attr) ) { - val = []; - for (var i = 0, len = start.length; i < len; ++i) { - val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); - } - - val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; - } - else { - val = superclass.doMethod.call(this, attr, start, end); - } - - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - superclass.setRuntimeAttribute.call(this, attr); - - if ( this.patterns.color.test(attr) ) { - var attributes = this.attributes; - var start = this.parseColor(this.runtimeAttributes[attr].start); - var end = this.parseColor(this.runtimeAttributes[attr].end); - // fix colors if going "by" - if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { - end = this.parseColor(attributes[attr].by); - - for (var i = 0, len = start.length; i < len; ++i) { - end[i] = start[i] + end[i]; - } - } - - this.runtimeAttributes[attr].start = start; - this.runtimeAttributes[attr].end = end; - } - }; -})();/* -TERMS OF USE - EASING EQUATIONS -Open source under the BSD License. -Copyright 2001 Robert Penner All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * Singleton that determines how an animation proceeds from start to end. - * @class Easing - * @namespace YAHOO.util -*/ - -YAHOO.util.Easing = { - - /** - * Uniform speed between points. - * @method easeNone - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeNone: function (t, b, c, d) { - return c*t/d + b; - }, - - /** - * Begins slowly and accelerates towards end. (quadratic) - * @method easeIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeIn: function (t, b, c, d) { - return c*(t/=d)*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quadratic) - * @method easeOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOut: function (t, b, c, d) { - return -c *(t/=d)*(t-2) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quadratic) - * @method easeBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBoth: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t + b; - return -c/2 * ((--t)*(t-2) - 1) + b; - }, - - /** - * Begins slowly and accelerates towards end. (quartic) - * @method easeInStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeInStrong: function (t, b, c, d) { - return c*(t/=d)*t*t*t + b; - }, - - /** - * Begins quickly and decelerates towards end. (quartic) - * @method easeOutStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeOutStrong: function (t, b, c, d) { - return -c * ((t=t/d-1)*t*t*t - 1) + b; - }, - - /** - * Begins slowly and decelerates towards end. (quartic) - * @method easeBothStrong - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - easeBothStrong: function (t, b, c, d) { - if ((t/=d/2) < 1) return c/2*t*t*t*t + b; - return -c/2 * ((t-=2)*t*t*t - 2) + b; - }, - - /** - * Snap in elastic effect. - * @method elasticIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - - elasticIn: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - }, - - /** - * Snap out elastic effect. - * @method elasticOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticOut: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; - }, - - /** - * Snap both elastic effect. - * @method elasticBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} p Period (optional) - * @return {Number} The computed value for the current animation frame - */ - elasticBoth: function (t, b, c, d, a, p) { - if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); - if (!a || a < Math.abs(c)) { a=c; var s=p/4; } - else var s = p/(2*Math.PI) * Math.asin (c/a); - if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; - }, - - /** - * Backtracks slightly, then reverses direction and moves to end. - * @method backIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backIn: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*(t/=d)*t*((s+1)*t - s) + b; - }, - - /** - * Overshoots end, then reverses and comes back to end. - * @method backOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backOut: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; - }, - - /** - * Backtracks slightly, then reverses direction, overshoots end, - * then reverses and comes back to end. - * @method backBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @param {Number} s Overshoot (optional) - * @return {Number} The computed value for the current animation frame - */ - backBoth: function (t, b, c, d, s) { - if (typeof s == 'undefined') s = 1.70158; - if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; - return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; - }, - - /** - * Bounce off of start. - * @method bounceIn - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceIn: function (t, b, c, d) { - return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; - }, - - /** - * Bounces off end. - * @method bounceOut - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceOut: function (t, b, c, d) { - if ((t/=d) < (1/2.75)) { - return c*(7.5625*t*t) + b; - } else if (t < (2/2.75)) { - return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; - } else if (t < (2.5/2.75)) { - return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; - } else { - return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; - } - }, - - /** - * Bounces off start and end. - * @method bounceBoth - * @param {Number} t Time value used to compute current value - * @param {Number} b Starting value - * @param {Number} c Delta between start and end values - * @param {Number} d Total length of animation - * @return {Number} The computed value for the current animation frame - */ - bounceBoth: function (t, b, c, d) { - if (t < d/2) return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; - return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; - } -}; - -/** - * Anim subclass for moving elements along a path defined by the "points" - * member of "attributes". All "points" are arrays with x, y coordinates. - *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Motion - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @constructor - * @extends YAHOO.util.Anim - * @param {String | HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ -(function() { - YAHOO.util.Motion = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Motion.superclass; - var proto = Y.Motion.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Motion " + id); - }; - - proto.patterns.points = /^points$/i; - - proto.setAttribute = function(attr, val, unit) { - if ( this.patterns.points.test(attr) ) { - unit = unit || 'px'; - superclass.setAttribute.call(this, 'left', val[0], unit); - superclass.setAttribute.call(this, 'top', val[1], unit); - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; - - proto.getAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var val = [ - superclass.getAttribute.call(this, 'left'), - superclass.getAttribute.call(this, 'top') - ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if ( this.patterns.points.test(attr) ) { - var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; - val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.setRuntimeAttribute = function(attr) { - if ( this.patterns.points.test(attr) ) { - var el = this.getEl(); - var attributes = this.attributes; - var start; - var control = attributes['points']['control'] || []; - var end; - var i, len; - - if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points - control = [control]; - } else { // break reference to attributes.points.control - var tmp = []; - for (i = 0, len = control.length; i< len; ++i) { - tmp[i] = control[i]; - } - control = tmp; - } - - if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative - Y.Dom.setStyle(el, 'position', 'relative'); - } - - if ( isset(attributes['points']['from']) ) { - Y.Dom.setXY(el, attributes['points']['from']); // set position to from point - } - else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position - - start = this.getAttribute('points'); // get actual top & left - - // TO beats BY, per SMIL 2.1 spec - if ( isset(attributes['points']['to']) ) { - end = translateValues.call(this, attributes['points']['to'], start); - - var pageXY = Y.Dom.getXY(this.getEl()); - for (i = 0, len = control.length; i < len; ++i) { - control[i] = translateValues.call(this, control[i], start); - } - - - } else if ( isset(attributes['points']['by']) ) { - end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; - - for (i = 0, len = control.length; i < len; ++i) { - control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; - } - } - - this.runtimeAttributes[attr] = [start]; - - if (control.length > 0) { - this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); - } - - this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; - } - else { - superclass.setRuntimeAttribute.call(this, attr); - } - }; - - var translateValues = function(val, start) { - var pageXY = Y.Dom.getXY(this.getEl()); - val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; - - return val; - }; - - var isset = function(prop) { - return (typeof prop !== 'undefined'); - }; -})(); -/** - * Anim subclass for scrolling elements to a position defined by the "scroll" - * member of "attributes". All "scroll" members are arrays with x, y scroll positions. - *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

- * @class Scroll - * @namespace YAHOO.util - * @requires YAHOO.util.Anim - * @requires YAHOO.util.AnimMgr - * @requires YAHOO.util.Easing - * @requires YAHOO.util.Bezier - * @requires YAHOO.util.Dom - * @requires YAHOO.util.Event - * @requires YAHOO.util.CustomEvent - * @extends YAHOO.util.Anim - * @constructor - * @param {String or HTMLElement} el Reference to the element that will be animated - * @param {Object} attributes The attribute(s) to be animated. - * Each attribute is an object with at minimum a "to" or "by" member defined. - * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). - * All attribute names use camelCase. - * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based - * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) - */ -(function() { - YAHOO.util.Scroll = function(el, attributes, duration, method) { - if (el) { // dont break existing subclasses not using YAHOO.extend - YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); - } - }; - - YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); - - // shorthand - var Y = YAHOO.util; - var superclass = Y.Scroll.superclass; - var proto = Y.Scroll.prototype; - - proto.toString = function() { - var el = this.getEl(); - var id = el.id || el.tagName; - return ("Scroll " + id); - }; - - proto.doMethod = function(attr, start, end) { - var val = null; - - if (attr == 'scroll') { - val = [ - this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), - this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) - ]; - - } else { - val = superclass.doMethod.call(this, attr, start, end); - } - return val; - }; - - proto.getAttribute = function(attr) { - var val = null; - var el = this.getEl(); - - if (attr == 'scroll') { - val = [ el.scrollLeft, el.scrollTop ]; - } else { - val = superclass.getAttribute.call(this, attr); - } - - return val; - }; - - proto.setAttribute = function(attr, val, unit) { - var el = this.getEl(); - - if (attr == 'scroll') { - el.scrollLeft = val[0]; - el.scrollTop = val[1]; - } else { - superclass.setAttribute.call(this, attr, val, unit); - } - }; -})(); +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 0.12.0 +*/ + +/** + * The animation module provides allows effects to be added to HTMLElements. + * @module animation + */ + +/** + * + * Base animation class that provides the interface for building animated effects. + *

Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Anim + * @namespace YAHOO.util + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + +YAHOO.util.Anim = function(el, attributes, duration, method) { + if (el) { + this.init(el, attributes, duration, method); + } +}; + +YAHOO.util.Anim.prototype = { + /** + * Provides a readable name for the Anim instance. + * @method toString + * @return {String} + */ + toString: function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Anim " + id); + }, + + patterns: { // cached for performance + noNegatives: /width|height|opacity|padding/i, // keep at zero or above + offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default + defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default + offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset + }, + + /** + * Returns the value computed by the animation's "method". + * @method doMethod + * @param {String} attr The name of the attribute. + * @param {Number} start The value this attribute should start from for this animation. + * @param {Number} end The value this attribute should end at for this animation. + * @return {Number} The Value to be applied to the attribute. + */ + doMethod: function(attr, start, end) { + return this.method(this.currentFrame, start, end - start, this.totalFrames); + }, + + /** + * Applies a value to an attribute. + * @method setAttribute + * @param {String} attr The name of the attribute. + * @param {Number} val The value to be applied to the attribute. + * @param {String} unit The unit ('px', '%', etc.) of the value. + */ + setAttribute: function(attr, val, unit) { + if ( this.patterns.noNegatives.test(attr) ) { + val = (val > 0) ? val : 0; + } + + YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); + }, + + /** + * Returns current value of the attribute. + * @method getAttribute + * @param {String} attr The name of the attribute. + * @return {Number} val The current value of the attribute. + */ + getAttribute: function(attr) { + var el = this.getEl(); + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { + return parseFloat(val); + } + + var a = this.patterns.offsetAttribute.exec(attr) || []; + var pos = !!( a[3] ); // top or left + var box = !!( a[2] ); // width or height + + // use offsets for width/height and abs pos top/left + if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { + val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; + } else { // default to zero for other 'auto' + val = 0; + } + + return val; + }, + + /** + * Returns the unit to use when none is supplied. + * @method getDefaultUnit + * @param {attr} attr The name of the attribute. + * @return {String} The default unit to be used. + */ + getDefaultUnit: function(attr) { + if ( this.patterns.defaultUnit.test(attr) ) { + return 'px'; + } + + return ''; + }, + + /** + * Sets the actual values to be used during the animation. + * @method setRuntimeAttribute + * Should only be needed for subclass use. + * @param {Object} attr The attribute object + * @private + */ + setRuntimeAttribute: function(attr) { + var start; + var end; + var attributes = this.attributes; + + this.runtimeAttributes[attr] = {}; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; + + if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { + return false; // note return; nothing to animate to + } + + start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); + + // To beats by, per SMIL 2.1 spec + if ( isset(attributes[attr]['to']) ) { + end = attributes[attr]['to']; + } else if ( isset(attributes[attr]['by']) ) { + if (start.constructor == Array) { + end = []; + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + attributes[attr]['by'][i]; + } + } else { + end = start + attributes[attr]['by']; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + + // set units if needed + this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); + }, + + /** + * Constructor for Anim instance. + * @method init + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ + init: function(el, attributes, duration, method) { + /** + * Whether or not the animation is running. + * @property isAnimated + * @private + * @type Boolean + */ + var isAnimated = false; + + /** + * A Date object that is created when the animation begins. + * @property startTime + * @private + * @type Date + */ + var startTime = null; + + /** + * The number of frames this animation was able to execute. + * @property actualFrames + * @private + * @type Int + */ + var actualFrames = 0; + + /** + * The element to be animated. + * @property el + * @private + * @type HTMLElement + */ + el = YAHOO.util.Dom.get(el); + + /** + * The collection of attributes to be animated. + * Each attribute must have at least a "to" or "by" defined in order to animate. + * If "to" is supplied, the animation will end with the attribute at that value. + * If "by" is supplied, the animation will end at that value plus its starting value. + * If both are supplied, "to" is used, and "by" is ignored. + * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). + * @property attributes + * @type Object + */ + this.attributes = attributes || {}; + + /** + * The length of the animation. Defaults to "1" (second). + * @property duration + * @type Number + */ + this.duration = duration || 1; + + /** + * The method that will provide values to the attribute(s) during the animation. + * Defaults to "YAHOO.util.Easing.easeNone". + * @property method + * @type Function + */ + this.method = method || YAHOO.util.Easing.easeNone; + + /** + * Whether or not the duration should be treated as seconds. + * Defaults to true. + * @property useSeconds + * @type Boolean + */ + this.useSeconds = true; // default to seconds + + /** + * The location of the current animation on the timeline. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property currentFrame + * @type Int + */ + this.currentFrame = 0; + + /** + * The total number of frames to be executed. + * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. + * @property totalFrames + * @type Int + */ + this.totalFrames = YAHOO.util.AnimMgr.fps; + + + /** + * Returns a reference to the animated element. + * @method getEl + * @return {HTMLElement} + */ + this.getEl = function() { return el; }; + + /** + * Checks whether the element is currently animated. + * @method isAnimated + * @return {Boolean} current value of isAnimated. + */ + this.isAnimated = function() { + return isAnimated; + }; + + /** + * Returns the animation start time. + * @method getStartTime + * @return {Date} current value of startTime. + */ + this.getStartTime = function() { + return startTime; + }; + + this.runtimeAttributes = {}; + + + + /** + * Starts the animation by registering it with the animation manager. + * @method animate + */ + this.animate = function() { + if ( this.isAnimated() ) { return false; } + + this.currentFrame = 0; + + this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; + + YAHOO.util.AnimMgr.registerElement(this); + }; + + /** + * Stops the animation. Normally called by AnimMgr when animation completes. + * @method stop + * @param {Boolean} finish (optional) If true, animation will jump to final frame. + */ + this.stop = function(finish) { + if (finish) { + this.currentFrame = this.totalFrames; + this._onTween.fire(); + } + YAHOO.util.AnimMgr.stop(this); + }; + + var onStart = function() { + this.onStart.fire(); + + this.runtimeAttributes = {}; + for (var attr in this.attributes) { + this.setRuntimeAttribute(attr); + } + + isAnimated = true; + actualFrames = 0; + startTime = new Date(); + }; + + /** + * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). + * @private + */ + + var onTween = function() { + var data = { + duration: new Date() - this.getStartTime(), + currentFrame: this.currentFrame + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', currentFrame: ' + data.currentFrame + ); + }; + + this.onTween.fire(data); + + var runtimeAttributes = this.runtimeAttributes; + + for (var attr in runtimeAttributes) { + this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); + } + + actualFrames += 1; + }; + + var onComplete = function() { + var actual_duration = (new Date() - startTime) / 1000 ; + + var data = { + duration: actual_duration, + frames: actualFrames, + fps: actualFrames / actual_duration + }; + + data.toString = function() { + return ( + 'duration: ' + data.duration + + ', frames: ' + data.frames + + ', fps: ' + data.fps + ); + }; + + isAnimated = false; + actualFrames = 0; + this.onComplete.fire(data); + }; + + /** + * Custom event that fires after onStart, useful in subclassing + * @private + */ + this._onStart = new YAHOO.util.CustomEvent('_start', this, true); + + /** + * Custom event that fires when animation begins + * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) + * @event onStart + */ + this.onStart = new YAHOO.util.CustomEvent('start', this); + + /** + * Custom event that fires between each frame + * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) + * @event onTween + */ + this.onTween = new YAHOO.util.CustomEvent('tween', this); + + /** + * Custom event that fires after onTween + * @private + */ + this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); + + /** + * Custom event that fires when animation ends + * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) + * @event onComplete + */ + this.onComplete = new YAHOO.util.CustomEvent('complete', this); + /** + * Custom event that fires after onComplete + * @private + */ + this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); + + this._onStart.subscribe(onStart); + this._onTween.subscribe(onTween); + this._onComplete.subscribe(onComplete); + } +}; + +/** + * Handles animation queueing and threading. + * Used by Anim and subclasses. + * @class AnimMgr + * @namespace YAHOO.util + */ +YAHOO.util.AnimMgr = new function() { + /** + * Reference to the animation Interval. + * @property thread + * @private + * @type Int + */ + var thread = null; + + /** + * The current queue of registered animation objects. + * @property queue + * @private + * @type Array + */ + var queue = []; + + /** + * The number of active animations. + * @property tweenCount + * @private + * @type Int + */ + var tweenCount = 0; + + /** + * Base frame rate (frames per second). + * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). + * @property fps + * @type Int + * + */ + this.fps = 200; + + /** + * Interval delay in milliseconds, defaults to fastest possible. + * @property delay + * @type Int + * + */ + this.delay = 1; + + /** + * Adds an animation instance to the animation queue. + * All animation instances must be registered in order to animate. + * @method registerElement + * @param {object} tween The Anim instance to be be registered + */ + this.registerElement = function(tween) { + queue[queue.length] = tween; + tweenCount += 1; + tween._onStart.fire(); + this.start(); + }; + + /** + * removes an animation instance from the animation queue. + * All animation instances must be registered in order to animate. + * @method unRegister + * @param {object} tween The Anim instance to be be registered + * @param {Int} index The index of the Anim instance + * @private + */ + this.unRegister = function(tween, index) { + tween._onComplete.fire(); + index = index || getIndex(tween); + if (index != -1) { queue.splice(index, 1); } + + tweenCount -= 1; + if (tweenCount <= 0) { this.stop(); } + }; + + /** + * Starts the animation thread. + * Only one thread can run at a time. + * @method start + */ + this.start = function() { + if (thread === null) { thread = setInterval(this.run, this.delay); } + }; + + /** + * Stops the animation thread or a specific animation instance. + * @method stop + * @param {object} tween A specific Anim instance to stop (optional) + * If no instance given, Manager stops thread and all animations. + */ + this.stop = function(tween) { + if (!tween) { + clearInterval(thread); + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i].isAnimated()) { + this.unRegister(tween, i); + } + } + queue = []; + thread = null; + tweenCount = 0; + } + else { + this.unRegister(tween); + } + }; + + /** + * Called per Interval to handle each animation frame. + * @method run + */ + this.run = function() { + for (var i = 0, len = queue.length; i < len; ++i) { + var tween = queue[i]; + if ( !tween || !tween.isAnimated() ) { continue; } + + if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) + { + tween.currentFrame += 1; + + if (tween.useSeconds) { + correctFrame(tween); + } + tween._onTween.fire(); + } + else { YAHOO.util.AnimMgr.stop(tween, i); } + } + }; + + var getIndex = function(anim) { + for (var i = 0, len = queue.length; i < len; ++i) { + if (queue[i] == anim) { + return i; // note return; + } + } + return -1; + }; + + /** + * On the fly frame correction to keep animation on time. + * @method correctFrame + * @private + * @param {Object} tween The Anim instance being corrected. + */ + var correctFrame = function(tween) { + var frames = tween.totalFrames; + var frame = tween.currentFrame; + var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); + var elapsed = (new Date() - tween.getStartTime()); + var tweak = 0; + + if (elapsed < tween.duration * 1000) { // check if falling behind + tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); + } else { // went over duration, so jump to end + tweak = frames - (frame + 1); + } + if (tweak > 0 && isFinite(tweak)) { // adjust if needed + if (tween.currentFrame + tweak >= frames) {// dont go past last frame + tweak = frames - (frame + 1); + } + + tween.currentFrame += tweak; + } + }; +}; +/** + * Used to calculate Bezier splines for any number of control points. + * @class Bezier + * @namespace YAHOO.util + * + */ +YAHOO.util.Bezier = new function() +{ + /** + * Get the current position of the animated element based on t. + * Each point is an array of "x" and "y" values (0 = x, 1 = y) + * At least 2 points are required (start and end). + * First point is start. Last point is end. + * Additional control points are optional. + * @method getPosition + * @param {Array} points An array containing Bezier points + * @param {Number} t A number between 0 and 1 which is the basis for determining current position + * @return {Array} An array containing int x and y member data + */ + this.getPosition = function(points, t) + { + var n = points.length; + var tmp = []; + + for (var i = 0; i < n; ++i){ + tmp[i] = [points[i][0], points[i][1]]; // save input + } + + for (var j = 1; j < n; ++j) { + for (i = 0; i < n - j; ++i) { + tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; + tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; + } + } + + return [ tmp[0][0], tmp[0][1] ]; + + }; +}; +/** + * Anim subclass for color transitions. + *

Usage: var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut); Color values can be specified with either 112233, #112233, + * [255,255,255], or rgb(255,255,255)

+ * @class ColorAnim + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @constructor + * @extends YAHOO.util.Anim + * @param {HTMLElement | String} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ +(function() { + YAHOO.util.ColorAnim = function(el, attributes, duration, method) { + YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); + }; + + YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.ColorAnim.superclass; + var proto = Y.ColorAnim.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("ColorAnim " + id); + }; + + proto.patterns.color = /color$/i; + proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; + proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; + proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; + proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari + + /** + * Attempts to parse the given string and return a 3-tuple. + * @method parseColor + * @param {String} s The string to parse. + * @return {Array} The 3-tuple of rgb values. + */ + proto.parseColor = function(s) { + if (s.length == 3) { return s; } + + var c = this.patterns.hex.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; + } + + c = this.patterns.rgb.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; + } + + c = this.patterns.hex3.exec(s); + if (c && c.length == 4) { + return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; + } + + return null; + }; + + proto.getAttribute = function(attr) { + var el = this.getEl(); + if ( this.patterns.color.test(attr) ) { + var val = YAHOO.util.Dom.getStyle(el, attr); + + if (this.patterns.transparent.test(val)) { // bgcolor default + var parent = el.parentNode; // try and get from an ancestor + val = Y.Dom.getStyle(parent, attr); + + while (parent && this.patterns.transparent.test(val)) { + parent = parent.parentNode; + val = Y.Dom.getStyle(parent, attr); + if (parent.tagName.toUpperCase() == 'HTML') { + val = '#fff'; + } + } + } + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val; + + if ( this.patterns.color.test(attr) ) { + val = []; + for (var i = 0, len = start.length; i < len; ++i) { + val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); + } + + val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; + } + else { + val = superclass.doMethod.call(this, attr, start, end); + } + + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + superclass.setRuntimeAttribute.call(this, attr); + + if ( this.patterns.color.test(attr) ) { + var attributes = this.attributes; + var start = this.parseColor(this.runtimeAttributes[attr].start); + var end = this.parseColor(this.runtimeAttributes[attr].end); + // fix colors if going "by" + if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { + end = this.parseColor(attributes[attr].by); + + for (var i = 0, len = start.length; i < len; ++i) { + end[i] = start[i] + end[i]; + } + } + + this.runtimeAttributes[attr].start = start; + this.runtimeAttributes[attr].end = end; + } + }; +})();/* +TERMS OF USE - EASING EQUATIONS +Open source under the BSD License. +Copyright 2001 Robert Penner All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Singleton that determines how an animation proceeds from start to end. + * @class Easing + * @namespace YAHOO.util +*/ + +YAHOO.util.Easing = { + + /** + * Uniform speed between points. + * @method easeNone + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeNone: function (t, b, c, d) { + return c*t/d + b; + }, + + /** + * Begins slowly and accelerates towards end. (quadratic) + * @method easeIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeIn: function (t, b, c, d) { + return c*(t/=d)*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quadratic) + * @method easeOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOut: function (t, b, c, d) { + return -c *(t/=d)*(t-2) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quadratic) + * @method easeBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBoth: function (t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t + b; + return -c/2 * ((--t)*(t-2) - 1) + b; + }, + + /** + * Begins slowly and accelerates towards end. (quartic) + * @method easeInStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeInStrong: function (t, b, c, d) { + return c*(t/=d)*t*t*t + b; + }, + + /** + * Begins quickly and decelerates towards end. (quartic) + * @method easeOutStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeOutStrong: function (t, b, c, d) { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + }, + + /** + * Begins slowly and decelerates towards end. (quartic) + * @method easeBothStrong + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + easeBothStrong: function (t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t*t + b; + return -c/2 * ((t-=2)*t*t*t - 2) + b; + }, + + /** + * Snap in elastic effect. + * @method elasticIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + + elasticIn: function (t, b, c, d, a, p) { + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (!a || a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + }, + + /** + * Snap out elastic effect. + * @method elasticOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticOut: function (t, b, c, d, a, p) { + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (!a || a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; + }, + + /** + * Snap both elastic effect. + * @method elasticBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} p Period (optional) + * @return {Number} The computed value for the current animation frame + */ + elasticBoth: function (t, b, c, d, a, p) { + if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); + if (!a || a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + }, + + /** + * Backtracks slightly, then reverses direction and moves to end. + * @method backIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backIn: function (t, b, c, d, s) { + if (typeof s == 'undefined') s = 1.70158; + return c*(t/=d)*t*((s+1)*t - s) + b; + }, + + /** + * Overshoots end, then reverses and comes back to end. + * @method backOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backOut: function (t, b, c, d, s) { + if (typeof s == 'undefined') s = 1.70158; + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + }, + + /** + * Backtracks slightly, then reverses direction, overshoots end, + * then reverses and comes back to end. + * @method backBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @param {Number} s Overshoot (optional) + * @return {Number} The computed value for the current animation frame + */ + backBoth: function (t, b, c, d, s) { + if (typeof s == 'undefined') s = 1.70158; + if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + }, + + /** + * Bounce off of start. + * @method bounceIn + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceIn: function (t, b, c, d) { + return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; + }, + + /** + * Bounces off end. + * @method bounceOut + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceOut: function (t, b, c, d) { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } else { + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + } + }, + + /** + * Bounces off start and end. + * @method bounceBoth + * @param {Number} t Time value used to compute current value + * @param {Number} b Starting value + * @param {Number} c Delta between start and end values + * @param {Number} d Total length of animation + * @return {Number} The computed value for the current animation frame + */ + bounceBoth: function (t, b, c, d) { + if (t < d/2) return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; + return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; + } +}; + +/** + * Anim subclass for moving elements along a path defined by the "points" + * member of "attributes". All "points" are arrays with x, y coordinates. + *

Usage: var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Motion + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @constructor + * @extends YAHOO.util.Anim + * @param {String | HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ +(function() { + YAHOO.util.Motion = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Motion.superclass; + var proto = Y.Motion.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Motion " + id); + }; + + proto.patterns.points = /^points$/i; + + proto.setAttribute = function(attr, val, unit) { + if ( this.patterns.points.test(attr) ) { + unit = unit || 'px'; + superclass.setAttribute.call(this, 'left', val[0], unit); + superclass.setAttribute.call(this, 'top', val[1], unit); + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; + + proto.getAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var val = [ + superclass.getAttribute.call(this, 'left'), + superclass.getAttribute.call(this, 'top') + ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if ( this.patterns.points.test(attr) ) { + var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; + val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.setRuntimeAttribute = function(attr) { + if ( this.patterns.points.test(attr) ) { + var el = this.getEl(); + var attributes = this.attributes; + var start; + var control = attributes['points']['control'] || []; + var end; + var i, len; + + if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points + control = [control]; + } else { // break reference to attributes.points.control + var tmp = []; + for (i = 0, len = control.length; i< len; ++i) { + tmp[i] = control[i]; + } + control = tmp; + } + + if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative + Y.Dom.setStyle(el, 'position', 'relative'); + } + + if ( isset(attributes['points']['from']) ) { + Y.Dom.setXY(el, attributes['points']['from']); // set position to from point + } + else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position + + start = this.getAttribute('points'); // get actual top & left + + // TO beats BY, per SMIL 2.1 spec + if ( isset(attributes['points']['to']) ) { + end = translateValues.call(this, attributes['points']['to'], start); + + var pageXY = Y.Dom.getXY(this.getEl()); + for (i = 0, len = control.length; i < len; ++i) { + control[i] = translateValues.call(this, control[i], start); + } + + + } else if ( isset(attributes['points']['by']) ) { + end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; + + for (i = 0, len = control.length; i < len; ++i) { + control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; + } + } + + this.runtimeAttributes[attr] = [start]; + + if (control.length > 0) { + this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); + } + + this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; + } + else { + superclass.setRuntimeAttribute.call(this, attr); + } + }; + + var translateValues = function(val, start) { + var pageXY = Y.Dom.getXY(this.getEl()); + val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; + + return val; + }; + + var isset = function(prop) { + return (typeof prop !== 'undefined'); + }; +})(); +/** + * Anim subclass for scrolling elements to a position defined by the "scroll" + * member of "attributes". All "scroll" members are arrays with x, y scroll positions. + *

Usage: var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);

+ * @class Scroll + * @namespace YAHOO.util + * @requires YAHOO.util.Anim + * @requires YAHOO.util.AnimMgr + * @requires YAHOO.util.Easing + * @requires YAHOO.util.Bezier + * @requires YAHOO.util.Dom + * @requires YAHOO.util.Event + * @requires YAHOO.util.CustomEvent + * @extends YAHOO.util.Anim + * @constructor + * @param {String or HTMLElement} el Reference to the element that will be animated + * @param {Object} attributes The attribute(s) to be animated. + * Each attribute is an object with at minimum a "to" or "by" member defined. + * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). + * All attribute names use camelCase. + * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based + * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) + */ +(function() { + YAHOO.util.Scroll = function(el, attributes, duration, method) { + if (el) { // dont break existing subclasses not using YAHOO.extend + YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); + + // shorthand + var Y = YAHOO.util; + var superclass = Y.Scroll.superclass; + var proto = Y.Scroll.prototype; + + proto.toString = function() { + var el = this.getEl(); + var id = el.id || el.tagName; + return ("Scroll " + id); + }; + + proto.doMethod = function(attr, start, end) { + var val = null; + + if (attr == 'scroll') { + val = [ + this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), + this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) + ]; + + } else { + val = superclass.doMethod.call(this, attr, start, end); + } + return val; + }; + + proto.getAttribute = function(attr) { + var val = null; + var el = this.getEl(); + + if (attr == 'scroll') { + val = [ el.scrollLeft, el.scrollTop ]; + } else { + val = superclass.getAttribute.call(this, attr); + } + + return val; + }; + + proto.setAttribute = function(attr, val, unit) { + var el = this.getEl(); + + if (attr == 'scroll') { + el.scrollLeft = val[0]; + el.scrollTop = val[1]; + } else { + superclass.setAttribute.call(this, attr, val, unit); + } + }; +})(); diff --git a/thirdpartyjs/yui/autocomplete/README b/thirdpartyjs/yui/autocomplete/README index 4470be2..88671a7 100644 --- a/thirdpartyjs/yui/autocomplete/README +++ b/thirdpartyjs/yui/autocomplete/README @@ -1,59 +1,59 @@ -AutoComplete Release Notes - -*** version 0.12.0 *** - -* The following constants must be defined as static class properties and are no longer -available as instance properties: - -YAHOO.widget.DataSource.ERROR_DATANULL -YAHOO.widget.DataSource.ERROR_DATAPARSE -YAHOO.widget.DS_XHR.TYPE_JSON -YAHOO.widget.DS_XHR.TYPE_XML -YAHOO.widget.DS_XHR.TYPE_FLAT -YAHOO.widget.DS_XHR.ERROR_DATAXHR - -* The property minQueryLength now supports zero and negative number values for -DS_JSFunction and DS_XHR objects, to enable null or empty string queries and to disable -AutoComplete functionality altogether, respectively. - -* Enabling the alwaysShowContainer feature will no longer send containerExpandEvent or -containerCollapseEvent. - - - -**** version 0.11.3 *** - -* The iFrameSrc property has been deprecated. Implementers no longer need to -specify an https URL to avoid IE security warnings when working with sites over -SSL. - - - -*** version 0.11.0 *** - -* The method getListIds() has been deprecated for getListItems(), which returns -an array of DOM references. - -* All classnames have been prefixed with "yui-ac-". - -* Container elements should no longer have CSS property "display" set to "none". - -* The useIFrame property can now be set after instantiation. - -* On some browsers, the unmatchedItemSelectEvent may not be fired properly when -delimiter characters are defined. - -* On some browsers, defining delimiter characters while enabling forceSelection -may result in unexpected behavior. - - - -*** version 0.10.0 *** - -* Initial release - -* In order to enable the useIFrame property, it should be set in the -constructor. - -* On some browsers, defining delimiter characters while enabling forceSelection -may result in unexpected behavior. +AutoComplete Release Notes + +*** version 0.12.0 *** + +* The following constants must be defined as static class properties and are no longer +available as instance properties: + +YAHOO.widget.DataSource.ERROR_DATANULL +YAHOO.widget.DataSource.ERROR_DATAPARSE +YAHOO.widget.DS_XHR.TYPE_JSON +YAHOO.widget.DS_XHR.TYPE_XML +YAHOO.widget.DS_XHR.TYPE_FLAT +YAHOO.widget.DS_XHR.ERROR_DATAXHR + +* The property minQueryLength now supports zero and negative number values for +DS_JSFunction and DS_XHR objects, to enable null or empty string queries and to disable +AutoComplete functionality altogether, respectively. + +* Enabling the alwaysShowContainer feature will no longer send containerExpandEvent or +containerCollapseEvent. + + + +**** version 0.11.3 *** + +* The iFrameSrc property has been deprecated. Implementers no longer need to +specify an https URL to avoid IE security warnings when working with sites over +SSL. + + + +*** version 0.11.0 *** + +* The method getListIds() has been deprecated for getListItems(), which returns +an array of DOM references. + +* All classnames have been prefixed with "yui-ac-". + +* Container elements should no longer have CSS property "display" set to "none". + +* The useIFrame property can now be set after instantiation. + +* On some browsers, the unmatchedItemSelectEvent may not be fired properly when +delimiter characters are defined. + +* On some browsers, defining delimiter characters while enabling forceSelection +may result in unexpected behavior. + + + +*** version 0.10.0 *** + +* Initial release + +* In order to enable the useIFrame property, it should be set in the +constructor. + +* On some browsers, defining delimiter characters while enabling forceSelection +may result in unexpected behavior. diff --git a/thirdpartyjs/yui/calendar/README b/thirdpartyjs/yui/calendar/README index de02c14..d40d6ac 100644 --- a/thirdpartyjs/yui/calendar/README +++ b/thirdpartyjs/yui/calendar/README @@ -1,107 +1,107 @@ -Calendar Release Notes - -*** version 0.12 *** - - - New documentation format implemented - - Calendar2up and Calendar_Core are now deprecated. Now, Calendar alone - represents the single Calendar instance, and CalendarGroup represents an - n-up instance, defaulting to 2up - - Added semantic style classes to Calendar elements to allow for custom - styling solely using CSS. - - Remapped all configuration properties to use the Config object - (familiar to those who use the Container collection of controls). - Property names are the same as their previous counterparts, but wrapped - into Calendar.cfg, allowing for runtime reconfiguration of most - properties. - - Added "title" property for setting the Calendar title - - Added "close" property for enabling and disabling the close icon - - Added "iframe" property for enabling an iframe shim in Internet - Explorer 6 and below to fix the select bleed-through bug - - pageDate moved to property: "pagedate" - - selectedDates moved to property: "selected" - - minDate moved to property : "mindate", which accepts a JavaScript Date - object like its predecessor, but also supports string dates - - maxDate moved to property : "maxdate", which accepts a JavaScript Date - object like its predecessor, but also supports string dates - - Moved style declarations to initStyles function - - Optimized event handling in - doSelectCell/doCellMouseOver/doCellMouseOut by only attaching the - listener to the outer Calendar container, and only reacting to events on - cells with the "selectable" CSS class. - - Added domEventMap field for applying DOM event listeners to cells - containing specific class and tag combinations. - - Moved all cell DOM event attachment to applyListeners function - - Added getDateByCellId / getDateFieldsByCellId helper functions - - Corrected DateMath.getWeekNumber to comply with ISO week number - handling - - Separated renderCellDefault style portions into styleCellDefault - function for easy extension - - Deprecated onBeforeSelect. Created beforeSelectEvent which - automatically subscribes to its deprecated predecessor. - - Deprecated onSelect. Created selectEvent, which automatically - subscribes to its deprecated predecessor. - - Deprecated onBeforeDeselect. Created beforeSelectEvent which - automatically subscribes to its deprecated predecessor. - - Deprecated onDeselect. Created beforeDeselectEvent, which - automatically subscribes to its deprecated predecessor. - - Deprecated onChangePage. Created changePageEvent, which automatically - subscribes to its deprecated predecessor. - - Deprecated onRender. Created renderEvent, which automatically - subscribes to its deprecated predecessor. - - Deprecated onReset. Created resetEvent, which automatically subscribes - to its deprecated predecessor. - - Deprecated onClear. Created clearEvent, which automatically subscribes - to its deprecated predecessor. - - Corrected setMonth documentation to refer to 0-11 indexed months. - - Added show and hide methods to Calendar for setting the Calendar's - display property. - - Optimized internal render classes to use innerHTML and string buffers - - Removed wireCustomEvents function - - Removed wireDefaultEvents function - - Removed doNextMonth / doPreviousMonth - - Removed all buildShell (header, body, footer) functions, since the - Calendar shell is now built dynamically on each render - - Wired all CalendarGroup events and configuration properties to be - properly delegated to Calendar - - Augmented CalendarGroup with all built-in renderers, label functions, - hide, show, and initStyles, creating API transparency between Calendar - and CalendarGroup. - - Made all tagName, createElement, and entity references XHTML compliant - - Fixed Daylight Saving Time bug for Brazilian time zone - -*** version 0.11.3 *** - - - Calendar_Core: Added arguments for selected/deselected dates to - onSelect/onDeselect - - CalendarGroup: Fixed bug where selected dates passed to constructor - were not represented in selectedDates - - Calendar2up: Now displays correctly in Opera 9 - -*** version 0.11.0 *** - - - DateMath: DateMath.add now properly adds weeks - - DateMath: between() function added - - DateMath: getWeekNumber() fixed to take starting day of week into - account - - All references to Calendar's built in CSS class handlers are removed, - replaced with calls to Dom utility (addClass, removeClass) - - Several CSS class constants now have clearer names - - All CSS classes are now properly namespaced to avoid CSS conflicts - - Fixed table:hover bug in CSS - - Calendar no longer requires the container ID and variable name to - match in order for month navigation to function properly - - Calendar month navigation arrows are now represented as background - images - -*** version 0.10.0 *** - - - Major performance improvements from attaching DOM events to associated - table cells only once, when the Calendar shell is built - - DOM events for mouseover/mouseout are now fired for all browsers (not - just Internet Explorer) - - Reset functionality bug fixed for 2-up Calendar view - -*** version 0.9.0 *** - -* Initial release - +Calendar Release Notes + +*** version 0.12 *** + + - New documentation format implemented + - Calendar2up and Calendar_Core are now deprecated. Now, Calendar alone + represents the single Calendar instance, and CalendarGroup represents an + n-up instance, defaulting to 2up + - Added semantic style classes to Calendar elements to allow for custom + styling solely using CSS. + - Remapped all configuration properties to use the Config object + (familiar to those who use the Container collection of controls). + Property names are the same as their previous counterparts, but wrapped + into Calendar.cfg, allowing for runtime reconfiguration of most + properties. + - Added "title" property for setting the Calendar title + - Added "close" property for enabling and disabling the close icon + - Added "iframe" property for enabling an iframe shim in Internet + Explorer 6 and below to fix the select bleed-through bug + - pageDate moved to property: "pagedate" + - selectedDates moved to property: "selected" + - minDate moved to property : "mindate", which accepts a JavaScript Date + object like its predecessor, but also supports string dates + - maxDate moved to property : "maxdate", which accepts a JavaScript Date + object like its predecessor, but also supports string dates + - Moved style declarations to initStyles function + - Optimized event handling in + doSelectCell/doCellMouseOver/doCellMouseOut by only attaching the + listener to the outer Calendar container, and only reacting to events on + cells with the "selectable" CSS class. + - Added domEventMap field for applying DOM event listeners to cells + containing specific class and tag combinations. + - Moved all cell DOM event attachment to applyListeners function + - Added getDateByCellId / getDateFieldsByCellId helper functions + - Corrected DateMath.getWeekNumber to comply with ISO week number + handling + - Separated renderCellDefault style portions into styleCellDefault + function for easy extension + - Deprecated onBeforeSelect. Created beforeSelectEvent which + automatically subscribes to its deprecated predecessor. + - Deprecated onSelect. Created selectEvent, which automatically + subscribes to its deprecated predecessor. + - Deprecated onBeforeDeselect. Created beforeSelectEvent which + automatically subscribes to its deprecated predecessor. + - Deprecated onDeselect. Created beforeDeselectEvent, which + automatically subscribes to its deprecated predecessor. + - Deprecated onChangePage. Created changePageEvent, which automatically + subscribes to its deprecated predecessor. + - Deprecated onRender. Created renderEvent, which automatically + subscribes to its deprecated predecessor. + - Deprecated onReset. Created resetEvent, which automatically subscribes + to its deprecated predecessor. + - Deprecated onClear. Created clearEvent, which automatically subscribes + to its deprecated predecessor. + - Corrected setMonth documentation to refer to 0-11 indexed months. + - Added show and hide methods to Calendar for setting the Calendar's + display property. + - Optimized internal render classes to use innerHTML and string buffers + - Removed wireCustomEvents function + - Removed wireDefaultEvents function + - Removed doNextMonth / doPreviousMonth + - Removed all buildShell (header, body, footer) functions, since the + Calendar shell is now built dynamically on each render + - Wired all CalendarGroup events and configuration properties to be + properly delegated to Calendar + - Augmented CalendarGroup with all built-in renderers, label functions, + hide, show, and initStyles, creating API transparency between Calendar + and CalendarGroup. + - Made all tagName, createElement, and entity references XHTML compliant + - Fixed Daylight Saving Time bug for Brazilian time zone + +*** version 0.11.3 *** + + - Calendar_Core: Added arguments for selected/deselected dates to + onSelect/onDeselect + - CalendarGroup: Fixed bug where selected dates passed to constructor + were not represented in selectedDates + - Calendar2up: Now displays correctly in Opera 9 + +*** version 0.11.0 *** + + - DateMath: DateMath.add now properly adds weeks + - DateMath: between() function added + - DateMath: getWeekNumber() fixed to take starting day of week into + account + - All references to Calendar's built in CSS class handlers are removed, + replaced with calls to Dom utility (addClass, removeClass) + - Several CSS class constants now have clearer names + - All CSS classes are now properly namespaced to avoid CSS conflicts + - Fixed table:hover bug in CSS + - Calendar no longer requires the container ID and variable name to + match in order for month navigation to function properly + - Calendar month navigation arrows are now represented as background + images + +*** version 0.10.0 *** + + - Major performance improvements from attaching DOM events to associated + table cells only once, when the Calendar shell is built + - DOM events for mouseover/mouseout are now fired for all browsers (not + just Internet Explorer) + - Reset functionality bug fixed for 2-up Calendar view + +*** version 0.9.0 *** + +* Initial release + diff --git a/thirdpartyjs/yui/calendar/assets/calendar.css b/thirdpartyjs/yui/calendar/assets/calendar.css index 0723f94..b97a705 100644 --- a/thirdpartyjs/yui/calendar/assets/calendar.css +++ b/thirdpartyjs/yui/calendar/assets/calendar.css @@ -1,191 +1,191 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -Version 0.12 -*/ - -.yui-calcontainer { - position:relative; - padding:5px; - background-color:#F7F9FB; - border:1px solid #7B9EBD; - float:left; - overflow:hidden; -} - -.yui-calcontainer iframe { - position:absolute; - border:none; - margin:0;padding:0; - left:-1px; - top:-1px; - z-index:0; - width:50em; - height:50em; -} - -.yui-calcontainer.multi { - padding:0; -} - -.yui-calcontainer.multi .groupcal { - padding:5px; - background-color:transparent; - z-index:1; - float:left; - position:relative; - border:none; -} - -.yui-calcontainer .title { - font:100% sans-serif; - color:#000; - font-weight:bold; - margin-bottom:5px; - height:25px; - position:absolute; - top:3px;left:5px; - z-index:1; -} - -.yui-calcontainer .close-icon { - position:absolute; - right:3px; - top:3px; - border:none; - z-index:1; -} - -/* Calendar element styles */ - -.yui-calendar { - font:100% sans-serif; - text-align:center; - border-spacing:0; - border-collapse:separate; - position:relative; -} - -.yui-calcontainer.withtitle { - padding-top:1.5em; -} - -.yui-calendar .calnavleft { - position:absolute; - background-repeat:no-repeat; - cursor:pointer; - top:2px; - bottom:0; - width:9px; - height:12px; - left:2px; - z-index:1; -} - -.yui-calendar .calnavright { - position:absolute; - background-repeat:no-repeat; - cursor:pointer; - top:2px; - bottom:0; - width:9px; - height:12px; - right:2px; - z-index:1; -} - -.yui-calendar td.calcell { - padding:.1em .2em; - border:1px solid #E0E0E0; - text-align:center; -} - -.yui-calendar td.calcell a { - color:#003DB8; - text-decoration:none; -} - -.yui-calendar td.calcell.today { - border:1px solid #000; -} - -.yui-calendar td.calcell.oom { - cursor:default; - color:#999; - background-color:#EEE; - border:1px solid #E0E0E0; -} - -.yui-calendar td.calcell.selected { - color:#003DB8; - background-color:#FFF19F; - border:1px solid #FF9900; -} - -.yui-calendar td.calcell.calcellhover { - cursor:pointer; - color:#FFF; - background-color:#FF9900; - border:1px solid #FF9900; -} - -.yui-calendar td.calcell.calcellhover a { - color:#FFF; -} - -.yui-calendar td.calcell.restricted { - text-decoration:line-through; -} - -.yui-calendar td.calcell.previous { - color:#CCC; -} - -.yui-calendar td.calcell.highlight1 { background-color:#CCFF99; } -.yui-calendar td.calcell.highlight2 { background-color:#99CCFF; } -.yui-calendar td.calcell.highlight3 { background-color:#FFCCCC; } -.yui-calendar td.calcell.highlight4 { background-color:#CCFF99; } - -.yui-calendar .calhead { - border:1px solid #E0E0E0; - vertical-align:middle; - background-color:#FFF; -} - -.yui-calendar .calheader { - position:relative; - width:100%; - text-align:center; -} - -.yui-calendar .calheader img { - border:none; -} - -.yui-calendar .calweekdaycell { - color:#666; - font-weight:normal; - text-align:center; - width:1.5em; -} - -.yui-calendar .calfoot { - background-color:#EEE; -} - -.yui-calendar .calrowhead, .yui-calendar .calrowfoot { - color:#666; - font-size:9px; - font-style:italic; - font-weight:normal; - width:15px; -} - -.yui-calendar .calrowhead { - border-right-width:2px; -} - -/*Specific changes for calendar running under fonts/reset */ -.yui-calendar a:hover {background:inherit;} -p#clear {clear:left; padding-top:10px;} +/* +Copyright (c) 2006, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +Version 0.12 +*/ + +.yui-calcontainer { + position:relative; + padding:5px; + background-color:#F7F9FB; + border:1px solid #7B9EBD; + float:left; + overflow:hidden; +} + +.yui-calcontainer iframe { + position:absolute; + border:none; + margin:0;padding:0; + left:-1px; + top:-1px; + z-index:0; + width:50em; + height:50em; +} + +.yui-calcontainer.multi { + padding:0; +} + +.yui-calcontainer.multi .groupcal { + padding:5px; + background-color:transparent; + z-index:1; + float:left; + position:relative; + border:none; +} + +.yui-calcontainer .title { + font:100% sans-serif; + color:#000; + font-weight:bold; + margin-bottom:5px; + height:25px; + position:absolute; + top:3px;left:5px; + z-index:1; +} + +.yui-calcontainer .close-icon { + position:absolute; + right:3px; + top:3px; + border:none; + z-index:1; +} + +/* Calendar element styles */ + +.yui-calendar { + font:100% sans-serif; + text-align:center; + border-spacing:0; + border-collapse:separate; + position:relative; +} + +.yui-calcontainer.withtitle { + padding-top:1.5em; +} + +.yui-calendar .calnavleft { + position:absolute; + background-repeat:no-repeat; + cursor:pointer; + top:2px; + bottom:0; + width:9px; + height:12px; + left:2px; + z-index:1; +} + +.yui-calendar .calnavright { + position:absolute; + background-repeat:no-repeat; + cursor:pointer; + top:2px; + bottom:0; + width:9px; + height:12px; + right:2px; + z-index:1; +} + +.yui-calendar td.calcell { + padding:.1em .2em; + border:1px solid #E0E0E0; + text-align:center; +} + +.yui-calendar td.calcell a { + color:#003DB8; + text-decoration:none; +} + +.yui-calendar td.calcell.today { + border:1px solid #000; +} + +.yui-calendar td.calcell.oom { + cursor:default; + color:#999; + background-color:#EEE; + border:1px solid #E0E0E0; +} + +.yui-calendar td.calcell.selected { + color:#003DB8; + background-color:#FFF19F; + border:1px solid #FF9900; +} + +.yui-calendar td.calcell.calcellhover { + cursor:pointer; + color:#FFF; + background-color:#FF9900; + border:1px solid #FF9900; +} + +.yui-calendar td.calcell.calcellhover a { + color:#FFF; +} + +.yui-calendar td.calcell.restricted { + text-decoration:line-through; +} + +.yui-calendar td.calcell.previous { + color:#CCC; +} + +.yui-calendar td.calcell.highlight1 { background-color:#CCFF99; } +.yui-calendar td.calcell.highlight2 { background-color:#99CCFF; } +.yui-calendar td.calcell.highlight3 { background-color:#FFCCCC; } +.yui-calendar td.calcell.highlight4 { background-color:#CCFF99; } + +.yui-calendar .calhead { + border:1px solid #E0E0E0; + vertical-align:middle; + background-color:#FFF; +} + +.yui-calendar .calheader { + position:relative; + width:100%; + text-align:center; +} + +.yui-calendar .calheader img { + border:none; +} + +.yui-calendar .calweekdaycell { + color:#666; + font-weight:normal; + text-align:center; + width:1.5em; +} + +.yui-calendar .calfoot { + background-color:#EEE; +} + +.yui-calendar .calrowhead, .yui-calendar .calrowfoot { + color:#666; + font-size:9px; + font-style:italic; + font-weight:normal; + width:15px; +} + +.yui-calendar .calrowhead { + border-right-width:2px; +} + +/*Specific changes for calendar running under fonts/reset */ +.yui-calendar a:hover {background:inherit;} +p#clear {clear:left; padding-top:10px;} diff --git a/thirdpartyjs/yui/calendar/calendar-debug.js b/thirdpartyjs/yui/calendar/calendar-debug.js index 3396980..8908d0e 100644 --- a/thirdpartyjs/yui/calendar/calendar-debug.js +++ b/thirdpartyjs/yui/calendar/calendar-debug.js @@ -1,4277 +1,4277 @@ -/* -Copyright (c) 2006, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version 0.12.0 -*/ - -/** -* Config is a utility used within an Object to allow the implementer to maintain a list of local configuration properties and listen for changes to those properties dynamically using CustomEvent. The initial values are also maintained so that the configuration can be reset at any given point to its initial state. -* @class YAHOO.util.Config -* @constructor -* @param {Object} owner The owner Object to which this Config Object belongs -*/ -YAHOO.util.Config = function(owner) { - if (owner) { - this.init(owner); - } else { - YAHOO.log("No owner specified for Config object", "error"); - } -}; - -YAHOO.util.Config.prototype = { - - /** - * Object reference to the owner of this Config Object - * @property owner - * @type Object - */ - owner : null, - - /** - * Boolean flag that specifies whether a queue is currently being executed - * @property queueInProgress - * @type Boolean - */ - queueInProgress : false, - - - /** - * Validates that the value passed in is a Boolean. - * @method checkBoolean - * @param {Object} val The value to validate - * @return {Boolean} true, if the value is valid - */ - checkBoolean: function(val) { - if (typeof val == 'boolean') { - return true; - } else { - return false; - } - }, - - /** - * Validates that the value passed in is a number. - * @method checkNumber - * @param {Object} val The value to validate - * @return {Boolean} true, if the value is valid - */ - checkNumber: function(val) { - if (isNaN(val)) { - return false; - } else { - return true; - } - } -}; - - -/** -* Initializes the configuration Object and all of its local members. -* @method init -* @param {Object} owner The owner Object to which this Config Object belongs -*/ -YAHOO.util.Config.prototype.init = function(owner) { - - this.owner = owner; - - /** - * Object reference to the owner of this Config Object - * @event configChangedEvent - */ - this.configChangedEvent = new YAHOO.util.CustomEvent("configChanged"); - this.queueInProgress = false; - - /* Private Members */ - - /** - * Maintains the local collection of configuration property objects and their specified values - * @property config - * @private - * @type Object - */ - var config = {}; - - /** - * Maintains the local collection of configuration property objects as they were initially applied. - * This object is used when resetting a property. - * @property initialConfig - * @private - * @type Object - */ - var initialConfig = {}; - - /** - * Maintains the local, normalized CustomEvent queue - * @property eventQueue - * @private - * @type Object - */ - var eventQueue = []; - - /** - * Fires a configuration property event using the specified value. - * @method fireEvent - * @private - * @param {String} key The configuration property's name - * @param {value} Object The value of the correct type for the property - */ - var fireEvent = function( key, value ) { - YAHOO.log("Firing Config event: " + key + "=" + value, "info"); - - key = key.toLowerCase(); - - var property = config[key]; - - if (typeof property != 'undefined' && property.event) { - property.event.fire(value); - } - }; - /* End Private Members */ - - /** - * Adds a property to the Config Object's private config hash. - * @method addProperty - * @param {String} key The configuration property's name - * @param {Object} propertyObject The Object containing all of this property's arguments - */ - this.addProperty = function( key, propertyObject ) { - key = key.toLowerCase(); - - YAHOO.log("Added property: " + key, "info"); - - config[key] = propertyObject; - - propertyObject.event = new YAHOO.util.CustomEvent(key); - propertyObject.key = key; - - if (propertyObject.handler) { - propertyObject.event.subscribe(propertyObject.handler, this.owner, true); - } - - this.setProperty(key, propertyObject.value, true); - - if (! propertyObject.suppressEvent) { - this.queueProperty(key, propertyObject.value); - } - }; - - /** - * Returns a key-value configuration map of the values currently set in the Config Object. - * @method getConfig - * @return {Object} The current config, represented in a key-value map - */ - this.getConfig = function() { - var cfg = {}; - - for (var prop in config) { - var property = config[prop]; - if (typeof property != 'undefined' && property.event) { - cfg[prop] = property.value; - } - } - - return cfg; - }; - - /** - * Returns the value of specified property. - * @method getProperty - * @param {String} key The name of the property - * @return {Object} The value of the specified property - */ - this.getProperty = function(key) { - key = key.toLowerCase(); - - var property = config[key]; - if (typeof property != 'undefined' && property.event) { - return property.value; - } else { - return undefined; - } - }; - - /** - * Resets the specified property's value to its initial value. - * @method resetProperty - * @param {String} key The name of the property - * @return {Boolean} True is the property was reset, false if not - */ - this.resetProperty = function(key) { - key = key.toLowerCase(); - - var property = config[key]; - if (typeof property != 'undefined' && property.event) { - if (initialConfig[key] && initialConfig[key] != 'undefined') { - this.setProperty(key, initialConfig[key]); - } - return true; - } else { - return false; - } - }; - - /** - * Sets the value of a property. If the silent property is passed as true, the property's event will not be fired. - * @method setProperty - * @param {String} key The name of the property - * @param {String} value The value to set the property to - * @param {Boolean} silent Whether the value should be set silently, without firing the property event. - * @return {Boolean} True, if the set was successful, false if it failed. - */ - this.setProperty = function(key, value, silent) { - key = key.toLowerCase(); - - YAHOO.log("setProperty: " + key + "=" + value, "info"); - - if (this.queueInProgress && ! silent) { - this.queueProperty(key,value); // Currently running through a queue... - return true; - } else { - var property = config[key]; - if (typeof property != 'undefined' && property.event) { - if (property.validator && ! property.validator(value)) { // validator - return false; - } else { - property.value = value; - if (! silent) { - fireEvent(key, value); - this.configChangedEvent.fire([key, value]); - } - return true; - } - } else { - return false; - } - } - }; - - /** - * Sets the value of a property and queues its event to execute. If the event is already scheduled to execute, it is - * moved from its current position to the end of the queue. - * @method queueProperty - * @param {String} key The name of the property - * @param {String} value The value to set the property to - * @return {Boolean} true, if the set was successful, false if it failed. - */ - this.queueProperty = function(key, value) { - key = key.toLowerCase(); - - YAHOO.log("queueProperty: " + key + "=" + value, "info"); - - var property = config[key]; - - if (typeof property != 'undefined' && property.event) { - if (typeof value != 'undefined' && property.validator && ! property.validator(value)) { // validator - return false; - } else { - - if (typeof value != 'undefined') { - property.value = value; - } else { - value = property.value; - } - - var foundDuplicate = false; - - for (var i=0;i 11) { - while (newMonth > 11) { - newMonth -= 12; - years += 1; - } - } - - d.setMonth(newMonth); - d.setFullYear(date.getFullYear() + years); - break; - case this.DAY: - d.setDate(date.getDate() + amount); - break; - case this.YEAR: - d.setFullYear(date.getFullYear() + amount); - break; - case this.WEEK: - d.setDate(date.getDate() + (amount * 7)); - break; - } - return d; - }, - - /** - * Subtracts the specified amount of time from the this instance. - * @method subtract - * @param {Date} date The JavaScript Date object to perform subtraction on - * @param {Number} field The this field constant to be used for performing subtraction. - * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. - * @return {Date} The resulting Date object - */ - subtract : function(date, field, amount) { - return this.add(date, field, (amount*-1)); - }, - - /** - * Determines whether a given date is before another date on the calendar. - * @method before - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs before the compared date; false if not. - */ - before : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() < ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is after another date on the calendar. - * @method after - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs after the compared date; false if not. - */ - after : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() > ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is between two other dates on the calendar. - * @method between - * @param {Date} date The date to check for - * @param {Date} dateBegin The start of the range - * @param {Date} dateEnd The end of the range - * @return {Boolean} true if the date occurs between the compared dates; false if not. - */ - between : function(date, dateBegin, dateEnd) { - if (this.after(date, dateBegin) && this.before(date, dateEnd)) { - return true; - } else { - return false; - } - }, - - /** - * Retrieves a JavaScript Date object representing January 1 of any given year. - * @method getJan1 - * @param {Number} calendarYear The calendar year for which to retrieve January 1 - * @return {Date} January 1 of the calendar year specified. - */ - getJan1 : function(calendarYear) { - return new Date(calendarYear,0,1); - }, - - /** - * Calculates the number of days the specified date is from January 1 of the specified calendar year. - * Passing January 1 to this function would return an offset value of zero. - * @method getDayOffset - * @param {Date} date The JavaScript date for which to find the offset - * @param {Number} calendarYear The calendar year to use for determining the offset - * @return {Number} The number of days since January 1 of the given year - */ - getDayOffset : function(date, calendarYear) { - var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. - - // Find the number of days the passed in date is away from the calendar year start - var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); - return dayOffset; - }, - - /** - * Calculates the week number for the given date. This function assumes that week 1 is the - * week in which January 1 appears, regardless of whether the week consists of a full 7 days. - * The calendar year can be specified to help find what a the week number would be for a given - * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or - * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction - * easily. - * @method getWeekNumber - * @param {Date} date The JavaScript date for which to find the week number - * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is - * the calendar year of parameter "date". - * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). - * @return {Number} The week number of the given date. - */ - getWeekNumber : function(date, calendarYear) { - date = this.clearTime(date); - var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); - - var jan1 = new Date(nearestThurs.getFullYear(),0,1); - var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; - - var weekNum = Math.ceil((dayOfYear)/ 7); - return weekNum; - }, - - /** - * Determines if a given week overlaps two different years. - * @method isYearOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different years. - */ - isYearOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Determines if a given week overlaps two different months. - * @method isMonthOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different months. - */ - isMonthOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getMonth() != weekBeginDate.getMonth()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Gets the first day of a month containing a given date. - * @method findMonthStart - * @param {Date} date The JavaScript Date used to calculate the month start - * @return {Date} The JavaScript Date representing the first day of the month - */ - findMonthStart : function(date) { - var start = new Date(date.getFullYear(), date.getMonth(), 1); - return start; - }, - - /** - * Gets the last day of a month containing a given date. - * @method findMonthEnd - * @param {Date} date The JavaScript Date used to calculate the month end - * @return {Date} The JavaScript Date representing the last day of the month - */ - findMonthEnd : function(date) { - var start = this.findMonthStart(date); - var nextMonth = this.add(start, this.MONTH, 1); - var end = this.subtract(nextMonth, this.DAY, 1); - return end; - }, - - /** - * Clears the time fields from a given date, effectively setting the time to midnight. - * @method clearTime - * @param {Date} date The JavaScript Date for which the time fields will be cleared - * @return {Date} The JavaScript Date cleared of all time fields - */ - clearTime : function(date) { - date.setHours(12,0,0,0); - return date; - } -}; - -/** -* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. -* @module Calendar -* @title Calendar Widget -* @namespace YAHOO.widget -* @requires yahoo,dom,event -*/ - -/** -* Calendar is the base class for the Calendar widget. In its most basic -* implementation, it has the ability to render a calendar widget on the page -* that can be manipulated to select a single date, move back and forth between -* months and years. -*

To construct the placeholder for the calendar widget, the code is as -* follows: -*

-* <div id="cal1Container"></div> -* -* Note that the table can be replaced with any kind of element. -*

-* @namespace YAHOO.widget -* @class Calendar -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar = function(id, containerId, config) { - this.init(id, containerId, config); -}; - -/** -* The path to be used for images loaded for the Calendar -* @property YAHOO.widget.Calendar.IMG_ROOT -* @static -* @type String -*/ -YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); - -/** -* Type constant used for renderers to represent an individual date (M/D/Y) -* @property YAHOO.widget.Calendar.DATE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.DATE = "D"; - -/** -* Type constant used for renderers to represent an individual date across any year (M/D) -* @property YAHOO.widget.Calendar.MONTH_DAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH_DAY = "MD"; - -/** -* Type constant used for renderers to represent a weekday -* @property YAHOO.widget.Calendar.WEEKDAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.WEEKDAY = "WD"; - -/** -* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) -* @property YAHOO.widget.Calendar.RANGE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.RANGE = "R"; - -/** -* Type constant used for renderers to represent a month across any year -* @property YAHOO.widget.Calendar.MONTH -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH = "M"; - -/** -* Constant that represents the total number of date cells that are displayed in a given month -* @property YAHOO.widget.Calendar.DISPLAY_DAYS -* @static -* @final -* @type Number -*/ -YAHOO.widget.Calendar.DISPLAY_DAYS = 42; - -/** -* Constant used for halting the execution of the remainder of the render stack -* @property YAHOO.widget.Calendar.STOP_RENDER -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.STOP_RENDER = "S"; - -YAHOO.widget.Calendar.prototype = { - - /** - * The configuration object used to set up the calendars various locale and style options. - * @property Config - * @private - * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. - * @type Object - */ - Config : null, - - /** - * The parent CalendarGroup, only to be set explicitly by the parent group - * @property parent - * @type CalendarGroup - */ - parent : null, - - /** - * The index of this item in the parent group - * @property index - * @type Number - */ - index : -1, - - /** - * The collection of calendar table cells - * @property cells - * @type HTMLTableCellElement[] - */ - cells : null, - - /** - * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. - * @property cellDates - * @type Array[](Number[]) - */ - cellDates : null, - - /** - * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. - * @property id - * @type String - */ - id : null, - - /** - * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. - * @property oDomContainer - * @type HTMLElement - */ - oDomContainer : null, - - /** - * A Date object representing today's date. - * @property today - * @type Date - */ - today : null, - - /** - * The list of render functions, along with required parameters, used to render cells. - * @property renderStack - * @type Array[] - */ - renderStack : null, - - /** - * A copy of the initial render functions created before rendering. - * @property _renderStack - * @private - * @type Array - */ - _renderStack : null, - - /** - * A Date object representing the month/year that the calendar is initially set to - * @property _pageDate - * @private - * @type Date - */ - _pageDate : null, - - /** - * The private list of initially selected dates. - * @property _selectedDates - * @private - * @type Array - */ - _selectedDates : null, - - /** - * A map of DOM event handlers to attach to cells associated with specific CSS class names - * @property domEventMap - * @type Object - */ - domEventMap : null -}; - - - -/** -* Initializes the Calendar widget. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { - this.logger = new YAHOO.widget.LogWriter("Calendar_Core " + id); - - this.initEvents(); - this.today = new Date(); - YAHOO.widget.DateMath.clearTime(this.today); - - this.id = id; - this.oDomContainer = document.getElementById(containerId); - if (! this.oDomContainer) { - this.logger.log("No valid container present.", "error"); - } - - /** - * The Config object used to hold the configuration variables for the Calendar - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the Calendar's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the Calendar's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.initStyles(); - - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); - - this.cellDates = []; - this.cells = []; - this.renderStack = []; - this._renderStack = []; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); -}; - -/** -* Renders the built-in IFRAME shim for the IE6 and below -* @method configIframe -*/ -YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { - var useIframe = args[0]; - - if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { - if (useIframe) { - var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); - - if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { - if (! YAHOO.util.Dom.inDocument(this.iframe)) { - this.iframe = document.createElement("iframe"); - this.iframe.src = "javascript:false;"; - YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); - this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); - } - } - } else { - if (this.iframe) { - if (this.iframe.parentNode) { - this.iframe.parentNode.removeChild(this.iframe); - } - this.iframe = null; - } - } - } -}; - -/** -* Default handler for the "title" property -* @method configTitle -*/ -YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { - var title = args[0]; - var close = this.cfg.getProperty("close"); - - var titleDiv; - - if (title && title !== "") { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); - titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; - titleDiv.innerHTML = title; - this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; - - if (titleDiv) { - YAHOO.util.Event.purgeElement(titleDiv); - this.oDomContainer.removeChild(titleDiv); - } - if (! close) { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Default handler for the "close" property -* @method configClose -*/ -YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { - var close = args[0]; - var title = this.cfg.getProperty("title"); - - var linkClose; - - if (close === true) { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); - linkClose.href = "javascript:void(null);"; - linkClose.className = "link-close"; - YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); - var imgClose = document.createElement("img"); - imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; - imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; - linkClose.appendChild(imgClose); - this.oDomContainer.appendChild(linkClose); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; - - if (linkClose) { - YAHOO.util.Event.purgeElement(linkClose); - this.oDomContainer.removeChild(linkClose); - } - if (! title || title === "") { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Initializes Calendar's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.Calendar.prototype.initEvents = function() { - - /** - * Fired before a selection is made - * @event beforeSelectEvent - */ - this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); - - /** - * Fired when a selection is made - * @event selectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.selectEvent = new YAHOO.util.CustomEvent("select"); - - /** - * Fired before a selection is made - * @event beforeDeselectEvent - */ - this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); - - /** - * Fired when a selection is made - * @event deselectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); - - /** - * Fired when the Calendar page is changed - * @event changePageEvent - */ - this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); - - /** - * Fired before the Calendar is rendered - * @event beforeRenderEvent - */ - this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); - - /** - * Fired when the Calendar is rendered - * @event renderEvent - */ - this.renderEvent = new YAHOO.util.CustomEvent("render"); - - /** - * Fired when the Calendar is reset - * @event resetEvent - */ - this.resetEvent = new YAHOO.util.CustomEvent("reset"); - - /** - * Fired when the Calendar is cleared - * @event clearEvent - */ - this.clearEvent = new YAHOO.util.CustomEvent("clear"); - - this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); - this.selectEvent.subscribe(this.onSelect, this, true); - this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); - this.deselectEvent.subscribe(this.onDeselect, this, true); - this.changePageEvent.subscribe(this.onChangePage, this, true); - this.renderEvent.subscribe(this.onRender, this, true); - this.resetEvent.subscribe(this.onReset, this, true); - this.clearEvent.subscribe(this.onClear, this, true); -}; - - -/** -* The default event function that is attached to a date link within a calendar cell -* when the calendar is rendered. -* @method doSelectCell -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { - var target = YAHOO.util.Event.getTarget(e); - - var cell,index,d,date; - - while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - cell = target; - - if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { - index = cell.id.split("cell")[1]; - d = cal.cellDates[index]; - date = new Date(d[0],d[1]-1,d[2]); - - cal.logger.log("Selecting cell " + index + " via click", "info"); - - if (cal.Options.MULTI_SELECT) { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - - var cellDate = cal.cellDates[index]; - var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); - - if (cellDateIndex > -1) { - cal.deselectCell(index); - } else { - cal.selectCell(index); - } - - } else { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - cal.selectCell(index); - } - } -}; - -/** -* The event that is executed when the user hovers over a cell -* @method doCellMouseOver -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -/** -* The event that is executed when the user moves the mouse out of a cell -* @method doCellMouseOut -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -YAHOO.widget.Calendar.prototype.setupConfig = function() { - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); - - /** - * The title to display above the Calendar's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this Calendar - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); - - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); - - /** - * Refreshes the locale values used to build the Calendar. - * @method refreshLocale - * @private - */ - var refreshLocale = function() { - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - }; - - this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); -}; - -/** -* The default handler for the "pagedate" property -* @method configPageDate -*/ -YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { - var val = args[0]; - var month, year, aMonthYear; - - if (val) { - if (val instanceof Date) { - val = YAHOO.widget.DateMath.findMonthStart(val); - this.cfg.setProperty("pagedate", val, true); - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } - return; - } else { - aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); - month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; - year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); - } - } else { - month = this.today.getMonth(); - year = this.today.getFullYear(); - } - - this.cfg.setProperty("pagedate", new Date(year, month, 1), true); - - this.logger.log("Set month/year to " + month + "/" + year, "info"); - - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } -}; - -/** -* The default handler for the "mindate" property -* @method configMinDate -*/ -YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "maxdate" property -* @method configMaxDate -*/ -YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "selected" property -* @method configSelected -*/ -YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { - var selected = args[0]; - - if (selected) { - if (typeof selected == 'string') { - this.cfg.setProperty("selected", this._parseDates(selected), true); - } - } - if (! this._selectedDates) { - this._selectedDates = this.cfg.getProperty("selected"); - } -}; - -/** -* The default handler for all configuration options properties -* @method configOptions -*/ -YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Options[type] = val; -}; - -/** -* The default handler for all configuration locale properties -* @method configLocale -*/ -YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Locale[type] = val; - - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - -}; - -/** -* The default handler for all configuration locale field length properties -* @method configLocaleValues -*/ -YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - - switch (type) { - case "LOCALE_MONTHS": - switch (val) { - case "short": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); - break; - case "long": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); - break; - } - break; - case "LOCALE_WEEKDAYS": - switch (val) { - case "1char": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); - break; - case "short": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); - break; - case "medium": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); - break; - case "long": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); - break; - } - - var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); - - if (START_WEEKDAY > 0) { - for (var w=0;w'; - html[html.length] = '
'; - - var renderLeft, renderRight = false; - - if (this.parent) { - if (this.index === 0) { - renderLeft = true; - } - if (this.index == (this.parent.cfg.getProperty("pages") -1)) { - renderRight = true; - } - } else { - renderLeft = true; - renderRight = true; - } - - var cal = this.parent || this; - - if (renderLeft) { - html[html.length] = ' '; - } - - html[html.length] = this.buildMonthLabel(); - - if (renderRight) { - html[html.length] = ' '; - } - - - html[html.length] = '
'; - html[html.length] = ''; - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEKDAYS")) { - html = this.buildWeekdays(html); - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the Calendar's weekday headers. -* @method buildWeekdays -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { - html[html.length] = ' '; - } - - for(var i=0;i'; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { - html[html.length] = ' '; - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar body. -* @method renderBody -* @param {Date} workingDate The current working Date being used for the render process -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { - this.logger.log("Rendering body", "info"); - - var startDay = this.cfg.getProperty("START_WEEKDAY"); - - this.preMonthDays = workingDate.getDay(); - if (startDay > 0) { - this.preMonthDays -= startDay; - } - if (this.preMonthDays < 0) { - this.preMonthDays += 7; - } - - this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); - this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; - - this.logger.log(this.preMonthDays + " preciding out-of-month days", "info"); - this.logger.log(this.monthDays + " month days", "info"); - this.logger.log(this.postMonthDays + " post-month days", "info"); - - workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); - this.logger.log("Calendar page starts on " + workingDate, "info"); - - var useDate,weekNum,weekClass; - useDate = this.cfg.getProperty("pagedate"); - - html[html.length] = ''; - - var i = 0; - - var tempDiv = document.createElement("div"); - var cell = document.createElement("td"); - tempDiv.appendChild(cell); - - var jan1 = new Date(useDate.getFullYear(),0,1); - - var cal = this.parent || this; - - for (var r=0;r<6;r++) { - - weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); - - weekClass = "w" + weekNum; - - if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { - break; - } else { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } - - for (var d=0;d<7;d++){ // Render actual days - - var cellRenderers = []; - - this.clearElement(cell); - - YAHOO.util.Dom.addClass(cell, "calcell"); - - cell.id = this.id + "_cell" + i; - this.logger.log("Rendering cell " + cell.id + " (" + workingDate.getFullYear() + "-" + (workingDate.getMonth()+1) + "-" + workingDate.getDate() + ")", "cellrender"); - - cell.innerHTML = i; - - var renderer = null; - - if (workingDate.getFullYear() == this.today.getFullYear() && - workingDate.getMonth() == this.today.getMonth() && - workingDate.getDate() == this.today.getDate()) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; - } - - this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates - - if (this.isDateOOM(workingDate)) { - cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; - } else { - - YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); - YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); - - for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { - renderer = rArray[2]; - - if (workingDate.getTime()==d2.getTime()) { - this.renderStack.splice(s,1); - } - } - break; - case YAHOO.widget.Calendar.WEEKDAY: - - var weekday = rArray[1][0]; - if (workingDate.getDay()+1 == weekday) { - renderer = rArray[2]; - } - break; - case YAHOO.widget.Calendar.MONTH: - - month = rArray[1][0]; - if (workingDate.getMonth()+1 == month) { - renderer = rArray[2]; - } - break; - } - - if (renderer) { - cellRenderers[cellRenderers.length]=renderer; - } - } - - } - - if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; - } - - var mindate = this.cfg.getProperty("mindate"); - var maxdate = this.cfg.getProperty("maxdate"); - - if (mindate) { - mindate = YAHOO.widget.DateMath.clearTime(mindate); - } - if (maxdate) { - maxdate = YAHOO.widget.DateMath.clearTime(maxdate); - } - - if ( - (mindate && (workingDate.getTime() < mindate.getTime())) || - (maxdate && (workingDate.getTime() > maxdate.getTime())) - ) { - cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; - } else { - cellRenderers[cellRenderers.length]=cal.styleCellDefault; - cellRenderers[cellRenderers.length]=cal.renderCellDefault; - } - - - - for (var x=0;x= 0 && i <= 6) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); - } - if ((i % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); - } - if (((i+1) % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); - } - - var postDays = this.postMonthDays; - if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { - var blankWeeks = Math.floor(postDays/7); - for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); - } - - html[html.length] = tempDiv.innerHTML; - - i++; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } - - html[html.length] = ''; - } - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar footer. In the default implementation, there is -* no footer. -* @method renderFooter -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; - -/** -* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute -* when the method is called: renderHeader, renderBody, renderFooter. -* Refer to the documentation for those methods for information on -* individual render tasks. -* @method render -*/ -YAHOO.widget.Calendar.prototype.render = function() { - this.beforeRenderEvent.fire(); - - // Find starting day of the current month - var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); - - this.resetRenderers(); - this.cellDates.length = 0; - - YAHOO.util.Event.purgeElement(this.oDomContainer, true); - - var html = []; - - html[html.length] = ''; - html = this.renderHeader(html); - html = this.renderBody(workingDate, html); - html = this.renderFooter(html); - html[html.length] = '
'; - - this.oDomContainer.innerHTML = html.join("\n"); - - this.applyListeners(); - this.cells = this.oDomContainer.getElementsByTagName("td"); - - this.cfg.refireEvent("title"); - this.cfg.refireEvent("close"); - this.cfg.refireEvent("iframe"); - - this.renderEvent.fire(); -}; - -/** -* Applies the Calendar's DOM listeners to applicable elements. -* @method applyListeners -*/ -YAHOO.widget.Calendar.prototype.applyListeners = function() { - - var root = this.oDomContainer; - var cal = this.parent || this; - - var linkLeft, linkRight; - - linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); - linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); - - if (linkLeft) { - this.linkLeft = linkLeft[0]; - YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); - } - - if (linkRight) { - this.linkRight = linkRight[0]; - YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); - } - - if (this.domEventMap) { - var el,elements; - for (var cls in this.domEventMap) { - if (this.domEventMap.hasOwnProperty(cls)) { - var items = this.domEventMap[cls]; - - if (! (items instanceof Array)) { - items = [items]; - } - - for (var i=0;i'; - return html; -}; - -/** -* Renders the row footer for a week. -* @method renderRowFooter -* @param {Number} weekNum The week number of the current row -* @param {Array} cell The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { - html[html.length] = '' + weekNum + ''; - return html; -}; - -/** -* Renders a single standard calendar cell in the calendar widget table. -* All logic for determining how a standard default cell will be rendered is -* encapsulated in this method, and must be accounted for when extending the -* widget class. -* @method renderCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { - cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; -}; - -/** -* Styles a selectable cell. -* @method styleCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); -}; - - -/** -* Renders a single standard calendar cell using the CSS hightlight1 style -* @method renderCellStyleHighlight1 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight2 style -* @method renderCellStyleHighlight2 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight3 style -* @method renderCellStyleHighlight3 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight4 style -* @method renderCellStyleHighlight4 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); -}; - -/** -* Applies the default style used for rendering today's date to the current calendar cell -* @method renderCellStyleToday -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); -}; - -/** -* Applies the default style used for rendering selected dates to the current calendar cell -* @method renderCellStyleSelected -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); -}; - -/** -* Applies the default style used for rendering dates that are not a part of the current -* month (preceding or trailing the cells for the current month) -* @method renderCellNotThisMonth -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -/** -* Renders the current calendar cell as a non-selectable "black-out" date using the default -* restricted style. -* @method renderBodyCellRestricted -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -// END BUILT-IN TABLE CELL RENDERERS - -// BEGIN MONTH NAVIGATION METHODS - -/** -* Adds the designated number of months to the current calendar month, and sets the current -* calendar page date to the new month. -* @method addMonths -* @param {Number} count The number of months to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtracts the designated number of months from the current calendar month, and sets the current -* calendar page date to the new month. -* @method subtractMonths -* @param {Number} count The number of months to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Adds the designated number of years to the current calendar, and sets the current -* calendar page date to the new month. -* @method addYears -* @param {Number} count The number of years to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtcats the designated number of years from the current calendar, and sets the current -* calendar page date to the new month. -* @method subtractYears -* @param {Number} count The number of years to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Navigates to the next month page in the calendar widget. -* @method nextMonth -*/ -YAHOO.widget.Calendar.prototype.nextMonth = function() { - this.addMonths(1); -}; - -/** -* Navigates to the previous month page in the calendar widget. -* @method previousMonth -*/ -YAHOO.widget.Calendar.prototype.previousMonth = function() { - this.subtractMonths(1); -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.Calendar.prototype.nextYear = function() { - this.addYears(1); -}; - -/** -* Navigates to the previous year in the currently selected month in the calendar widget. -* @method previousYear -*/ -YAHOO.widget.Calendar.prototype.previousYear = function() { - this.subtractYears(1); -}; - -// END MONTH NAVIGATION METHODS - -// BEGIN SELECTION METHODS - -/** -* Resets the calendar widget to the originally selected month and year, and -* sets the calendar to the initial selection(s). -* @method reset -*/ -YAHOO.widget.Calendar.prototype.reset = function() { - this.cfg.resetProperty("selected"); - this.cfg.resetProperty("pagedate"); - this.resetEvent.fire(); -}; - -/** -* Clears the selected dates in the current calendar widget and sets the calendar -* to the current month and year. -* @method clear -*/ -YAHOO.widget.Calendar.prototype.clear = function() { - this.cfg.setProperty("selected", []); - this.cfg.setProperty("pagedate", new Date(this.today.getTime())); - this.clearEvent.fire(); -}; - -/** -* Selects a date or a collection of dates on the current calendar. This method, by default, -* does not call the render method explicitly. Once selection has completed, render must be -* called for the changes to be reflected visually. -* @method select -* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -*/ -YAHOO.widget.Calendar.prototype.select = function(date) { - this.logger.log("Select: " + date, "info"); - - this.beforeSelectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var aToBeSelected = this._toFieldArray(date); - this.logger.log("Selection field array: " + aToBeSelected, "info"); - - for (var a=0;a -1) { - if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && - this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { - YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); - } - - selected.splice(cellDateIndex, 1); - } - - - if (this.parent) { - this.parent.cfg.setProperty("selected", selected); - } else { - this.cfg.setProperty("selected", selected); - } - - this.deselectEvent.fire(selectDate); - return this.getSelectedDates(); -}; - -/** -* Deselects all dates on the current calendar. -* @method deselectAll -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -* Assuming that this function executes properly, the return value should be an empty array. -* However, the empty array is returned for the sake of being able to check the selection status -* of the calendar. -*/ -YAHOO.widget.Calendar.prototype.deselectAll = function() { - this.beforeDeselectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var count = selected.length; - var sel = selected.concat(); - - if (this.parent) { - this.parent.cfg.setProperty("selected", []); - } else { - this.cfg.setProperty("selected", []); - } - - if (count > 0) { - this.deselectEvent.fire(sel); - } - - return this.getSelectedDates(); -}; - -// END SELECTION METHODS - -// BEGIN TYPE CONVERSION METHODS - -/** -* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure -* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. -* @method _toFieldArray -* @private -* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Array[](Number[])} Array of date field arrays -*/ -YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { - var returnDate = []; - - if (date instanceof Date) { - returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; - } else if (typeof date == 'string') { - returnDate = this._parseDates(date); - } else if (date instanceof Array) { - for (var i=0;i -*
-*
-* -* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. -* @namespace YAHOO.widget -* @class CalendarGroup -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup = function(id, containerId, config) { - if (arguments.length > 0) { - this.init(id, containerId, config); - } -}; - -/** -* Initializes the calendar group. All subclasses must call this method in order for the -* group to be initialized properly. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { - this.logger = new YAHOO.widget.LogWriter("CalendarGroup " + id); - - this.initEvents(); - this.initStyles(); - - /** - * The collection of Calendar pages contained within the CalendarGroup - * @property pages - * @type YAHOO.widget.Calendar[] - */ - this.pages = []; - - /** - * The unique id associated with the CalendarGroup - * @property id - * @type String - */ - this.id = id; - - /** - * The unique id associated with the CalendarGroup container - * @property containerId - * @type String - */ - this.containerId = containerId; - - /** - * The outer containing element for the CalendarGroup - * @property oDomContainer - * @type HTMLElement - */ - this.oDomContainer = document.getElementById(containerId); - - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); - - /** - * The Config object used to hold the configuration variables for the CalendarGroup - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the CalendarGroup's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the CalendarGroup's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); - - // OPERA HACK FOR MISWRAPPED FLOATS - if (this.browser == "opera"){ - var fixWidth = function() { - var startW = this.oDomContainer.offsetWidth; - var w = 0; - for (var p=0;p 0) { - this.oDomContainer.style.width = w + "px"; - } - }; - this.renderEvent.subscribe(fixWidth,this,true); - } - - this.logger.log("Initialized " + pageCount + "-page CalendarGroup", "info"); -}; - - -YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { - /** - * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. - * @config pages - * @type Number - * @default 2 - */ - this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); - - /** - * The title to display above the CalendarGroup's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this CalendarGroup - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - -}; - -/** -* Initializes CalendarGroup's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.CalendarGroup.prototype.initEvents = function() { - var me = this; - - /** - * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents - * @method sub - * @private - * @param {Function} fn The function to subscribe to this CustomEvent - * @param {Object} obj The CustomEvent's scope object - * @param {Boolean} bOverride Whether or not to apply scope correction - */ - var sub = function(fn, obj, bOverride) { - for (var p=0;p0) { - year+=1; - } - cal.setYear(year); - } -}; -/** -* Calls the render function of all child calendars within the group. -* @method render -*/ -YAHOO.widget.CalendarGroup.prototype.render = function() { - this.renderHeader(); - for (var p=0;p=0;--p) { - var cal = this.pages[p]; - cal.previousMonth(); - } -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.CalendarGroup.prototype.nextYear = function() { - for (var p=0;p 11) { + while (newMonth > 11) { + newMonth -= 12; + years += 1; + } + } + + d.setMonth(newMonth); + d.setFullYear(date.getFullYear() + years); + break; + case this.DAY: + d.setDate(date.getDate() + amount); + break; + case this.YEAR: + d.setFullYear(date.getFullYear() + amount); + break; + case this.WEEK: + d.setDate(date.getDate() + (amount * 7)); + break; + } + return d; + }, + + /** + * Subtracts the specified amount of time from the this instance. + * @method subtract + * @param {Date} date The JavaScript Date object to perform subtraction on + * @param {Number} field The this field constant to be used for performing subtraction. + * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. + * @return {Date} The resulting Date object + */ + subtract : function(date, field, amount) { + return this.add(date, field, (amount*-1)); + }, + + /** + * Determines whether a given date is before another date on the calendar. + * @method before + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs before the compared date; false if not. + */ + before : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() < ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is after another date on the calendar. + * @method after + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs after the compared date; false if not. + */ + after : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() > ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is between two other dates on the calendar. + * @method between + * @param {Date} date The date to check for + * @param {Date} dateBegin The start of the range + * @param {Date} dateEnd The end of the range + * @return {Boolean} true if the date occurs between the compared dates; false if not. + */ + between : function(date, dateBegin, dateEnd) { + if (this.after(date, dateBegin) && this.before(date, dateEnd)) { + return true; + } else { + return false; + } + }, + + /** + * Retrieves a JavaScript Date object representing January 1 of any given year. + * @method getJan1 + * @param {Number} calendarYear The calendar year for which to retrieve January 1 + * @return {Date} January 1 of the calendar year specified. + */ + getJan1 : function(calendarYear) { + return new Date(calendarYear,0,1); + }, + + /** + * Calculates the number of days the specified date is from January 1 of the specified calendar year. + * Passing January 1 to this function would return an offset value of zero. + * @method getDayOffset + * @param {Date} date The JavaScript date for which to find the offset + * @param {Number} calendarYear The calendar year to use for determining the offset + * @return {Number} The number of days since January 1 of the given year + */ + getDayOffset : function(date, calendarYear) { + var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. + + // Find the number of days the passed in date is away from the calendar year start + var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); + return dayOffset; + }, + + /** + * Calculates the week number for the given date. This function assumes that week 1 is the + * week in which January 1 appears, regardless of whether the week consists of a full 7 days. + * The calendar year can be specified to help find what a the week number would be for a given + * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or + * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction + * easily. + * @method getWeekNumber + * @param {Date} date The JavaScript date for which to find the week number + * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is + * the calendar year of parameter "date". + * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). + * @return {Number} The week number of the given date. + */ + getWeekNumber : function(date, calendarYear) { + date = this.clearTime(date); + var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); + + var jan1 = new Date(nearestThurs.getFullYear(),0,1); + var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; + + var weekNum = Math.ceil((dayOfYear)/ 7); + return weekNum; + }, + + /** + * Determines if a given week overlaps two different years. + * @method isYearOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different years. + */ + isYearOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Determines if a given week overlaps two different months. + * @method isMonthOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different months. + */ + isMonthOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getMonth() != weekBeginDate.getMonth()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Gets the first day of a month containing a given date. + * @method findMonthStart + * @param {Date} date The JavaScript Date used to calculate the month start + * @return {Date} The JavaScript Date representing the first day of the month + */ + findMonthStart : function(date) { + var start = new Date(date.getFullYear(), date.getMonth(), 1); + return start; + }, + + /** + * Gets the last day of a month containing a given date. + * @method findMonthEnd + * @param {Date} date The JavaScript Date used to calculate the month end + * @return {Date} The JavaScript Date representing the last day of the month + */ + findMonthEnd : function(date) { + var start = this.findMonthStart(date); + var nextMonth = this.add(start, this.MONTH, 1); + var end = this.subtract(nextMonth, this.DAY, 1); + return end; + }, + + /** + * Clears the time fields from a given date, effectively setting the time to midnight. + * @method clearTime + * @param {Date} date The JavaScript Date for which the time fields will be cleared + * @return {Date} The JavaScript Date cleared of all time fields + */ + clearTime : function(date) { + date.setHours(12,0,0,0); + return date; + } +}; + +/** +* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. +* @module Calendar +* @title Calendar Widget +* @namespace YAHOO.widget +* @requires yahoo,dom,event +*/ + +/** +* Calendar is the base class for the Calendar widget. In its most basic +* implementation, it has the ability to render a calendar widget on the page +* that can be manipulated to select a single date, move back and forth between +* months and years. +*

To construct the placeholder for the calendar widget, the code is as +* follows: +*

+* <div id="cal1Container"></div> +* +* Note that the table can be replaced with any kind of element. +*

+* @namespace YAHOO.widget +* @class Calendar +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar = function(id, containerId, config) { + this.init(id, containerId, config); +}; + +/** +* The path to be used for images loaded for the Calendar +* @property YAHOO.widget.Calendar.IMG_ROOT +* @static +* @type String +*/ +YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); + +/** +* Type constant used for renderers to represent an individual date (M/D/Y) +* @property YAHOO.widget.Calendar.DATE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.DATE = "D"; + +/** +* Type constant used for renderers to represent an individual date across any year (M/D) +* @property YAHOO.widget.Calendar.MONTH_DAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH_DAY = "MD"; + +/** +* Type constant used for renderers to represent a weekday +* @property YAHOO.widget.Calendar.WEEKDAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.WEEKDAY = "WD"; + +/** +* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) +* @property YAHOO.widget.Calendar.RANGE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.RANGE = "R"; + +/** +* Type constant used for renderers to represent a month across any year +* @property YAHOO.widget.Calendar.MONTH +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH = "M"; + +/** +* Constant that represents the total number of date cells that are displayed in a given month +* @property YAHOO.widget.Calendar.DISPLAY_DAYS +* @static +* @final +* @type Number +*/ +YAHOO.widget.Calendar.DISPLAY_DAYS = 42; + +/** +* Constant used for halting the execution of the remainder of the render stack +* @property YAHOO.widget.Calendar.STOP_RENDER +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.STOP_RENDER = "S"; + +YAHOO.widget.Calendar.prototype = { + + /** + * The configuration object used to set up the calendars various locale and style options. + * @property Config + * @private + * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. + * @type Object + */ + Config : null, + + /** + * The parent CalendarGroup, only to be set explicitly by the parent group + * @property parent + * @type CalendarGroup + */ + parent : null, + + /** + * The index of this item in the parent group + * @property index + * @type Number + */ + index : -1, + + /** + * The collection of calendar table cells + * @property cells + * @type HTMLTableCellElement[] + */ + cells : null, + + /** + * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. + * @property cellDates + * @type Array[](Number[]) + */ + cellDates : null, + + /** + * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. + * @property id + * @type String + */ + id : null, + + /** + * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. + * @property oDomContainer + * @type HTMLElement + */ + oDomContainer : null, + + /** + * A Date object representing today's date. + * @property today + * @type Date + */ + today : null, + + /** + * The list of render functions, along with required parameters, used to render cells. + * @property renderStack + * @type Array[] + */ + renderStack : null, + + /** + * A copy of the initial render functions created before rendering. + * @property _renderStack + * @private + * @type Array + */ + _renderStack : null, + + /** + * A Date object representing the month/year that the calendar is initially set to + * @property _pageDate + * @private + * @type Date + */ + _pageDate : null, + + /** + * The private list of initially selected dates. + * @property _selectedDates + * @private + * @type Array + */ + _selectedDates : null, + + /** + * A map of DOM event handlers to attach to cells associated with specific CSS class names + * @property domEventMap + * @type Object + */ + domEventMap : null +}; + + + +/** +* Initializes the Calendar widget. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { + this.logger = new YAHOO.widget.LogWriter("Calendar_Core " + id); + + this.initEvents(); + this.today = new Date(); + YAHOO.widget.DateMath.clearTime(this.today); + + this.id = id; + this.oDomContainer = document.getElementById(containerId); + if (! this.oDomContainer) { + this.logger.log("No valid container present.", "error"); + } + + /** + * The Config object used to hold the configuration variables for the Calendar + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the Calendar's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the Calendar's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.initStyles(); + + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); + + this.cellDates = []; + this.cells = []; + this.renderStack = []; + this._renderStack = []; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); +}; + +/** +* Renders the built-in IFRAME shim for the IE6 and below +* @method configIframe +*/ +YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { + var useIframe = args[0]; + + if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { + if (useIframe) { + var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); + + if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { + if (! YAHOO.util.Dom.inDocument(this.iframe)) { + this.iframe = document.createElement("iframe"); + this.iframe.src = "javascript:false;"; + YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); + this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); + } + } + } else { + if (this.iframe) { + if (this.iframe.parentNode) { + this.iframe.parentNode.removeChild(this.iframe); + } + this.iframe = null; + } + } + } +}; + +/** +* Default handler for the "title" property +* @method configTitle +*/ +YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { + var title = args[0]; + var close = this.cfg.getProperty("close"); + + var titleDiv; + + if (title && title !== "") { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); + titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; + titleDiv.innerHTML = title; + this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; + + if (titleDiv) { + YAHOO.util.Event.purgeElement(titleDiv); + this.oDomContainer.removeChild(titleDiv); + } + if (! close) { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Default handler for the "close" property +* @method configClose +*/ +YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { + var close = args[0]; + var title = this.cfg.getProperty("title"); + + var linkClose; + + if (close === true) { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); + linkClose.href = "javascript:void(null);"; + linkClose.className = "link-close"; + YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); + var imgClose = document.createElement("img"); + imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; + imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; + linkClose.appendChild(imgClose); + this.oDomContainer.appendChild(linkClose); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; + + if (linkClose) { + YAHOO.util.Event.purgeElement(linkClose); + this.oDomContainer.removeChild(linkClose); + } + if (! title || title === "") { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Initializes Calendar's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.Calendar.prototype.initEvents = function() { + + /** + * Fired before a selection is made + * @event beforeSelectEvent + */ + this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); + + /** + * Fired when a selection is made + * @event selectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.selectEvent = new YAHOO.util.CustomEvent("select"); + + /** + * Fired before a selection is made + * @event beforeDeselectEvent + */ + this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); + + /** + * Fired when a selection is made + * @event deselectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); + + /** + * Fired when the Calendar page is changed + * @event changePageEvent + */ + this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); + + /** + * Fired before the Calendar is rendered + * @event beforeRenderEvent + */ + this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); + + /** + * Fired when the Calendar is rendered + * @event renderEvent + */ + this.renderEvent = new YAHOO.util.CustomEvent("render"); + + /** + * Fired when the Calendar is reset + * @event resetEvent + */ + this.resetEvent = new YAHOO.util.CustomEvent("reset"); + + /** + * Fired when the Calendar is cleared + * @event clearEvent + */ + this.clearEvent = new YAHOO.util.CustomEvent("clear"); + + this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); + this.selectEvent.subscribe(this.onSelect, this, true); + this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); + this.deselectEvent.subscribe(this.onDeselect, this, true); + this.changePageEvent.subscribe(this.onChangePage, this, true); + this.renderEvent.subscribe(this.onRender, this, true); + this.resetEvent.subscribe(this.onReset, this, true); + this.clearEvent.subscribe(this.onClear, this, true); +}; + + +/** +* The default event function that is attached to a date link within a calendar cell +* when the calendar is rendered. +* @method doSelectCell +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { + var target = YAHOO.util.Event.getTarget(e); + + var cell,index,d,date; + + while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + cell = target; + + if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { + index = cell.id.split("cell")[1]; + d = cal.cellDates[index]; + date = new Date(d[0],d[1]-1,d[2]); + + cal.logger.log("Selecting cell " + index + " via click", "info"); + + if (cal.Options.MULTI_SELECT) { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + + var cellDate = cal.cellDates[index]; + var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); + + if (cellDateIndex > -1) { + cal.deselectCell(index); + } else { + cal.selectCell(index); + } + + } else { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + cal.selectCell(index); + } + } +}; + +/** +* The event that is executed when the user hovers over a cell +* @method doCellMouseOver +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +/** +* The event that is executed when the user moves the mouse out of a cell +* @method doCellMouseOut +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +YAHOO.widget.Calendar.prototype.setupConfig = function() { + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); + + /** + * The title to display above the Calendar's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this Calendar + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); + + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); + + /** + * Refreshes the locale values used to build the Calendar. + * @method refreshLocale + * @private + */ + var refreshLocale = function() { + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + }; + + this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); +}; + +/** +* The default handler for the "pagedate" property +* @method configPageDate +*/ +YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { + var val = args[0]; + var month, year, aMonthYear; + + if (val) { + if (val instanceof Date) { + val = YAHOO.widget.DateMath.findMonthStart(val); + this.cfg.setProperty("pagedate", val, true); + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } + return; + } else { + aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); + month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; + year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); + } + } else { + month = this.today.getMonth(); + year = this.today.getFullYear(); + } + + this.cfg.setProperty("pagedate", new Date(year, month, 1), true); + + this.logger.log("Set month/year to " + month + "/" + year, "info"); + + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } +}; + +/** +* The default handler for the "mindate" property +* @method configMinDate +*/ +YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "maxdate" property +* @method configMaxDate +*/ +YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "selected" property +* @method configSelected +*/ +YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { + var selected = args[0]; + + if (selected) { + if (typeof selected == 'string') { + this.cfg.setProperty("selected", this._parseDates(selected), true); + } + } + if (! this._selectedDates) { + this._selectedDates = this.cfg.getProperty("selected"); + } +}; + +/** +* The default handler for all configuration options properties +* @method configOptions +*/ +YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Options[type] = val; +}; + +/** +* The default handler for all configuration locale properties +* @method configLocale +*/ +YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Locale[type] = val; + + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + +}; + +/** +* The default handler for all configuration locale field length properties +* @method configLocaleValues +*/ +YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + + switch (type) { + case "LOCALE_MONTHS": + switch (val) { + case "short": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); + break; + case "long": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); + break; + } + break; + case "LOCALE_WEEKDAYS": + switch (val) { + case "1char": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); + break; + case "short": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); + break; + case "medium": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); + break; + case "long": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); + break; + } + + var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); + + if (START_WEEKDAY > 0) { + for (var w=0;w'; + html[html.length] = '
'; + + var renderLeft, renderRight = false; + + if (this.parent) { + if (this.index === 0) { + renderLeft = true; + } + if (this.index == (this.parent.cfg.getProperty("pages") -1)) { + renderRight = true; + } + } else { + renderLeft = true; + renderRight = true; + } + + var cal = this.parent || this; + + if (renderLeft) { + html[html.length] = ' '; + } + + html[html.length] = this.buildMonthLabel(); + + if (renderRight) { + html[html.length] = ' '; + } + + + html[html.length] = '
'; + html[html.length] = ''; + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEKDAYS")) { + html = this.buildWeekdays(html); + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the Calendar's weekday headers. +* @method buildWeekdays +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { + html[html.length] = ' '; + } + + for(var i=0;i'; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { + html[html.length] = ' '; + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar body. +* @method renderBody +* @param {Date} workingDate The current working Date being used for the render process +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { + this.logger.log("Rendering body", "info"); + + var startDay = this.cfg.getProperty("START_WEEKDAY"); + + this.preMonthDays = workingDate.getDay(); + if (startDay > 0) { + this.preMonthDays -= startDay; + } + if (this.preMonthDays < 0) { + this.preMonthDays += 7; + } + + this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); + this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; + + this.logger.log(this.preMonthDays + " preciding out-of-month days", "info"); + this.logger.log(this.monthDays + " month days", "info"); + this.logger.log(this.postMonthDays + " post-month days", "info"); + + workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); + this.logger.log("Calendar page starts on " + workingDate, "info"); + + var useDate,weekNum,weekClass; + useDate = this.cfg.getProperty("pagedate"); + + html[html.length] = ''; + + var i = 0; + + var tempDiv = document.createElement("div"); + var cell = document.createElement("td"); + tempDiv.appendChild(cell); + + var jan1 = new Date(useDate.getFullYear(),0,1); + + var cal = this.parent || this; + + for (var r=0;r<6;r++) { + + weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); + + weekClass = "w" + weekNum; + + if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { + break; + } else { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } + + for (var d=0;d<7;d++){ // Render actual days + + var cellRenderers = []; + + this.clearElement(cell); + + YAHOO.util.Dom.addClass(cell, "calcell"); + + cell.id = this.id + "_cell" + i; + this.logger.log("Rendering cell " + cell.id + " (" + workingDate.getFullYear() + "-" + (workingDate.getMonth()+1) + "-" + workingDate.getDate() + ")", "cellrender"); + + cell.innerHTML = i; + + var renderer = null; + + if (workingDate.getFullYear() == this.today.getFullYear() && + workingDate.getMonth() == this.today.getMonth() && + workingDate.getDate() == this.today.getDate()) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; + } + + this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates + + if (this.isDateOOM(workingDate)) { + cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; + } else { + + YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); + YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); + + for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { + renderer = rArray[2]; + + if (workingDate.getTime()==d2.getTime()) { + this.renderStack.splice(s,1); + } + } + break; + case YAHOO.widget.Calendar.WEEKDAY: + + var weekday = rArray[1][0]; + if (workingDate.getDay()+1 == weekday) { + renderer = rArray[2]; + } + break; + case YAHOO.widget.Calendar.MONTH: + + month = rArray[1][0]; + if (workingDate.getMonth()+1 == month) { + renderer = rArray[2]; + } + break; + } + + if (renderer) { + cellRenderers[cellRenderers.length]=renderer; + } + } + + } + + if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; + } + + var mindate = this.cfg.getProperty("mindate"); + var maxdate = this.cfg.getProperty("maxdate"); + + if (mindate) { + mindate = YAHOO.widget.DateMath.clearTime(mindate); + } + if (maxdate) { + maxdate = YAHOO.widget.DateMath.clearTime(maxdate); + } + + if ( + (mindate && (workingDate.getTime() < mindate.getTime())) || + (maxdate && (workingDate.getTime() > maxdate.getTime())) + ) { + cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; + } else { + cellRenderers[cellRenderers.length]=cal.styleCellDefault; + cellRenderers[cellRenderers.length]=cal.renderCellDefault; + } + + + + for (var x=0;x= 0 && i <= 6) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); + } + if ((i % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); + } + if (((i+1) % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); + } + + var postDays = this.postMonthDays; + if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { + var blankWeeks = Math.floor(postDays/7); + for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); + } + + html[html.length] = tempDiv.innerHTML; + + i++; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } + + html[html.length] = ''; + } + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar footer. In the default implementation, there is +* no footer. +* @method renderFooter +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; + +/** +* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute +* when the method is called: renderHeader, renderBody, renderFooter. +* Refer to the documentation for those methods for information on +* individual render tasks. +* @method render +*/ +YAHOO.widget.Calendar.prototype.render = function() { + this.beforeRenderEvent.fire(); + + // Find starting day of the current month + var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); + + this.resetRenderers(); + this.cellDates.length = 0; + + YAHOO.util.Event.purgeElement(this.oDomContainer, true); + + var html = []; + + html[html.length] = ''; + html = this.renderHeader(html); + html = this.renderBody(workingDate, html); + html = this.renderFooter(html); + html[html.length] = '
'; + + this.oDomContainer.innerHTML = html.join("\n"); + + this.applyListeners(); + this.cells = this.oDomContainer.getElementsByTagName("td"); + + this.cfg.refireEvent("title"); + this.cfg.refireEvent("close"); + this.cfg.refireEvent("iframe"); + + this.renderEvent.fire(); +}; + +/** +* Applies the Calendar's DOM listeners to applicable elements. +* @method applyListeners +*/ +YAHOO.widget.Calendar.prototype.applyListeners = function() { + + var root = this.oDomContainer; + var cal = this.parent || this; + + var linkLeft, linkRight; + + linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); + linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); + + if (linkLeft) { + this.linkLeft = linkLeft[0]; + YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); + } + + if (linkRight) { + this.linkRight = linkRight[0]; + YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); + } + + if (this.domEventMap) { + var el,elements; + for (var cls in this.domEventMap) { + if (this.domEventMap.hasOwnProperty(cls)) { + var items = this.domEventMap[cls]; + + if (! (items instanceof Array)) { + items = [items]; + } + + for (var i=0;i'; + return html; +}; + +/** +* Renders the row footer for a week. +* @method renderRowFooter +* @param {Number} weekNum The week number of the current row +* @param {Array} cell The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { + html[html.length] = '' + weekNum + ''; + return html; +}; + +/** +* Renders a single standard calendar cell in the calendar widget table. +* All logic for determining how a standard default cell will be rendered is +* encapsulated in this method, and must be accounted for when extending the +* widget class. +* @method renderCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { + cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; +}; + +/** +* Styles a selectable cell. +* @method styleCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); +}; + + +/** +* Renders a single standard calendar cell using the CSS hightlight1 style +* @method renderCellStyleHighlight1 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight2 style +* @method renderCellStyleHighlight2 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight3 style +* @method renderCellStyleHighlight3 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight4 style +* @method renderCellStyleHighlight4 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); +}; + +/** +* Applies the default style used for rendering today's date to the current calendar cell +* @method renderCellStyleToday +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); +}; + +/** +* Applies the default style used for rendering selected dates to the current calendar cell +* @method renderCellStyleSelected +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); +}; + +/** +* Applies the default style used for rendering dates that are not a part of the current +* month (preceding or trailing the cells for the current month) +* @method renderCellNotThisMonth +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +/** +* Renders the current calendar cell as a non-selectable "black-out" date using the default +* restricted style. +* @method renderBodyCellRestricted +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +// END BUILT-IN TABLE CELL RENDERERS + +// BEGIN MONTH NAVIGATION METHODS + +/** +* Adds the designated number of months to the current calendar month, and sets the current +* calendar page date to the new month. +* @method addMonths +* @param {Number} count The number of months to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtracts the designated number of months from the current calendar month, and sets the current +* calendar page date to the new month. +* @method subtractMonths +* @param {Number} count The number of months to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Adds the designated number of years to the current calendar, and sets the current +* calendar page date to the new month. +* @method addYears +* @param {Number} count The number of years to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtcats the designated number of years from the current calendar, and sets the current +* calendar page date to the new month. +* @method subtractYears +* @param {Number} count The number of years to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Navigates to the next month page in the calendar widget. +* @method nextMonth +*/ +YAHOO.widget.Calendar.prototype.nextMonth = function() { + this.addMonths(1); +}; + +/** +* Navigates to the previous month page in the calendar widget. +* @method previousMonth +*/ +YAHOO.widget.Calendar.prototype.previousMonth = function() { + this.subtractMonths(1); +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.Calendar.prototype.nextYear = function() { + this.addYears(1); +}; + +/** +* Navigates to the previous year in the currently selected month in the calendar widget. +* @method previousYear +*/ +YAHOO.widget.Calendar.prototype.previousYear = function() { + this.subtractYears(1); +}; + +// END MONTH NAVIGATION METHODS + +// BEGIN SELECTION METHODS + +/** +* Resets the calendar widget to the originally selected month and year, and +* sets the calendar to the initial selection(s). +* @method reset +*/ +YAHOO.widget.Calendar.prototype.reset = function() { + this.cfg.resetProperty("selected"); + this.cfg.resetProperty("pagedate"); + this.resetEvent.fire(); +}; + +/** +* Clears the selected dates in the current calendar widget and sets the calendar +* to the current month and year. +* @method clear +*/ +YAHOO.widget.Calendar.prototype.clear = function() { + this.cfg.setProperty("selected", []); + this.cfg.setProperty("pagedate", new Date(this.today.getTime())); + this.clearEvent.fire(); +}; + +/** +* Selects a date or a collection of dates on the current calendar. This method, by default, +* does not call the render method explicitly. Once selection has completed, render must be +* called for the changes to be reflected visually. +* @method select +* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +*/ +YAHOO.widget.Calendar.prototype.select = function(date) { + this.logger.log("Select: " + date, "info"); + + this.beforeSelectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var aToBeSelected = this._toFieldArray(date); + this.logger.log("Selection field array: " + aToBeSelected, "info"); + + for (var a=0;a -1) { + if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && + this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { + YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); + } + + selected.splice(cellDateIndex, 1); + } + + + if (this.parent) { + this.parent.cfg.setProperty("selected", selected); + } else { + this.cfg.setProperty("selected", selected); + } + + this.deselectEvent.fire(selectDate); + return this.getSelectedDates(); +}; + +/** +* Deselects all dates on the current calendar. +* @method deselectAll +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +* Assuming that this function executes properly, the return value should be an empty array. +* However, the empty array is returned for the sake of being able to check the selection status +* of the calendar. +*/ +YAHOO.widget.Calendar.prototype.deselectAll = function() { + this.beforeDeselectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var count = selected.length; + var sel = selected.concat(); + + if (this.parent) { + this.parent.cfg.setProperty("selected", []); + } else { + this.cfg.setProperty("selected", []); + } + + if (count > 0) { + this.deselectEvent.fire(sel); + } + + return this.getSelectedDates(); +}; + +// END SELECTION METHODS + +// BEGIN TYPE CONVERSION METHODS + +/** +* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure +* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. +* @method _toFieldArray +* @private +* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Array[](Number[])} Array of date field arrays +*/ +YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { + var returnDate = []; + + if (date instanceof Date) { + returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; + } else if (typeof date == 'string') { + returnDate = this._parseDates(date); + } else if (date instanceof Array) { + for (var i=0;i +*
+*
+* +* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. +* @namespace YAHOO.widget +* @class CalendarGroup +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup = function(id, containerId, config) { + if (arguments.length > 0) { + this.init(id, containerId, config); + } +}; + +/** +* Initializes the calendar group. All subclasses must call this method in order for the +* group to be initialized properly. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { + this.logger = new YAHOO.widget.LogWriter("CalendarGroup " + id); + + this.initEvents(); + this.initStyles(); + + /** + * The collection of Calendar pages contained within the CalendarGroup + * @property pages + * @type YAHOO.widget.Calendar[] + */ + this.pages = []; + + /** + * The unique id associated with the CalendarGroup + * @property id + * @type String + */ + this.id = id; + + /** + * The unique id associated with the CalendarGroup container + * @property containerId + * @type String + */ + this.containerId = containerId; + + /** + * The outer containing element for the CalendarGroup + * @property oDomContainer + * @type HTMLElement + */ + this.oDomContainer = document.getElementById(containerId); + + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); + + /** + * The Config object used to hold the configuration variables for the CalendarGroup + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the CalendarGroup's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the CalendarGroup's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); + + // OPERA HACK FOR MISWRAPPED FLOATS + if (this.browser == "opera"){ + var fixWidth = function() { + var startW = this.oDomContainer.offsetWidth; + var w = 0; + for (var p=0;p 0) { + this.oDomContainer.style.width = w + "px"; + } + }; + this.renderEvent.subscribe(fixWidth,this,true); + } + + this.logger.log("Initialized " + pageCount + "-page CalendarGroup", "info"); +}; + + +YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { + /** + * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. + * @config pages + * @type Number + * @default 2 + */ + this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); + + /** + * The title to display above the CalendarGroup's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this CalendarGroup + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + +}; + +/** +* Initializes CalendarGroup's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.CalendarGroup.prototype.initEvents = function() { + var me = this; + + /** + * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents + * @method sub + * @private + * @param {Function} fn The function to subscribe to this CustomEvent + * @param {Object} obj The CustomEvent's scope object + * @param {Boolean} bOverride Whether or not to apply scope correction + */ + var sub = function(fn, obj, bOverride) { + for (var p=0;p0) { + year+=1; + } + cal.setYear(year); + } +}; +/** +* Calls the render function of all child calendars within the group. +* @method render +*/ +YAHOO.widget.CalendarGroup.prototype.render = function() { + this.renderHeader(); + for (var p=0;p=0;--p) { + var cal = this.pages[p]; + cal.previousMonth(); + } +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.CalendarGroup.prototype.nextYear = function() { + for (var p=0;p11){while(newMonth>11){newMonth-=12;years+=1;}} -d.setMonth(newMonth);d.setFullYear(date.getFullYear()+years);break;case this.DAY:d.setDate(date.getDate()+amount);break;case this.YEAR:d.setFullYear(date.getFullYear()+amount);break;case this.WEEK:d.setDate(date.getDate()+(amount*7));break;} -return d;},subtract:function(date,field,amount){return this.add(date,field,(amount*-1));},before:function(date,compareTo){var ms=compareTo.getTime();if(date.getTime()ms){return true;}else{return false;}},between:function(date,dateBegin,dateEnd){if(this.after(date,dateBegin)&&this.before(date,dateEnd)){return true;}else{return false;}},getJan1:function(calendarYear){return new Date(calendarYear,0,1);},getDayOffset:function(date,calendarYear){var beginYear=this.getJan1(calendarYear);var dayOffset=Math.ceil((date.getTime()-beginYear.getTime())/this.ONE_DAY_MS);return dayOffset;},getWeekNumber:function(date,calendarYear){date=this.clearTime(date);var nearestThurs=new Date(date.getTime()+(4*this.ONE_DAY_MS)-((date.getDay())*this.ONE_DAY_MS));var jan1=new Date(nearestThurs.getFullYear(),0,1);var dayOfYear=((nearestThurs.getTime()-jan1.getTime())/this.ONE_DAY_MS)-1;var weekNum=Math.ceil((dayOfYear)/7);return weekNum;},isYearOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getFullYear()!=weekBeginDate.getFullYear()){overlaps=true;} -return overlaps;},isMonthOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getMonth()!=weekBeginDate.getMonth()){overlaps=true;} -return overlaps;},findMonthStart:function(date){var start=new Date(date.getFullYear(),date.getMonth(),1);return start;},findMonthEnd:function(date){var start=this.findMonthStart(date);var nextMonth=this.add(start,this.MONTH,1);var end=this.subtract(nextMonth,this.DAY,1);return end;},clearTime:function(date){date.setHours(12,0,0,0);return date;}};YAHOO.widget.Calendar=function(id,containerId,config){this.init(id,containerId,config);};YAHOO.widget.Calendar.IMG_ROOT=(window.location.href.toLowerCase().indexOf("https")===0?"https://a248.e.akamai.net/sec.yimg.com/i/":"http://us.i1.yimg.com/us.yimg.com/i/");YAHOO.widget.Calendar.DATE="D";YAHOO.widget.Calendar.MONTH_DAY="MD";YAHOO.widget.Calendar.WEEKDAY="WD";YAHOO.widget.Calendar.RANGE="R";YAHOO.widget.Calendar.MONTH="M";YAHOO.widget.Calendar.DISPLAY_DAYS=42;YAHOO.widget.Calendar.STOP_RENDER="S";YAHOO.widget.Calendar.prototype={Config:null,parent:null,index:-1,cells:null,cellDates:null,id:null,oDomContainer:null,today:null,renderStack:null,_renderStack:null,_pageDate:null,_selectedDates:null,domEventMap:null};YAHOO.widget.Calendar.prototype.init=function(id,containerId,config){this.initEvents();this.today=new Date();YAHOO.widget.DateMath.clearTime(this.today);this.id=id;this.oDomContainer=document.getElementById(containerId);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.initStyles();YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_SINGLE);this.cellDates=[];this.cells=[];this.renderStack=[];this._renderStack=[];this.setupConfig();if(config){this.cfg.applyConfig(config,true);} -this.cfg.fireQueue();};YAHOO.widget.Calendar.prototype.configIframe=function(type,args,obj){var useIframe=args[0];if(YAHOO.util.Dom.inDocument(this.oDomContainer)){if(useIframe){var pos=YAHOO.util.Dom.getStyle(this.oDomContainer,"position");if(this.browser=="ie"&&(pos=="absolute"||pos=="relative")){if(!YAHOO.util.Dom.inDocument(this.iframe)){this.iframe=document.createElement("iframe");this.iframe.src="javascript:false;";YAHOO.util.Dom.setStyle(this.iframe,"opacity","0");this.oDomContainer.insertBefore(this.iframe,this.oDomContainer.firstChild);}}}else{if(this.iframe){if(this.iframe.parentNode){this.iframe.parentNode.removeChild(this.iframe);} -this.iframe=null;}}}};YAHOO.widget.Calendar.prototype.configTitle=function(type,args,obj){var title=args[0];var close=this.cfg.getProperty("close");var titleDiv;if(title&&title!==""){titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||document.createElement("div");titleDiv.className=YAHOO.widget.CalendarGroup.CSS_2UPTITLE;titleDiv.innerHTML=title;this.oDomContainer.insertBefore(titleDiv,this.oDomContainer.firstChild);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||null;if(titleDiv){YAHOO.util.Event.purgeElement(titleDiv);this.oDomContainer.removeChild(titleDiv);} -if(!close){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.configClose=function(type,args,obj){var close=args[0];var title=this.cfg.getProperty("title");var linkClose;if(close===true){linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||document.createElement("a");linkClose.href="javascript:void(null);";linkClose.className="link-close";YAHOO.util.Event.addListener(linkClose,"click",this.hide,this,true);var imgClose=document.createElement("img");imgClose.src=YAHOO.widget.Calendar.IMG_ROOT+"us/my/bn/x_d.gif";imgClose.className=YAHOO.widget.CalendarGroup.CSS_2UPCLOSE;linkClose.appendChild(imgClose);this.oDomContainer.appendChild(linkClose);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||null;if(linkClose){YAHOO.util.Event.purgeElement(linkClose);this.oDomContainer.removeChild(linkClose);} -if(!title||title===""){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.initEvents=function(){this.beforeSelectEvent=new YAHOO.util.CustomEvent("beforeSelect");this.selectEvent=new YAHOO.util.CustomEvent("select");this.beforeDeselectEvent=new YAHOO.util.CustomEvent("beforeDeselect");this.deselectEvent=new YAHOO.util.CustomEvent("deselect");this.changePageEvent=new YAHOO.util.CustomEvent("changePage");this.beforeRenderEvent=new YAHOO.util.CustomEvent("beforeRender");this.renderEvent=new YAHOO.util.CustomEvent("render");this.resetEvent=new YAHOO.util.CustomEvent("reset");this.clearEvent=new YAHOO.util.CustomEvent("clear");this.beforeSelectEvent.subscribe(this.onBeforeSelect,this,true);this.selectEvent.subscribe(this.onSelect,this,true);this.beforeDeselectEvent.subscribe(this.onBeforeDeselect,this,true);this.deselectEvent.subscribe(this.onDeselect,this,true);this.changePageEvent.subscribe(this.onChangePage,this,true);this.renderEvent.subscribe(this.onRender,this,true);this.resetEvent.subscribe(this.onReset,this,true);this.clearEvent.subscribe(this.onClear,this,true);};YAHOO.widget.Calendar.prototype.doSelectCell=function(e,cal){var target=YAHOO.util.Event.getTarget(e);var cell,index,d,date;while(target.tagName.toLowerCase()!="td"&&!YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} -cell=target;if(YAHOO.util.Dom.hasClass(cell,cal.Style.CSS_CELL_SELECTABLE)){index=cell.id.split("cell")[1];d=cal.cellDates[index];date=new Date(d[0],d[1]-1,d[2]);var link;if(cal.Options.MULTI_SELECT){link=cell.getElementsByTagName("a")[0];if(link){link.blur();} -var cellDate=cal.cellDates[index];var cellDateIndex=cal._indexOfSelectedFieldArray(cellDate);if(cellDateIndex>-1){cal.deselectCell(index);}else{cal.selectCell(index);}}else{link=cell.getElementsByTagName("a")[0];if(link){link.blur();} -cal.selectCell(index);}}};YAHOO.widget.Calendar.prototype.doCellMouseOver=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} -while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} -if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.addClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.doCellMouseOut=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} -while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} -if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.removeClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.setupConfig=function(){this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.configSelected});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.configIframe,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.configMinDate});this.cfg.addProperty("maxdate",{value:null,handler:this.configMaxDate});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.configOptions,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.configOptions});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.configOptions});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.configLocale});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.configLocale});var refreshLocale=function(){this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};this.cfg.subscribeToConfigEvent("START_WEEKDAY",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_LONG",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG",refreshLocale,this,true);this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.configLocaleValues});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.configLocaleValues});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.configLocale});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.configLocale});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.configLocale});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.configLocale,validator:this.cfg.checkNumber});};YAHOO.widget.Calendar.prototype.configPageDate=function(type,args,obj){var val=args[0];var month,year,aMonthYear;if(val){if(val instanceof Date){val=YAHOO.widget.DateMath.findMonthStart(val);this.cfg.setProperty("pagedate",val,true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");} -return;}else{aMonthYear=val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER"));month=parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1],10)-1;year=parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1],10);}}else{month=this.today.getMonth();year=this.today.getFullYear();} -this.cfg.setProperty("pagedate",new Date(year,month,1),true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");}};YAHOO.widget.Calendar.prototype.configMinDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("mindate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configMaxDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("maxdate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configSelected=function(type,args,obj){var selected=args[0];if(selected){if(typeof selected=='string'){this.cfg.setProperty("selected",this._parseDates(selected),true);}} -if(!this._selectedDates){this._selectedDates=this.cfg.getProperty("selected");}};YAHOO.widget.Calendar.prototype.configOptions=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Options[type]=val;};YAHOO.widget.Calendar.prototype.configLocale=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Locale[type]=val;this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};YAHOO.widget.Calendar.prototype.configLocaleValues=function(type,args,obj){type=type.toUpperCase();var val=args[0];switch(type){case"LOCALE_MONTHS":switch(val){case"short":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_SHORT").concat();break;case"long":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_LONG").concat();break;} -break;case"LOCALE_WEEKDAYS":switch(val){case"1char":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_1CHAR").concat();break;case"short":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_SHORT").concat();break;case"medium":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_MEDIUM").concat();break;case"long":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_LONG").concat();break;} -var START_WEEKDAY=this.cfg.getProperty("START_WEEKDAY");if(START_WEEKDAY>0){for(var w=0;w';html[html.length]='
';var renderLeft,renderRight=false;if(this.parent){if(this.index===0){renderLeft=true;} -if(this.index==(this.parent.cfg.getProperty("pages")-1)){renderRight=true;}}else{renderLeft=true;renderRight=true;} -var cal=this.parent||this;if(renderLeft){html[html.length]=' ';} -html[html.length]=this.buildMonthLabel();if(renderRight){html[html.length]=' ';} -html[html.length]='
';html[html.length]='';html[html.length]='';if(this.cfg.getProperty("SHOW_WEEKDAYS")){html=this.buildWeekdays(html);} -html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.buildWeekdays=function(html){html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html[html.length]=' ';} -for(var i=0;i'+this.Locale.LOCALE_WEEKDAYS[i]+'';} -if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html[html.length]=' ';} -html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderBody=function(workingDate,html){var startDay=this.cfg.getProperty("START_WEEKDAY");this.preMonthDays=workingDate.getDay();if(startDay>0){this.preMonthDays-=startDay;} -if(this.preMonthDays<0){this.preMonthDays+=7;} -this.monthDays=YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate();this.postMonthDays=YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays;workingDate=YAHOO.widget.DateMath.subtract(workingDate,YAHOO.widget.DateMath.DAY,this.preMonthDays);var useDate,weekNum,weekClass;useDate=this.cfg.getProperty("pagedate");html[html.length]='';var i=0;var tempDiv=document.createElement("div");var cell=document.createElement("td");tempDiv.appendChild(cell);var jan1=new Date(useDate.getFullYear(),0,1);var cal=this.parent||this;for(var r=0;r<6;r++){weekNum=YAHOO.widget.DateMath.getWeekNumber(workingDate,useDate.getFullYear(),startDay);weekClass="w"+weekNum;if(r!==0&&this.isDateOOM(workingDate)&&this.cfg.getProperty("HIDE_BLANK_WEEKS")===true){break;}else{html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html=this.renderRowHeader(weekNum,html);} -for(var d=0;d<7;d++){var cellRenderers=[];this.clearElement(cell);YAHOO.util.Dom.addClass(cell,"calcell");cell.id=this.id+"_cell"+i;cell.innerHTML=i;var renderer=null;if(workingDate.getFullYear()==this.today.getFullYear()&&workingDate.getMonth()==this.today.getMonth()&&workingDate.getDate()==this.today.getDate()){cellRenderers[cellRenderers.length]=cal.renderCellStyleToday;} -this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()];if(this.isDateOOM(workingDate)){cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth;}else{YAHOO.util.Dom.addClass(cell,"wd"+workingDate.getDay());YAHOO.util.Dom.addClass(cell,"d"+workingDate.getDate());for(var s=0;s=d1.getTime()&&workingDate.getTime()<=d2.getTime()){renderer=rArray[2];if(workingDate.getTime()==d2.getTime()){this.renderStack.splice(s,1);}} -break;case YAHOO.widget.Calendar.WEEKDAY:var weekday=rArray[1][0];if(workingDate.getDay()+1==weekday){renderer=rArray[2];} -break;case YAHOO.widget.Calendar.MONTH:month=rArray[1][0];if(workingDate.getMonth()+1==month){renderer=rArray[2];} -break;} -if(renderer){cellRenderers[cellRenderers.length]=renderer;}}} -if(this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()])>-1){cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected;} -var mindate=this.cfg.getProperty("mindate");var maxdate=this.cfg.getProperty("maxdate");if(mindate){mindate=YAHOO.widget.DateMath.clearTime(mindate);} -if(maxdate){maxdate=YAHOO.widget.DateMath.clearTime(maxdate);} -if((mindate&&(workingDate.getTime()maxdate.getTime()))){cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate;}else{cellRenderers[cellRenderers.length]=cal.styleCellDefault;cellRenderers[cellRenderers.length]=cal.renderCellDefault;} -for(var x=0;x=0&&i<=6){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TOP);} -if((i%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_LEFT);} -if(((i+1)%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RIGHT);} -var postDays=this.postMonthDays;if(postDays>=7&&this.cfg.getProperty("HIDE_BLANK_WEEKS")){var blankWeeks=Math.floor(postDays/7);for(var p=0;p=((this.preMonthDays+postDays+this.monthDays)-7)){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_BOTTOM);} -html[html.length]=tempDiv.innerHTML;i++;} -if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html=this.renderRowFooter(weekNum,html);} -html[html.length]='';}} -html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderFooter=function(html){return html;};YAHOO.widget.Calendar.prototype.render=function(){this.beforeRenderEvent.fire();var workingDate=YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate"));this.resetRenderers();this.cellDates.length=0;YAHOO.util.Event.purgeElement(this.oDomContainer,true);var html=[];html[html.length]='';html=this.renderHeader(html);html=this.renderBody(workingDate,html);html=this.renderFooter(html);html[html.length]='
';this.oDomContainer.innerHTML=html.join("\n");this.applyListeners();this.cells=this.oDomContainer.getElementsByTagName("td");this.cfg.refireEvent("title");this.cfg.refireEvent("close");this.cfg.refireEvent("iframe");this.renderEvent.fire();};YAHOO.widget.Calendar.prototype.applyListeners=function(){var root=this.oDomContainer;var cal=this.parent||this;var linkLeft,linkRight;linkLeft=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT,"a",root);linkRight=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT,"a",root);if(linkLeft){this.linkLeft=linkLeft[0];YAHOO.util.Event.addListener(this.linkLeft,"mousedown",cal.previousMonth,cal,true);} -if(linkRight){this.linkRight=linkRight[0];YAHOO.util.Event.addListener(this.linkRight,"mousedown",cal.nextMonth,cal,true);} -if(this.domEventMap){var el,elements;for(var cls in this.domEventMap){if(this.domEventMap.hasOwnProperty(cls)){var items=this.domEventMap[cls];if(!(items instanceof Array)){items=[items];} -for(var i=0;i'+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderRowFooter=function(weekNum,html){html[html.length]=''+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderCellDefault=function(workingDate,cell){cell.innerHTML=''+this.buildDayLabel(workingDate)+"";};YAHOO.widget.Calendar.prototype.styleCellDefault=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTABLE);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT1);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT2);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT3);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT4);};YAHOO.widget.Calendar.prototype.renderCellStyleToday=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TODAY);};YAHOO.widget.Calendar.prototype.renderCellStyleSelected=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTED);};YAHOO.widget.Calendar.prototype.renderCellNotThisMonth=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_OOM);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.renderBodyCellRestricted=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL);YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RESTRICTED);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.addMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.addYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.nextMonth=function(){this.addMonths(1);};YAHOO.widget.Calendar.prototype.previousMonth=function(){this.subtractMonths(1);};YAHOO.widget.Calendar.prototype.nextYear=function(){this.addYears(1);};YAHOO.widget.Calendar.prototype.previousYear=function(){this.subtractYears(1);};YAHOO.widget.Calendar.prototype.reset=function(){this.cfg.resetProperty("selected");this.cfg.resetProperty("pagedate");this.resetEvent.fire();};YAHOO.widget.Calendar.prototype.clear=function(){this.cfg.setProperty("selected",[]);this.cfg.setProperty("pagedate",new Date(this.today.getTime()));this.clearEvent.fire();};YAHOO.widget.Calendar.prototype.select=function(date){this.beforeSelectEvent.fire();var selected=this.cfg.getProperty("selected");var aToBeSelected=this._toFieldArray(date);for(var a=0;a-1){if(this.cfg.getProperty("pagedate").getMonth()==dCellDate.getMonth()&&this.cfg.getProperty("pagedate").getFullYear()==dCellDate.getFullYear()){YAHOO.util.Dom.removeClass(cell,this.Style.CSS_CELL_SELECTED);} -selected.splice(cellDateIndex,1);} -if(this.parent){this.parent.cfg.setProperty("selected",selected);}else{this.cfg.setProperty("selected",selected);} -this.deselectEvent.fire(selectDate);return this.getSelectedDates();};YAHOO.widget.Calendar.prototype.deselectAll=function(){this.beforeDeselectEvent.fire();var selected=this.cfg.getProperty("selected");var count=selected.length;var sel=selected.concat();if(this.parent){this.parent.cfg.setProperty("selected",[]);}else{this.cfg.setProperty("selected",[]);} -if(count>0){this.deselectEvent.fire(sel);} -return this.getSelectedDates();};YAHOO.widget.Calendar.prototype._toFieldArray=function(date){var returnDate=[];if(date instanceof Date){returnDate=[[date.getFullYear(),date.getMonth()+1,date.getDate()]];}else if(typeof date=='string'){returnDate=this._parseDates(date);}else if(date instanceof Array){for(var i=0;i0){this.init(id,containerId,config);}};YAHOO.widget.CalendarGroup.prototype.init=function(id,containerId,config){this.initEvents();this.initStyles();this.pages=[];this.id=id;this.containerId=containerId;this.oDomContainer=document.getElementById(containerId);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_MULTI_UP);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.setupConfig();if(config){this.cfg.applyConfig(config,true);} -this.cfg.fireQueue();if(this.browser=="opera"){var fixWidth=function(){var startW=this.oDomContainer.offsetWidth;var w=0;for(var p=0;p0){this.oDomContainer.style.width=w+"px";}};this.renderEvent.subscribe(fixWidth,this,true);}};YAHOO.widget.CalendarGroup.prototype.setupConfig=function(){this.cfg.addProperty("pages",{value:2,validator:this.cfg.checkNumber,handler:this.configPages});this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.delegateConfig});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("maxdate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.delegateConfig});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.delegateConfig});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.delegateConfig});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.delegateConfig});this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.delegateConfig});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.delegateConfig});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.delegateConfig});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.delegateConfig});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.delegateConfig});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.delegateConfig,validator:this.cfg.checkNumber});};YAHOO.widget.CalendarGroup.prototype.initEvents=function(){var me=this;var sub=function(fn,obj,bOverride){for(var p=0;p0){year+=1;} -cal.setYear(year);}};YAHOO.widget.CalendarGroup.prototype.render=function(){this.renderHeader();for(var p=0;p=0;--p){var cal=this.pages[p];cal.previousMonth();}};YAHOO.widget.CalendarGroup.prototype.nextYear=function(){for(var p=0;p11){while(newMonth>11){newMonth-=12;years+=1;}} +d.setMonth(newMonth);d.setFullYear(date.getFullYear()+years);break;case this.DAY:d.setDate(date.getDate()+amount);break;case this.YEAR:d.setFullYear(date.getFullYear()+amount);break;case this.WEEK:d.setDate(date.getDate()+(amount*7));break;} +return d;},subtract:function(date,field,amount){return this.add(date,field,(amount*-1));},before:function(date,compareTo){var ms=compareTo.getTime();if(date.getTime()ms){return true;}else{return false;}},between:function(date,dateBegin,dateEnd){if(this.after(date,dateBegin)&&this.before(date,dateEnd)){return true;}else{return false;}},getJan1:function(calendarYear){return new Date(calendarYear,0,1);},getDayOffset:function(date,calendarYear){var beginYear=this.getJan1(calendarYear);var dayOffset=Math.ceil((date.getTime()-beginYear.getTime())/this.ONE_DAY_MS);return dayOffset;},getWeekNumber:function(date,calendarYear){date=this.clearTime(date);var nearestThurs=new Date(date.getTime()+(4*this.ONE_DAY_MS)-((date.getDay())*this.ONE_DAY_MS));var jan1=new Date(nearestThurs.getFullYear(),0,1);var dayOfYear=((nearestThurs.getTime()-jan1.getTime())/this.ONE_DAY_MS)-1;var weekNum=Math.ceil((dayOfYear)/7);return weekNum;},isYearOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getFullYear()!=weekBeginDate.getFullYear()){overlaps=true;} +return overlaps;},isMonthOverlapWeek:function(weekBeginDate){var overlaps=false;var nextWeek=this.add(weekBeginDate,this.DAY,6);if(nextWeek.getMonth()!=weekBeginDate.getMonth()){overlaps=true;} +return overlaps;},findMonthStart:function(date){var start=new Date(date.getFullYear(),date.getMonth(),1);return start;},findMonthEnd:function(date){var start=this.findMonthStart(date);var nextMonth=this.add(start,this.MONTH,1);var end=this.subtract(nextMonth,this.DAY,1);return end;},clearTime:function(date){date.setHours(12,0,0,0);return date;}};YAHOO.widget.Calendar=function(id,containerId,config){this.init(id,containerId,config);};YAHOO.widget.Calendar.IMG_ROOT=(window.location.href.toLowerCase().indexOf("https")===0?"https://a248.e.akamai.net/sec.yimg.com/i/":"http://us.i1.yimg.com/us.yimg.com/i/");YAHOO.widget.Calendar.DATE="D";YAHOO.widget.Calendar.MONTH_DAY="MD";YAHOO.widget.Calendar.WEEKDAY="WD";YAHOO.widget.Calendar.RANGE="R";YAHOO.widget.Calendar.MONTH="M";YAHOO.widget.Calendar.DISPLAY_DAYS=42;YAHOO.widget.Calendar.STOP_RENDER="S";YAHOO.widget.Calendar.prototype={Config:null,parent:null,index:-1,cells:null,cellDates:null,id:null,oDomContainer:null,today:null,renderStack:null,_renderStack:null,_pageDate:null,_selectedDates:null,domEventMap:null};YAHOO.widget.Calendar.prototype.init=function(id,containerId,config){this.initEvents();this.today=new Date();YAHOO.widget.DateMath.clearTime(this.today);this.id=id;this.oDomContainer=document.getElementById(containerId);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.initStyles();YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,this.Style.CSS_SINGLE);this.cellDates=[];this.cells=[];this.renderStack=[];this._renderStack=[];this.setupConfig();if(config){this.cfg.applyConfig(config,true);} +this.cfg.fireQueue();};YAHOO.widget.Calendar.prototype.configIframe=function(type,args,obj){var useIframe=args[0];if(YAHOO.util.Dom.inDocument(this.oDomContainer)){if(useIframe){var pos=YAHOO.util.Dom.getStyle(this.oDomContainer,"position");if(this.browser=="ie"&&(pos=="absolute"||pos=="relative")){if(!YAHOO.util.Dom.inDocument(this.iframe)){this.iframe=document.createElement("iframe");this.iframe.src="javascript:false;";YAHOO.util.Dom.setStyle(this.iframe,"opacity","0");this.oDomContainer.insertBefore(this.iframe,this.oDomContainer.firstChild);}}}else{if(this.iframe){if(this.iframe.parentNode){this.iframe.parentNode.removeChild(this.iframe);} +this.iframe=null;}}}};YAHOO.widget.Calendar.prototype.configTitle=function(type,args,obj){var title=args[0];var close=this.cfg.getProperty("close");var titleDiv;if(title&&title!==""){titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||document.createElement("div");titleDiv.className=YAHOO.widget.CalendarGroup.CSS_2UPTITLE;titleDiv.innerHTML=title;this.oDomContainer.insertBefore(titleDiv,this.oDomContainer.firstChild);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{titleDiv=YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE,"div",this.oDomContainer)[0]||null;if(titleDiv){YAHOO.util.Event.purgeElement(titleDiv);this.oDomContainer.removeChild(titleDiv);} +if(!close){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.configClose=function(type,args,obj){var close=args[0];var title=this.cfg.getProperty("title");var linkClose;if(close===true){linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||document.createElement("a");linkClose.href="javascript:void(null);";linkClose.className="link-close";YAHOO.util.Event.addListener(linkClose,"click",this.hide,this,true);var imgClose=document.createElement("img");imgClose.src=YAHOO.widget.Calendar.IMG_ROOT+"us/my/bn/x_d.gif";imgClose.className=YAHOO.widget.CalendarGroup.CSS_2UPCLOSE;linkClose.appendChild(imgClose);this.oDomContainer.appendChild(linkClose);YAHOO.util.Dom.addClass(this.oDomContainer,"withtitle");}else{linkClose=YAHOO.util.Dom.getElementsByClassName("link-close","a",this.oDomContainer)[0]||null;if(linkClose){YAHOO.util.Event.purgeElement(linkClose);this.oDomContainer.removeChild(linkClose);} +if(!title||title===""){YAHOO.util.Dom.removeClass(this.oDomContainer,"withtitle");}}};YAHOO.widget.Calendar.prototype.initEvents=function(){this.beforeSelectEvent=new YAHOO.util.CustomEvent("beforeSelect");this.selectEvent=new YAHOO.util.CustomEvent("select");this.beforeDeselectEvent=new YAHOO.util.CustomEvent("beforeDeselect");this.deselectEvent=new YAHOO.util.CustomEvent("deselect");this.changePageEvent=new YAHOO.util.CustomEvent("changePage");this.beforeRenderEvent=new YAHOO.util.CustomEvent("beforeRender");this.renderEvent=new YAHOO.util.CustomEvent("render");this.resetEvent=new YAHOO.util.CustomEvent("reset");this.clearEvent=new YAHOO.util.CustomEvent("clear");this.beforeSelectEvent.subscribe(this.onBeforeSelect,this,true);this.selectEvent.subscribe(this.onSelect,this,true);this.beforeDeselectEvent.subscribe(this.onBeforeDeselect,this,true);this.deselectEvent.subscribe(this.onDeselect,this,true);this.changePageEvent.subscribe(this.onChangePage,this,true);this.renderEvent.subscribe(this.onRender,this,true);this.resetEvent.subscribe(this.onReset,this,true);this.clearEvent.subscribe(this.onClear,this,true);};YAHOO.widget.Calendar.prototype.doSelectCell=function(e,cal){var target=YAHOO.util.Event.getTarget(e);var cell,index,d,date;while(target.tagName.toLowerCase()!="td"&&!YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} +cell=target;if(YAHOO.util.Dom.hasClass(cell,cal.Style.CSS_CELL_SELECTABLE)){index=cell.id.split("cell")[1];d=cal.cellDates[index];date=new Date(d[0],d[1]-1,d[2]);var link;if(cal.Options.MULTI_SELECT){link=cell.getElementsByTagName("a")[0];if(link){link.blur();} +var cellDate=cal.cellDates[index];var cellDateIndex=cal._indexOfSelectedFieldArray(cellDate);if(cellDateIndex>-1){cal.deselectCell(index);}else{cal.selectCell(index);}}else{link=cell.getElementsByTagName("a")[0];if(link){link.blur();} +cal.selectCell(index);}}};YAHOO.widget.Calendar.prototype.doCellMouseOver=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} +while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} +if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.addClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.doCellMouseOut=function(e,cal){var target;if(e){target=YAHOO.util.Event.getTarget(e);}else{target=this;} +while(target.tagName.toLowerCase()!="td"){target=target.parentNode;if(target.tagName.toLowerCase()=="html"){return;}} +if(YAHOO.util.Dom.hasClass(target,cal.Style.CSS_CELL_SELECTABLE)){YAHOO.util.Dom.removeClass(target,cal.Style.CSS_CELL_HOVER);}};YAHOO.widget.Calendar.prototype.setupConfig=function(){this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.configSelected});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.configIframe,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.configMinDate});this.cfg.addProperty("maxdate",{value:null,handler:this.configMaxDate});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.configOptions,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.configOptions,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.configOptions});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.configOptions});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.configLocale});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.configLocale});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.configLocale});var refreshLocale=function(){this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};this.cfg.subscribeToConfigEvent("START_WEEKDAY",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("MONTHS_LONG",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM",refreshLocale,this,true);this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG",refreshLocale,this,true);this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.configLocaleValues});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.configLocaleValues});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.configLocale});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.configLocale});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.configLocale});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.configLocale,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.configLocale,validator:this.cfg.checkNumber});};YAHOO.widget.Calendar.prototype.configPageDate=function(type,args,obj){var val=args[0];var month,year,aMonthYear;if(val){if(val instanceof Date){val=YAHOO.widget.DateMath.findMonthStart(val);this.cfg.setProperty("pagedate",val,true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");} +return;}else{aMonthYear=val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER"));month=parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1],10)-1;year=parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1],10);}}else{month=this.today.getMonth();year=this.today.getFullYear();} +this.cfg.setProperty("pagedate",new Date(year,month,1),true);if(!this._pageDate){this._pageDate=this.cfg.getProperty("pagedate");}};YAHOO.widget.Calendar.prototype.configMinDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("mindate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configMaxDate=function(type,args,obj){var val=args[0];if(typeof val=='string'){val=this._parseDate(val);this.cfg.setProperty("maxdate",new Date(val[0],(val[1]-1),val[2]));}};YAHOO.widget.Calendar.prototype.configSelected=function(type,args,obj){var selected=args[0];if(selected){if(typeof selected=='string'){this.cfg.setProperty("selected",this._parseDates(selected),true);}} +if(!this._selectedDates){this._selectedDates=this.cfg.getProperty("selected");}};YAHOO.widget.Calendar.prototype.configOptions=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Options[type]=val;};YAHOO.widget.Calendar.prototype.configLocale=function(type,args,obj){type=type.toUpperCase();var val=args[0];this.Locale[type]=val;this.cfg.refireEvent("LOCALE_MONTHS");this.cfg.refireEvent("LOCALE_WEEKDAYS");};YAHOO.widget.Calendar.prototype.configLocaleValues=function(type,args,obj){type=type.toUpperCase();var val=args[0];switch(type){case"LOCALE_MONTHS":switch(val){case"short":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_SHORT").concat();break;case"long":this.Locale.LOCALE_MONTHS=this.cfg.getProperty("MONTHS_LONG").concat();break;} +break;case"LOCALE_WEEKDAYS":switch(val){case"1char":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_1CHAR").concat();break;case"short":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_SHORT").concat();break;case"medium":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_MEDIUM").concat();break;case"long":this.Locale.LOCALE_WEEKDAYS=this.cfg.getProperty("WEEKDAYS_LONG").concat();break;} +var START_WEEKDAY=this.cfg.getProperty("START_WEEKDAY");if(START_WEEKDAY>0){for(var w=0;w';html[html.length]='
';var renderLeft,renderRight=false;if(this.parent){if(this.index===0){renderLeft=true;} +if(this.index==(this.parent.cfg.getProperty("pages")-1)){renderRight=true;}}else{renderLeft=true;renderRight=true;} +var cal=this.parent||this;if(renderLeft){html[html.length]=' ';} +html[html.length]=this.buildMonthLabel();if(renderRight){html[html.length]=' ';} +html[html.length]='
';html[html.length]='';html[html.length]='';if(this.cfg.getProperty("SHOW_WEEKDAYS")){html=this.buildWeekdays(html);} +html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.buildWeekdays=function(html){html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html[html.length]=' ';} +for(var i=0;i'+this.Locale.LOCALE_WEEKDAYS[i]+'';} +if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html[html.length]=' ';} +html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderBody=function(workingDate,html){var startDay=this.cfg.getProperty("START_WEEKDAY");this.preMonthDays=workingDate.getDay();if(startDay>0){this.preMonthDays-=startDay;} +if(this.preMonthDays<0){this.preMonthDays+=7;} +this.monthDays=YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate();this.postMonthDays=YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays;workingDate=YAHOO.widget.DateMath.subtract(workingDate,YAHOO.widget.DateMath.DAY,this.preMonthDays);var useDate,weekNum,weekClass;useDate=this.cfg.getProperty("pagedate");html[html.length]='';var i=0;var tempDiv=document.createElement("div");var cell=document.createElement("td");tempDiv.appendChild(cell);var jan1=new Date(useDate.getFullYear(),0,1);var cal=this.parent||this;for(var r=0;r<6;r++){weekNum=YAHOO.widget.DateMath.getWeekNumber(workingDate,useDate.getFullYear(),startDay);weekClass="w"+weekNum;if(r!==0&&this.isDateOOM(workingDate)&&this.cfg.getProperty("HIDE_BLANK_WEEKS")===true){break;}else{html[html.length]='';if(this.cfg.getProperty("SHOW_WEEK_HEADER")){html=this.renderRowHeader(weekNum,html);} +for(var d=0;d<7;d++){var cellRenderers=[];this.clearElement(cell);YAHOO.util.Dom.addClass(cell,"calcell");cell.id=this.id+"_cell"+i;cell.innerHTML=i;var renderer=null;if(workingDate.getFullYear()==this.today.getFullYear()&&workingDate.getMonth()==this.today.getMonth()&&workingDate.getDate()==this.today.getDate()){cellRenderers[cellRenderers.length]=cal.renderCellStyleToday;} +this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()];if(this.isDateOOM(workingDate)){cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth;}else{YAHOO.util.Dom.addClass(cell,"wd"+workingDate.getDay());YAHOO.util.Dom.addClass(cell,"d"+workingDate.getDate());for(var s=0;s=d1.getTime()&&workingDate.getTime()<=d2.getTime()){renderer=rArray[2];if(workingDate.getTime()==d2.getTime()){this.renderStack.splice(s,1);}} +break;case YAHOO.widget.Calendar.WEEKDAY:var weekday=rArray[1][0];if(workingDate.getDay()+1==weekday){renderer=rArray[2];} +break;case YAHOO.widget.Calendar.MONTH:month=rArray[1][0];if(workingDate.getMonth()+1==month){renderer=rArray[2];} +break;} +if(renderer){cellRenderers[cellRenderers.length]=renderer;}}} +if(this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()])>-1){cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected;} +var mindate=this.cfg.getProperty("mindate");var maxdate=this.cfg.getProperty("maxdate");if(mindate){mindate=YAHOO.widget.DateMath.clearTime(mindate);} +if(maxdate){maxdate=YAHOO.widget.DateMath.clearTime(maxdate);} +if((mindate&&(workingDate.getTime()maxdate.getTime()))){cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate;}else{cellRenderers[cellRenderers.length]=cal.styleCellDefault;cellRenderers[cellRenderers.length]=cal.renderCellDefault;} +for(var x=0;x=0&&i<=6){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TOP);} +if((i%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_LEFT);} +if(((i+1)%7)===0){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RIGHT);} +var postDays=this.postMonthDays;if(postDays>=7&&this.cfg.getProperty("HIDE_BLANK_WEEKS")){var blankWeeks=Math.floor(postDays/7);for(var p=0;p=((this.preMonthDays+postDays+this.monthDays)-7)){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_BOTTOM);} +html[html.length]=tempDiv.innerHTML;i++;} +if(this.cfg.getProperty("SHOW_WEEK_FOOTER")){html=this.renderRowFooter(weekNum,html);} +html[html.length]='';}} +html[html.length]='';return html;};YAHOO.widget.Calendar.prototype.renderFooter=function(html){return html;};YAHOO.widget.Calendar.prototype.render=function(){this.beforeRenderEvent.fire();var workingDate=YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate"));this.resetRenderers();this.cellDates.length=0;YAHOO.util.Event.purgeElement(this.oDomContainer,true);var html=[];html[html.length]='';html=this.renderHeader(html);html=this.renderBody(workingDate,html);html=this.renderFooter(html);html[html.length]='
';this.oDomContainer.innerHTML=html.join("\n");this.applyListeners();this.cells=this.oDomContainer.getElementsByTagName("td");this.cfg.refireEvent("title");this.cfg.refireEvent("close");this.cfg.refireEvent("iframe");this.renderEvent.fire();};YAHOO.widget.Calendar.prototype.applyListeners=function(){var root=this.oDomContainer;var cal=this.parent||this;var linkLeft,linkRight;linkLeft=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT,"a",root);linkRight=YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT,"a",root);if(linkLeft){this.linkLeft=linkLeft[0];YAHOO.util.Event.addListener(this.linkLeft,"mousedown",cal.previousMonth,cal,true);} +if(linkRight){this.linkRight=linkRight[0];YAHOO.util.Event.addListener(this.linkRight,"mousedown",cal.nextMonth,cal,true);} +if(this.domEventMap){var el,elements;for(var cls in this.domEventMap){if(this.domEventMap.hasOwnProperty(cls)){var items=this.domEventMap[cls];if(!(items instanceof Array)){items=[items];} +for(var i=0;i'+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderRowFooter=function(weekNum,html){html[html.length]=''+weekNum+'';return html;};YAHOO.widget.Calendar.prototype.renderCellDefault=function(workingDate,cell){cell.innerHTML=''+this.buildDayLabel(workingDate)+"";};YAHOO.widget.Calendar.prototype.styleCellDefault=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTABLE);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT1);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT2);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT3);};YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_HIGHLIGHT4);};YAHOO.widget.Calendar.prototype.renderCellStyleToday=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_TODAY);};YAHOO.widget.Calendar.prototype.renderCellStyleSelected=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_SELECTED);};YAHOO.widget.Calendar.prototype.renderCellNotThisMonth=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_OOM);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.renderBodyCellRestricted=function(workingDate,cell){YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL);YAHOO.util.Dom.addClass(cell,this.Style.CSS_CELL_RESTRICTED);cell.innerHTML=workingDate.getDate();return YAHOO.widget.Calendar.STOP_RENDER;};YAHOO.widget.Calendar.prototype.addMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractMonths=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.MONTH,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.addYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.subtractYears=function(count){this.cfg.setProperty("pagedate",YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"),YAHOO.widget.DateMath.YEAR,count));this.resetRenderers();this.changePageEvent.fire();};YAHOO.widget.Calendar.prototype.nextMonth=function(){this.addMonths(1);};YAHOO.widget.Calendar.prototype.previousMonth=function(){this.subtractMonths(1);};YAHOO.widget.Calendar.prototype.nextYear=function(){this.addYears(1);};YAHOO.widget.Calendar.prototype.previousYear=function(){this.subtractYears(1);};YAHOO.widget.Calendar.prototype.reset=function(){this.cfg.resetProperty("selected");this.cfg.resetProperty("pagedate");this.resetEvent.fire();};YAHOO.widget.Calendar.prototype.clear=function(){this.cfg.setProperty("selected",[]);this.cfg.setProperty("pagedate",new Date(this.today.getTime()));this.clearEvent.fire();};YAHOO.widget.Calendar.prototype.select=function(date){this.beforeSelectEvent.fire();var selected=this.cfg.getProperty("selected");var aToBeSelected=this._toFieldArray(date);for(var a=0;a-1){if(this.cfg.getProperty("pagedate").getMonth()==dCellDate.getMonth()&&this.cfg.getProperty("pagedate").getFullYear()==dCellDate.getFullYear()){YAHOO.util.Dom.removeClass(cell,this.Style.CSS_CELL_SELECTED);} +selected.splice(cellDateIndex,1);} +if(this.parent){this.parent.cfg.setProperty("selected",selected);}else{this.cfg.setProperty("selected",selected);} +this.deselectEvent.fire(selectDate);return this.getSelectedDates();};YAHOO.widget.Calendar.prototype.deselectAll=function(){this.beforeDeselectEvent.fire();var selected=this.cfg.getProperty("selected");var count=selected.length;var sel=selected.concat();if(this.parent){this.parent.cfg.setProperty("selected",[]);}else{this.cfg.setProperty("selected",[]);} +if(count>0){this.deselectEvent.fire(sel);} +return this.getSelectedDates();};YAHOO.widget.Calendar.prototype._toFieldArray=function(date){var returnDate=[];if(date instanceof Date){returnDate=[[date.getFullYear(),date.getMonth()+1,date.getDate()]];}else if(typeof date=='string'){returnDate=this._parseDates(date);}else if(date instanceof Array){for(var i=0;i0){this.init(id,containerId,config);}};YAHOO.widget.CalendarGroup.prototype.init=function(id,containerId,config){this.initEvents();this.initStyles();this.pages=[];this.id=id;this.containerId=containerId;this.oDomContainer=document.getElementById(containerId);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_CONTAINER);YAHOO.util.Dom.addClass(this.oDomContainer,YAHOO.widget.CalendarGroup.CSS_MULTI_UP);this.cfg=new YAHOO.util.Config(this);this.Options={};this.Locale={};this.setupConfig();if(config){this.cfg.applyConfig(config,true);} +this.cfg.fireQueue();if(this.browser=="opera"){var fixWidth=function(){var startW=this.oDomContainer.offsetWidth;var w=0;for(var p=0;p0){this.oDomContainer.style.width=w+"px";}};this.renderEvent.subscribe(fixWidth,this,true);}};YAHOO.widget.CalendarGroup.prototype.setupConfig=function(){this.cfg.addProperty("pages",{value:2,validator:this.cfg.checkNumber,handler:this.configPages});this.cfg.addProperty("pagedate",{value:new Date(),handler:this.configPageDate});this.cfg.addProperty("selected",{value:[],handler:this.delegateConfig});this.cfg.addProperty("title",{value:"",handler:this.configTitle});this.cfg.addProperty("close",{value:false,handler:this.configClose});this.cfg.addProperty("iframe",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("mindate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("maxdate",{value:null,handler:this.delegateConfig});this.cfg.addProperty("MULTI_SELECT",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("START_WEEKDAY",{value:0,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("SHOW_WEEKDAYS",{value:true,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_HEADER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("SHOW_WEEK_FOOTER",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("HIDE_BLANK_WEEKS",{value:false,handler:this.delegateConfig,validator:this.cfg.checkBoolean});this.cfg.addProperty("NAV_ARROW_LEFT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/callt.gif",handler:this.delegateConfig});this.cfg.addProperty("NAV_ARROW_RIGHT",{value:YAHOO.widget.Calendar.IMG_ROOT+"us/tr/calrt.gif",handler:this.delegateConfig});this.cfg.addProperty("MONTHS_SHORT",{value:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],handler:this.delegateConfig});this.cfg.addProperty("MONTHS_LONG",{value:["January","February","March","April","May","June","July","August","September","October","November","December"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_1CHAR",{value:["S","M","T","W","T","F","S"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_SHORT",{value:["Su","Mo","Tu","We","Th","Fr","Sa"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_MEDIUM",{value:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],handler:this.delegateConfig});this.cfg.addProperty("WEEKDAYS_LONG",{value:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],handler:this.delegateConfig});this.cfg.addProperty("LOCALE_MONTHS",{value:"long",handler:this.delegateConfig});this.cfg.addProperty("LOCALE_WEEKDAYS",{value:"short",handler:this.delegateConfig});this.cfg.addProperty("DATE_DELIMITER",{value:",",handler:this.delegateConfig});this.cfg.addProperty("DATE_FIELD_DELIMITER",{value:"/",handler:this.delegateConfig});this.cfg.addProperty("DATE_RANGE_DELIMITER",{value:"-",handler:this.delegateConfig});this.cfg.addProperty("MY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MY_YEAR_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MD_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_MONTH_POSITION",{value:1,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_DAY_POSITION",{value:2,handler:this.delegateConfig,validator:this.cfg.checkNumber});this.cfg.addProperty("MDY_YEAR_POSITION",{value:3,handler:this.delegateConfig,validator:this.cfg.checkNumber});};YAHOO.widget.CalendarGroup.prototype.initEvents=function(){var me=this;var sub=function(fn,obj,bOverride){for(var p=0;p0){year+=1;} +cal.setYear(year);}};YAHOO.widget.CalendarGroup.prototype.render=function(){this.renderHeader();for(var p=0;p=0;--p){var cal=this.pages[p];cal.previousMonth();}};YAHOO.widget.CalendarGroup.prototype.nextYear=function(){for(var p=0;p 11) { - while (newMonth > 11) { - newMonth -= 12; - years += 1; - } - } - - d.setMonth(newMonth); - d.setFullYear(date.getFullYear() + years); - break; - case this.DAY: - d.setDate(date.getDate() + amount); - break; - case this.YEAR: - d.setFullYear(date.getFullYear() + amount); - break; - case this.WEEK: - d.setDate(date.getDate() + (amount * 7)); - break; - } - return d; - }, - - /** - * Subtracts the specified amount of time from the this instance. - * @method subtract - * @param {Date} date The JavaScript Date object to perform subtraction on - * @param {Number} field The this field constant to be used for performing subtraction. - * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. - * @return {Date} The resulting Date object - */ - subtract : function(date, field, amount) { - return this.add(date, field, (amount*-1)); - }, - - /** - * Determines whether a given date is before another date on the calendar. - * @method before - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs before the compared date; false if not. - */ - before : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() < ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is after another date on the calendar. - * @method after - * @param {Date} date The Date object to compare with the compare argument - * @param {Date} compareTo The Date object to use for the comparison - * @return {Boolean} true if the date occurs after the compared date; false if not. - */ - after : function(date, compareTo) { - var ms = compareTo.getTime(); - if (date.getTime() > ms) { - return true; - } else { - return false; - } - }, - - /** - * Determines whether a given date is between two other dates on the calendar. - * @method between - * @param {Date} date The date to check for - * @param {Date} dateBegin The start of the range - * @param {Date} dateEnd The end of the range - * @return {Boolean} true if the date occurs between the compared dates; false if not. - */ - between : function(date, dateBegin, dateEnd) { - if (this.after(date, dateBegin) && this.before(date, dateEnd)) { - return true; - } else { - return false; - } - }, - - /** - * Retrieves a JavaScript Date object representing January 1 of any given year. - * @method getJan1 - * @param {Number} calendarYear The calendar year for which to retrieve January 1 - * @return {Date} January 1 of the calendar year specified. - */ - getJan1 : function(calendarYear) { - return new Date(calendarYear,0,1); - }, - - /** - * Calculates the number of days the specified date is from January 1 of the specified calendar year. - * Passing January 1 to this function would return an offset value of zero. - * @method getDayOffset - * @param {Date} date The JavaScript date for which to find the offset - * @param {Number} calendarYear The calendar year to use for determining the offset - * @return {Number} The number of days since January 1 of the given year - */ - getDayOffset : function(date, calendarYear) { - var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. - - // Find the number of days the passed in date is away from the calendar year start - var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); - return dayOffset; - }, - - /** - * Calculates the week number for the given date. This function assumes that week 1 is the - * week in which January 1 appears, regardless of whether the week consists of a full 7 days. - * The calendar year can be specified to help find what a the week number would be for a given - * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or - * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction - * easily. - * @method getWeekNumber - * @param {Date} date The JavaScript date for which to find the week number - * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is - * the calendar year of parameter "date". - * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). - * @return {Number} The week number of the given date. - */ - getWeekNumber : function(date, calendarYear) { - date = this.clearTime(date); - var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); - - var jan1 = new Date(nearestThurs.getFullYear(),0,1); - var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; - - var weekNum = Math.ceil((dayOfYear)/ 7); - return weekNum; - }, - - /** - * Determines if a given week overlaps two different years. - * @method isYearOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different years. - */ - isYearOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Determines if a given week overlaps two different months. - * @method isMonthOverlapWeek - * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. - * @return {Boolean} true if the date overlaps two different months. - */ - isMonthOverlapWeek : function(weekBeginDate) { - var overlaps = false; - var nextWeek = this.add(weekBeginDate, this.DAY, 6); - if (nextWeek.getMonth() != weekBeginDate.getMonth()) { - overlaps = true; - } - return overlaps; - }, - - /** - * Gets the first day of a month containing a given date. - * @method findMonthStart - * @param {Date} date The JavaScript Date used to calculate the month start - * @return {Date} The JavaScript Date representing the first day of the month - */ - findMonthStart : function(date) { - var start = new Date(date.getFullYear(), date.getMonth(), 1); - return start; - }, - - /** - * Gets the last day of a month containing a given date. - * @method findMonthEnd - * @param {Date} date The JavaScript Date used to calculate the month end - * @return {Date} The JavaScript Date representing the last day of the month - */ - findMonthEnd : function(date) { - var start = this.findMonthStart(date); - var nextMonth = this.add(start, this.MONTH, 1); - var end = this.subtract(nextMonth, this.DAY, 1); - return end; - }, - - /** - * Clears the time fields from a given date, effectively setting the time to midnight. - * @method clearTime - * @param {Date} date The JavaScript Date for which the time fields will be cleared - * @return {Date} The JavaScript Date cleared of all time fields - */ - clearTime : function(date) { - date.setHours(12,0,0,0); - return date; - } -}; - -/** -* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. -* @module Calendar -* @title Calendar Widget -* @namespace YAHOO.widget -* @requires yahoo,dom,event -*/ - -/** -* Calendar is the base class for the Calendar widget. In its most basic -* implementation, it has the ability to render a calendar widget on the page -* that can be manipulated to select a single date, move back and forth between -* months and years. -*

To construct the placeholder for the calendar widget, the code is as -* follows: -*

-* <div id="cal1Container"></div> -* -* Note that the table can be replaced with any kind of element. -*

-* @namespace YAHOO.widget -* @class Calendar -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar = function(id, containerId, config) { - this.init(id, containerId, config); -}; - -/** -* The path to be used for images loaded for the Calendar -* @property YAHOO.widget.Calendar.IMG_ROOT -* @static -* @type String -*/ -YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); - -/** -* Type constant used for renderers to represent an individual date (M/D/Y) -* @property YAHOO.widget.Calendar.DATE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.DATE = "D"; - -/** -* Type constant used for renderers to represent an individual date across any year (M/D) -* @property YAHOO.widget.Calendar.MONTH_DAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH_DAY = "MD"; - -/** -* Type constant used for renderers to represent a weekday -* @property YAHOO.widget.Calendar.WEEKDAY -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.WEEKDAY = "WD"; - -/** -* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) -* @property YAHOO.widget.Calendar.RANGE -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.RANGE = "R"; - -/** -* Type constant used for renderers to represent a month across any year -* @property YAHOO.widget.Calendar.MONTH -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.MONTH = "M"; - -/** -* Constant that represents the total number of date cells that are displayed in a given month -* @property YAHOO.widget.Calendar.DISPLAY_DAYS -* @static -* @final -* @type Number -*/ -YAHOO.widget.Calendar.DISPLAY_DAYS = 42; - -/** -* Constant used for halting the execution of the remainder of the render stack -* @property YAHOO.widget.Calendar.STOP_RENDER -* @static -* @final -* @type String -*/ -YAHOO.widget.Calendar.STOP_RENDER = "S"; - -YAHOO.widget.Calendar.prototype = { - - /** - * The configuration object used to set up the calendars various locale and style options. - * @property Config - * @private - * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. - * @type Object - */ - Config : null, - - /** - * The parent CalendarGroup, only to be set explicitly by the parent group - * @property parent - * @type CalendarGroup - */ - parent : null, - - /** - * The index of this item in the parent group - * @property index - * @type Number - */ - index : -1, - - /** - * The collection of calendar table cells - * @property cells - * @type HTMLTableCellElement[] - */ - cells : null, - - /** - * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. - * @property cellDates - * @type Array[](Number[]) - */ - cellDates : null, - - /** - * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. - * @property id - * @type String - */ - id : null, - - /** - * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. - * @property oDomContainer - * @type HTMLElement - */ - oDomContainer : null, - - /** - * A Date object representing today's date. - * @property today - * @type Date - */ - today : null, - - /** - * The list of render functions, along with required parameters, used to render cells. - * @property renderStack - * @type Array[] - */ - renderStack : null, - - /** - * A copy of the initial render functions created before rendering. - * @property _renderStack - * @private - * @type Array - */ - _renderStack : null, - - /** - * A Date object representing the month/year that the calendar is initially set to - * @property _pageDate - * @private - * @type Date - */ - _pageDate : null, - - /** - * The private list of initially selected dates. - * @property _selectedDates - * @private - * @type Array - */ - _selectedDates : null, - - /** - * A map of DOM event handlers to attach to cells associated with specific CSS class names - * @property domEventMap - * @type Object - */ - domEventMap : null -}; - - - -/** -* Initializes the Calendar widget. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { - this.initEvents(); - this.today = new Date(); - YAHOO.widget.DateMath.clearTime(this.today); - - this.id = id; - this.oDomContainer = document.getElementById(containerId); - - /** - * The Config object used to hold the configuration variables for the Calendar - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the Calendar's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the Calendar's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.initStyles(); - - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); - - this.cellDates = []; - this.cells = []; - this.renderStack = []; - this._renderStack = []; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); -}; - -/** -* Renders the built-in IFRAME shim for the IE6 and below -* @method configIframe -*/ -YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { - var useIframe = args[0]; - - if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { - if (useIframe) { - var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); - - if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { - if (! YAHOO.util.Dom.inDocument(this.iframe)) { - this.iframe = document.createElement("iframe"); - this.iframe.src = "javascript:false;"; - YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); - this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); - } - } - } else { - if (this.iframe) { - if (this.iframe.parentNode) { - this.iframe.parentNode.removeChild(this.iframe); - } - this.iframe = null; - } - } - } -}; - -/** -* Default handler for the "title" property -* @method configTitle -*/ -YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { - var title = args[0]; - var close = this.cfg.getProperty("close"); - - var titleDiv; - - if (title && title !== "") { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); - titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; - titleDiv.innerHTML = title; - this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; - - if (titleDiv) { - YAHOO.util.Event.purgeElement(titleDiv); - this.oDomContainer.removeChild(titleDiv); - } - if (! close) { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Default handler for the "close" property -* @method configClose -*/ -YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { - var close = args[0]; - var title = this.cfg.getProperty("title"); - - var linkClose; - - if (close === true) { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); - linkClose.href = "javascript:void(null);"; - linkClose.className = "link-close"; - YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); - var imgClose = document.createElement("img"); - imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; - imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; - linkClose.appendChild(imgClose); - this.oDomContainer.appendChild(linkClose); - YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); - } else { - linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; - - if (linkClose) { - YAHOO.util.Event.purgeElement(linkClose); - this.oDomContainer.removeChild(linkClose); - } - if (! title || title === "") { - YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); - } - } -}; - -/** -* Initializes Calendar's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.Calendar.prototype.initEvents = function() { - - /** - * Fired before a selection is made - * @event beforeSelectEvent - */ - this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); - - /** - * Fired when a selection is made - * @event selectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.selectEvent = new YAHOO.util.CustomEvent("select"); - - /** - * Fired before a selection is made - * @event beforeDeselectEvent - */ - this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); - - /** - * Fired when a selection is made - * @event deselectEvent - * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. - */ - this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); - - /** - * Fired when the Calendar page is changed - * @event changePageEvent - */ - this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); - - /** - * Fired before the Calendar is rendered - * @event beforeRenderEvent - */ - this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); - - /** - * Fired when the Calendar is rendered - * @event renderEvent - */ - this.renderEvent = new YAHOO.util.CustomEvent("render"); - - /** - * Fired when the Calendar is reset - * @event resetEvent - */ - this.resetEvent = new YAHOO.util.CustomEvent("reset"); - - /** - * Fired when the Calendar is cleared - * @event clearEvent - */ - this.clearEvent = new YAHOO.util.CustomEvent("clear"); - - this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); - this.selectEvent.subscribe(this.onSelect, this, true); - this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); - this.deselectEvent.subscribe(this.onDeselect, this, true); - this.changePageEvent.subscribe(this.onChangePage, this, true); - this.renderEvent.subscribe(this.onRender, this, true); - this.resetEvent.subscribe(this.onReset, this, true); - this.clearEvent.subscribe(this.onClear, this, true); -}; - - -/** -* The default event function that is attached to a date link within a calendar cell -* when the calendar is rendered. -* @method doSelectCell -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { - var target = YAHOO.util.Event.getTarget(e); - - var cell,index,d,date; - - while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - cell = target; - - if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { - index = cell.id.split("cell")[1]; - d = cal.cellDates[index]; - date = new Date(d[0],d[1]-1,d[2]); - - var link; - - if (cal.Options.MULTI_SELECT) { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - - var cellDate = cal.cellDates[index]; - var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); - - if (cellDateIndex > -1) { - cal.deselectCell(index); - } else { - cal.selectCell(index); - } - - } else { - link = cell.getElementsByTagName("a")[0]; - if (link) { - link.blur(); - } - cal.selectCell(index); - } - } -}; - -/** -* The event that is executed when the user hovers over a cell -* @method doCellMouseOver -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -/** -* The event that is executed when the user moves the mouse out of a cell -* @method doCellMouseOut -* @param {DOMEvent} e The event -* @param {Calendar} cal A reference to the calendar passed by the Event utility -*/ -YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { - var target; - if (e) { - target = YAHOO.util.Event.getTarget(e); - } else { - target = this; - } - - while (target.tagName.toLowerCase() != "td") { - target = target.parentNode; - if (target.tagName.toLowerCase() == "html") { - return; - } - } - - if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { - YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); - } -}; - -YAHOO.widget.Calendar.prototype.setupConfig = function() { - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); - - /** - * The title to display above the Calendar's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this Calendar - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); - - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); - - /** - * Refreshes the locale values used to build the Calendar. - * @method refreshLocale - * @private - */ - var refreshLocale = function() { - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - }; - - this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); - this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); -}; - -/** -* The default handler for the "pagedate" property -* @method configPageDate -*/ -YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { - var val = args[0]; - var month, year, aMonthYear; - - if (val) { - if (val instanceof Date) { - val = YAHOO.widget.DateMath.findMonthStart(val); - this.cfg.setProperty("pagedate", val, true); - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } - return; - } else { - aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); - month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; - year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); - } - } else { - month = this.today.getMonth(); - year = this.today.getFullYear(); - } - - this.cfg.setProperty("pagedate", new Date(year, month, 1), true); - if (! this._pageDate) { - this._pageDate = this.cfg.getProperty("pagedate"); - } -}; - -/** -* The default handler for the "mindate" property -* @method configMinDate -*/ -YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "maxdate" property -* @method configMaxDate -*/ -YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { - var val = args[0]; - if (typeof val == 'string') { - val = this._parseDate(val); - this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); - } -}; - -/** -* The default handler for the "selected" property -* @method configSelected -*/ -YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { - var selected = args[0]; - - if (selected) { - if (typeof selected == 'string') { - this.cfg.setProperty("selected", this._parseDates(selected), true); - } - } - if (! this._selectedDates) { - this._selectedDates = this.cfg.getProperty("selected"); - } -}; - -/** -* The default handler for all configuration options properties -* @method configOptions -*/ -YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Options[type] = val; -}; - -/** -* The default handler for all configuration locale properties -* @method configLocale -*/ -YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - this.Locale[type] = val; - - this.cfg.refireEvent("LOCALE_MONTHS"); - this.cfg.refireEvent("LOCALE_WEEKDAYS"); - -}; - -/** -* The default handler for all configuration locale field length properties -* @method configLocaleValues -*/ -YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { - type = type.toUpperCase(); - var val = args[0]; - - switch (type) { - case "LOCALE_MONTHS": - switch (val) { - case "short": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); - break; - case "long": - this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); - break; - } - break; - case "LOCALE_WEEKDAYS": - switch (val) { - case "1char": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); - break; - case "short": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); - break; - case "medium": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); - break; - case "long": - this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); - break; - } - - var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); - - if (START_WEEKDAY > 0) { - for (var w=0;w'; - html[html.length] = '
'; - - var renderLeft, renderRight = false; - - if (this.parent) { - if (this.index === 0) { - renderLeft = true; - } - if (this.index == (this.parent.cfg.getProperty("pages") -1)) { - renderRight = true; - } - } else { - renderLeft = true; - renderRight = true; - } - - var cal = this.parent || this; - - if (renderLeft) { - html[html.length] = ' '; - } - - html[html.length] = this.buildMonthLabel(); - - if (renderRight) { - html[html.length] = ' '; - } - - - html[html.length] = '
'; - html[html.length] = ''; - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEKDAYS")) { - html = this.buildWeekdays(html); - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the Calendar's weekday headers. -* @method buildWeekdays -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { - html[html.length] = ' '; - } - - for(var i=0;i'; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { - html[html.length] = ' '; - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar body. -* @method renderBody -* @param {Date} workingDate The current working Date being used for the render process -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { - - var startDay = this.cfg.getProperty("START_WEEKDAY"); - - this.preMonthDays = workingDate.getDay(); - if (startDay > 0) { - this.preMonthDays -= startDay; - } - if (this.preMonthDays < 0) { - this.preMonthDays += 7; - } - - this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); - this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; - - workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); - - var useDate,weekNum,weekClass; - useDate = this.cfg.getProperty("pagedate"); - - html[html.length] = ''; - - var i = 0; - - var tempDiv = document.createElement("div"); - var cell = document.createElement("td"); - tempDiv.appendChild(cell); - - var jan1 = new Date(useDate.getFullYear(),0,1); - - var cal = this.parent || this; - - for (var r=0;r<6;r++) { - - weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); - - weekClass = "w" + weekNum; - - if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { - break; - } else { - - html[html.length] = ''; - - if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } - - for (var d=0;d<7;d++){ // Render actual days - - var cellRenderers = []; - - this.clearElement(cell); - - YAHOO.util.Dom.addClass(cell, "calcell"); - - cell.id = this.id + "_cell" + i; - - cell.innerHTML = i; - - var renderer = null; - - if (workingDate.getFullYear() == this.today.getFullYear() && - workingDate.getMonth() == this.today.getMonth() && - workingDate.getDate() == this.today.getDate()) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; - } - - this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates - - if (this.isDateOOM(workingDate)) { - cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; - } else { - - YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); - YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); - - for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { - renderer = rArray[2]; - - if (workingDate.getTime()==d2.getTime()) { - this.renderStack.splice(s,1); - } - } - break; - case YAHOO.widget.Calendar.WEEKDAY: - - var weekday = rArray[1][0]; - if (workingDate.getDay()+1 == weekday) { - renderer = rArray[2]; - } - break; - case YAHOO.widget.Calendar.MONTH: - - month = rArray[1][0]; - if (workingDate.getMonth()+1 == month) { - renderer = rArray[2]; - } - break; - } - - if (renderer) { - cellRenderers[cellRenderers.length]=renderer; - } - } - - } - - if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { - cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; - } - - var mindate = this.cfg.getProperty("mindate"); - var maxdate = this.cfg.getProperty("maxdate"); - - if (mindate) { - mindate = YAHOO.widget.DateMath.clearTime(mindate); - } - if (maxdate) { - maxdate = YAHOO.widget.DateMath.clearTime(maxdate); - } - - if ( - (mindate && (workingDate.getTime() < mindate.getTime())) || - (maxdate && (workingDate.getTime() > maxdate.getTime())) - ) { - cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; - } else { - cellRenderers[cellRenderers.length]=cal.styleCellDefault; - cellRenderers[cellRenderers.length]=cal.renderCellDefault; - } - - - - for (var x=0;x= 0 && i <= 6) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); - } - if ((i % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); - } - if (((i+1) % 7) === 0) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); - } - - var postDays = this.postMonthDays; - if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { - var blankWeeks = Math.floor(postDays/7); - for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); - } - - html[html.length] = tempDiv.innerHTML; - - i++; - } - - if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } - - html[html.length] = ''; - } - } - - html[html.length] = ''; - - return html; -}; - -/** -* Renders the calendar footer. In the default implementation, there is -* no footer. -* @method renderFooter -* @param {Array} html The current working HTML array -* @return {Array} The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; - -/** -* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute -* when the method is called: renderHeader, renderBody, renderFooter. -* Refer to the documentation for those methods for information on -* individual render tasks. -* @method render -*/ -YAHOO.widget.Calendar.prototype.render = function() { - this.beforeRenderEvent.fire(); - - // Find starting day of the current month - var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); - - this.resetRenderers(); - this.cellDates.length = 0; - - YAHOO.util.Event.purgeElement(this.oDomContainer, true); - - var html = []; - - html[html.length] = ''; - html = this.renderHeader(html); - html = this.renderBody(workingDate, html); - html = this.renderFooter(html); - html[html.length] = '
'; - - this.oDomContainer.innerHTML = html.join("\n"); - - this.applyListeners(); - this.cells = this.oDomContainer.getElementsByTagName("td"); - - this.cfg.refireEvent("title"); - this.cfg.refireEvent("close"); - this.cfg.refireEvent("iframe"); - - this.renderEvent.fire(); -}; - -/** -* Applies the Calendar's DOM listeners to applicable elements. -* @method applyListeners -*/ -YAHOO.widget.Calendar.prototype.applyListeners = function() { - - var root = this.oDomContainer; - var cal = this.parent || this; - - var linkLeft, linkRight; - - linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); - linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); - - if (linkLeft) { - this.linkLeft = linkLeft[0]; - YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); - } - - if (linkRight) { - this.linkRight = linkRight[0]; - YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); - } - - if (this.domEventMap) { - var el,elements; - for (var cls in this.domEventMap) { - if (this.domEventMap.hasOwnProperty(cls)) { - var items = this.domEventMap[cls]; - - if (! (items instanceof Array)) { - items = [items]; - } - - for (var i=0;i'; - return html; -}; - -/** -* Renders the row footer for a week. -* @method renderRowFooter -* @param {Number} weekNum The week number of the current row -* @param {Array} cell The current working HTML array -*/ -YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { - html[html.length] = '' + weekNum + ''; - return html; -}; - -/** -* Renders a single standard calendar cell in the calendar widget table. -* All logic for determining how a standard default cell will be rendered is -* encapsulated in this method, and must be accounted for when extending the -* widget class. -* @method renderCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { - cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; -}; - -/** -* Styles a selectable cell. -* @method styleCellDefault -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); -}; - - -/** -* Renders a single standard calendar cell using the CSS hightlight1 style -* @method renderCellStyleHighlight1 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight2 style -* @method renderCellStyleHighlight2 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight3 style -* @method renderCellStyleHighlight3 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); -}; - -/** -* Renders a single standard calendar cell using the CSS hightlight4 style -* @method renderCellStyleHighlight4 -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); -}; - -/** -* Applies the default style used for rendering today's date to the current calendar cell -* @method renderCellStyleToday -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); -}; - -/** -* Applies the default style used for rendering selected dates to the current calendar cell -* @method renderCellStyleSelected -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); -}; - -/** -* Applies the default style used for rendering dates that are not a part of the current -* month (preceding or trailing the cells for the current month) -* @method renderCellNotThisMonth -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -/** -* Renders the current calendar cell as a non-selectable "black-out" date using the default -* restricted style. -* @method renderBodyCellRestricted -* @param {Date} workingDate The current working Date object being used to generate the calendar -* @param {HTMLTableCellElement} cell The current working cell in the calendar -* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering -* should not be terminated -*/ -YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); - YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); - cell.innerHTML=workingDate.getDate(); - return YAHOO.widget.Calendar.STOP_RENDER; -}; - -// END BUILT-IN TABLE CELL RENDERERS - -// BEGIN MONTH NAVIGATION METHODS - -/** -* Adds the designated number of months to the current calendar month, and sets the current -* calendar page date to the new month. -* @method addMonths -* @param {Number} count The number of months to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtracts the designated number of months from the current calendar month, and sets the current -* calendar page date to the new month. -* @method subtractMonths -* @param {Number} count The number of months to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Adds the designated number of years to the current calendar, and sets the current -* calendar page date to the new month. -* @method addYears -* @param {Number} count The number of years to add to the current calendar -*/ -YAHOO.widget.Calendar.prototype.addYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Subtcats the designated number of years from the current calendar, and sets the current -* calendar page date to the new month. -* @method subtractYears -* @param {Number} count The number of years to subtract from the current calendar -*/ -YAHOO.widget.Calendar.prototype.subtractYears = function(count) { - this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); - this.resetRenderers(); - this.changePageEvent.fire(); -}; - -/** -* Navigates to the next month page in the calendar widget. -* @method nextMonth -*/ -YAHOO.widget.Calendar.prototype.nextMonth = function() { - this.addMonths(1); -}; - -/** -* Navigates to the previous month page in the calendar widget. -* @method previousMonth -*/ -YAHOO.widget.Calendar.prototype.previousMonth = function() { - this.subtractMonths(1); -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.Calendar.prototype.nextYear = function() { - this.addYears(1); -}; - -/** -* Navigates to the previous year in the currently selected month in the calendar widget. -* @method previousYear -*/ -YAHOO.widget.Calendar.prototype.previousYear = function() { - this.subtractYears(1); -}; - -// END MONTH NAVIGATION METHODS - -// BEGIN SELECTION METHODS - -/** -* Resets the calendar widget to the originally selected month and year, and -* sets the calendar to the initial selection(s). -* @method reset -*/ -YAHOO.widget.Calendar.prototype.reset = function() { - this.cfg.resetProperty("selected"); - this.cfg.resetProperty("pagedate"); - this.resetEvent.fire(); -}; - -/** -* Clears the selected dates in the current calendar widget and sets the calendar -* to the current month and year. -* @method clear -*/ -YAHOO.widget.Calendar.prototype.clear = function() { - this.cfg.setProperty("selected", []); - this.cfg.setProperty("pagedate", new Date(this.today.getTime())); - this.clearEvent.fire(); -}; - -/** -* Selects a date or a collection of dates on the current calendar. This method, by default, -* does not call the render method explicitly. Once selection has completed, render must be -* called for the changes to be reflected visually. -* @method select -* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -*/ -YAHOO.widget.Calendar.prototype.select = function(date) { - this.beforeSelectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var aToBeSelected = this._toFieldArray(date); - - for (var a=0;a -1) { - if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && - this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { - YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); - } - - selected.splice(cellDateIndex, 1); - } - - - if (this.parent) { - this.parent.cfg.setProperty("selected", selected); - } else { - this.cfg.setProperty("selected", selected); - } - - this.deselectEvent.fire(selectDate); - return this.getSelectedDates(); -}; - -/** -* Deselects all dates on the current calendar. -* @method deselectAll -* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. -* Assuming that this function executes properly, the return value should be an empty array. -* However, the empty array is returned for the sake of being able to check the selection status -* of the calendar. -*/ -YAHOO.widget.Calendar.prototype.deselectAll = function() { - this.beforeDeselectEvent.fire(); - - var selected = this.cfg.getProperty("selected"); - var count = selected.length; - var sel = selected.concat(); - - if (this.parent) { - this.parent.cfg.setProperty("selected", []); - } else { - this.cfg.setProperty("selected", []); - } - - if (count > 0) { - this.deselectEvent.fire(sel); - } - - return this.getSelectedDates(); -}; - -// END SELECTION METHODS - -// BEGIN TYPE CONVERSION METHODS - -/** -* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure -* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. -* @method _toFieldArray -* @private -* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are -* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). -* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). -* This method can also take a JavaScript Date object or an array of Date objects. -* @return {Array[](Number[])} Array of date field arrays -*/ -YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { - var returnDate = []; - - if (date instanceof Date) { - returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; - } else if (typeof date == 'string') { - returnDate = this._parseDates(date); - } else if (date instanceof Array) { - for (var i=0;i -*
-*
-* -* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. -* @namespace YAHOO.widget -* @class CalendarGroup -* @constructor -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup = function(id, containerId, config) { - if (arguments.length > 0) { - this.init(id, containerId, config); - } -}; - -/** -* Initializes the calendar group. All subclasses must call this method in order for the -* group to be initialized properly. -* @method init -* @param {String} id The id of the table element that will represent the calendar widget -* @param {String} containerId The id of the container div element that will wrap the calendar table -* @param {Object} config The configuration object containing the Calendar's arguments -*/ -YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { - this.initEvents(); - this.initStyles(); - - /** - * The collection of Calendar pages contained within the CalendarGroup - * @property pages - * @type YAHOO.widget.Calendar[] - */ - this.pages = []; - - /** - * The unique id associated with the CalendarGroup - * @property id - * @type String - */ - this.id = id; - - /** - * The unique id associated with the CalendarGroup container - * @property containerId - * @type String - */ - this.containerId = containerId; - - /** - * The outer containing element for the CalendarGroup - * @property oDomContainer - * @type HTMLElement - */ - this.oDomContainer = document.getElementById(containerId); - - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); - YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); - - /** - * The Config object used to hold the configuration variables for the CalendarGroup - * @property cfg - * @type YAHOO.util.Config - */ - this.cfg = new YAHOO.util.Config(this); - - /** - * The local object which contains the CalendarGroup's options - * @property Options - * @type Object - */ - this.Options = {}; - - /** - * The local object which contains the CalendarGroup's locale settings - * @property Locale - * @type Object - */ - this.Locale = {}; - - this.setupConfig(); - - if (config) { - this.cfg.applyConfig(config, true); - } - - this.cfg.fireQueue(); - - // OPERA HACK FOR MISWRAPPED FLOATS - if (this.browser == "opera"){ - var fixWidth = function() { - var startW = this.oDomContainer.offsetWidth; - var w = 0; - for (var p=0;p 0) { - this.oDomContainer.style.width = w + "px"; - } - }; - this.renderEvent.subscribe(fixWidth,this,true); - } -}; - - -YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { - /** - * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. - * @config pages - * @type Number - * @default 2 - */ - this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); - - /** - * The month/year representing the current visible Calendar date (mm/yyyy) - * @config pagedate - * @type String - * @default today's date - */ - this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); - - /** - * The date or range of dates representing the current Calendar selection - * @config selected - * @type String - * @default [] - */ - this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); - - /** - * The title to display above the CalendarGroup's month header - * @config title - * @type String - * @default "" - */ - this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); - - /** - * Whether or not a close button should be displayed for this CalendarGroup - * @config close - * @type Boolean - * @default false - */ - this.cfg.addProperty("close", { value:false, handler:this.configClose } ); - - /** - * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. - * @config iframe - * @type Boolean - * @default true - */ - this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The minimum selectable date in the current Calendar (mm/dd/yyyy) - * @config mindate - * @type String - * @default null - */ - this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); - - /** - * The maximum selectable date in the current Calendar (mm/dd/yyyy) - * @config maxdate - * @type String - * @default null - */ - this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); - - // Options properties - - /** - * True if the Calendar should allow multiple selections. False by default. - * @config MULTI_SELECT - * @type Boolean - * @default false - */ - this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The weekday the week begins on. Default is 0 (Sunday). - * @config START_WEEKDAY - * @type number - * @default 0 - */ - this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * True if the Calendar should show weekday labels. True by default. - * @config SHOW_WEEKDAYS - * @type Boolean - * @default true - */ - this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row headers. False by default. - * @config SHOW_WEEK_HEADER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should show week row footers. False by default. - * @config SHOW_WEEK_FOOTER - * @type Boolean - * @default false - */ - this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * True if the Calendar should suppress weeks that are not a part of the current month. False by default. - * @config HIDE_BLANK_WEEKS - * @type Boolean - * @default false - */ - this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_LEFT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" - */ - this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); - - /** - * The image that should be used for the left navigation arrow. - * @config NAV_ARROW_RIGHT - * @type String - * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" - */ - this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); - - // Locale properties - - /** - * The short month labels for the current locale. - * @config MONTHS_SHORT - * @type String[] - * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - */ - this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); - - /** - * The long month labels for the current locale. - * @config MONTHS_LONG - * @type String[] - * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" - */ - this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); - - /** - * The 1-character weekday labels for the current locale. - * @config WEEKDAYS_1CHAR - * @type String[] - * @default ["S", "M", "T", "W", "T", "F", "S"] - */ - this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); - - /** - * The short weekday labels for the current locale. - * @config WEEKDAYS_SHORT - * @type String[] - * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] - */ - this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); - - /** - * The medium weekday labels for the current locale. - * @config WEEKDAYS_MEDIUM - * @type String[] - * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] - */ - this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); - - /** - * The long weekday labels for the current locale. - * @config WEEKDAYS_LONG - * @type String[] - * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] - */ - this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); - - /** - * The setting that determines which length of month labels should be used. Possible values are "short" and "long". - * @config LOCALE_MONTHS - * @type String - * @default "long" - */ - this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); - - /** - * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". - * @config LOCALE_WEEKDAYS - * @type String - * @default "short" - */ - this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); - - /** - * The value used to delimit individual dates in a date string passed to various Calendar functions. - * @config DATE_DELIMITER - * @type String - * @default "," - */ - this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); - - /** - * The value used to delimit date fields in a date string passed to various Calendar functions. - * @config DATE_FIELD_DELIMITER - * @type String - * @default "/" - */ - this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); - - /** - * The value used to delimit date ranges in a date string passed to various Calendar functions. - * @config DATE_RANGE_DELIMITER - * @type String - * @default "-" - */ - this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); - - /** - * The position of the month in a month/year date string - * @config MY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/year date string - * @config MY_YEAR_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day date string - * @config MD_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/year date string - * @config MD_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the month in a month/day/year date string - * @config MDY_MONTH_POSITION - * @type Number - * @default 1 - */ - this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the day in a month/day/year date string - * @config MDY_DAY_POSITION - * @type Number - * @default 2 - */ - this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - - /** - * The position of the year in a month/day/year date string - * @config MDY_YEAR_POSITION - * @type Number - * @default 3 - */ - this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); - -}; - -/** -* Initializes CalendarGroup's built-in CustomEvents -* @method initEvents -*/ -YAHOO.widget.CalendarGroup.prototype.initEvents = function() { - var me = this; - - /** - * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents - * @method sub - * @private - * @param {Function} fn The function to subscribe to this CustomEvent - * @param {Object} obj The CustomEvent's scope object - * @param {Boolean} bOverride Whether or not to apply scope correction - */ - var sub = function(fn, obj, bOverride) { - for (var p=0;p0) { - year+=1; - } - cal.setYear(year); - } -}; -/** -* Calls the render function of all child calendars within the group. -* @method render -*/ -YAHOO.widget.CalendarGroup.prototype.render = function() { - this.renderHeader(); - for (var p=0;p=0;--p) { - var cal = this.pages[p]; - cal.previousMonth(); - } -}; - -/** -* Navigates to the next year in the currently selected month in the calendar widget. -* @method nextYear -*/ -YAHOO.widget.CalendarGroup.prototype.nextYear = function() { - for (var p=0;p 11) { + while (newMonth > 11) { + newMonth -= 12; + years += 1; + } + } + + d.setMonth(newMonth); + d.setFullYear(date.getFullYear() + years); + break; + case this.DAY: + d.setDate(date.getDate() + amount); + break; + case this.YEAR: + d.setFullYear(date.getFullYear() + amount); + break; + case this.WEEK: + d.setDate(date.getDate() + (amount * 7)); + break; + } + return d; + }, + + /** + * Subtracts the specified amount of time from the this instance. + * @method subtract + * @param {Date} date The JavaScript Date object to perform subtraction on + * @param {Number} field The this field constant to be used for performing subtraction. + * @param {Number} amount The number of units (measured in the field constant) to subtract from the date. + * @return {Date} The resulting Date object + */ + subtract : function(date, field, amount) { + return this.add(date, field, (amount*-1)); + }, + + /** + * Determines whether a given date is before another date on the calendar. + * @method before + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs before the compared date; false if not. + */ + before : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() < ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is after another date on the calendar. + * @method after + * @param {Date} date The Date object to compare with the compare argument + * @param {Date} compareTo The Date object to use for the comparison + * @return {Boolean} true if the date occurs after the compared date; false if not. + */ + after : function(date, compareTo) { + var ms = compareTo.getTime(); + if (date.getTime() > ms) { + return true; + } else { + return false; + } + }, + + /** + * Determines whether a given date is between two other dates on the calendar. + * @method between + * @param {Date} date The date to check for + * @param {Date} dateBegin The start of the range + * @param {Date} dateEnd The end of the range + * @return {Boolean} true if the date occurs between the compared dates; false if not. + */ + between : function(date, dateBegin, dateEnd) { + if (this.after(date, dateBegin) && this.before(date, dateEnd)) { + return true; + } else { + return false; + } + }, + + /** + * Retrieves a JavaScript Date object representing January 1 of any given year. + * @method getJan1 + * @param {Number} calendarYear The calendar year for which to retrieve January 1 + * @return {Date} January 1 of the calendar year specified. + */ + getJan1 : function(calendarYear) { + return new Date(calendarYear,0,1); + }, + + /** + * Calculates the number of days the specified date is from January 1 of the specified calendar year. + * Passing January 1 to this function would return an offset value of zero. + * @method getDayOffset + * @param {Date} date The JavaScript date for which to find the offset + * @param {Number} calendarYear The calendar year to use for determining the offset + * @return {Number} The number of days since January 1 of the given year + */ + getDayOffset : function(date, calendarYear) { + var beginYear = this.getJan1(calendarYear); // Find the start of the year. This will be in week 1. + + // Find the number of days the passed in date is away from the calendar year start + var dayOffset = Math.ceil((date.getTime()-beginYear.getTime()) / this.ONE_DAY_MS); + return dayOffset; + }, + + /** + * Calculates the week number for the given date. This function assumes that week 1 is the + * week in which January 1 appears, regardless of whether the week consists of a full 7 days. + * The calendar year can be specified to help find what a the week number would be for a given + * date if the date overlaps years. For instance, a week may be considered week 1 of 2005, or + * week 53 of 2004. Specifying the optional calendarYear allows one to make this distinction + * easily. + * @method getWeekNumber + * @param {Date} date The JavaScript date for which to find the week number + * @param {Number} calendarYear OPTIONAL - The calendar year to use for determining the week number. Default is + * the calendar year of parameter "date". + * @param {Number} weekStartsOn OPTIONAL - The integer (0-6) representing which day a week begins on. Default is 0 (for Sunday). + * @return {Number} The week number of the given date. + */ + getWeekNumber : function(date, calendarYear) { + date = this.clearTime(date); + var nearestThurs = new Date(date.getTime() + (4 * this.ONE_DAY_MS) - ((date.getDay()) * this.ONE_DAY_MS)); + + var jan1 = new Date(nearestThurs.getFullYear(),0,1); + var dayOfYear = ((nearestThurs.getTime() - jan1.getTime()) / this.ONE_DAY_MS) - 1; + + var weekNum = Math.ceil((dayOfYear)/ 7); + return weekNum; + }, + + /** + * Determines if a given week overlaps two different years. + * @method isYearOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different years. + */ + isYearOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getFullYear() != weekBeginDate.getFullYear()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Determines if a given week overlaps two different months. + * @method isMonthOverlapWeek + * @param {Date} weekBeginDate The JavaScript Date representing the first day of the week. + * @return {Boolean} true if the date overlaps two different months. + */ + isMonthOverlapWeek : function(weekBeginDate) { + var overlaps = false; + var nextWeek = this.add(weekBeginDate, this.DAY, 6); + if (nextWeek.getMonth() != weekBeginDate.getMonth()) { + overlaps = true; + } + return overlaps; + }, + + /** + * Gets the first day of a month containing a given date. + * @method findMonthStart + * @param {Date} date The JavaScript Date used to calculate the month start + * @return {Date} The JavaScript Date representing the first day of the month + */ + findMonthStart : function(date) { + var start = new Date(date.getFullYear(), date.getMonth(), 1); + return start; + }, + + /** + * Gets the last day of a month containing a given date. + * @method findMonthEnd + * @param {Date} date The JavaScript Date used to calculate the month end + * @return {Date} The JavaScript Date representing the last day of the month + */ + findMonthEnd : function(date) { + var start = this.findMonthStart(date); + var nextMonth = this.add(start, this.MONTH, 1); + var end = this.subtract(nextMonth, this.DAY, 1); + return end; + }, + + /** + * Clears the time fields from a given date, effectively setting the time to midnight. + * @method clearTime + * @param {Date} date The JavaScript Date for which the time fields will be cleared + * @return {Date} The JavaScript Date cleared of all time fields + */ + clearTime : function(date) { + date.setHours(12,0,0,0); + return date; + } +}; + +/** +* The Calendar component is a UI control that enables users to choose one or more dates from a graphical calendar presented in a one-month ("one-up") or two-month ("two-up") interface. Calendars are generated entirely via script and can be navigated without any page refreshes. +* @module Calendar +* @title Calendar Widget +* @namespace YAHOO.widget +* @requires yahoo,dom,event +*/ + +/** +* Calendar is the base class for the Calendar widget. In its most basic +* implementation, it has the ability to render a calendar widget on the page +* that can be manipulated to select a single date, move back and forth between +* months and years. +*

To construct the placeholder for the calendar widget, the code is as +* follows: +*

+* <div id="cal1Container"></div> +* +* Note that the table can be replaced with any kind of element. +*

+* @namespace YAHOO.widget +* @class Calendar +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar = function(id, containerId, config) { + this.init(id, containerId, config); +}; + +/** +* The path to be used for images loaded for the Calendar +* @property YAHOO.widget.Calendar.IMG_ROOT +* @static +* @type String +*/ +YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https") === 0 ? "https://a248.e.akamai.net/sec.yimg.com/i/" : "http://us.i1.yimg.com/us.yimg.com/i/"); + +/** +* Type constant used for renderers to represent an individual date (M/D/Y) +* @property YAHOO.widget.Calendar.DATE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.DATE = "D"; + +/** +* Type constant used for renderers to represent an individual date across any year (M/D) +* @property YAHOO.widget.Calendar.MONTH_DAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH_DAY = "MD"; + +/** +* Type constant used for renderers to represent a weekday +* @property YAHOO.widget.Calendar.WEEKDAY +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.WEEKDAY = "WD"; + +/** +* Type constant used for renderers to represent a range of individual dates (M/D/Y-M/D/Y) +* @property YAHOO.widget.Calendar.RANGE +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.RANGE = "R"; + +/** +* Type constant used for renderers to represent a month across any year +* @property YAHOO.widget.Calendar.MONTH +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.MONTH = "M"; + +/** +* Constant that represents the total number of date cells that are displayed in a given month +* @property YAHOO.widget.Calendar.DISPLAY_DAYS +* @static +* @final +* @type Number +*/ +YAHOO.widget.Calendar.DISPLAY_DAYS = 42; + +/** +* Constant used for halting the execution of the remainder of the render stack +* @property YAHOO.widget.Calendar.STOP_RENDER +* @static +* @final +* @type String +*/ +YAHOO.widget.Calendar.STOP_RENDER = "S"; + +YAHOO.widget.Calendar.prototype = { + + /** + * The configuration object used to set up the calendars various locale and style options. + * @property Config + * @private + * @deprecated Configuration properties should be set by calling Calendar.cfg.setProperty. + * @type Object + */ + Config : null, + + /** + * The parent CalendarGroup, only to be set explicitly by the parent group + * @property parent + * @type CalendarGroup + */ + parent : null, + + /** + * The index of this item in the parent group + * @property index + * @type Number + */ + index : -1, + + /** + * The collection of calendar table cells + * @property cells + * @type HTMLTableCellElement[] + */ + cells : null, + + /** + * The collection of calendar cell dates that is parallel to the cells collection. The array contains dates field arrays in the format of [YYYY, M, D]. + * @property cellDates + * @type Array[](Number[]) + */ + cellDates : null, + + /** + * The id that uniquely identifies this calendar. This id should match the id of the placeholder element on the page. + * @property id + * @type String + */ + id : null, + + /** + * The DOM element reference that points to this calendar's container element. The calendar will be inserted into this element when the shell is rendered. + * @property oDomContainer + * @type HTMLElement + */ + oDomContainer : null, + + /** + * A Date object representing today's date. + * @property today + * @type Date + */ + today : null, + + /** + * The list of render functions, along with required parameters, used to render cells. + * @property renderStack + * @type Array[] + */ + renderStack : null, + + /** + * A copy of the initial render functions created before rendering. + * @property _renderStack + * @private + * @type Array + */ + _renderStack : null, + + /** + * A Date object representing the month/year that the calendar is initially set to + * @property _pageDate + * @private + * @type Date + */ + _pageDate : null, + + /** + * The private list of initially selected dates. + * @property _selectedDates + * @private + * @type Array + */ + _selectedDates : null, + + /** + * A map of DOM event handlers to attach to cells associated with specific CSS class names + * @property domEventMap + * @type Object + */ + domEventMap : null +}; + + + +/** +* Initializes the Calendar widget. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.Calendar.prototype.init = function(id, containerId, config) { + this.initEvents(); + this.today = new Date(); + YAHOO.widget.DateMath.clearTime(this.today); + + this.id = id; + this.oDomContainer = document.getElementById(containerId); + + /** + * The Config object used to hold the configuration variables for the Calendar + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the Calendar's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the Calendar's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.initStyles(); + + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, this.Style.CSS_SINGLE); + + this.cellDates = []; + this.cells = []; + this.renderStack = []; + this._renderStack = []; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); +}; + +/** +* Renders the built-in IFRAME shim for the IE6 and below +* @method configIframe +*/ +YAHOO.widget.Calendar.prototype.configIframe = function(type, args, obj) { + var useIframe = args[0]; + + if (YAHOO.util.Dom.inDocument(this.oDomContainer)) { + if (useIframe) { + var pos = YAHOO.util.Dom.getStyle(this.oDomContainer, "position"); + + if (this.browser == "ie" && (pos == "absolute" || pos == "relative")) { + if (! YAHOO.util.Dom.inDocument(this.iframe)) { + this.iframe = document.createElement("iframe"); + this.iframe.src = "javascript:false;"; + YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0"); + this.oDomContainer.insertBefore(this.iframe, this.oDomContainer.firstChild); + } + } + } else { + if (this.iframe) { + if (this.iframe.parentNode) { + this.iframe.parentNode.removeChild(this.iframe); + } + this.iframe = null; + } + } + } +}; + +/** +* Default handler for the "title" property +* @method configTitle +*/ +YAHOO.widget.Calendar.prototype.configTitle = function(type, args, obj) { + var title = args[0]; + var close = this.cfg.getProperty("close"); + + var titleDiv; + + if (title && title !== "") { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || document.createElement("div"); + titleDiv.className = YAHOO.widget.CalendarGroup.CSS_2UPTITLE; + titleDiv.innerHTML = title; + this.oDomContainer.insertBefore(titleDiv, this.oDomContainer.firstChild); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + titleDiv = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.CalendarGroup.CSS_2UPTITLE, "div", this.oDomContainer)[0] || null; + + if (titleDiv) { + YAHOO.util.Event.purgeElement(titleDiv); + this.oDomContainer.removeChild(titleDiv); + } + if (! close) { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Default handler for the "close" property +* @method configClose +*/ +YAHOO.widget.Calendar.prototype.configClose = function(type, args, obj) { + var close = args[0]; + var title = this.cfg.getProperty("title"); + + var linkClose; + + if (close === true) { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || document.createElement("a"); + linkClose.href = "javascript:void(null);"; + linkClose.className = "link-close"; + YAHOO.util.Event.addListener(linkClose, "click", this.hide, this, true); + var imgClose = document.createElement("img"); + imgClose.src = YAHOO.widget.Calendar.IMG_ROOT + "us/my/bn/x_d.gif"; + imgClose.className = YAHOO.widget.CalendarGroup.CSS_2UPCLOSE; + linkClose.appendChild(imgClose); + this.oDomContainer.appendChild(linkClose); + YAHOO.util.Dom.addClass(this.oDomContainer, "withtitle"); + } else { + linkClose = YAHOO.util.Dom.getElementsByClassName("link-close", "a", this.oDomContainer)[0] || null; + + if (linkClose) { + YAHOO.util.Event.purgeElement(linkClose); + this.oDomContainer.removeChild(linkClose); + } + if (! title || title === "") { + YAHOO.util.Dom.removeClass(this.oDomContainer, "withtitle"); + } + } +}; + +/** +* Initializes Calendar's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.Calendar.prototype.initEvents = function() { + + /** + * Fired before a selection is made + * @event beforeSelectEvent + */ + this.beforeSelectEvent = new YAHOO.util.CustomEvent("beforeSelect"); + + /** + * Fired when a selection is made + * @event selectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.selectEvent = new YAHOO.util.CustomEvent("select"); + + /** + * Fired before a selection is made + * @event beforeDeselectEvent + */ + this.beforeDeselectEvent = new YAHOO.util.CustomEvent("beforeDeselect"); + + /** + * Fired when a selection is made + * @event deselectEvent + * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD]. + */ + this.deselectEvent = new YAHOO.util.CustomEvent("deselect"); + + /** + * Fired when the Calendar page is changed + * @event changePageEvent + */ + this.changePageEvent = new YAHOO.util.CustomEvent("changePage"); + + /** + * Fired before the Calendar is rendered + * @event beforeRenderEvent + */ + this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender"); + + /** + * Fired when the Calendar is rendered + * @event renderEvent + */ + this.renderEvent = new YAHOO.util.CustomEvent("render"); + + /** + * Fired when the Calendar is reset + * @event resetEvent + */ + this.resetEvent = new YAHOO.util.CustomEvent("reset"); + + /** + * Fired when the Calendar is cleared + * @event clearEvent + */ + this.clearEvent = new YAHOO.util.CustomEvent("clear"); + + this.beforeSelectEvent.subscribe(this.onBeforeSelect, this, true); + this.selectEvent.subscribe(this.onSelect, this, true); + this.beforeDeselectEvent.subscribe(this.onBeforeDeselect, this, true); + this.deselectEvent.subscribe(this.onDeselect, this, true); + this.changePageEvent.subscribe(this.onChangePage, this, true); + this.renderEvent.subscribe(this.onRender, this, true); + this.resetEvent.subscribe(this.onReset, this, true); + this.clearEvent.subscribe(this.onClear, this, true); +}; + + +/** +* The default event function that is attached to a date link within a calendar cell +* when the calendar is rendered. +* @method doSelectCell +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doSelectCell = function(e, cal) { + var target = YAHOO.util.Event.getTarget(e); + + var cell,index,d,date; + + while (target.tagName.toLowerCase() != "td" && ! YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + cell = target; + + if (YAHOO.util.Dom.hasClass(cell, cal.Style.CSS_CELL_SELECTABLE)) { + index = cell.id.split("cell")[1]; + d = cal.cellDates[index]; + date = new Date(d[0],d[1]-1,d[2]); + + var link; + + if (cal.Options.MULTI_SELECT) { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + + var cellDate = cal.cellDates[index]; + var cellDateIndex = cal._indexOfSelectedFieldArray(cellDate); + + if (cellDateIndex > -1) { + cal.deselectCell(index); + } else { + cal.selectCell(index); + } + + } else { + link = cell.getElementsByTagName("a")[0]; + if (link) { + link.blur(); + } + cal.selectCell(index); + } + } +}; + +/** +* The event that is executed when the user hovers over a cell +* @method doCellMouseOver +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOver = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.addClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +/** +* The event that is executed when the user moves the mouse out of a cell +* @method doCellMouseOut +* @param {DOMEvent} e The event +* @param {Calendar} cal A reference to the calendar passed by the Event utility +*/ +YAHOO.widget.Calendar.prototype.doCellMouseOut = function(e, cal) { + var target; + if (e) { + target = YAHOO.util.Event.getTarget(e); + } else { + target = this; + } + + while (target.tagName.toLowerCase() != "td") { + target = target.parentNode; + if (target.tagName.toLowerCase() == "html") { + return; + } + } + + if (YAHOO.util.Dom.hasClass(target, cal.Style.CSS_CELL_SELECTABLE)) { + YAHOO.util.Dom.removeClass(target, cal.Style.CSS_CELL_HOVER); + } +}; + +YAHOO.widget.Calendar.prototype.setupConfig = function() { + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.configSelected } ); + + /** + * The title to display above the Calendar's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this Calendar + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.configIframe, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.configMinDate } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.configMaxDate } ); + + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.configOptions, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.configOptions, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.configOptions } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.configOptions } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.configLocale } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.configLocale } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.configLocale } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.configLocale } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.configLocale } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.configLocale } ); + + /** + * Refreshes the locale values used to build the Calendar. + * @method refreshLocale + * @private + */ + var refreshLocale = function() { + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + }; + + this.cfg.subscribeToConfigEvent("START_WEEKDAY", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("MONTHS_LONG", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_1CHAR", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_SHORT", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_MEDIUM", refreshLocale, this, true); + this.cfg.subscribeToConfigEvent("WEEKDAYS_LONG", refreshLocale, this, true); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.configLocaleValues } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.configLocaleValues } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.configLocale } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.configLocale } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.configLocale } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.configLocale, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.configLocale, validator:this.cfg.checkNumber } ); +}; + +/** +* The default handler for the "pagedate" property +* @method configPageDate +*/ +YAHOO.widget.Calendar.prototype.configPageDate = function(type, args, obj) { + var val = args[0]; + var month, year, aMonthYear; + + if (val) { + if (val instanceof Date) { + val = YAHOO.widget.DateMath.findMonthStart(val); + this.cfg.setProperty("pagedate", val, true); + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } + return; + } else { + aMonthYear = val.split(this.cfg.getProperty("DATE_FIELD_DELIMITER")); + month = parseInt(aMonthYear[this.cfg.getProperty("MY_MONTH_POSITION")-1], 10)-1; + year = parseInt(aMonthYear[this.cfg.getProperty("MY_YEAR_POSITION")-1], 10); + } + } else { + month = this.today.getMonth(); + year = this.today.getFullYear(); + } + + this.cfg.setProperty("pagedate", new Date(year, month, 1), true); + if (! this._pageDate) { + this._pageDate = this.cfg.getProperty("pagedate"); + } +}; + +/** +* The default handler for the "mindate" property +* @method configMinDate +*/ +YAHOO.widget.Calendar.prototype.configMinDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("mindate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "maxdate" property +* @method configMaxDate +*/ +YAHOO.widget.Calendar.prototype.configMaxDate = function(type, args, obj) { + var val = args[0]; + if (typeof val == 'string') { + val = this._parseDate(val); + this.cfg.setProperty("maxdate", new Date(val[0],(val[1]-1),val[2])); + } +}; + +/** +* The default handler for the "selected" property +* @method configSelected +*/ +YAHOO.widget.Calendar.prototype.configSelected = function(type, args, obj) { + var selected = args[0]; + + if (selected) { + if (typeof selected == 'string') { + this.cfg.setProperty("selected", this._parseDates(selected), true); + } + } + if (! this._selectedDates) { + this._selectedDates = this.cfg.getProperty("selected"); + } +}; + +/** +* The default handler for all configuration options properties +* @method configOptions +*/ +YAHOO.widget.Calendar.prototype.configOptions = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Options[type] = val; +}; + +/** +* The default handler for all configuration locale properties +* @method configLocale +*/ +YAHOO.widget.Calendar.prototype.configLocale = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + this.Locale[type] = val; + + this.cfg.refireEvent("LOCALE_MONTHS"); + this.cfg.refireEvent("LOCALE_WEEKDAYS"); + +}; + +/** +* The default handler for all configuration locale field length properties +* @method configLocaleValues +*/ +YAHOO.widget.Calendar.prototype.configLocaleValues = function(type, args, obj) { + type = type.toUpperCase(); + var val = args[0]; + + switch (type) { + case "LOCALE_MONTHS": + switch (val) { + case "short": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_SHORT").concat(); + break; + case "long": + this.Locale.LOCALE_MONTHS = this.cfg.getProperty("MONTHS_LONG").concat(); + break; + } + break; + case "LOCALE_WEEKDAYS": + switch (val) { + case "1char": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_1CHAR").concat(); + break; + case "short": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_SHORT").concat(); + break; + case "medium": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_MEDIUM").concat(); + break; + case "long": + this.Locale.LOCALE_WEEKDAYS = this.cfg.getProperty("WEEKDAYS_LONG").concat(); + break; + } + + var START_WEEKDAY = this.cfg.getProperty("START_WEEKDAY"); + + if (START_WEEKDAY > 0) { + for (var w=0;w'; + html[html.length] = '
'; + + var renderLeft, renderRight = false; + + if (this.parent) { + if (this.index === 0) { + renderLeft = true; + } + if (this.index == (this.parent.cfg.getProperty("pages") -1)) { + renderRight = true; + } + } else { + renderLeft = true; + renderRight = true; + } + + var cal = this.parent || this; + + if (renderLeft) { + html[html.length] = ' '; + } + + html[html.length] = this.buildMonthLabel(); + + if (renderRight) { + html[html.length] = ' '; + } + + + html[html.length] = '
'; + html[html.length] = ''; + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEKDAYS")) { + html = this.buildWeekdays(html); + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the Calendar's weekday headers. +* @method buildWeekdays +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.buildWeekdays = function(html) { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { + html[html.length] = ' '; + } + + for(var i=0;i'; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { + html[html.length] = ' '; + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar body. +* @method renderBody +* @param {Date} workingDate The current working Date being used for the render process +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderBody = function(workingDate, html) { + + var startDay = this.cfg.getProperty("START_WEEKDAY"); + + this.preMonthDays = workingDate.getDay(); + if (startDay > 0) { + this.preMonthDays -= startDay; + } + if (this.preMonthDays < 0) { + this.preMonthDays += 7; + } + + this.monthDays = YAHOO.widget.DateMath.findMonthEnd(workingDate).getDate(); + this.postMonthDays = YAHOO.widget.Calendar.DISPLAY_DAYS-this.preMonthDays-this.monthDays; + + workingDate = YAHOO.widget.DateMath.subtract(workingDate, YAHOO.widget.DateMath.DAY, this.preMonthDays); + + var useDate,weekNum,weekClass; + useDate = this.cfg.getProperty("pagedate"); + + html[html.length] = ''; + + var i = 0; + + var tempDiv = document.createElement("div"); + var cell = document.createElement("td"); + tempDiv.appendChild(cell); + + var jan1 = new Date(useDate.getFullYear(),0,1); + + var cal = this.parent || this; + + for (var r=0;r<6;r++) { + + weekNum = YAHOO.widget.DateMath.getWeekNumber(workingDate, useDate.getFullYear(), startDay); + + weekClass = "w" + weekNum; + + if (r !== 0 && this.isDateOOM(workingDate) && this.cfg.getProperty("HIDE_BLANK_WEEKS") === true) { + break; + } else { + + html[html.length] = ''; + + if (this.cfg.getProperty("SHOW_WEEK_HEADER")) { html = this.renderRowHeader(weekNum, html); } + + for (var d=0;d<7;d++){ // Render actual days + + var cellRenderers = []; + + this.clearElement(cell); + + YAHOO.util.Dom.addClass(cell, "calcell"); + + cell.id = this.id + "_cell" + i; + + cell.innerHTML = i; + + var renderer = null; + + if (workingDate.getFullYear() == this.today.getFullYear() && + workingDate.getMonth() == this.today.getMonth() && + workingDate.getDate() == this.today.getDate()) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleToday; + } + + this.cellDates[this.cellDates.length]=[workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]; // Add this date to cellDates + + if (this.isDateOOM(workingDate)) { + cellRenderers[cellRenderers.length]=cal.renderCellNotThisMonth; + } else { + + YAHOO.util.Dom.addClass(cell, "wd" + workingDate.getDay()); + YAHOO.util.Dom.addClass(cell, "d" + workingDate.getDate()); + + for (var s=0;s= d1.getTime() && workingDate.getTime() <= d2.getTime()) { + renderer = rArray[2]; + + if (workingDate.getTime()==d2.getTime()) { + this.renderStack.splice(s,1); + } + } + break; + case YAHOO.widget.Calendar.WEEKDAY: + + var weekday = rArray[1][0]; + if (workingDate.getDay()+1 == weekday) { + renderer = rArray[2]; + } + break; + case YAHOO.widget.Calendar.MONTH: + + month = rArray[1][0]; + if (workingDate.getMonth()+1 == month) { + renderer = rArray[2]; + } + break; + } + + if (renderer) { + cellRenderers[cellRenderers.length]=renderer; + } + } + + } + + if (this._indexOfSelectedFieldArray([workingDate.getFullYear(),workingDate.getMonth()+1,workingDate.getDate()]) > -1) { + cellRenderers[cellRenderers.length]=cal.renderCellStyleSelected; + } + + var mindate = this.cfg.getProperty("mindate"); + var maxdate = this.cfg.getProperty("maxdate"); + + if (mindate) { + mindate = YAHOO.widget.DateMath.clearTime(mindate); + } + if (maxdate) { + maxdate = YAHOO.widget.DateMath.clearTime(maxdate); + } + + if ( + (mindate && (workingDate.getTime() < mindate.getTime())) || + (maxdate && (workingDate.getTime() > maxdate.getTime())) + ) { + cellRenderers[cellRenderers.length]=cal.renderOutOfBoundsDate; + } else { + cellRenderers[cellRenderers.length]=cal.styleCellDefault; + cellRenderers[cellRenderers.length]=cal.renderCellDefault; + } + + + + for (var x=0;x= 0 && i <= 6) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TOP); + } + if ((i % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_LEFT); + } + if (((i+1) % 7) === 0) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RIGHT); + } + + var postDays = this.postMonthDays; + if (postDays >= 7 && this.cfg.getProperty("HIDE_BLANK_WEEKS")) { + var blankWeeks = Math.floor(postDays/7); + for (var p=0;p= ((this.preMonthDays+postDays+this.monthDays)-7)) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_BOTTOM); + } + + html[html.length] = tempDiv.innerHTML; + + i++; + } + + if (this.cfg.getProperty("SHOW_WEEK_FOOTER")) { html = this.renderRowFooter(weekNum, html); } + + html[html.length] = ''; + } + } + + html[html.length] = ''; + + return html; +}; + +/** +* Renders the calendar footer. In the default implementation, there is +* no footer. +* @method renderFooter +* @param {Array} html The current working HTML array +* @return {Array} The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderFooter = function(html) { return html; }; + +/** +* Renders the calendar after it has been configured. The render() method has a specific call chain that will execute +* when the method is called: renderHeader, renderBody, renderFooter. +* Refer to the documentation for those methods for information on +* individual render tasks. +* @method render +*/ +YAHOO.widget.Calendar.prototype.render = function() { + this.beforeRenderEvent.fire(); + + // Find starting day of the current month + var workingDate = YAHOO.widget.DateMath.findMonthStart(this.cfg.getProperty("pagedate")); + + this.resetRenderers(); + this.cellDates.length = 0; + + YAHOO.util.Event.purgeElement(this.oDomContainer, true); + + var html = []; + + html[html.length] = ''; + html = this.renderHeader(html); + html = this.renderBody(workingDate, html); + html = this.renderFooter(html); + html[html.length] = '
'; + + this.oDomContainer.innerHTML = html.join("\n"); + + this.applyListeners(); + this.cells = this.oDomContainer.getElementsByTagName("td"); + + this.cfg.refireEvent("title"); + this.cfg.refireEvent("close"); + this.cfg.refireEvent("iframe"); + + this.renderEvent.fire(); +}; + +/** +* Applies the Calendar's DOM listeners to applicable elements. +* @method applyListeners +*/ +YAHOO.widget.Calendar.prototype.applyListeners = function() { + + var root = this.oDomContainer; + var cal = this.parent || this; + + var linkLeft, linkRight; + + linkLeft = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_LEFT, "a", root); + linkRight = YAHOO.util.Dom.getElementsByClassName(this.Style.CSS_NAV_RIGHT, "a", root); + + if (linkLeft) { + this.linkLeft = linkLeft[0]; + YAHOO.util.Event.addListener(this.linkLeft, "mousedown", cal.previousMonth, cal, true); + } + + if (linkRight) { + this.linkRight = linkRight[0]; + YAHOO.util.Event.addListener(this.linkRight, "mousedown", cal.nextMonth, cal, true); + } + + if (this.domEventMap) { + var el,elements; + for (var cls in this.domEventMap) { + if (this.domEventMap.hasOwnProperty(cls)) { + var items = this.domEventMap[cls]; + + if (! (items instanceof Array)) { + items = [items]; + } + + for (var i=0;i'; + return html; +}; + +/** +* Renders the row footer for a week. +* @method renderRowFooter +* @param {Number} weekNum The week number of the current row +* @param {Array} cell The current working HTML array +*/ +YAHOO.widget.Calendar.prototype.renderRowFooter = function(weekNum, html) { + html[html.length] = '' + weekNum + ''; + return html; +}; + +/** +* Renders a single standard calendar cell in the calendar widget table. +* All logic for determining how a standard default cell will be rendered is +* encapsulated in this method, and must be accounted for when extending the +* widget class. +* @method renderCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell) { + cell.innerHTML = '' + this.buildDayLabel(workingDate) + ""; +}; + +/** +* Styles a selectable cell. +* @method styleCellDefault +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.styleCellDefault = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTABLE); +}; + + +/** +* Renders a single standard calendar cell using the CSS hightlight1 style +* @method renderCellStyleHighlight1 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight1 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT1); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight2 style +* @method renderCellStyleHighlight2 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight2 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT2); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight3 style +* @method renderCellStyleHighlight3 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight3 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT3); +}; + +/** +* Renders a single standard calendar cell using the CSS hightlight4 style +* @method renderCellStyleHighlight4 +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleHighlight4 = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_HIGHLIGHT4); +}; + +/** +* Applies the default style used for rendering today's date to the current calendar cell +* @method renderCellStyleToday +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleToday = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_TODAY); +}; + +/** +* Applies the default style used for rendering selected dates to the current calendar cell +* @method renderCellStyleSelected +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellStyleSelected = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_SELECTED); +}; + +/** +* Applies the default style used for rendering dates that are not a part of the current +* month (preceding or trailing the cells for the current month) +* @method renderCellNotThisMonth +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderCellNotThisMonth = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_OOM); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +/** +* Renders the current calendar cell as a non-selectable "black-out" date using the default +* restricted style. +* @method renderBodyCellRestricted +* @param {Date} workingDate The current working Date object being used to generate the calendar +* @param {HTMLTableCellElement} cell The current working cell in the calendar +* @return {String} YAHOO.widget.Calendar.STOP_RENDER if rendering should stop with this style, null or nothing if rendering +* should not be terminated +*/ +YAHOO.widget.Calendar.prototype.renderBodyCellRestricted = function(workingDate, cell) { + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL); + YAHOO.util.Dom.addClass(cell, this.Style.CSS_CELL_RESTRICTED); + cell.innerHTML=workingDate.getDate(); + return YAHOO.widget.Calendar.STOP_RENDER; +}; + +// END BUILT-IN TABLE CELL RENDERERS + +// BEGIN MONTH NAVIGATION METHODS + +/** +* Adds the designated number of months to the current calendar month, and sets the current +* calendar page date to the new month. +* @method addMonths +* @param {Number} count The number of months to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtracts the designated number of months from the current calendar month, and sets the current +* calendar page date to the new month. +* @method subtractMonths +* @param {Number} count The number of months to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractMonths = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.MONTH, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Adds the designated number of years to the current calendar, and sets the current +* calendar page date to the new month. +* @method addYears +* @param {Number} count The number of years to add to the current calendar +*/ +YAHOO.widget.Calendar.prototype.addYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.add(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Subtcats the designated number of years from the current calendar, and sets the current +* calendar page date to the new month. +* @method subtractYears +* @param {Number} count The number of years to subtract from the current calendar +*/ +YAHOO.widget.Calendar.prototype.subtractYears = function(count) { + this.cfg.setProperty("pagedate", YAHOO.widget.DateMath.subtract(this.cfg.getProperty("pagedate"), YAHOO.widget.DateMath.YEAR, count)); + this.resetRenderers(); + this.changePageEvent.fire(); +}; + +/** +* Navigates to the next month page in the calendar widget. +* @method nextMonth +*/ +YAHOO.widget.Calendar.prototype.nextMonth = function() { + this.addMonths(1); +}; + +/** +* Navigates to the previous month page in the calendar widget. +* @method previousMonth +*/ +YAHOO.widget.Calendar.prototype.previousMonth = function() { + this.subtractMonths(1); +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.Calendar.prototype.nextYear = function() { + this.addYears(1); +}; + +/** +* Navigates to the previous year in the currently selected month in the calendar widget. +* @method previousYear +*/ +YAHOO.widget.Calendar.prototype.previousYear = function() { + this.subtractYears(1); +}; + +// END MONTH NAVIGATION METHODS + +// BEGIN SELECTION METHODS + +/** +* Resets the calendar widget to the originally selected month and year, and +* sets the calendar to the initial selection(s). +* @method reset +*/ +YAHOO.widget.Calendar.prototype.reset = function() { + this.cfg.resetProperty("selected"); + this.cfg.resetProperty("pagedate"); + this.resetEvent.fire(); +}; + +/** +* Clears the selected dates in the current calendar widget and sets the calendar +* to the current month and year. +* @method clear +*/ +YAHOO.widget.Calendar.prototype.clear = function() { + this.cfg.setProperty("selected", []); + this.cfg.setProperty("pagedate", new Date(this.today.getTime())); + this.clearEvent.fire(); +}; + +/** +* Selects a date or a collection of dates on the current calendar. This method, by default, +* does not call the render method explicitly. Once selection has completed, render must be +* called for the changes to be reflected visually. +* @method select +* @param {String/Date/Date[]} date The date string of dates to select in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +*/ +YAHOO.widget.Calendar.prototype.select = function(date) { + this.beforeSelectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var aToBeSelected = this._toFieldArray(date); + + for (var a=0;a -1) { + if (this.cfg.getProperty("pagedate").getMonth() == dCellDate.getMonth() && + this.cfg.getProperty("pagedate").getFullYear() == dCellDate.getFullYear()) { + YAHOO.util.Dom.removeClass(cell, this.Style.CSS_CELL_SELECTED); + } + + selected.splice(cellDateIndex, 1); + } + + + if (this.parent) { + this.parent.cfg.setProperty("selected", selected); + } else { + this.cfg.setProperty("selected", selected); + } + + this.deselectEvent.fire(selectDate); + return this.getSelectedDates(); +}; + +/** +* Deselects all dates on the current calendar. +* @method deselectAll +* @return {Date[]} Array of JavaScript Date objects representing all individual dates that are currently selected. +* Assuming that this function executes properly, the return value should be an empty array. +* However, the empty array is returned for the sake of being able to check the selection status +* of the calendar. +*/ +YAHOO.widget.Calendar.prototype.deselectAll = function() { + this.beforeDeselectEvent.fire(); + + var selected = this.cfg.getProperty("selected"); + var count = selected.length; + var sel = selected.concat(); + + if (this.parent) { + this.parent.cfg.setProperty("selected", []); + } else { + this.cfg.setProperty("selected", []); + } + + if (count > 0) { + this.deselectEvent.fire(sel); + } + + return this.getSelectedDates(); +}; + +// END SELECTION METHODS + +// BEGIN TYPE CONVERSION METHODS + +/** +* Converts a date (either a JavaScript Date object, or a date string) to the internal data structure +* used to represent dates: [[yyyy,mm,dd],[yyyy,mm,dd]]. +* @method _toFieldArray +* @private +* @param {String/Date/Date[]} date The date string of dates to deselect in the current calendar. Valid formats are +* individual date(s) (12/24/2005,12/26/2005) or date range(s) (12/24/2005-1/1/2006). +* Multiple comma-delimited dates can also be passed to this method (12/24/2005,12/11/2005-12/13/2005). +* This method can also take a JavaScript Date object or an array of Date objects. +* @return {Array[](Number[])} Array of date field arrays +*/ +YAHOO.widget.Calendar.prototype._toFieldArray = function(date) { + var returnDate = []; + + if (date instanceof Date) { + returnDate = [[date.getFullYear(), date.getMonth()+1, date.getDate()]]; + } else if (typeof date == 'string') { + returnDate = this._parseDates(date); + } else if (date instanceof Array) { + for (var i=0;i +*
+*
+* +* The tables for the calendars ("cal1_0" and "cal1_1") will be inserted into those containers. +* @namespace YAHOO.widget +* @class CalendarGroup +* @constructor +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup = function(id, containerId, config) { + if (arguments.length > 0) { + this.init(id, containerId, config); + } +}; + +/** +* Initializes the calendar group. All subclasses must call this method in order for the +* group to be initialized properly. +* @method init +* @param {String} id The id of the table element that will represent the calendar widget +* @param {String} containerId The id of the container div element that will wrap the calendar table +* @param {Object} config The configuration object containing the Calendar's arguments +*/ +YAHOO.widget.CalendarGroup.prototype.init = function(id, containerId, config) { + this.initEvents(); + this.initStyles(); + + /** + * The collection of Calendar pages contained within the CalendarGroup + * @property pages + * @type YAHOO.widget.Calendar[] + */ + this.pages = []; + + /** + * The unique id associated with the CalendarGroup + * @property id + * @type String + */ + this.id = id; + + /** + * The unique id associated with the CalendarGroup container + * @property containerId + * @type String + */ + this.containerId = containerId; + + /** + * The outer containing element for the CalendarGroup + * @property oDomContainer + * @type HTMLElement + */ + this.oDomContainer = document.getElementById(containerId); + + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_CONTAINER); + YAHOO.util.Dom.addClass(this.oDomContainer, YAHOO.widget.CalendarGroup.CSS_MULTI_UP); + + /** + * The Config object used to hold the configuration variables for the CalendarGroup + * @property cfg + * @type YAHOO.util.Config + */ + this.cfg = new YAHOO.util.Config(this); + + /** + * The local object which contains the CalendarGroup's options + * @property Options + * @type Object + */ + this.Options = {}; + + /** + * The local object which contains the CalendarGroup's locale settings + * @property Locale + * @type Object + */ + this.Locale = {}; + + this.setupConfig(); + + if (config) { + this.cfg.applyConfig(config, true); + } + + this.cfg.fireQueue(); + + // OPERA HACK FOR MISWRAPPED FLOATS + if (this.browser == "opera"){ + var fixWidth = function() { + var startW = this.oDomContainer.offsetWidth; + var w = 0; + for (var p=0;p 0) { + this.oDomContainer.style.width = w + "px"; + } + }; + this.renderEvent.subscribe(fixWidth,this,true); + } +}; + + +YAHOO.widget.CalendarGroup.prototype.setupConfig = function() { + /** + * The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments. + * @config pages + * @type Number + * @default 2 + */ + this.cfg.addProperty("pages", { value:2, validator:this.cfg.checkNumber, handler:this.configPages } ); + + /** + * The month/year representing the current visible Calendar date (mm/yyyy) + * @config pagedate + * @type String + * @default today's date + */ + this.cfg.addProperty("pagedate", { value:new Date(), handler:this.configPageDate } ); + + /** + * The date or range of dates representing the current Calendar selection + * @config selected + * @type String + * @default [] + */ + this.cfg.addProperty("selected", { value:[], handler:this.delegateConfig } ); + + /** + * The title to display above the CalendarGroup's month header + * @config title + * @type String + * @default "" + */ + this.cfg.addProperty("title", { value:"", handler:this.configTitle } ); + + /** + * Whether or not a close button should be displayed for this CalendarGroup + * @config close + * @type Boolean + * @default false + */ + this.cfg.addProperty("close", { value:false, handler:this.configClose } ); + + /** + * Whether or not an iframe shim should be placed under the Calendar to prevent select boxes from bleeding through in Internet Explorer 6 and below. + * @config iframe + * @type Boolean + * @default true + */ + this.cfg.addProperty("iframe", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The minimum selectable date in the current Calendar (mm/dd/yyyy) + * @config mindate + * @type String + * @default null + */ + this.cfg.addProperty("mindate", { value:null, handler:this.delegateConfig } ); + + /** + * The maximum selectable date in the current Calendar (mm/dd/yyyy) + * @config maxdate + * @type String + * @default null + */ + this.cfg.addProperty("maxdate", { value:null, handler:this.delegateConfig } ); + + // Options properties + + /** + * True if the Calendar should allow multiple selections. False by default. + * @config MULTI_SELECT + * @type Boolean + * @default false + */ + this.cfg.addProperty("MULTI_SELECT", { value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The weekday the week begins on. Default is 0 (Sunday). + * @config START_WEEKDAY + * @type number + * @default 0 + */ + this.cfg.addProperty("START_WEEKDAY", { value:0, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * True if the Calendar should show weekday labels. True by default. + * @config SHOW_WEEKDAYS + * @type Boolean + * @default true + */ + this.cfg.addProperty("SHOW_WEEKDAYS", { value:true, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row headers. False by default. + * @config SHOW_WEEK_HEADER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_HEADER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should show week row footers. False by default. + * @config SHOW_WEEK_FOOTER + * @type Boolean + * @default false + */ + this.cfg.addProperty("SHOW_WEEK_FOOTER",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * True if the Calendar should suppress weeks that are not a part of the current month. False by default. + * @config HIDE_BLANK_WEEKS + * @type Boolean + * @default false + */ + this.cfg.addProperty("HIDE_BLANK_WEEKS",{ value:false, handler:this.delegateConfig, validator:this.cfg.checkBoolean } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_LEFT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif" + */ + this.cfg.addProperty("NAV_ARROW_LEFT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/callt.gif", handler:this.delegateConfig } ); + + /** + * The image that should be used for the left navigation arrow. + * @config NAV_ARROW_RIGHT + * @type String + * @default YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif" + */ + this.cfg.addProperty("NAV_ARROW_RIGHT", { value:YAHOO.widget.Calendar.IMG_ROOT + "us/tr/calrt.gif", handler:this.delegateConfig } ); + + // Locale properties + + /** + * The short month labels for the current locale. + * @config MONTHS_SHORT + * @type String[] + * @default ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + */ + this.cfg.addProperty("MONTHS_SHORT", { value:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], handler:this.delegateConfig } ); + + /** + * The long month labels for the current locale. + * @config MONTHS_LONG + * @type String[] + * @default ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + */ + this.cfg.addProperty("MONTHS_LONG", { value:["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], handler:this.delegateConfig } ); + + /** + * The 1-character weekday labels for the current locale. + * @config WEEKDAYS_1CHAR + * @type String[] + * @default ["S", "M", "T", "W", "T", "F", "S"] + */ + this.cfg.addProperty("WEEKDAYS_1CHAR", { value:["S", "M", "T", "W", "T", "F", "S"], handler:this.delegateConfig } ); + + /** + * The short weekday labels for the current locale. + * @config WEEKDAYS_SHORT + * @type String[] + * @default ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + */ + this.cfg.addProperty("WEEKDAYS_SHORT", { value:["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], handler:this.delegateConfig } ); + + /** + * The medium weekday labels for the current locale. + * @config WEEKDAYS_MEDIUM + * @type String[] + * @default ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] + */ + this.cfg.addProperty("WEEKDAYS_MEDIUM", { value:["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], handler:this.delegateConfig } ); + + /** + * The long weekday labels for the current locale. + * @config WEEKDAYS_LONG + * @type String[] + * @default ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + */ + this.cfg.addProperty("WEEKDAYS_LONG", { value:["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], handler:this.delegateConfig } ); + + /** + * The setting that determines which length of month labels should be used. Possible values are "short" and "long". + * @config LOCALE_MONTHS + * @type String + * @default "long" + */ + this.cfg.addProperty("LOCALE_MONTHS", { value:"long", handler:this.delegateConfig } ); + + /** + * The setting that determines which length of weekday labels should be used. Possible values are "1char", "short", "medium", and "long". + * @config LOCALE_WEEKDAYS + * @type String + * @default "short" + */ + this.cfg.addProperty("LOCALE_WEEKDAYS", { value:"short", handler:this.delegateConfig } ); + + /** + * The value used to delimit individual dates in a date string passed to various Calendar functions. + * @config DATE_DELIMITER + * @type String + * @default "," + */ + this.cfg.addProperty("DATE_DELIMITER", { value:",", handler:this.delegateConfig } ); + + /** + * The value used to delimit date fields in a date string passed to various Calendar functions. + * @config DATE_FIELD_DELIMITER + * @type String + * @default "/" + */ + this.cfg.addProperty("DATE_FIELD_DELIMITER",{ value:"/", handler:this.delegateConfig } ); + + /** + * The value used to delimit date ranges in a date string passed to various Calendar functions. + * @config DATE_RANGE_DELIMITER + * @type String + * @default "-" + */ + this.cfg.addProperty("DATE_RANGE_DELIMITER",{ value:"-", handler:this.delegateConfig } ); + + /** + * The position of the month in a month/year date string + * @config MY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/year date string + * @config MY_YEAR_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MY_YEAR_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day date string + * @config MD_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MD_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/year date string + * @config MD_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MD_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the month in a month/day/year date string + * @config MDY_MONTH_POSITION + * @type Number + * @default 1 + */ + this.cfg.addProperty("MDY_MONTH_POSITION", { value:1, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the day in a month/day/year date string + * @config MDY_DAY_POSITION + * @type Number + * @default 2 + */ + this.cfg.addProperty("MDY_DAY_POSITION", { value:2, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + + /** + * The position of the year in a month/day/year date string + * @config MDY_YEAR_POSITION + * @type Number + * @default 3 + */ + this.cfg.addProperty("MDY_YEAR_POSITION", { value:3, handler:this.delegateConfig, validator:this.cfg.checkNumber } ); + +}; + +/** +* Initializes CalendarGroup's built-in CustomEvents +* @method initEvents +*/ +YAHOO.widget.CalendarGroup.prototype.initEvents = function() { + var me = this; + + /** + * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents + * @method sub + * @private + * @param {Function} fn The function to subscribe to this CustomEvent + * @param {Object} obj The CustomEvent's scope object + * @param {Boolean} bOverride Whether or not to apply scope correction + */ + var sub = function(fn, obj, bOverride) { + for (var p=0;p0) { + year+=1; + } + cal.setYear(year); + } +}; +/** +* Calls the render function of all child calendars within the group. +* @method render +*/ +YAHOO.widget.CalendarGroup.prototype.render = function() { + this.renderHeader(); + for (var p=0;p=0;--p) { + var cal = this.pages[p]; + cal.previousMonth(); + } +}; + +/** +* Navigates to the next year in the currently selected month in the calendar widget. +* @method nextYear +*/ +YAHOO.widget.CalendarGroup.prototype.nextYear = function() { + for (var p=0;p