code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','vi',{uicolor:{title:'Giao diện người dùng Color Picker',preview:'Xem trước trực tiếp',config:'Dán chuỗi này vào tập tin config.js của bạn',predefined:'Tập màu định nghĩa sẵn'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','hr',{uicolor:{title:'UI odabir boja',preview:'Pregled uživo',config:'Zalijepite ovaj tekst u Vašu config.js datoteku.',predefined:'Već postavljeni setovi boja'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','tr',{uicolor:{title:'UI Renk Seçicisi',preview:'Canlı önizleme',config:'Bu dizeyi config.js dosyasının içine yapıştırın',predefined:'Önceden tanımlanmış renk kümeleri'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fr',{uicolor:{title:'UI Sélecteur de couleur',preview:'Aperçu',config:'Collez cette chaîne de caractères dans votre fichier config.js',predefined:'Palettes de couleurs prédéfinies'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','zh-cn',{uicolor:{title:'用户界面颜色选择器',preview:'即时预览',config:'粘贴此字符串到你的 config.js 文件',predefined:'预定义颜色集'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','eo',{uicolor:{title:'UI Kolorselektilo',preview:'Vidigi la aspekton',config:'Gluu tiun signoĉenon en vian dosieron config.js',predefined:'Antaŭdifinita koloraro'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','da',{uicolor:{title:'Brugerflade på farvevælger',preview:'Vis liveeksempel',config:'Indsæt denne streng i din config.js fil',predefined:'Prædefinerede farveskemaer'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nb',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','bg',{uicolor:{title:'ПИ избор на цвят',preview:'Преглед',config:'Вмъкнете този низ във Вашия config.js fajl',predefined:'Предефинирани цветови палитри'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','el',{uicolor:{title:'Διεπαφή Επιλογέα Χρωμάτων',preview:'Ζωντανή Προεπισκόπηση',config:'Επικολλήστε αυτό το κείμενο στο αρχείο config.js',predefined:'Προκαθορισμένα σύνολα χρωμάτων'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fi',{uicolor:{title:'Käyttöliittymän värivalitsin',preview:'Esikatsele',config:'Liitä tämä merkkijono config.js tiedostoosi',predefined:'Esimääritellyt värijoukot'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cy',{uicolor:{title:"Dewisydd Lliwiau'r UI",preview:'Rhagolwg Byw',config:"Gludwch y llinyn hwn i'ch ffeil config.js",predefined:"Setiau lliw wedi'u cyn-ddiffinio"}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','no',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','mk',{uicolor:{title:'Палета со бои',preview:'Преглед',config:'Залепи го овој текст во config.js датотеката',predefined:'Предефинирани множества на бои'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fa',{uicolor:{title:'انتخاب رنگ UI',preview:'پیشنمایش زنده',config:'این رشته را در فایل config.js خود بچسبانید.',predefined:'مجموعه رنگ از پیش تعریف شده'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','et',{uicolor:{title:'Värvivalija kasutajaliides',preview:'Automaatne eelvaade',config:'Aseta see sõne oma config.js faili.',predefined:'Eelmääratud värvikomplektid'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','uk',{uicolor:{title:'Color Picker Інтерфейс',preview:'Перегляд наживо',config:'Вставте цей рядок у файл config.js',predefined:'Стандартний набір кольорів'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cs',{uicolor:{title:'Výběr barvy rozhraní',preview:'Živý náhled',config:'Vložte tento řetězec do Vašeho souboru config.js',predefined:'Přednastavené sady barev'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','pt-br',{uicolor:{title:'Paleta de Cores',preview:'Visualização ao vivo',config:'Cole o texto no seu arquivo config.js',predefined:'Conjuntos de cores predefinidos'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','nl',{devTools:{title:'Elementinformatie',dialogName:'Naam dialoogvenster',tabName:'Tabnaam',elementId:'Element ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','ug',{devTools:{title:'ئېلېمېنت ئۇچۇرى',dialogName:'سۆزلەشكۈ كۆزنەك ئاتى',tabName:'Tab ئاتى',elementId:'ئېلېمېنت كىملىكى',elementType:'ئېلېمېنت تىپى'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','it',{devTools:{title:'Informazioni elemento',dialogName:'Nome finestra di dialogo',tabName:'Nome Tab',elementId:'ID Elemento',elementType:'Tipo elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','de',{devTools:{title:'Elementinformation',dialogName:'Dialogfenstername',tabName:'Reitername',elementId:'Element ID',elementType:'Elementtyp'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','pl',{devTools:{title:'Informacja o elemencie',dialogName:'Nazwa okna dialogowego',tabName:'Nazwa zakładki',elementId:'ID elementu',elementType:'Typ elementu'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','vi',{devTools:{title:'Thông tin thành ph',dialogName:'Tên hộp tho',tabName:'Tên th',elementId:'Mã thành ph',elementType:'Loại thành ph'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','hr',{devTools:{title:'Informacije elementa',dialogName:'Naziv prozora za dijalog',tabName:'Naziva jahača',elementId:'ID elementa',elementType:'Vrsta elementa'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','tr',{devTools:{title:'Eleman Bilgisi',dialogName:'İletişim pencere ismi',tabName:'Sekme adı',elementId:'Eleman ID',elementType:'Eleman türü'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fr',{devTools:{title:"Information sur l'élément",dialogName:'Nom de la fenêtre de dialogue',tabName:"Nom de l'onglet",elementId:"ID de l'élément",elementType:"Type de l'élément"}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','zh-cn',{devTools:{title:'元素信息',dialogName:'对话框窗口名称',tabName:'Tab 名称',elementId:'元素 ID',elementType:'元素类型'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','eo',{devTools:{title:'Informo pri la elemento',dialogName:'Nomo de la dialogfenestro',tabName:'Langetnomo',elementId:'ID de la elemento',elementType:'Tipo de la elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','en',{devTools:{title:'Element Information',dialogName:'Dialog window name',tabName:'Tab name',elementId:'Element ID',elementType:'Element type'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','da',{devTools:{title:'Information på elementet',dialogName:'Dialogboks',tabName:'Tab beskrivelse',elementId:'ID på element',elementType:'Type af element'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','nb',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','bg',{devTools:{title:'Информация за елемента',dialogName:'Име на диалоговия прозорец',tabName:'Име на таб',elementId:'ID на елемента',elementType:'Тип на елемента'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','el',{devTools:{title:'Πληροφορίες Στοιχείου',dialogName:'Όνομα παραθύρου διαλόγου',tabName:'Όνομα καρτέλας',elementId:'ID Στοιχείου',elementType:'Τύπος στοιχείου'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fi',{devTools:{title:'Elementin tiedot',dialogName:'Dialogi-ikkunan nimi',tabName:'Välilehden nimi',elementId:'Elementin ID',elementType:'Elementin tyyppi'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','cy',{devTools:{title:'Gwybodaeth am yr Elfen',dialogName:'Enw ffenestr y deialog',tabName:"Enw'r tab",elementId:'ID yr Elfen',elementType:'Math yr elfen'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','no',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fa',{devTools:{title:'اطلاعات عنصر',dialogName:'نام پنجره محاورهای',tabName:'نام برگه',elementId:'ID عنصر',elementType:'نوع عنصر'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','et',{devTools:{title:'Elemendi andmed',dialogName:'Dialoogiakna nimi',tabName:'Saki nimi',elementId:'Elemendi ID',elementType:'Elemendi liik'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','he',{devTools:{title:'מידע על האלמנט',dialogName:'שם הדיאלוג',tabName:'שם הטאב',elementId:'ID של האלמנט',elementType:'סוג האלמנט'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','uk',{devTools:{title:'Відомості про Елемент',dialogName:'Заголовок діалогового вікна',tabName:'Назва вкладки',elementId:'Ідентифікатор Елемента',elementType:'Тип Елемента'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','cs',{devTools:{title:'Informace o prvku',dialogName:'Název dialogového okna',tabName:'Název karty',elementId:'ID prvku',elementType:'Typ prvku'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','pt-br',{devTools:{title:'Informação do Elemento',dialogName:'Nome da janela de diálogo',tabName:'Nome da aba',elementId:'ID do elemento',elementType:'Tipo do elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','gu',{devTools:{title:'પ્રાથમિક માહિતી',dialogName:'વિન્ડોનું નામ',tabName:'ટેબનું નામ',elementId:'પ્રાથમિક આઈડી',elementType:'પ્રાથમિક પ્રકાર'}});
| JavaScript |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('docprops',{init:function(a){var b=new CKEDITOR.dialogCommand('docProps');b.modes={wysiwyg:a.config.fullPage};a.addCommand('docProps',b);CKEDITOR.dialog.add('docProps',this.path+'dialogs/docprops.js');a.ui.addButton('DocProps',{label:a.lang.docprops.label,command:'docProps'});}});
| JavaScript |
/**
* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{ name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } },
{ name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } },
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
// (This requires the "stylescombo" plugin)
/*
{ name: 'Strong', element: 'strong', overrides: 'b' },
{ name: 'Emphasis', element: 'em' , overrides: 'i' },
{ name: 'Underline', element: 'u' },
{ name: 'Strikethrough', element: 'strike' },
{ name: 'Subscript', element: 'sub' },
{ name: 'Superscript', element: 'sup' },
*/
{ name: 'Marker', element: 'span', attributes: { 'class': 'marker' } },
{ name: 'Big', element: 'big' },
{ name: 'Small', element: 'small' },
{ name: 'Typewriter', element: 'tt' },
{ name: 'Computer Code', element: 'code' },
{ name: 'Keyboard Phrase', element: 'kbd' },
{ name: 'Sample Text', element: 'samp' },
{ name: 'Variable', element: 'var' },
{ name: 'Deleted Text', element: 'del' },
{ name: 'Inserted Text', element: 'ins' },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
{ name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } },
{ name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } },
/* Object Styles */
{
name: 'Styled image (left)',
element: 'img',
attributes: { 'class': 'left' }
},
{
name: 'Styled image (right)',
element: 'img',
attributes: { 'class': 'right' }
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
] );
| JavaScript |
/**
* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'myDialog', function( editor ) {
return {
title: 'My Dialog',
minWidth: 400,
minHeight: 200,
contents: [
{
id: 'tab1',
label: 'First Tab',
title: 'First Tab',
elements: [
{
id: 'input1',
type: 'text',
label: 'Text Field'
},
{
id: 'select1',
type: 'select',
label: 'Select Field',
items: [
[ 'option1', 'value1' ],
[ 'option2', 'value2' ]
]
}
]
},
{
id: 'tab2',
label: 'Second Tab',
title: 'Second Tab',
elements: [
{
id: 'button1',
type: 'button',
label: 'Button Field'
}
]
}
]
};
} );
| JavaScript |
/**
* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
// Tool scripts for the sample pages.
// This file can be ignored and is not required to make use of CKEditor.
( function() {
CKEDITOR.on( 'instanceReady', function( ev ) {
// Check for sample compliance.
var editor = ev.editor,
meta = CKEDITOR.document.$.getElementsByName( 'ckeditor-sample-required-plugins' ),
requires = meta.length ? CKEDITOR.dom.element.get( meta[ 0 ] ).getAttribute( 'content' ).split( ',' ) : [],
missing = [],
i;
if ( requires.length ) {
for ( i = 0; i < requires.length; i++ ) {
if ( !editor.plugins[ requires[ i ] ] )
missing.push( '<code>' + requires[ i ] + '</code>' );
}
if ( missing.length ) {
var warn = CKEDITOR.dom.element.createFromHtml(
'<div class="warning">' +
'<span>To fully experience this demo, the ' + missing.join( ', ' ) + ' plugin' + ( missing.length > 1 ? 's are' : ' is' ) + ' required.</span>' +
'</div>'
);
warn.insertBefore( editor.container );
}
}
// Set icons.
var doc = new CKEDITOR.dom.document( document ),
icons = doc.find( '.button_icon' );
for ( i = 0; i < icons.count(); i++ ) {
var icon = icons.getItem( i ),
name = icon.getAttribute( 'data-icon' ),
style = CKEDITOR.skin.getIconStyle( name, ( CKEDITOR.lang.dir == 'rtl' ) );
icon.addClass( 'cke_button_icon' );
icon.addClass( 'cke_button__' + name + '_icon' );
icon.setAttribute( 'style', style );
icon.setStyle( 'float', 'none' );
}
} );
} )();
| JavaScript |
function fn_OpenModalDialog(sUrl, sParam, width, height) {
try {
var strReturn = "";
var winx = (screen.width - width) / 2;
var winy = (screen.height - height) / 2;
var settings = "dialogHeight: " + height + "px; ";
settings += "dialogWidth: " + width + "px; ";
settings += "dialogTop: " + winy + "px; ";
settings += "dialogLeft: " + winx + "px; ";
settings += "scroll :no; ";
settings += "resizable :no; ";
settings += "help :no; ";
settings += "status :no; ";
settings += "unadorned :no; ";
strReturn = window.showModalDialog("../Common/ModalDialog.htm?" + sUrl, sParam, settings);
return strReturn;
}
catch (exception) {
alert(exception.description);
}
}
function MM_swapImgRestore() { //v3.0
var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MM_preloadImages() { //v3.0
var d = document; if (d.images) {
if (!d.MM_p) d.MM_p = new Array();
var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
}
}
function MM_findObj(n, d) { //v4.01
var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
}
if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
if (!x && d.getElementById) x = d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
} | JavaScript |
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* Feature model class for Store Locator library.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Representation of a feature of a store. (e.g. 24 hours, BYO, etc).
* @example <pre>
* var feature = new storeLocator.Feature('24hour', 'Open 24 Hours');
* </pre>
* @param {string} id unique identifier for this feature.
* @param {string} name display name of this feature.
* @constructor
* @implements storeLocator_Feature
*/
storeLocator.Feature = function(id, name) {
this.id_ = id;
this.name_ = name;
};
storeLocator['Feature'] = storeLocator.Feature;
/**
* Gets this Feature's ID.
* @return {string} this feature's ID.
*/
storeLocator.Feature.prototype.getId = function() {
return this.id_;
};
/**
* Gets this Feature's display name.
* @return {string} this feature's display name.
*/
storeLocator.Feature.prototype.getDisplayName = function() {
return this.name_;
};
storeLocator.Feature.prototype.toString = function() {
return this.getDisplayName();
};
| JavaScript |
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* Allows developers to specify a static set of stores to be used in the
* storelocator.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A DataFeed with a static set of stores. Provides sorting of stores by
* proximity and feature filtering (store must have <em>all</em> features from
* the filter).
* @example <pre>
* var dataFeed = new storeLocator.StaticDataFeed();
* jQuery.getJSON('stores.json', function(json) {
* var stores = parseStores(json);
* dataFeed.setStores(stores);
* });
* new storeLocator.View(map, dataFeed);
* </pre>
* @implements {storeLocator.DataFeed}
* @constructor
* @implements storeLocator_StaticDataFeed
*/
storeLocator.StaticDataFeed = function() {
/**
* The static list of stores.
* @private
* @type {Array.<storeLocator.Store>}
*/
this.stores_ = [];
};
storeLocator['StaticDataFeed'] = storeLocator.StaticDataFeed;
/**
* This will contain a callback to be called if getStores was called before
* setStores (i.e. if the map is waiting for data from the data source).
* @private
* @type {Function}
*/
storeLocator.StaticDataFeed.prototype.firstCallback_;
/**
* Set the stores for this data feed.
* @param {!Array.<!storeLocator.Store>} stores the stores for this data feed.
*/
storeLocator.StaticDataFeed.prototype.setStores = function(stores) {
this.stores_ = stores;
if (this.firstCallback_) {
this.firstCallback_();
} else {
delete this.firstCallback_;
}
};
/**
* @inheritDoc
*/
storeLocator.StaticDataFeed.prototype.getStores = function(bounds, features,
callback) {
// Prevent race condition - if getStores is called before stores are loaded.
if (!this.stores_.length) {
var that = this;
this.firstCallback_ = function() {
that.getStores(bounds, features, callback);
};
return;
}
// Filter stores for features.
var stores = [];
for (var i = 0, store; store = this.stores_[i]; i++) {
if (store.hasAllFeatures(features)) {
stores.push(store);
}
}
this.sortByDistance_(bounds.getCenter(), stores);
callback(stores);
};
/**
* Sorts a list of given stores by distance from a point in ascending order.
* Directly manipulates the given array (has side effects).
* @private
* @param {google.maps.LatLng} latLng the point to sort from.
* @param {!Array.<!storeLocator.Store>} stores the stores to sort.
*/
storeLocator.StaticDataFeed.prototype.sortByDistance_ = function(latLng,
stores) {
stores.sort(function(a, b) {
return a.distanceTo(latLng) - b.distanceTo(latLng);
});
};
| JavaScript |
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* FeatureSet class for Store Locator library. A mutable, ordered set of
* storeLocator.Features.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A mutable, ordered set of <code>storeLocator.Feature</code>s.
* @example <pre>
* var feature1 = new storeLocator.Feature('1', 'Feature One');
* var feature2 = new storeLocator.Feature('2', 'Feature Two');
* var feature3 = new storeLocator.Feature('3', 'Feature Three');
*
* var featureSet = new storeLocator.FeatureSet(feature1, feature2, feature3);
* </pre>
* @param {...storeLocator.Feature} var_args the initial features to add to
* the set.
* @constructor
* @implements storeLocator_FeatureSet
*/
storeLocator.FeatureSet = function(var_args) {
/**
* Stores references to the actual Feature.
* @private
* @type {!Array.<storeLocator.Feature>}
*/
this.array_ = [];
/**
* Maps from a Feature's id to its array index.
* @private
* @type {Object.<string, number>}
*/
this.hash_ = {};
for (var i = 0, feature; feature = arguments[i]; i++) {
this.add(feature);
}
};
storeLocator['FeatureSet'] = storeLocator.FeatureSet;
/**
* Adds the given feature to the set, if it doesn't exist in the set already.
* Else, removes the feature from the set.
* @param {!storeLocator.Feature} feature the feature to toggle.
*/
storeLocator.FeatureSet.prototype.toggle = function(feature) {
if (this.contains(feature)) {
this.remove(feature);
} else {
this.add(feature);
}
};
/**
* Check if a feature exists within this set.
* @param {!storeLocator.Feature} feature the feature.
* @return {boolean} true if the set contains the given feature.
*/
storeLocator.FeatureSet.prototype.contains = function(feature) {
return feature.getId() in this.hash_;
};
/**
* Gets a Feature object from the set, by the feature id.
* @param {string} featureId the feature's id.
* @return {storeLocator.Feature} the feature, if the set contains it.
*/
storeLocator.FeatureSet.prototype.getById = function(featureId) {
if (featureId in this.hash_) {
return this.array_[this.hash_[featureId]];
}
return null;
};
/**
* Adds a feature to the set.
* @param {storeLocator.Feature} feature the feature to add.
*/
storeLocator.FeatureSet.prototype.add = function(feature) {
if (!feature) {
return;
}
this.array_.push(feature);
this.hash_[feature.getId()] = this.array_.length - 1;
};
/**
* Removes a feature from the set, if it already exists in the set. If it does
* not already exist in the set, this function is a no op.
* @param {!storeLocator.Feature} feature the feature to remove.
*/
storeLocator.FeatureSet.prototype.remove = function(feature) {
if (!this.contains(feature)) {
return;
}
this.array_[this.hash_[feature.getId()]] = null;
delete this.hash_[feature.getId()];
};
/**
* Get the contents of this set as an Array.
* @return {Array.<!storeLocator.Feature>} the features in the set, in the order
* they were inserted.
*/
storeLocator.FeatureSet.prototype.asList = function() {
var filtered = [];
for (var i = 0, ii = this.array_.length; i < ii; i++) {
var elem = this.array_[i];
if (elem !== null) {
filtered.push(elem);
}
}
return filtered;
};
/**
* Empty feature set.
* @type storeLocator.FeatureSet
* @const
*/
storeLocator.FeatureSet.NONE = new storeLocator.FeatureSet;
| JavaScript |
// Copyright 2012 Google Inc.
/**
* @name Store Locator for Google Maps API V3
* @version 0.1
* @author Chris Broadfoot (Google)
* @fileoverview
* This library makes it easy to create a fully-featured Store Locator for
* your business's website.
*/
/**
* @license
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Namespace for Store Locator.
* @constructor
*/
var storeLocator = function() {};
window['storeLocator'] = storeLocator;
/**
* Convert from degrees to radians.
* @private
* @param {number} degrees the number in degrees.
* @return {number} the number in radians.
*/
storeLocator.toRad_ = function(degrees) {
return degrees * Math.PI / 180;
};
| JavaScript |
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* An info panel, which complements the map view of the Store Locator.
* Provides a list of stores, location search, feature filter, and directions.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* An info panel, to complement the map view.
* Provides a list of stores, location search, feature filter, and directions.
* @example <pre>
* var container = document.getElementById('panel');
* var panel = new storeLocator.Panel(container, {
* view: view,
* locationSearchLabel: 'Location:'
* });
* google.maps.event.addListener(panel, 'geocode', function(result) {
* geocodeMarker.setPosition(result.geometry.location);
* });
* </pre>
* @extends {google.maps.MVCObject}
* @param {!Node} el the element to contain this panel.
* @param {storeLocator.PanelOptions} opt_options
* @constructor
* @implements storeLocator_Panel
*/
storeLocator.Panel = function(el, opt_options) {
this.el_ = $(el);
this.el_.addClass('storelocator-panel');
this.settings_ = $.extend({
'locationSearch': true,
'locationSearchLabel': 'Where are you?',
'featureFilter': true,
'directions': true,
'view': null
}, opt_options);
this.directionsRenderer_ = new google.maps.DirectionsRenderer({
draggable: true
});
this.directionsService_ = new google.maps.DirectionsService;
this.init_();
};
storeLocator['Panel'] = storeLocator.Panel;
storeLocator.Panel.prototype = new google.maps.MVCObject;
/**
* Initialise the info panel
* @private
*/
storeLocator.Panel.prototype.init_ = function() {
var that = this;
this.itemCache_ = {};
if (this.settings_['view']) {
this.set('view', this.settings_['view']);
}
this.filter_ = $('<form class="storelocator-filter"/>');
this.el_.append(this.filter_);
if (this.settings_['locationSearch']) {
this.locationSearch_ = $('<div class="location-search"><h4>' +
this.settings_['locationSearchLabel'] + '</h4><input></div>');
this.filter_.append(this.locationSearch_);
if (typeof google.maps.places != 'undefined') {
this.initAutocomplete_();
} else {
this.filter_.submit(function() {
that.searchPosition($('input', that.locationSearch_).val());
});
}
this.filter_.submit(function() {
return false;
});
google.maps.event.addListener(this, 'geocode', function(place) {
if (that.searchPositionTimeout_) {
window.clearTimeout(that.searchPositionTimeout_);
}
if (!place.geometry) {
that.searchPosition(place.name);
return;
}
this.directionsFrom_ = place.geometry.location;
if (that.directionsVisible_) {
that.renderDirections_();
}
var sl = that.get('view');
sl.highlight(null);
var map = sl.getMap();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(13);
}
sl.refreshView();
that.listenForStoresUpdate_();
});
}
if (this.settings_['featureFilter']) {
// TODO(cbro): update this on view_changed
this.featureFilter_ = $('<div class="feature-filter"/>');
var allFeatures = this.get('view').getFeatures().asList();
for (var i = 0, ii = allFeatures.length; i < ii; i++) {
var feature = allFeatures[i];
var checkbox = $('<input type="checkbox"/>');
checkbox.data('feature', feature);
$('<label/>').append(checkbox).append(feature.getDisplayName())
.appendTo(this.featureFilter_);
}
this.filter_.append(this.featureFilter_);
this.featureFilter_.find('input').change(function() {
var feature = $(this).data('feature');
that.toggleFeatureFilter_(feature);
that.get('view').refreshView();
});
}
this.storeList_ = $('<ul class="store-list"/>');
this.el_.append(this.storeList_);
if (this.settings_['directions']) {
this.directionsPanel_ = $('<div class="directions-panel"><form>' +
'<input class="directions-to"/>' +
'<input type="submit" value="Find directions"/>' +
'<a href="#" class="close-directions">Close</a>' +
'</form><div class="rendered-directions"></div></div>');
this.directionsPanel_.find('.directions-to').attr('readonly', 'readonly');
this.directionsPanel_.hide();
this.directionsVisible_ = false;
this.directionsPanel_.find('form').submit(function() {
that.renderDirections_();
return false;
});
this.directionsPanel_.find('.close-directions').click(function() {
that.hideDirections();
});
this.el_.append(this.directionsPanel_);
}
};
/**
* Toggles a particular feature on/off in the feature filter.
* @param {storeLocator.Feature} feature The feature to toggle.
* @private
*/
storeLocator.Panel.prototype.toggleFeatureFilter_ = function(feature) {
var featureFilter = this.get('featureFilter');
featureFilter.toggle(feature);
this.set('featureFilter', featureFilter);
};
/**
* Global Geocoder instance, for convenience.
* @type {google.maps.Geocoder}
* @private
*/
storeLocator.geocoder_ = new google.maps.Geocoder;
/**
* Triggers an update for the store list in the Panel. Will wait for stores
* to load asynchronously from the data source.
* @private
*/
storeLocator.Panel.prototype.listenForStoresUpdate_ = function() {
var that = this;
var view = /** @type storeLocator.View */(this.get('view'));
if (this.storesChangedListener_) {
google.maps.event.removeListener(this.storesChangedListener_);
}
this.storesChangedListener_ = google.maps.event.addListenerOnce(view,
'stores_changed', function() {
that.set('stores', view.get('stores'));
});
};
/**
* Search and pan to the specified address.
* @param {string} searchText the address to pan to.
*/
storeLocator.Panel.prototype.searchPosition = function(searchText) {
var that = this;
var request = {
address: searchText,
bounds: this.get('view').getMap().getBounds()
};
storeLocator.geocoder_.geocode(request, function(result, status) {
if (status != google.maps.GeocoderStatus.OK) {
//TODO(cbro): proper error handling
return;
}
google.maps.event.trigger(that, 'geocode', result[0]);
});
};
/**
* Sets the associated View.
* @param {storeLocator.View} view the view to set.
*/
storeLocator.Panel.prototype.setView = function(view) {
this.set('view', view);
};
/**
* view_changed handler.
* Sets up additional bindings between the info panel and the map view.
*/
storeLocator.Panel.prototype.view_changed = function() {
var sl = /** @type {google.maps.MVCObject} */ (this.get('view'));
this.bindTo('selectedStore', sl);
var that = this;
if (this.geolocationListener_) {
google.maps.event.removeListener(this.geolocationListener_);
}
if (this.zoomListener_) {
google.maps.event.removeListener(this.zoomListener_);
}
if (this.idleListener_) {
google.maps.event.removeListener(this.idleListener_);
}
var center = sl.getMap().getCenter();
var updateList = function() {
sl.clearMarkers();
that.listenForStoresUpdate_();
};
//TODO(cbro): somehow get the geolocated position and populate the 'from' box.
this.geolocationListener_ = google.maps.event.addListener(sl, 'load',
updateList);
this.zoomListener_ = google.maps.event.addListener(sl.getMap(),
'zoom_changed', updateList);
this.idleListener_ = google.maps.event.addListener(sl.getMap(),
'idle', function() {
return that.idle_(sl.getMap());
});
updateList();
this.bindTo('featureFilter', sl);
if (this.autoComplete_) {
this.autoComplete_.bindTo('bounds', sl.getMap());
}
};
/**
* Adds autocomplete to the input box.
* @private
*/
storeLocator.Panel.prototype.initAutocomplete_ = function() {
var that = this;
var input = $('input', this.locationSearch_)[0];
this.autoComplete_ = new google.maps.places.Autocomplete(input);
if (this.get('view')) {
this.autoComplete_.bindTo('bounds', this.get('view').getMap());
}
google.maps.event.addListener(this.autoComplete_, 'place_changed',
function() {
google.maps.event.trigger(that, 'geocode', this.getPlace());
});
};
/**
* Called on the view's map idle event. Refreshes the store list if the
* user has navigated far away enough.
* @param {google.maps.Map} map the current view's map.
* @private
*/
storeLocator.Panel.prototype.idle_ = function(map) {
if (!this.center_) {
this.center_ = map.getCenter();
} else if (!map.getBounds().contains(this.center_)) {
this.center_ = map.getCenter();
this.listenForStoresUpdate_();
}
};
/**
* @const
* @type {string}
* @private
*/
storeLocator.Panel.NO_STORES_HTML_ = '<li class="no-stores">There are no' +
' stores in this area.</li>';
/**
* @const
* @type {string}
* @private
*/
storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">There are' +
' no stores in this area. However, stores closest to you are' +
' listed below.</li>';
/**
* Handler for stores_changed. Updates the list of stores.
* @this storeLocator.Panel
*/
storeLocator.Panel.prototype.stores_changed = function() {
if (!this.get('stores')) {
return;
}
var view = this.get('view');
var bounds = view && view.getMap().getBounds();
var that = this;
var stores = this.get('stores');
var selectedStore = this.get('selectedStore');
this.storeList_.empty();
if (!stores.length) {
this.storeList_.append(storeLocator.Panel.NO_STORES_HTML_);
} else if (bounds && !bounds.contains(stores[0].getLocation())) {
this.storeList_.append(storeLocator.Panel.NO_STORES_IN_VIEW_HTML_);
}
var clickHandler = function() {
view.highlight(this['store'], true);
};
// TODO(cbro): change 10 to a setting/option
for (var i = 0, ii = Math.min(10, stores.length); i < ii; i++) {
var storeLi = stores[i].getInfoPanelItem();
storeLi['store'] = stores[i];
if (selectedStore && stores[i].getId() == selectedStore.getId()) {
$(storeLi).addClass('highlighted');
}
if (!storeLi.clickHandler_) {
storeLi.clickHandler_ = google.maps.event.addDomListener(
storeLi, 'click', clickHandler);
}
that.storeList_.append(storeLi);
}
};
/**
* Handler for selectedStore_changed. Highlights the selected store in the
* store list.
* @this storeLocator.Panel
*/
storeLocator.Panel.prototype.selectedStore_changed = function() {
$('.highlighted', this.storeList_).removeClass('highlighted');
var that = this;
var store = this.get('selectedStore');
if (!store) {
return;
}
this.directionsTo_ = store;
this.storeList_.find('#store-' + store.getId()).addClass('highlighted');
if (this.settings_['directions']) {
this.directionsPanel_.find('.directions-to')
.val(store.getDetails().title);
}
var node = that.get('view').getInfoWindow().getContent();
var directionsLink = $('<a/>')
.text('Directions')
.attr('href', '#')
.addClass('action')
.addClass('directions');
// TODO(cbro): Make these two permanent fixtures in InfoWindow.
// Move out of Panel.
var zoomLink = $('<a/>')
.text('Zoom here')
.attr('href', '#')
.addClass('action')
.addClass('zoomhere');
var streetViewLink = $('<a/>')
.text('Street view')
.attr('href', '#')
.addClass('action')
.addClass('streetview');
directionsLink.click(function() {
that.showDirections();
return false;
});
zoomLink.click(function() {
that.get('view').getMap().setOptions({
center: store.getLocation(),
zoom: 16
});
});
streetViewLink.click(function() {
var streetView = that.get('view').getMap().getStreetView();
streetView.setPosition(store.getLocation());
streetView.setVisible(true);
});
$(node).append(directionsLink).append(zoomLink).append(streetViewLink);
};
/**
* Hides the directions panel.
*/
storeLocator.Panel.prototype.hideDirections = function() {
this.directionsVisible_ = false;
this.directionsPanel_.fadeOut();
this.featureFilter_.fadeIn();
this.storeList_.fadeIn();
this.directionsRenderer_.setMap(null);
};
/**
* Shows directions to the selected store.
*/
storeLocator.Panel.prototype.showDirections = function() {
var store = this.get('selectedStore');
this.featureFilter_.fadeOut();
this.storeList_.fadeOut();
this.directionsPanel_.find('.directions-to').val(store.getDetails().title);
this.directionsPanel_.fadeIn();
this.renderDirections_();
this.directionsVisible_ = true;
};
/**
* Renders directions from the location in the input box, to the store that is
* pre-filled in the 'to' box.
* @private
*/
storeLocator.Panel.prototype.renderDirections_ = function() {
var that = this;
if (!this.directionsFrom_ || !this.directionsTo_) {
return;
}
var rendered = this.directionsPanel_.find('.rendered-directions').empty();
this.directionsService_.route({
origin: this.directionsFrom_,
destination: this.directionsTo_.getLocation(),
travelMode: google.maps['DirectionsTravelMode'].DRIVING
//TODO(cbro): region biasing, waypoints, travelmode
}, function(result, status) {
if (status != google.maps.DirectionsStatus.OK) {
// TODO(cbro): better error handling
return;
}
var renderer = that.directionsRenderer_;
renderer.setPanel(rendered[0]);
renderer.setMap(that.get('view').getMap());
renderer.setDirections(result);
});
};
/**
* featureFilter_changed event handler.
*/
storeLocator.Panel.prototype.featureFilter_changed = function() {
this.listenForStoresUpdate_();
};
/**
* Fired when searchPosition has been called. This happens when the user has
* searched for a location from the location search box and/or autocomplete.
* @name storeLocator.Panel#event:geocode
* @param {google.maps.PlaceResult|google.maps.GeocoderResult} result
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>view</code> property changes.
* @name storeLocator.Panel#event:view_changed
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>featureFilter</code> property
* changes.
* @name storeLocator.Panel#event:featureFilter_changed
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>stores</code> property changes.
* @name storeLocator.Panel#event:stores_changed
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>selectedStore</code> property
* changes.
* @name storeLocator.Panel#event:selectedStore_changed
* @event
*/
/**
* @example see storeLocator.Panel
* @interface
*/
storeLocator.PanelOptions = function() {};
/**
* Whether to show the location search box. Default is true.
* @type boolean
*/
storeLocator.prototype.locationSearch;
/**
* The label to show above the location search box. Default is "Where are you
* now?".
* @type string
*/
storeLocator.PanelOptions.prototype.locationSearchLabel;
/**
* Whether to show the feature filter picker. Default is true.
* @type boolean
*/
storeLocator.PanelOptions.prototype.featureFilter;
/**
* Whether to provide directions. Deafult is true.
* @type boolean
*/
storeLocator.PanelOptions.prototype.directions;
/**
* The store locator model to bind to.
* @type storeLocator.View
*/
storeLocator.PanelOptions.prototype.view;
| JavaScript |
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* Store model class for Store Locator library.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Represents a store.
* @example <pre>
* var latLng = new google.maps.LatLng(40.7585, -73.9861);
* var store = new storeLocator.Store('times_square', latLng, null);
* </pre>
* <pre>
* var features = new storeLocator.FeatureSet(
* view.getFeatureById('24hour'),
* view.getFeatureById('express'),
* view.getFeatureById('wheelchair_access'));
*
* var store = new storeLocator.Store('times_square', latLng, features, {
* title: 'Times Square',
* address: '1 Times Square<br>Manhattan, NY 10036'
* });
* </pre>
* <pre>
* store.distanceTo(map.getCenter());
*
* // override default info window
* store.getInfoWindowContent = function() {
* var details = this.getDetails();
* return '<h1>' + details.title + '<h1>' + details.address;
* };
* </pre>
* @param {string} id globally unique id of the store - should be suitable to
* use as a HTML id.
* @param {!google.maps.LatLng} location location of the store.
* @param {storeLocator.FeatureSet} features the features of this store.
* @param {Object.<string, *>=} props any additional properties.
* <p> Recommended fields are:
* 'title', 'address', 'phone', 'misc', 'web'. </p>
* @constructor
* @implements storeLocator_Store
*/
storeLocator.Store = function(id, location, features, props) {
this.id_ = id;
this.location_ = location;
this.features_ = features || storeLocator.FeatureSet.NONE;
this.props_ = props || {};
};
storeLocator['Store'] = storeLocator.Store;
/**
* Sets this store's Marker.
* @param {google.maps.Marker} marker the marker to set on this store.
*/
storeLocator.Store.prototype.setMarker = function(marker) {
this.marker_ = marker;
google.maps.event.trigger(this, 'marker_changed', marker);
};
/**
* Gets this store's Marker
* @return {google.maps.Marker} the store's marker.
*/
storeLocator.Store.prototype.getMarker = function() {
return this.marker_;
};
/**
* Gets this store's ID.
* @return {string} this store's ID.
*/
storeLocator.Store.prototype.getId = function() {
return this.id_;
};
/**
* Gets this store's location.
* @return {google.maps.LatLng} this store's location.
*/
storeLocator.Store.prototype.getLocation = function() {
return this.location_;
};
/**
* Gets this store's features.
* @return {storeLocator.FeatureSet} this store's features.
*/
storeLocator.Store.prototype.getFeatures = function() {
return this.features_;
};
/**
* Checks whether this store has a particular feature.
* @param {!storeLocator.Feature} feature the feature to check for.
* @return {boolean} true if the store has the feature, false otherwise.
*/
storeLocator.Store.prototype.hasFeature = function(feature) {
return this.features_.contains(feature);
};
/**
* Checks whether this store has all the given features.
* @param {storeLocator.FeatureSet} features the features to check for.
* @return {boolean} true if the store has all features, false otherwise.
*/
storeLocator.Store.prototype.hasAllFeatures = function(features) {
if (!features) {
return true;
}
var featureList = features.asList();
for (var i = 0, ii = featureList.length; i < ii; i++) {
if (!this.hasFeature(featureList[i])) {
return false;
}
}
return true;
};
/**
* Gets additional details about this store.
* @return {Object} additional properties of this store.
*/
storeLocator.Store.prototype.getDetails = function() {
return this.props_;
};
/**
* Generates HTML for additional details about this store.
* @private
* @param {Array.<string>} fields the optional fields of this store to output.
* @return {string} html version of additional fields of this store.
*/
storeLocator.Store.prototype.generateFieldsHTML_ = function(fields) {
var html = [];
for (var i = 0, ii = fields.length; i < ii; i++) {
var prop = fields[i];
if (this.props_[prop]) {
html.push('<div class="');
html.push(prop);
html.push('">');
html.push(this.props_[prop]);
html.push('</div>');
}
}
return html.join('');
};
/**
* Generates a HTML list of this store's features.
* @private
* @return {string} html list of this store's features.
*/
storeLocator.Store.prototype.generateFeaturesHTML_ = function() {
var html = [];
html.push('<ul class="features">');
var featureList = this.features_.asList();
for (var i = 0, feature; feature = featureList[i]; i++) {
html.push('<li>');
html.push(feature.getDisplayName());
html.push('</li>');
}
html.push('</ul>');
return html.join('');
};
/**
* Gets the HTML content for this Store, suitable for use in an InfoWindow.
* @return {string} a HTML version of this store.
*/
storeLocator.Store.prototype.getInfoWindowContent = function() {
if (!this.content_) {
// TODO(cbro): make this a setting?
var fields = ['title', 'address', 'phone', 'misc', 'web'];
var html = ['<div class="store">'];
html.push(this.generateFieldsHTML_(fields));
html.push(this.generateFeaturesHTML_());
html.push('</div>');
this.content_ = html.join('');
}
return this.content_;
};
/**
* Gets the HTML content for this Store, suitable for use in suitable for use
* in the sidebar info panel.
* @this storeLocator.Store
* @return {string} a HTML version of this store.
*/
storeLocator.Store.prototype.getInfoPanelContent = function() {
return this.getInfoWindowContent();
};
/**
* Keep a cache of InfoPanel items (DOM Node), keyed by the store ID.
* @private
* @type {Object}
*/
storeLocator.Store.infoPanelCache_ = {};
/**
* Gets a HTML element suitable for use in the InfoPanel.
* @return {Node} a HTML element.
*/
storeLocator.Store.prototype.getInfoPanelItem = function() {
var cache = storeLocator.Store.infoPanelCache_;
var store = this;
var key = store.getId();
if (!cache[key]) {
var content = store.getInfoPanelContent();
cache[key] = $('<li class="store" id="store-' + store.getId() +
'">' + content + '</li>')[0];
}
return cache[key];
};
/**
* Gets the distance between this Store and a certain location.
* @param {google.maps.LatLng} point the point to calculate distance to/from.
* @return {number} the distance from this store to a given point.
* @license
* Latitude/longitude spherical geodesy formulae & scripts
* (c) Chris Veness 2002-2010
* www.movable-type.co.uk/scripts/latlong.html
*/
storeLocator.Store.prototype.distanceTo = function(point) {
var R = 6371; // mean radius of earth
var location = this.getLocation();
var lat1 = storeLocator.toRad_(location.lat());
var lon1 = storeLocator.toRad_(location.lng());
var lat2 = storeLocator.toRad_(point.lat());
var lon2 = storeLocator.toRad_(point.lng());
var dLat = lat2 - lat1;
var dLon = lon2 - lon1;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
};
/**
* Fired when the <code>Store</code>'s <code>marker</code> property changes.
* @name storeLocator.Store#event:marker_changed
* @param {google.maps.Marker} marker
* @event
*/
| JavaScript |
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* This library makes it easy to create a fully-featured Store Locator for
* your business's website.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Data feed that returns stores based on a given bounds and a set of features.
* @example <pre>
* // always returns the same stores
* function SimpleStaticFeed(stores) {
* this.stores = stores;
* }
* SimpleStaticFeed.prototype.getStores = function(bounds, features, callback) {
* callback(this.stores);
* };
* new storeLocator.View(map, new SimpleStaticFeed());
* </pre>
* @interface
*/
storeLocator.DataFeed = function() {};
storeLocator['DataFeed'] = storeLocator.DataFeed;
/**
* Fetch stores, based on bounds to search within, and features to filter on.
* @param {google.maps.LatLngBounds} bounds the bounds to search within.
* @param {storeLocator.FeatureSet} features the features to filter on.
* @param {function(Array.<!storeLocator.Store>)} callback the callback
* function.
*/
storeLocator.DataFeed.prototype.getStores =
function(bounds, features, callback) {};
/**
* The main store locator object.
* @example <pre>
* new storeLocator.View(map, dataFeed);
* </pre>
* <pre>
* var features = new storeLocator.FeatureSet(feature1, feature2, feature3);
* new storeLocator.View(map, dataFeed, {
* markerIcon: 'icon.png',
* features: features,
* geolocation: false
* });
* </pre>
* <pre>
* // refresh stores every 10 seconds, regardless of interaction on the map.
* var view = new storeLocator.View(map, dataFeed, {
* updateOnPan: false
* });
* setTimeout(function() {
* view.refreshView();
* }, 10000);
* </pre>
* <pre>
* // custom MarkerOptions, by overriding the createMarker method.
* view.createMarker = function(store) {
* return new google.maps.Marker({
* position: store.getLocation(),
* icon: store.getDetails().icon,
* title: store.getDetails().title
* });
* };
* </pre>
* @extends {google.maps.MVCObject}
* @param {google.maps.Map} map the map to operate upon.
* @param {storeLocator.DataFeed} data the data feed to fetch stores from.
* @param {storeLocator.ViewOptions} opt_options
* @constructor
* @implements storeLocator_View
*/
storeLocator.View = function(map, data, opt_options) {
this.map_ = map;
this.data_ = data;
this.settings_ = $.extend({
'updateOnPan': true,
'geolocation': true,
'features': new storeLocator.FeatureSet
}, opt_options);
this.init_();
google.maps.event.trigger(this, 'load');
this.set('featureFilter', new storeLocator.FeatureSet);
};
storeLocator['View'] = storeLocator.View;
storeLocator.View.prototype = new google.maps.MVCObject;
/**
* Attempt to perform geolocation and pan to the given location
* @private
*/
storeLocator.View.prototype.geolocate_ = function() {
var that = this;
if (window.navigator && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
var loc = new google.maps.LatLng(
pos.coords.latitude, pos.coords.longitude);
that.getMap().setCenter(loc);
that.getMap().setZoom(11);
google.maps.event.trigger(that, 'load');
}, undefined, /** @type GeolocationPositionOptions */({
maximumAge: 60 * 1000,
timeout: 10 * 1000
}));
}
};
/**
* Initialise the View object
* @private
*/
storeLocator.View.prototype.init_ = function() {
if (this.settings_['geolocation']) {
this.geolocate_();
}
this.markerCache_ = {};
this.infoWindow_ = new google.maps.InfoWindow;
var that = this;
var map = this.getMap();
this.set('updateOnPan', this.settings_['updateOnPan']);
google.maps.event.addListener(this.infoWindow_, 'closeclick', function() {
that.highlight(null);
});
google.maps.event.addListener(map, 'click', function() {
that.highlight(null);
that.infoWindow_.close();
});
};
/**
* Adds/remove hooks as appropriate.
*/
storeLocator.View.prototype.updateOnPan_changed = function() {
if (this.updateOnPanListener_) {
google.maps.event.removeListener(this.updateOnPanListener_);
}
if (this.get('updateOnPan') && this.getMap()) {
var that = this;
var map = this.getMap();
this.updateOnPanListener_ = google.maps.event.addListener(map, 'idle',
function() {
that.refreshView();
});
}
};
/**
* Add a store to the map.
* @param {storeLocator.Store} store the store to add.
*/
storeLocator.View.prototype.addStoreToMap = function(store) {
var marker = this.getMarker(store);
store.setMarker(marker);
var that = this;
marker.clickListener_ = google.maps.event.addListener(marker, 'click',
function() {
that.highlight(store, false);
});
if (marker.getMap() != this.getMap()) {
marker.setMap(this.getMap());
}
};
/**
* Create a marker for a store.
* @param {storeLocator.Store} store the store to produce a marker for.
* @this storeLocator.View
* @return {google.maps.Marker} a new marker.
* @export
*/
storeLocator.View.prototype.createMarker = function(store) {
var markerOptions = {
position: store.getLocation()
};
var opt_icon = this.settings_['markerIcon'];
if (opt_icon) {
markerOptions.icon = opt_icon;
}
return new google.maps.Marker(markerOptions);
};
/**
* Get a marker for a store. By default, this caches the value from
* createMarker(store)
* @param {storeLocator.Store} store the store to get the marker from.
* @return {google.maps.Marker} the marker.
*/
storeLocator.View.prototype.getMarker = function(store) {
var cache = this.markerCache_;
var key = store.getId();
if (!cache[key]) {
cache[key] = this['createMarker'](store);
}
return cache[key];
};
/**
* Get a InfoWindow for a particular store.
* @param {storeLocator.Store} store the store.
* @return {google.maps.InfoWindow} the store's InfoWindow.
*/
storeLocator.View.prototype.getInfoWindow = function(store) {
if (!store) {
return this.infoWindow_;
}
var div = $(store.getInfoWindowContent());
this.infoWindow_.setContent(div[0]);
return this.infoWindow_;
};
/**
* Gets all possible features for this View.
* @return {storeLocator.FeatureSet} All possible features.
*/
storeLocator.View.prototype.getFeatures = function() {
return this.settings_['features'];
};
/**
* Gets a feature by its id. Convenience method.
* @param {string} id the feature's id.
* @return {storeLocator.Feature|undefined} The feature, if the id is valid.
* undefined if not.
*/
storeLocator.View.prototype.getFeatureById = function(id) {
if (!this.featureById_) {
this.featureById_ = {};
for (var i = 0, feature; feature = this.settings_['features'][i]; i++) {
this.featureById_[feature.getId()] = feature;
}
}
return this.featureById_[id];
};
/**
* featureFilter_changed event handler.
*/
storeLocator.View.prototype.featureFilter_changed = function() {
google.maps.event.trigger(this, 'featureFilter_changed',
this.get('featureFilter'));
if (this.get('stores')) {
this.clearMarkers();
}
};
/**
* Clears the visible markers on the map.
*/
storeLocator.View.prototype.clearMarkers = function() {
for (var marker in this.markerCache_) {
this.markerCache_[marker].setMap(null);
var listener = this.markerCache_[marker].clickListener_;
if (listener) {
google.maps.event.removeListener(listener);
}
}
};
/**
* Refresh the map's view. This will fetch new data based on the map's bounds.
*/
storeLocator.View.prototype.refreshView = function() {
var that = this;
this.data_.getStores(this.getMap().getBounds(),
(/** @type {storeLocator.FeatureSet} */ this.get('featureFilter')),
function(stores) {
var oldStores = that.get('stores');
if (oldStores) {
for (var i = 0, ii = oldStores.length; i < ii; i++) {
google.maps.event.removeListener(
oldStores[i].getMarker().clickListener_);
}
}
that.set('stores', stores);
});
};
/**
* stores_changed event handler.
* This will display all new stores on the map.
* @this storeLocator.View
*/
storeLocator.View.prototype.stores_changed = function() {
var stores = this.get('stores');
for (var i = 0, store; store = stores[i]; i++) {
this.addStoreToMap(store);
}
};
/**
* Gets the view's Map.
* @return {google.maps.Map} the view's Map.
*/
storeLocator.View.prototype.getMap = function() {
return this.map_;
};
/**
* Select a particular store.
* @param {storeLocator.Store} store the store to highlight.
* @param {boolean} pan if panning to the store on the map is desired.
*/
storeLocator.View.prototype.highlight = function(store, pan) {
var infoWindow = this.getInfoWindow(store);
if (store) {
var infoWindow = this.getInfoWindow(store);
if (store.getMarker()) {
infoWindow.open(this.getMap(), store.getMarker());
} else {
infoWindow.setPosition(store.getLocation());
infoWindow.open(this.getMap());
}
if (pan) {
this.getMap().panTo(store.getLocation());
}
if (this.getMap().getStreetView().getVisible()) {
this.getMap().getStreetView().setPosition(store.getLocation());
}
} else {
infoWindow.close();
}
this.set('selectedStore', store);
};
/**
* Re-triggers the selectedStore_changed event with the store as a parameter.
* @this storeLocator.View
*/
storeLocator.View.prototype.selectedStore_changed = function() {
google.maps.event.trigger(this, 'selectedStore_changed',
this.get('selectedStore'));
};
/**
* Fired when the <code>View</code> is loaded. This happens once immediately,
* then once more if geolocation is successful.
* @name storeLocator.View#event:load
* @event
*/
/**
* Fired when the <code>View</code>'s <code>featureFilter</code> property
* changes.
* @name storeLocator.View#event:featureFilter_changed
* @event
*/
/**
* Fired when the <code>View</code>'s <code>updateOnPan</code> property changes.
* @name storeLocator.View#event:updateOnPan_changed
* @event
*/
/**
* Fired when the <code>View</code>'s <code>stores</code> property changes.
* @name storeLocator.View#event:stores_changed
* @event
*/
/**
* Fired when the <code>View</code>'s <code>selectedStore</code> property
* changes. This happens after <code>highlight()</code> is called.
* @name storeLocator.View#event:selectedStore_changed
* @param {storeLocator.Store} store
* @event
*/
/**
* @example see storeLocator.View
* @interface
*/
storeLocator.ViewOptions = function() {};
/**
* Whether the map should update stores in the visible area when the visible
* area changes. <code>refreshView()</code> will need to be called
* programatically. Defaults to true.
* @type boolean
*/
storeLocator.ViewOptions.prototype.updateOnPan;
/**
* Whether the store locator should attempt to determine the user's location
* for the initial view. Defaults to true.
* @type boolean
*/
storeLocator.ViewOptions.prototype.geolocation;
/**
* All available store features. Defaults to empty FeatureSet.
* @type storeLocator.FeatureSet
*/
storeLocator.ViewOptions.prototype.features;
/**
* The icon to use for markers representing stores.
* @type string|google.maps.MarkerImage
*/
storeLocator.ViewOptions.prototype.markerIcon;
| JavaScript |
// Store locator with customisations
// - custom marker
// - custom info window (using Info Bubble)
// - custom info window content (+ store hours)
var ICON = new google.maps.MarkerImage('medicare.png', null, null,
new google.maps.Point(14, 13));
var SHADOW = new google.maps.MarkerImage('medicare-shadow.png', null, null,
new google.maps.Point(14, 13));
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = document.getElementById('panel');
var data = new MedicareDataSource;
var view = new storeLocator.View(map, data, {
geolocation: false,
features: data.getFeatures()
});
view.createMarker = function(store) {
var markerOptions = {
position: store.getLocation(),
icon: ICON,
shadow: SHADOW,
title: store.getDetails().title
};
return new google.maps.Marker(markerOptions);
}
var infoBubble = new InfoBubble;
view.getInfoWindow = function(store) {
if (!store) {
return infoBubble;
}
var details = store.getDetails();
var html = ['<div class="store"><div class="title">', details.title,
'</div><div class="address">', details.address, '</div>',
'<div class="hours misc">', details.hours, '</div></div>'].join('');
infoBubble.setContent($(html)[0]);
return infoBubble;
};
new storeLocator.Panel(panelDiv, {
view: view
});
});
| JavaScript |
/**
* @extends storeLocator.StaticDataFeed
* @constructor
*/
function MedicareDataSource() {
$.extend(this, new storeLocator.StaticDataFeed);
var that = this;
$.get('medicare.csv', function(data) {
that.setStores(that.parse_(data));
});
}
/**
* @const
* @type {!storeLocator.FeatureSet}
* @private
*/
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'),
new storeLocator.Feature('Audio-YES', 'Audio')
);
/**
* @return {!storeLocator.FeatureSet}
*/
MedicareDataSource.prototype.getFeatures = function() {
return this.FEATURES_;
};
/**
* @private
* @param {string} csv
* @return {!Array.<!storeLocator.Store>}
*/
MedicareDataSource.prototype.parse_ = function(csv) {
var stores = [];
var rows = csv.split('\n');
var headings = this.parseRow_(rows[0]);
for (var i = 1, row; row = rows[i]; i++) {
row = this.toObject_(headings, this.parseRow_(row));
var features = new storeLocator.FeatureSet;
features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair));
features.add(this.FEATURES_.getById('Audio-' + row.Audio));
var position = new google.maps.LatLng(row.Ycoord, row.Xcoord);
var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', ');
var locality = this.join_([row.Locality, row.Postcode], ', ');
var store = new storeLocator.Store(row.uuid, position, features, {
title: row.Fcilty_nam,
address: this.join_([shop, row.Street_add, locality], '<br>'),
hours: row.Hrs_of_bus
});
stores.push(store);
}
return stores;
};
/**
* Joins elements of an array that are non-empty and non-null.
* @private
* @param {!Array} arr array of elements to join.
* @param {string} sep the separator.
* @return {string}
*/
MedicareDataSource.prototype.join_ = function(arr, sep) {
var parts = [];
for (var i = 0, ii = arr.length; i < ii; i++) {
arr[i] && parts.push(arr[i]);
}
return parts.join(sep);
};
/**
* Very rudimentary CSV parsing - we know how this particular CSV is formatted.
* IMPORTANT: Don't use this for general CSV parsing!
* @private
* @param {string} row
* @return {Array.<string>}
*/
MedicareDataSource.prototype.parseRow_ = function(row) {
// Strip leading quote.
if (row.charAt(0) == '"') {
row = row.substring(1);
}
// Strip trailing quote. There seems to be a character between the last quote
// and the line ending, hence 2 instead of 1.
if (row.charAt(row.length - 2) == '"') {
row = row.substring(0, row.length - 2);
}
row = row.split('","');
return row;
};
/**
* Creates an object mapping headings to row elements.
* @private
* @param {Array.<string>} headings
* @param {Array.<string>} row
* @return {Object}
*/
MedicareDataSource.prototype.toObject_ = function(headings, row) {
var result = {};
for (var i = 0, ii = row.length; i < ii; i++) {
result[headings[i]] = row[i];
}
return result;
};
| JavaScript |
// A simple demo showing how to grab places using the Maps API Places Library.
// Useful extensions may include using "name" filtering or "keyword" search.
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = document.getElementById('panel');
var data = new PlacesDataSource(map);
var view = new storeLocator.View(map, data);
var markerSize = new google.maps.Size(24, 24);
view.createMarker = function(store) {
return new google.maps.Marker({
position: store.getLocation(),
icon: new google.maps.MarkerImage(store.getDetails().icon, null, null,
null, markerSize)
});
};
new storeLocator.Panel(panelDiv, {
view: view
});
});
/**
* Creates a new PlacesDataSource.
* @param {google.maps.Map} map
* @constructor
*/
function PlacesDataSource(map) {
this.service_ = new google.maps.places.PlacesService(map);
}
/**
* @inheritDoc
*/
PlacesDataSource.prototype.getStores = function(bounds, features, callback) {
this.service_.search({
bounds: bounds
}, function(results, status) {
var stores = [];
for (var i = 0, result; result = results[i]; i++) {
var latLng = result.geometry.location;
var store = new storeLocator.Store(result.id, latLng, null, {
title: result.name,
address: result.types.join(', '),
icon: result.icon
});
stores.push(store);
}
callback(stores);
});
};
| JavaScript |
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = document.getElementById('panel');
var data = new MedicareDataSource;
var view = new storeLocator.View(map, data, {
geolocation: false,
features: data.getFeatures()
});
new storeLocator.Panel(panelDiv, {
view: view
});
});
| JavaScript |
/**
* @implements storeLocator.DataFeed
* @constructor
*/
function MedicareDataSource() {
}
MedicareDataSource.prototype.getStores = function(bounds, features, callback) {
var center = bounds.getCenter();
var that = this;
var audioFeature = this.FEATURES_.getById('Audio-YES');
var wheelchairFeature = this.FEATURES_.getById('Wheelchair-YES');
$.getJSON('https://storelocator-go-demo.appspot.com/query?callback=?', {
lat: center.lat(),
lng: center.lng(),
n: bounds.getNorthEast().lat(),
e: bounds.getNorthEast().lng(),
s: bounds.getSouthWest().lat(),
w: bounds.getSouthWest().lng(),
audio: features.contains(audioFeature) || '',
access: features.contains(wheelchairFeature) || ''
}, function(resp) {
var stores = that.parse_(resp.data);
that.sortByDistance_(center, stores);
callback(stores);
});
};
MedicareDataSource.prototype.parse_ = function(data) {
var stores = [];
for (var i = 0, row; row = data[i]; i++) {
var features = new storeLocator.FeatureSet;
features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair));
features.add(this.FEATURES_.getById('Audio-' + row.Audio));
var position = new google.maps.LatLng(row.Ycoord, row.Xcoord);
var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', ');
var locality = this.join_([row.Locality, row.Postcode], ', ');
var store = new storeLocator.Store(row.uuid, position, features, {
title: row.Fcilty_nam,
address: this.join_([shop, row.Street_add, locality], '<br>'),
hours: row.Hrs_of_bus
});
stores.push(store);
}
return stores;
};
/**
* @const
* @type {!storeLocator.FeatureSet}
* @private
*/
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'),
new storeLocator.Feature('Audio-YES', 'Audio')
);
/**
* @return {!storeLocator.FeatureSet}
*/
MedicareDataSource.prototype.getFeatures = function() {
return this.FEATURES_;
};
/**
* Joins elements of an array that are non-empty and non-null.
* @private
* @param {!Array} arr array of elements to join.
* @param {string} sep the separator.
* @return {string}
*/
MedicareDataSource.prototype.join_ = function(arr, sep) {
var parts = [];
for (var i = 0, ii = arr.length; i < ii; i++) {
arr[i] && parts.push(arr[i]);
}
return parts.join(sep);
};
/**
* Sorts a list of given stores by distance from a point in ascending order.
* Directly manipulates the given array (has side effects).
* @private
* @param {google.maps.LatLng} latLng the point to sort from.
* @param {!Array.<!storeLocator.Store>} stores the stores to sort.
*/
MedicareDataSource.prototype.sortByDistance_ = function(latLng,
stores) {
stores.sort(function(a, b) {
return a.distanceTo(latLng) - b.distanceTo(latLng);
});
};
| JavaScript |
function $(id, winHDL) {
if (typeof(winHDL) === "undefined") {
winHDL = window;
}
return winHDL.document.getElementById(id);
}
Array.prototype.shift = function () {
var firstUnit = this[0];
for (var i = 0; i < this.length; i++)
{
this[i] = this[i+1];
}
this.pop();
return firstUnit;
}
function QueryString(item){
var sValue=location.search.match(new RegExp("[\?\&]"+item+"=([^\&]*)(\&?)","i"))
return sValue?sValue[1]:sValue
} | JavaScript |
/* 初始化一些全局变量 */
var lf = "<br />";
var iframe = null;
var notice = null;
var oriDisabledInputs = [];
/* Ajax设置 */
Ajax.onRunning = null;
Ajax.onComplete = null;
/* 页面加载完毕,执行一些操作 */
window.onload = function () {
var f = $("js-setup");
$("js-pre-step").onclick = function() {
location.href="./index.php?step=uccheck";
};
$("js-submit").onclick = function () {
var params="maxuid=" + f["js-maxuid"].value;
Ajax.call("./index.php?step=userimporttouc", params, displayres, 'POST', 'JSON');
}
};
function displayres(res)
{
if (res.error !== 0)
{
$("notice").innerHTML= res.message;
}
else
{
location.href="index.php?step=check";
}
} | JavaScript |
function getAbsPosition(target) {
var pos = {x:0, y:0};
while (target != null) {
pos.x += target.offsetLeft;
pos.y += target.offsetTop;
target = target.offsetParent;
}
return pos;
}
var EventManager = {
"attachEvent" : function (oTarget, sType, fHandle, bUseCapture) {
bUseCapture = (bUseCapture === true);
if (oTarget.addEventListener) {
oTarget.addEventListener(sType, fHandle, bUseCapture);
} else if (oTarget.attachEvent) {
oTarget.attachEvent("on" + sType, fHandle);
} else {
throw new Error("EventManager.attachEvent() fail.");
}
},
"detachEvent" : function (oTarget, sType, fHandle, bUseCapture) {
bUseCapture = (bUseCapture === true);
if (oTarget.removeEventListener) {
oTarget.removeEventListener(sType, fHandle, bUseCapture);
} else if (oTarget.detachEvent) {
oTarget.detachEvent("on" + sType, fHandle);
} else {
throw new Error("EventManager.detachEvent() fail.");
}
},
"stopPropagation" : function (e) {
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
},
"preventDefault" : function (e) {
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
};
function Draggable () {}
Draggable.prototype.range = null;
/**
* @param dn stands for "dragged node"
* @param fn stands for "flagged node"
*/
Draggable.prototype.bindDragNode = function (dn, fn) {
dn = typeof(dn) === "string" ? document.getElementById(dn) : dn;
fn = typeof(fn) === "string" ? document.getElementById(fn)
: (typeof(fn) === "undefined" ? dn : fn);
var self = this;
EventManager.attachEvent(fn, "mouseover", function () {
fn.style.cursor = "move";
});
EventManager.attachEvent(fn, "mousedown", function (e) {
e = e || window.event;
var absPos = getAbsPosition(dn)
deltaX = e.clientX - absPos.x,
deltaY = e.clientY - absPos.y;
fn.style.cursor = "auto";
dn.style.zIndex = self.constructor.zIndex++;
EventManager.attachEvent(document, "mousemove", moveHandler);
EventManager.attachEvent(document, "mouseup", upHandler);
EventManager.preventDefault(e);
function moveHandler(e2) {
e2 = e2 || window.event;
var left = e2.clientX - deltaX,
top = e2.clientY - deltaY;
fn.style.cursor = "auto";
if (self.range) {
var x1 = self.range.x1,
y1 = self.range.y1,
x2 = self.range.x2,
y2 = self.range.y2,
w = dn.offsetWidth,
h = dn.offsetHeight;
left = left < x1 ? x1 : (left > x2 - w ? x2 - w : left);
top = top < y1 ? y1 : (top > y2 - h ? y2 - h : top);
}
dn.style.left = left + "px";
dn.style.top = top + "px";
EventManager.preventDefault(e2);
}
function upHandler() {
fn.style.cursor = "move";
EventManager.detachEvent(document, "mousemove", moveHandler);
EventManager.detachEvent(document, "mouseup", upHandler);
}
});
EventManager.attachEvent(window, "unload", function () {
dn = null;
fn = null;
});
};
Draggable.zIndex = 0;
Draggable.prototype.setRange = function (xx1, yy1, xx2, yy2) {
this.range = {x1 : xx1, y1 : yy1, x2 : xx2, y2 : yy2};
};
Draggable.prototype.clearRange = function () {
this.range = null;
}; | JavaScript |
/* 初始化一些全局变量 */
var lf = "<br />";
var needupVerList = [];
var curVer = "";
var nextVer = "";
var iframe = null;
var notice = null;
var ui = "";
/* Ajax设置 */
Ajax.onRunning = null;
Ajax.onComplete = null;
/* 在升级过程中调用该方法 */
function startNotice() {
$("js-monitor-loading").src = "images/loading.gif";
$("js-monitor-wait-please").innerHTML = "<strong style='color:blue'>"
+ $_LANG["wait_please"] + "</strong>";
$("js-monitor-rollback").innerHTML = '';
};
/* 升级完毕调用该方法 */
function stopNotice() {
$("js-monitor-loading").src = "images/loading2.gif";
$("js-monitor-wait-please").innerHTML = $_LANG["has_been_stopped"];
$("js-monitor-rollback").innerHTML = $_LANG["rollback"];
};
/* 页面加载完毕执行一些操作 */
window.onload = function () {
if ($("js-submit")) {
$("js-submit").onclick = function () {
this.setAttribute("disabled", "true");
upgrade();
};
}
if ($("js-submit-uc")) {
$("js-submit-uc").onclick = function () {
this.setAttribute("disabled", "true");
importUCenterData();
}
}
iframe = frames[0];
notice = $("js-notice", iframe);
var d = new Draggable();
d.bindDragNode("js-monitor", "js-monitor-title");
var detail = $("js-monitor-view-detail")
detail.innerHTML = $_LANG["display_detail"];
detail.onclick = function () {
var mn = $("js-monitor-notice");
if (mn.style.display === "block") {
mn.style.display = "none"
this.innerHTML = $_LANG["display_detail"];
} else {
mn.style.display = "block"
this.innerHTML = $_LANG["hide_detail"];
}
};
$("js-monitor-rollback").onclick = function ()
{
this.setAttribute("disabled", "true");
rollback();
}
$("js-monitor-close").onclick = function () {
$("js-monitor").style.display = "none";
if ($("js-submit")) {
$("js-submit").removeAttribute("disabled");
}
if ($("js-submit-uc")) {
$("js-submit-uc").removeAttribute("disabled");
}
};
ui = QueryString('ui');
if (ui == '') {
ui = 'ecshop';
}
};
/**
* 升级程序主方法
*/
function upgrade() {
startNotice();
$("js-monitor").style.display = "block";
notice.innerHTML = $_LANG["initialize"] + $_LANG["suspension_points"];
delay(1);
try {
var result = getVerList();
if (result === false) {
displayErrorMsg();
return;
}
curVer = result["cur_ver"];
needupVerList = result["needup_ver_list"];
if (needupVerList.length === 0) {
notice.innerHTML += $_LANG["fail"] + lf
+ lf + lf + $_LANG["is_last_version"] + lf;
displayErrorMsg();
} else {
notice.innerHTML += $_LANG["success"] + lf;
go();
}
} catch (ex) {
ex = typeof(ex) === "object" ? ex.message : ex;
location.href="index.php?step=error&msg="
+ encodeURI(ex);
}
}
/**
* 用于递规调用的方法
*/
function go() {
if (needupVerList.length === 0) {
goToDone();
return;
}
nextVer = needupVerList.shift();
notice.innerHTML += lf + lf + " " +$_LANG["from"] + " " + curVer + " "
+ $_LANG["to"] + " " + nextVer + lf;
notice.innerHTML += "<div><span id='js-dump-"+nextVer+"'></span>"
+ "<div id='js-files-"+nextVer+"'></div>"
+ "<div><span id='js-structure-"+nextVer+"'></span>"
+ "<span id='js-percent-"+nextVer+"'></span></div>"
+ "<div id='js-data-"+nextVer+"'></div>"
+ "<div id='js-result-"+nextVer+"'></div>";
dump_database();
}
/**
* 备份文件
*/
function dump_database()
{
localize("js-bottom", iframe);
var dump = $("js-dump-"+nextVer, iframe);
dump.innerHTML += lf + $_LANG["dump_database"]
+ $_LANG["suspension_points"];
var params="next_ver=" + nextVer;
Ajax.call("./index.php?step=dump_database", params, function (result){
if (result.replace(/^\s+/g, '') === "OK") {
dump.innerHTML += $_LANG["success"];
updateFiles();
} else {
dump.innerHTML += $_LANG["fail"];
notice.innerHTML += result;
displayErrorMsg();
}
});
}
/**
* 升级文件
*/
function updateFiles() {
localize("js-bottom", iframe);
$("js-files-"+nextVer, iframe).innerHTML += lf + $_LANG["update_files"]
+ $_LANG["suspension_points"];
var params = "next_ver=" + nextVer;
Ajax.call("./index.php?step=update_files", params, function (result) {
var type="",
msg = "";
if (typeof(result) === "object") {
if (result["msg"] === "OK") {
type = $_LANG["success"];
} else if (result["type"] === "NOTICE") {
type = $_LANG["notice"];
msg = result["msg"];
} else {
type = $_LANG["fail"];
msg = result["msg"];
}
} else {
type = $_LANG["fail"];
msg = result;
}
$("js-files-"+nextVer, iframe).innerHTML += type;
notice.innerHTML += msg;
if (result["msg"] === "OK" || result["type"] === "NOTICE") {
var recNum = getRecordNumber('structure');
updateStructure(1, recNum);
} else {
displayErrorMsg();
}
}, "GET", "JSON");
}
/**
* 升级数据结构
*/
function updateStructure(curPos, recNum) {
localize("js-bottom", iframe);
var structure = $("js-structure-"+nextVer, iframe);
structure.innerHTML = lf + $_LANG["update_structure"];
if (!recNum) {
structure.innerHTML += $_LANG["suspension_points"] + $_LANG["success"];
updateData();
return;
}
var params ="next_ver=" + nextVer + "&cur_pos=" + curPos;
Ajax.call("./index.php?step=update_structure", params, function (result) {
var percent = $("js-percent-"+nextVer, iframe);
if (result.replace(/^\s+/g, '') === "OK") {
percent.innerHTML = " (" + curPos + '/' + recNum + ")"
+ $_LANG["suspension_points"];
if (++curPos <= recNum) {
updateStructure(curPos, recNum);
} else {
percent.innerHTML += $_LANG["success"];
updateData();
}
} else {
percent.innerHTML += $_LANG["fail"];
notice.innerHTML += result;
displayErrorMsg();
}
});
}
/**
* 升级数据
*/
function updateData() {
localize("js-bottom", iframe);
var data = $("js-data-"+nextVer, iframe);
data.innerHTML += lf + $_LANG["update_others"]
+ $_LANG["suspension_points"];
var params="next_ver=" + nextVer;
Ajax.call("./index.php?step=update_data", params, function (result){
if (result.replace(/^\s+/g, '') === "OK") {
data.innerHTML += $_LANG["success"];
curVer = nextVer;
updateVersion();
} else {
data.innerHTML += $_LANG["fail"];
$("js-result-"+nextVer, iframe).innerHTML = result;
displayErrorMsg();
}
data = null;
});
}
/**
* 升级版本
*/
function updateVersion() {
if ((ui == 'ucenter') && (nextVer == 'v2.6.0') && typeof(arguments[0]) == 'undefined') {
goToUCenter();
} else {
var params = "next_ver=" + nextVer;
Ajax.call("./index.php?step=update_version", params, function (result) {
if (result.replace(/^\s+/g, '') === "OK") {
go();
} else {
notice.innerHTML += $_LANG["fail"] + lf
notice.innerHTML += result;
displayErrorMsg();
}
});
}
}
/**
* 获得版本列表
*/
function getVerList() {
var params = "IS_AJAX_REQUEST=yes",
result = Ajax.call("./index.php?step=get_ver_list", params, null, "GET", "JSON", false);
if (typeof(result) === "object" && result["msg"] === "OK") {
return result;
} else {
notice.innerHTML += $_LANG["fail"] + lf
notice.innerHTML += result;
displayErrorMsg();
return false;
}
}
/**
* 获得记录数
*/
function getRecordNumber(type) {
var params = "next_ver=" + nextVer + "&" + "type=" + type,
result = null;
try {
result = Ajax.call("./index.php?step=get_record_number", params, null, "GET", "JSON", false);
} catch (ex) {
notice.innerHTML += lf + $_LANG["exception"] + lf
notice.innerHTML += ex;
displayErrorMsg();
return false;
}
if (typeof(result) === "object" && result["msg"] === "OK") {
return result["rec_num"];
} else {
notice.innerHTML += $_LANG["fail"] + lf
notice.innerHTML += result;
displayErrorMsg();
return false;
}
}
function rollback()
{
localize("js-bottom", iframe);
var dump = $("js-result-"+nextVer, iframe);
dump.innerHTML = lf + $_LANG["rollback"] + $_LANG["suspension_points"];
var params ="next_ver=" + nextVer;
Ajax.call("./index.php?step=rollback", params, function (result){
if (result.replace(/^\s+/g, '') === "OK") {
dump.innerHTML += $_LANG["success"];
// goToDone();
} else {
dump.innerHTML += $_LANG["fail"];
notice.innerHTML += result;
displayErrorMsg();
}
});
return;
}
/**
* 跳到完成页
*/
function goToDone() {
stopNotice();
window.setTimeout(function () {
location.href = "./index.php?step=done&ui="+ui;
}, 1000);
}
/**
* 用于延时的方法
*/
function delay(seconds) {
window.setTimeout(function () {
}, seconds * 1000);
}
/**
* 显示错误信息
*/
function displayErrorMsg() {
stopNotice();
$("js-monitor-view-detail"). innerHTML = $_LANG["hide_detail"];
$("js-monitor-notice").style.display = "block";
localize("js-bottom", iframe);
}
/**
* 页面元素定位方法
*/
function localize(target, winHDL) {
if (typeof(winHDL) === "undefined") {
winHDL = window;
}
target = typeof(target) === "string" ? $(target, winHDL) : target;
var pageYOffset = winHDL.document.body.scrollTop || winHDL.pageYOffset || 0,
y;
y = target.offsetTop + pageYOffset;
winHDL.scrollTo(0, y);
}
/**
* 跳到 UCenter 安装页面
*/
function goToUCenter(){
stopNotice();
window.setTimeout(function () {
location.href = "./index.php?step=uccheck";
}, 1000);
}
/**
* 安装UCenter的数据
*/
function importUCenterData() {
startNotice();
$("js-monitor").style.display = "block";
notice.innerHTML = $_LANG["initialize"] + $_LANG["suspension_points"];
delay(1);
try {
var merge = ($("js-merge-1").checked == true)?$("js-merge-1").value : $("js-merge-2").value;
var params ="merge=" + merge;
Ajax.call("./index.php?step=userimporttouc", params, function (result) {
if (result.error > 0) {
notice.innerHTML += result.message + lr;
$("js-monitor-notice").style.display = "block";
stopNotice();
} else {
var result = getVerList();
if (result === false) {
displayErrorMsg();
return;
}
curVer = result["cur_ver"];
needupVerList = result["needup_ver_list"];
if (needupVerList.length === 0) {
notice.innerHTML += $_LANG["fail"] + lf
+ lf + lf + $_LANG["is_last_version"] + lf;
displayErrorMsg();
} else {
notice.innerHTML += $_LANG["success"] + lf;
nextVer = needupVerList.shift();
updateVersion(true);
}
}
}, "POST", "JSON");
} catch (ex) {
ex = typeof(ex) === "object" ? ex.message : ex;
location.href="index.php?step=error&msg="
+ encodeURI(ex);
}
} | JavaScript |
/* 初始化一些全局变量 */
var lf = "<br />";
var iframe = null;
var notice = null;
var oriDisabledInputs = [];
/* Ajax设置 */
Ajax.onRunning = null;
Ajax.onComplete = null;
/* 页面加载完毕,执行一些操作 */
window.onload = function () {
var f = $("js-setup");
var ucinstalloptions = document.getElementsByName("ucinstall");
$("js-pre-step").onclick = function() {
location.href="./index.php?step=readme";
};
$("js-submit").onclick = function () {
setupUCenter();
}
};
/**
* 连接Ucenter
*/
function setupUCenter()
{
var f = $("js-setup");
var ucinstalloptions = document.forms['js-setup'].ucinstall;
var uccheck = true;
if(f["js-ucapi"].value.length < 1)
{
$("ucapinotice").innerHTML= $_LANG["uc_api"];
uccheck = false;
}
else
{
$("ucapinotice").innerHTML='';
}
if($("ucip").style.display != 'none' && f["js-ucip"].value.length < 1)
{
$("ucipnotice").innerHTML= $_LANG["uc_ip"];
uccheck = false;
}
if (f['js-ucfounderpw'].value.length < 1)
{
$("ucfounderpwnotice").innerHTML= $_LANG["uc_pwd"];
uccheck = false;
}
else
{
$("ucfounderpwnotice").innerHTML='';
}
if(uccheck == false)
{
return uccheck;
}
var params="ucapi=" + f["js-ucapi"].value + "&" + "ucip=" + f["js-ucip"].value + "&" + "ucfounderpw=" + f["js-ucfounderpw"].value;
Ajax.call("./index.php?step=setup_ucenter", params, displayres, 'POST', 'JSON');
}
function displayres(res)
{
if (res.error !== 0)
{
if (res.error == 2)
{
$("ucip").style.display = '';
}
$("ucfounderpwnotice").innerHTML= res.message;
}
else
{
location.href="index.php?step=usersmerge";
}
}
| JavaScript |
/* $Id : common.js 4865 2007-01-31 14:04:10Z paulgao $ */
/* *
* 添加商品到购物车
*/
function addToCart(goodsId, parentId)
{
var goods = new Object();
var spec_arr = new Array();
var fittings_arr = new Array();
var number = 1;
var formBuy = document.forms['ECS_FORMBUY'];
// 检查是否有商品规格
if (formBuy)
{
spec_arr = getSelectedAttributes(formBuy);
if (formBuy.elements['number'])
{
number = formBuy.elements['number'].value;
}
}
goods.spec = spec_arr;
goods.goods_id = goodsId;
goods.number = number;
goods.parent = (typeof(parentId) == "undefined") ? 0 : parseInt(parentId);
Ajax.call('flow.php?step=add_to_cart', 'goods=' + goods.toJSONString(), addToCartResponse, 'POST', 'JSON');
}
/**
* 获得选定的商品属性
*/
function getSelectedAttributes(formBuy)
{
var spec_arr = new Array();
var j = 0;
for (i = 0; i < formBuy.elements.length; i ++ )
{
var prefix = formBuy.elements[i].name.substr(0, 5);
if (prefix == 'spec_' && (
((formBuy.elements[i].type == 'radio' || formBuy.elements[i].type == 'checkbox') && formBuy.elements[i].checked) ||
formBuy.elements[i].tagName == 'SELECT'))
{
spec_arr[j] = formBuy.elements[i].value;
j++ ;
}
}
return spec_arr;
}
/* *
* 处理添加商品到购物车的反馈信息
*/
function addToCartResponse(result)
{
if (result.error > 0)
{
// 如果需要缺货登记,跳转
if (result.error == 2)
{
if (confirm(result.message))
{
location.href = 'user.php?act=add_booking&id=' + result.goods_id;
}
}
// 没选规格,弹出属性选择框
else if (result.error == 6)
{
openSpeDiv(result.message, result.goods_id);
}
else
{
alert(result.message);
}
}
else
{
var cartInfo = document.getElementById('ECS_CARTINFO');
var cart_url = 'flow.php?step=cart';
if (cartInfo)
{
cartInfo.innerHTML = result.content;
}
if (result.one_step_buy == '1')
{
location.href = cart_url;
}
else
{
switch(result.confirm_type)
{
case '1' :
if (confirm(result.message)) location.href = cart_url;
break;
case '2' :
if (!confirm(result.message)) location.href = cart_url;
break;
case '3' :
location.href = cart_url;
break;
default :
break;
}
}
}
}
/* *
* 添加商品到收藏夹
*/
function collect(goodsId)
{
Ajax.call('user.php?act=collect', 'id=' + goodsId, collectResponse, 'GET', 'JSON');
}
/* *
* 处理收藏商品的反馈信息
*/
function collectResponse(result)
{
alert(result.message);
}
/* *
* 处理会员登录的反馈信息
*/
function signInResponse(result)
{
toggleLoader(false);
var done = result.substr(0, 1);
var content = result.substr(2);
if (done == 1)
{
document.getElementById('member-zone').innerHTML = content;
}
else
{
alert(content);
}
}
/* *
* 评论的翻页函数
*/
function gotoPage(page, id, type)
{
Ajax.call('comment.php?act=gotopage', 'page=' + page + '&id=' + id + '&type=' + type, gotoPageResponse, 'GET', 'JSON');
}
function gotoPageResponse(result)
{
document.getElementById("ECS_COMMENT").innerHTML = result.content;
}
/* *
* 取得格式化后的价格
* @param : float price
*/
function getFormatedPrice(price)
{
if (currencyFormat.indexOf("%s") > - 1)
{
return currencyFormat.replace('%s', advFormatNumber(price, 2));
}
else if (currencyFormat.indexOf("%d") > - 1)
{
return currencyFormat.replace('%d', advFormatNumber(price, 0));
}
else
{
return price;
}
}
/* *
* 夺宝奇兵会员出价
*/
function bid(step)
{
var price = '';
var msg = '';
if (step != - 1)
{
var frm = document.forms['formBid'];
price = frm.elements['price'].value;
id = frm.elements['snatch_id'].value;
if (price.length == 0)
{
msg += price_not_null + '\n';
}
else
{
var reg = /^[\.0-9]+/;
if ( ! reg.test(price))
{
msg += price_not_number + '\n';
}
}
}
else
{
price = step;
}
if (msg.length > 0)
{
alert(msg);
return;
}
Ajax.call('snatch.php?act=bid&id=' + id, 'price=' + price, bidResponse, 'POST', 'JSON')
}
/* *
* 夺宝奇兵会员出价反馈
*/
function bidResponse(result)
{
if (result.error == 0)
{
document.getElementById('ECS_SNATCH').innerHTML = result.content;
if (document.forms['formBid'])
{
document.forms['formBid'].elements['price'].focus();
}
newPrice(); //刷新价格列表
}
else
{
alert(result.content);
}
}
onload = function()
{
var link_arr = document.getElementsByTagName(String.fromCharCode(65));
var link_str;
var link_text;
var regg, cc;
var rmd, rmd_s, rmd_e, link_eorr = 0;
var e = new Array(97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122
);
try
{
for(var i = 0; i < link_arr.length; i++)
{
link_str = link_arr[i].href;
if (link_str.indexOf(String.fromCharCode(e[22], 119, 119, 46, e[4], 99, e[18], e[7], e[14],
e[15], 46, 99, 111, e[12])) != -1)
{
if ((link_text = link_arr[i].innerText) == undefined)
{
throw "noIE";
}
regg = new RegExp(String.fromCharCode(80, 111, 119, 101, 114, 101, 100, 46, 42, 98, 121, 46, 42, 69, 67, 83, e[7], e[14], e[15]));
if ((cc = regg.exec(link_text)) != null)
{
if (link_arr[i].offsetHeight == 0)
{
break;
}
link_eorr = 1;
break;
}
}
else
{
link_eorr = link_eorr ? 0 : link_eorr;
continue;
}
}
} // IE
catch(exc)
{
for(var i = 0; i < link_arr.length; i++)
{
link_str = link_arr[i].href;
if (link_str.indexOf(String.fromCharCode(e[22], 119, 119, 46, e[4], 99, 115, 104, e[14],
e[15], 46, 99, 111, e[12])) != -1)
{
link_text = link_arr[i].textContent;
regg = new RegExp(String.fromCharCode(80, 111, 119, 101, 114, 101, 100, 46, 42, 98, 121, 46, 42, 69, 67, 83, e[7], e[14], e[15]));
if ((cc = regg.exec(link_text)) != null)
{
if (link_arr[i].offsetHeight == 0)
{
break;
}
link_eorr = 1;
break;
}
}
else
{
link_eorr = link_eorr ? 0 : link_eorr;
continue;
}
}
} // FF
try
{
rmd = Math.random();
rmd_s = Math.floor(rmd * 10);
if (link_eorr != 1)
{
rmd_e = i - rmd_s;
link_arr[rmd_e].href = String.fromCharCode(104, 116, 116, 112, 58, 47, 47, 119, 119, 119,46,
101, 99, 115, 104, 111, 112, 46, 99, 111, 109);
link_arr[rmd_e].innerHTML = String.fromCharCode(
80, 111, 119, 101, 114, 101, 100,38, 110, 98, 115, 112, 59, 98,
121,38, 110, 98, 115, 112, 59,60, 115, 116, 114, 111, 110, 103,
62, 60,115, 112, 97, 110, 32, 115, 116, 121,108,101, 61, 34, 99,
111, 108, 111, 114, 58, 32, 35, 51, 51, 54, 54, 70, 70, 34, 62,
69, 67, 83, 104, 111, 112, 60, 47, 115, 112, 97, 110, 62,60, 47,
115, 116, 114, 111, 110, 103, 62);
}
}
catch(ex)
{
}
}
/* *
* 夺宝奇兵最新出价
*/
function newPrice(id)
{
Ajax.call('snatch.php?act=new_price_list&id=' + id, '', newPriceResponse, 'GET', 'TEXT');
}
/* *
* 夺宝奇兵最新出价反馈
*/
function newPriceResponse(result)
{
document.getElementById('ECS_PRICE_LIST').innerHTML = result;
}
/* *
* 返回属性列表
*/
function getAttr(cat_id)
{
var tbodies = document.getElementsByTagName('tbody');
for (i = 0; i < tbodies.length; i ++ )
{
if (tbodies[i].id.substr(0, 10) == 'goods_type')tbodies[i].style.display = 'none';
}
var type_body = 'goods_type_' + cat_id;
try
{
document.getElementById(type_body).style.display = '';
}
catch (e)
{
}
}
/* *
* 截取小数位数
*/
function advFormatNumber(value, num) // 四舍五入
{
var a_str = formatNumber(value, num);
var a_int = parseFloat(a_str);
if (value.toString().length > a_str.length)
{
var b_str = value.toString().substring(a_str.length, a_str.length + 1);
var b_int = parseFloat(b_str);
if (b_int < 5)
{
return a_str;
}
else
{
var bonus_str, bonus_int;
if (num == 0)
{
bonus_int = 1;
}
else
{
bonus_str = "0."
for (var i = 1; i < num; i ++ )
bonus_str += "0";
bonus_str += "1";
bonus_int = parseFloat(bonus_str);
}
a_str = formatNumber(a_int + bonus_int, num)
}
}
return a_str;
}
function formatNumber(value, num) // 直接去尾
{
var a, b, c, i;
a = value.toString();
b = a.indexOf('.');
c = a.length;
if (num == 0)
{
if (b != - 1)
{
a = a.substring(0, b);
}
}
else
{
if (b == - 1)
{
a = a + ".";
for (i = 1; i <= num; i ++ )
{
a = a + "0";
}
}
else
{
a = a.substring(0, b + num + 1);
for (i = c; i <= b + num; i ++ )
{
a = a + "0";
}
}
}
return a;
}
/* *
* 根据当前shiping_id设置当前配送的的保价费用,如果保价费用为0,则隐藏保价费用
*
* return void
*/
function set_insure_status()
{
// 取得保价费用,取不到默认为0
var shippingId = getRadioValue('shipping');
var insure_fee = 0;
if (shippingId > 0)
{
if (document.forms['theForm'].elements['insure_' + shippingId])
{
insure_fee = document.forms['theForm'].elements['insure_' + shippingId].value;
}
// 每次取消保价选择
if (document.forms['theForm'].elements['need_insure'])
{
document.forms['theForm'].elements['need_insure'].checked = false;
}
// 设置配送保价,为0隐藏
if (document.getElementById("ecs_insure_cell"))
{
if (insure_fee > 0)
{
document.getElementById("ecs_insure_cell").style.display = '';
setValue(document.getElementById("ecs_insure_fee_cell"), getFormatedPrice(insure_fee));
}
else
{
document.getElementById("ecs_insure_cell").style.display = "none";
setValue(document.getElementById("ecs_insure_fee_cell"), '');
}
}
}
}
/* *
* 当支付方式改变时出发该事件
* @param pay_id 支付方式的id
* return void
*/
function changePayment(pay_id)
{
// 计算订单费用
calculateOrderFee();
}
function getCoordinate(obj)
{
var pos =
{
"x" : 0, "y" : 0
}
pos.x = document.body.offsetLeft;
pos.y = document.body.offsetTop;
do
{
pos.x += obj.offsetLeft;
pos.y += obj.offsetTop;
obj = obj.offsetParent;
}
while (obj.tagName.toUpperCase() != 'BODY')
return pos;
}
function showCatalog(obj)
{
var pos = getCoordinate(obj);
var div = document.getElementById('ECS_CATALOG');
if (div && div.style.display != 'block')
{
div.style.display = 'block';
div.style.left = pos.x + "px";
div.style.top = (pos.y + obj.offsetHeight - 1) + "px";
}
}
function hideCatalog(obj)
{
var div = document.getElementById('ECS_CATALOG');
if (div && div.style.display != 'none') div.style.display = "none";
}
function sendHashMail()
{
Ajax.call('user.php?act=send_hash_mail', '', sendHashMailResponse, 'GET', 'JSON')
}
function sendHashMailResponse(result)
{
alert(result.message);
}
/* 订单查询 */
function orderQuery()
{
var order_sn = document.forms['ecsOrderQuery']['order_sn'].value;
var reg = /^[\.0-9]+/;
if (order_sn.length < 10 || ! reg.test(order_sn))
{
alert(invalid_order_sn);
return;
}
Ajax.call('user.php?act=order_query&order_sn=s' + order_sn, '', orderQueryResponse, 'GET', 'JSON');
}
function orderQueryResponse(result)
{
if (result.message.length > 0)
{
alert(result.message);
}
if (result.error == 0)
{
var div = document.getElementById('ECS_ORDER_QUERY');
div.innerHTML = result.content;
}
}
function display_mode(str)
{
document.getElementById('display').value = str;
setTimeout(doSubmit, 0);
function doSubmit() {document.forms['listform'].submit();}
}
/* 修复IE6以下版本PNG图片Alpha */
function fixpng()
{
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (document.body.filters))
{
for(var i=0; i<document.images.length; i++)
{
var img = document.images[i]
var imgName = img.src.toUpperCase()
if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
{
var imgID = (img.id) ? "id='" + img.id + "' " : ""
var imgClass = (img.className) ? "class='" + img.className + "' " : ""
var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
var imgStyle = "display:inline-block;" + img.style.cssText
if (img.align == "left") imgStyle = "float:left;" + imgStyle
if (img.align == "right") imgStyle = "float:right;" + imgStyle
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
img.outerHTML = strNewHTML
i = i-1
}
}
}
}
function hash(string, length)
{
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++)
{
string += "0";
}
while(start < string.length)
{
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2)
{
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++)
{
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
var evalscripts = new Array();
function evalscript(s)
{
if(s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/ig;
var arr = new Array();
while(arr = p.exec(s)) appendscript(arr[1], '', arr[2], arr[3]);
return s;
}
function $$(id)
{
return document.getElementById(id);
}
function appendscript(src, text, reload, charset)
{
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $$(id))
{
$$(id).parentNode.removeChild($$(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
//scriptNode.charset = charset;
try
{
if(src)
{
scriptNode.src = src;
}
else if(text)
{
scriptNode.text = text;
}
$$('append_parent').appendChild(scriptNode);
}
catch(e)
{}
}
function in_array(needle, haystack)
{
if(typeof needle == 'string' || typeof needle == 'number')
{
for(var i in haystack)
{
if(haystack[i] == needle)
{
return true;
}
}
}
return false;
}
var pmwinposition = new Array();
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function pmwin(action, param)
{
var objs = document.getElementsByTagName("OBJECT");
if(action == 'open')
{
for(i = 0;i < objs.length; i ++)
{
if(objs[i].style.visibility != 'hidden')
{
objs[i].setAttribute("oldvisibility", objs[i].style.visibility);
objs[i].style.visibility = 'hidden';
}
}
var clientWidth = document.body.clientWidth;
var clientHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
var pmwidth = 800;
var pmheight = clientHeight * 0.9;
if(!$$('pmlayer'))
{
div = document.createElement('div');div.id = 'pmlayer';
div.style.width = pmwidth + 'px';
div.style.height = pmheight + 'px';
div.style.left = ((clientWidth - pmwidth) / 2) + 'px';
div.style.position = 'absolute';
div.style.zIndex = '999';
$$('append_parent').appendChild(div);
$$('pmlayer').innerHTML = '<div style="width: 800px; background: #666666; margin: 5px auto; text-align: left">' +
'<div style="width: 800px; height: ' + pmheight + 'px; padding: 1px; background: #FFFFFF; border: 1px solid #7597B8; position: relative; left: -6px; top: -3px">' +
'<div onmousedown="pmwindrag(event, 1)" onmousemove="pmwindrag(event, 2)" onmouseup="pmwindrag(event, 3)" style="cursor: move; position: relative; left: 0px; top: 0px; width: 800px; height: 30px; margin-bottom: -30px;"></div>' +
'<a href="###" onclick="pmwin(\'close\')"><img style="position: absolute; right: 20px; top: 15px" src="images/close.gif" title="关闭" /></a>' +
'<iframe id="pmframe" name="pmframe" style="width:' + pmwidth + 'px;height:100%" allowTransparency="true" frameborder="0"></iframe></div></div>';
}
$$('pmlayer').style.display = '';
$$('pmlayer').style.top = ((clientHeight - pmheight) / 2 + scrollTop) + 'px';
if(!param)
{
pmframe.location = 'pm.php';
}
else
{
pmframe.location = 'pm.php?' + param;
}
}
else if(action == 'close')
{
for(i = 0;i < objs.length; i ++)
{
if(objs[i].attributes['oldvisibility'])
{
objs[i].style.visibility = objs[i].attributes['oldvisibility'].nodeValue;
objs[i].removeAttribute('oldvisibility');
}
}
hiddenobj = new Array();
$$('pmlayer').style.display = 'none';
}
}
var pmwindragstart = new Array();
function pmwindrag(e, op)
{
if(op == 1)
{
pmwindragstart = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
pmwindragstart[2] = parseInt($$('pmlayer').style.left);
pmwindragstart[3] = parseInt($$('pmlayer').style.top);
doane(e);
}
else if(op == 2 && pmwindragstart[0])
{
var pmwindragnow = is_ie ? [event.clientX, event.clientY] : [e.clientX, e.clientY];
$$('pmlayer').style.left = (pmwindragstart[2] + pmwindragnow[0] - pmwindragstart[0]) + 'px';
$$('pmlayer').style.top = (pmwindragstart[3] + pmwindragnow[1] - pmwindragstart[1]) + 'px';
doane(e);
}
else if(op == 3)
{
pmwindragstart = [];
doane(e);
}
}
function doane(event)
{
e = event ? event : window.event;
if(is_ie)
{
e.returnValue = false;
e.cancelBubble = true;
}
else if(e)
{
e.stopPropagation();
e.preventDefault();
}
}
/* *
* 添加礼包到购物车
*/
function addPackageToCart(packageId)
{
var package_info = new Object();
var number = 1;
package_info.package_id = packageId
package_info.number = number;
Ajax.call('flow.php?step=add_package_to_cart', 'package_info=' + package_info.toJSONString(), addPackageToCartResponse, 'POST', 'JSON');
}
/* *
* 处理添加礼包到购物车的反馈信息
*/
function addPackageToCartResponse(result)
{
if (result.error > 0)
{
if (result.error == 2)
{
if (confirm(result.message))
{
location.href = 'user.php?act=add_booking&id=' + result.goods_id;
}
}
else
{
alert(result.message);
}
}
else
{
var cartInfo = document.getElementById('ECS_CARTINFO');
var cart_url = 'flow.php?step=cart';
if (cartInfo)
{
cartInfo.innerHTML = result.content;
}
if (result.one_step_buy == '1')
{
location.href = cart_url;
}
else
{
switch(result.confirm_type)
{
case '1' :
if (confirm(result.message)) location.href = cart_url;
break;
case '2' :
if (!confirm(result.message)) location.href = cart_url;
break;
case '3' :
location.href = cart_url;
break;
default :
break;
}
}
}
}
function setSuitShow(suitId)
{
var suit = document.getElementById('suit_'+suitId);
if(suit == null)
{
return;
}
if(suit.style.display=='none')
{
suit.style.display='';
}
else
{
suit.style.display='none';
}
}
/* 以下四个函数为属性选择弹出框的功能函数部分 */
//检测层是否已经存在
function docEle()
{
return document.getElementById(arguments[0]) || false;
}
//生成属性选择层
function openSpeDiv(message, goods_id)
{
var _id = "speDiv";
var m = "mask";
if (docEle(_id)) document.removeChild(docEle(_id));
if (docEle(m)) document.removeChild(docEle(m));
//计算上卷元素值
var scrollPos;
if (typeof window.pageYOffset != 'undefined')
{
scrollPos = window.pageYOffset;
}
else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat')
{
scrollPos = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined')
{
scrollPos = document.body.scrollTop;
}
var i = 0;
var sel_obj = document.getElementsByTagName('select');
while (sel_obj[i])
{
sel_obj[i].style.visibility = "hidden";
i++;
}
// 新激活图层
var newDiv = document.createElement("div");
newDiv.id = _id;
newDiv.style.position = "absolute";
newDiv.style.zIndex = "10000";
newDiv.style.width = "300px";
newDiv.style.height = "260px";
newDiv.style.top = (parseInt(scrollPos + 200)) + "px";
newDiv.style.left = (parseInt(document.body.offsetWidth) - 200) / 2 + "px"; // 屏幕居中
newDiv.style.overflow = "auto";
newDiv.style.background = "#FFF";
newDiv.style.border = "3px solid #59B0FF";
newDiv.style.padding = "5px";
//生成层内内容
newDiv.innerHTML = '<h4 style="font-size:14; margin:15 0 0 15;">' + select_spe + "</h4>";
for (var spec = 0; spec < message.length; spec++)
{
newDiv.innerHTML += '<hr style="color: #EBEBED; height:1px;"><h6 style="text-align:left; background:#ffffff; margin-left:15px;">' + message[spec]['name'] + '</h6>';
if (message[spec]['attr_type'] == 1)
{
for (var val_arr = 0; val_arr < message[spec]['values'].length; val_arr++)
{
newDiv.innerHTML += "<input style='margin-left:15px;' type='radio' name='spec_" + message[spec]['attr_id'] + "' value='" + message[spec]['values'][val_arr]['id'] + "' id='spec_value_" + message[spec]['values'][val_arr]['id'] + "' /><font color=#555555>" + message[spec]['values'][val_arr]['label'] + '</font> [' + message[spec]['values'][val_arr]['format_price'] + ']</font><br />';
}
newDiv.innerHTML += "<input type='hidden' name='spec_list' value='" + val_arr + "' />";
}
else
{
for (var val_arr = 0; val_arr < message[spec]['values'].length; val_arr++)
{
newDiv.innerHTML += "<input style='margin-left:15px;' type='checkbox' name='spec_" + message[spec]['attr_id'] + "' value='" + message[spec]['values'][val_arr]['id'] + "' id='spec_value_" + message[spec]['values'][val_arr]['id'] + "' /><font color=#555555>" + message[spec]['values'][val_arr]['label'] + ' [' + message[spec]['values'][val_arr]['format_price'] + ']</font><br />';
}
newDiv.innerHTML += "<input type='hidden' name='spec_list' value='" + val_arr + "' />";
}
}
newDiv.innerHTML += "<br /><center>[<a href='javascript:submit_div(" + goods_id + ")' class='f6' >" + btn_buy + "</a>] [<a href='javascript:cancel_div()' class='f6' >" + is_cancel + "</a>]</center>";
document.body.appendChild(newDiv);
// mask图层
var newMask = document.createElement("div");
newMask.id = m;
newMask.style.position = "absolute";
newMask.style.zIndex = "9999";
newMask.style.width = document.body.scrollWidth + "px";
newMask.style.height = document.body.scrollHeight + "px";
newMask.style.top = "0px";
newMask.style.left = "0px";
newMask.style.background = "#FFF";
newMask.style.filter = "alpha(opacity=30)";
newMask.style.opacity = "0.40";
document.body.appendChild(newMask);
}
//获取选择属性后,再次提交到购物车
function submit_div(goods_id)
{
var goods = new Object();
var spec_arr = new Array();
var fittings_arr = new Array();
var number = 1;
var input_arr = document.getElementsByTagName('input');
var spec_arr = new Array();
var j = 0;
for (i = 0; i < input_arr.length; i ++ )
{
var prefix = input_arr[i].name.substr(0, 5);
if (prefix == 'spec_' && (
((input_arr[i].type == 'radio' || input_arr[i].type == 'checkbox') && input_arr[i].checked)))
{
spec_arr[j] = input_arr[i].value;
j++ ;
}
}
goods.spec = spec_arr;
goods.goods_id = goods_id;
goods.number = number;
goods.parent = (typeof(parentId) == "undefined") ? 0 : parseInt(parentId);
Ajax.call('flow.php?step=add_to_cart', 'goods=' + goods.toJSONString(), addToCartResponse, 'POST', 'JSON');
document.body.removeChild(docEle('speDiv'));
document.body.removeChild(docEle('mask'));
var i = 0;
var sel_obj = document.getElementsByTagName('select');
while (sel_obj[i])
{
sel_obj[i].style.visibility = "";
i++;
}
}
// 关闭mask和新图层
function cancel_div()
{
document.body.removeChild(docEle('speDiv'));
document.body.removeChild(docEle('mask'));
var i = 0;
var sel_obj = document.getElementsByTagName('select');
while (sel_obj[i])
{
sel_obj[i].style.visibility = "";
i++;
}
}
| JavaScript |
/* $Id : user.js 4865 2007-01-31 14:04:10Z paulgao $ */
/* *
* 修改会员信息
*/
function userEdit()
{
var frm = document.forms['formEdit'];
var email = frm.elements['email'].value;
var msg = '';
var reg = null;
if (email.length == 0)
{
msg += email_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
msg += email_error + '\n';
}
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* 会员修改密码 */
function editPassword()
{
var frm = document.forms['formPassword'];
var old_password = frm.elements['old_password'].value;
var new_password = frm.elements['new_password'].value;
var confirm_password = frm.elements['comfirm_password'].value;
var msg = '';
var reg = null;
if (old_password.length == 0)
{
msg += old_password_empty + '\n';
}
if (new_password.length == 0)
{
msg += new_password_empty + '\n';
}
if (confirm_password.length == 0)
{
msg += confirm_password_empty + '\n';
}
if (new_password.length > 0 && confirm_password.length > 0)
{
if (new_password != confirm_password)
{
msg += both_password_error + '\n';
}
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 对会员的留言输入作处理
*/
function submitMsg()
{
var frm = document.forms['formMsg'];
var msg_title = frm.elements['msg_title'].value;
var msg_content = frm.elements['msg_content'].value;
var msg = '';
if (msg_title.length == 0)
{
msg += msg_title_empty + '\n';
}
if (msg_content.length == 0)
{
msg += msg_content_empty + '\n'
}
if (msg_title.length > 200)
{
msg += msg_title_limit + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 会员找回密码时,对输入作处理
*/
function submitPwdInfo()
{
var frm = document.forms['getPassword'];
var user_name = frm.elements['user_name'].value;
var email = frm.elements['email'].value;
var errorMsg = '';
if (user_name.length == 0)
{
errorMsg += user_name_empty + '\n';
}
if (email.length == 0)
{
errorMsg += email_address_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
errorMsg += email_address_error + '\n';
}
}
if (errorMsg.length > 0)
{
alert(errorMsg);
return false;
}
return true;
}
/* *
* 会员找回密码时,对输入作处理
*/
function submitPwd()
{
var frm = document.forms['getPassword2'];
var password = frm.elements['new_password'].value;
var confirm_password = frm.elements['confirm_password'].value;
var errorMsg = '';
if (password.length == 0)
{
errorMsg += new_password_empty + '\n';
}
if (confirm_password.length == 0)
{
errorMsg += confirm_password_empty + '\n';
}
if (confirm_password != password)
{
errorMsg += both_password_error + '\n';
}
if (errorMsg.length > 0)
{
alert(errorMsg);
return false;
}
else
{
return true;
}
}
/* *
* 处理会员提交的缺货登记
*/
function addBooking()
{
var frm = document.forms['formBooking'];
var goods_id = frm.elements['id'].value;
var rec_id = frm.elements['rec_id'].value;
var number = frm.elements['number'].value;
var desc = frm.elements['desc'].value;
var linkman = frm.elements['linkman'].value;
var email = frm.elements['email'].value;
var tel = frm.elements['tel'].value;
var msg = "";
if (number.length == 0)
{
msg += booking_amount_empty + '\n';
}
else
{
var reg = /^[0-9]+/;
if ( ! reg.test(number))
{
msg += booking_amount_error + '\n';
}
}
if (desc.length == 0)
{
msg += describe_empty + '\n';
}
if (linkman.length == 0)
{
msg += contact_username_empty + '\n';
}
if (email.length == 0)
{
msg += email_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
msg += email_error + '\n';
}
}
if (tel.length == 0)
{
msg += contact_phone_empty + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
return true;
}
/* *
* 会员登录
*/
function userLogin()
{
var frm = document.forms['formLogin'];
var username = frm.elements['username'].value;
var password = frm.elements['password'].value;
var msg = '';
if (username.length == 0)
{
msg += username_empty + '\n';
}
if (password.length == 0)
{
msg += password_empty + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
function chkstr(str)
{
for (var i = 0; i < str.length; i++)
{
if (str.charCodeAt(i) < 127 && !str.substr(i,1).match(/^\w+$/ig))
{
return false;
}
}
return true;
}
function check_password( password )
{
if ( password.length < 6 )
{
document.getElementById('password_notice').innerHTML = password_shorter;
}
else
{
document.getElementById('password_notice').innerHTML = msg_can_rg;
}
}
function check_conform_password( conform_password )
{
password = document.getElementById('password1').value;
if ( conform_password.length < 6 )
{
document.getElementById('conform_password_notice').innerHTML = password_shorter;
return false;
}
if ( conform_password != password )
{
document.getElementById('conform_password_notice').innerHTML = confirm_password_invalid;
}
else
{
document.getElementById('conform_password_notice').innerHTML = msg_can_rg;
}
}
function is_registered( username )
{
var submit_disabled = false;
var unlen = username.replace(/[^\x00-\xff]/g, "**").length;
if ( username == '' )
{
document.getElementById('username_notice').innerHTML = msg_un_blank;
var submit_disabled = true;
}
if ( !chkstr( username ) )
{
document.getElementById('username_notice').innerHTML = msg_un_format;
var submit_disabled = true;
}
if ( unlen < 3 )
{
document.getElementById('username_notice').innerHTML = username_shorter;
var submit_disabled = true;
}
if ( unlen > 14 )
{
document.getElementById('username_notice').innerHTML = msg_un_length;
var submit_disabled = true;
}
if ( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=is_registered', 'username=' + username, registed_callback , 'GET', 'TEXT', true, true );
}
function registed_callback(result)
{
if ( result == "true" )
{
document.getElementById('username_notice').innerHTML = msg_can_rg;
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
document.getElementById('username_notice').innerHTML = msg_un_registered;
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
function checkEmail(email)
{
var submit_disabled = false;
if (email == '')
{
document.getElementById('email_notice').innerHTML = msg_email_blank;
submit_disabled = true;
}
else if (!Utils.isEmail(email))
{
document.getElementById('email_notice').innerHTML = msg_email_format;
submit_disabled = true;
}
if( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=check_email', 'email=' + email, check_email_callback , 'GET', 'TEXT', true, true );
}
function check_email_callback(result)
{
if ( result == 'ok' )
{
document.getElementById('email_notice').innerHTML = msg_can_rg;
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
document.getElementById('email_notice').innerHTML = msg_email_registered;
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
/* *
* 处理注册用户
*/
function register()
{
var frm = document.forms['formUser'];
var username = Utils.trim(frm.elements['username'].value);
var email = frm.elements['email'].value;
var password = Utils.trim(frm.elements['password'].value);
var confirm_password = Utils.trim(frm.elements['confirm_password'].value);
var checked_agreement = frm.elements['agreement'].checked;
var msn = frm.elements['other[msn]'] ? Utils.trim(frm.elements['other[msn]'].value) : '';
var qq = frm.elements['other[qq]'] ? Utils.trim(frm.elements['other[qq]'].value) : '';
var home_phone = frm.elements['other[home_phone]'] ? Utils.trim(frm.elements['other[home_phone]'].value) : '';
var office_phone = frm.elements['other[office_phone]'] ? Utils.trim(frm.elements['other[office_phone]'].value) : '';
var mobile_phone = frm.elements['other[mobile_phone]'] ? Utils.trim(frm.elements['other[mobile_phone]'].value) : '';
var msg = "";
// 检查输入
var msg = '';
if (username.length == 0)
{
msg += username_empty + '\n';
}
else if (username.match(/^\s*$|^c:\\con\\con$|[%,\'\*\"\s\t\<\>\&\\]/))
{
msg += username_invalid + '\n';
}
else if (username.length < 3)
{
//msg += username_shorter + '\n';
}
if (email.length == 0)
{
msg += email_empty + '\n';
}
else
{
if ( ! (Utils.isEmail(email)))
{
msg += email_invalid + '\n';
}
}
if (password.length == 0)
{
msg += password_empty + '\n';
}
else if (password.length < 6)
{
msg += password_shorter + '\n';
}
if (confirm_password != password )
{
msg += confirm_password_invalid + '\n';
}
if(checked_agreement != true)
{
msg += agreement + '\n';
}
if (msn.length > 0 && (!Utils.isEmail(msn)))
{
msg += msn_invalid + '\n';
}
if (qq.length > 0 && (!Utils.isNumber(qq)))
{
msg += qq_invalid + '\n';
}
if (office_phone.length>0)
{
var reg = /^[\d|\-|\s]+$/;
if (!reg.test(office_phone))
{
msg += office_phone_invalid + '\n';
}
}
if (home_phone.length>0)
{
var reg = /^[\d|\-|\s]+$/;
if (!reg.test(home_phone))
{
msg += home_phone_invalid + '\n';
}
}
if (mobile_phone.length>0)
{
var reg = /^[\d|\-|\s]+$/;
if (!reg.test(mobile_phone))
{
msg += mobile_phone_invalid + '\n';
}
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 用户中心订单保存地址信息
*/
function saveOrderAddress(id)
{
var frm = document.forms['formAddress'];
var consignee = frm.elements['consignee'].value;
var email = frm.elements['email'].value;
var address = frm.elements['address'].value;
var zipcode = frm.elements['zipcode'].value;
var tel = frm.elements['tel'].value;
var mobile = frm.elements['mobile'].value;
var sign_building = frm.elements['sign_building'].value;
var best_time = frm.elements['best_time'].value;
if (id == 0)
{
alert(current_ss_not_unshipped);
return false;
}
var msg = '';
if (address.length == 0)
{
msg += address_name_not_null + "\n";
}
if (consignee.length == 0)
{
msg += consignee_not_null + "\n";
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 会员余额申请
*/
function submitSurplus()
{
var frm = document.forms['formSurplus'];
var surplus_type = frm.elements['surplus_type'].value;
var surplus_amount = frm.elements['amount'].value;
var process_notic = frm.elements['user_note'].value;
var payment_id = 0;
var msg = '';
if (surplus_amount.length == 0 )
{
msg += surplus_amount_empty + "\n";
}
else
{
var reg = /^[\.0-9]+/;
if ( ! reg.test(surplus_amount))
{
msg += surplus_amount_error + '\n';
}
}
if (process_notic.length == 0)
{
msg += process_desc + "\n";
}
if (msg.length > 0)
{
alert(msg);
return false;
}
if (surplus_type == 0)
{
for (i = 0; i < frm.elements.length ; i ++)
{
if (frm.elements[i].name=="payment_id" && frm.elements[i].checked)
{
payment_id = frm.elements[i].value;
break;
}
}
if (payment_id == 0)
{
alert(payment_empty);
return false;
}
}
return true;
}
/* *
* 处理用户添加一个红包
*/
function addBonus()
{
var frm = document.forms['addBouns'];
var bonus_sn = frm.elements['bonus_sn'].value;
if (bonus_sn.length == 0)
{
alert(bonus_sn_empty);
return false;
}
else
{
var reg = /^[0-9]{10}$/;
if ( ! reg.test(bonus_sn))
{
alert(bonus_sn_error);
return false;
}
}
return true;
}
/* *
* 合并订单检查
*/
function mergeOrder()
{
if (!confirm(confirm_merge))
{
return false;
}
var frm = document.forms['formOrder'];
var from_order = frm.elements['from_order'].value;
var to_order = frm.elements['to_order'].value;
var msg = '';
if (from_order == 0)
{
msg += from_order_empty + '\n';
}
if (to_order == 0)
{
msg += to_order_empty + '\n';
}
else if (to_order == from_order)
{
msg += order_same + '\n';
}
if (msg.length > 0)
{
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 订单中的商品返回购物车
* @param int orderId 订单号
*/
function returnToCart(orderId)
{
Ajax.call('user.php?act=return_to_cart', 'order_id=' + orderId, returnToCartResponse, 'POST', 'JSON');
}
function returnToCartResponse(result)
{
alert(result.message);
}
/* *
* 检测密码强度
* @param string pwd 密码
*/
function checkIntensity(pwd)
{
var Mcolor = "#FFF",Lcolor = "#FFF",Hcolor = "#FFF";
var m=0;
var Modes = 0;
for (i=0; i<pwd.length; i++)
{
var charType = 0;
var t = pwd.charCodeAt(i);
if (t>=48 && t <=57)
{
charType = 1;
}
else if (t>=65 && t <=90)
{
charType = 2;
}
else if (t>=97 && t <=122)
charType = 4;
else
charType = 4;
Modes |= charType;
}
for (i=0;i<4;i++)
{
if (Modes & 1) m++;
Modes>>>=1;
}
if (pwd.length<=4)
{
m = 1;
}
switch(m)
{
case 1 :
Lcolor = "2px solid red";
Mcolor = Hcolor = "2px solid #DADADA";
break;
case 2 :
Mcolor = "2px solid #f90";
Lcolor = Hcolor = "2px solid #DADADA";
break;
case 3 :
Hcolor = "2px solid #3c0";
Lcolor = Mcolor = "2px solid #DADADA";
break;
case 4 :
Hcolor = "2px solid #3c0";
Lcolor = Mcolor = "2px solid #DADADA";
break;
default :
Hcolor = Mcolor = Lcolor = "";
break;
}
if (document.getElementById("pwd_lower"))
{
document.getElementById("pwd_lower").style.borderBottom = Lcolor;
document.getElementById("pwd_middle").style.borderBottom = Mcolor;
document.getElementById("pwd_high").style.borderBottom = Hcolor;
}
}
function changeType(obj)
{
if (obj.getAttribute("min") && document.getElementById("ECS_AMOUNT"))
{
document.getElementById("ECS_AMOUNT").disabled = false;
document.getElementById("ECS_AMOUNT").value = obj.getAttribute("min");
if (document.getElementById("ECS_NOTICE") && obj.getAttribute("to") && obj.getAttribute('fee'))
{
var fee = parseInt(obj.getAttribute("fee"));
var to = parseInt(obj.getAttribute("to"));
if (fee < 0)
{
to = to + fee * 2;
}
document.getElementById("ECS_NOTICE").innerHTML = notice_result + to;
}
}
}
function calResult()
{
var amount = document.getElementById("ECS_AMOUNT").value;
var notice = document.getElementById("ECS_NOTICE");
reg = /^\d+$/;
if (!reg.test(amount))
{
notice.innerHTML = notice_not_int;
return;
}
amount = parseInt(amount);
var frm = document.forms['transform'];
for(i=0; i < frm.elements['type'].length; i++)
{
if (frm.elements['type'][i].checked)
{
var min = parseInt(frm.elements['type'][i].getAttribute("min"));
var to = parseInt(frm.elements['type'][i].getAttribute("to"));
var fee = parseInt(frm.elements['type'][i].getAttribute("fee"));
var result = 0;
if (amount < min)
{
notice.innerHTML = notice_overflow + min;
return;
}
if (fee > 0)
{
result = (amount - fee) * to / (min -fee);
}
else
{
//result = (amount + fee* min /(to+fee)) * (to + fee) / min ;
result = amount * (to + fee) / min + fee;
}
notice.innerHTML = notice_result + parseInt(result + 0.5);
}
}
}
| JavaScript |
/* $Id : auto_complete.js 4865 2007-01-31 14:04:10Z paulgao $ */
function autoComplete(obj, hidden, url, callback)
{
this.borderStyle = '1px solid #000';
this.highlight = '#000080';
this.highlightText = '#FFF';
this.background = '#FFF';
this.params = '';
var textbox = obj;
var hidden = hidden;
var oldValue = '';
var flag = false;
var url = url;
this.call = function()
{
if (flag)
{
flag = false;
return;
}
if (url == '')
{
return;
}
if (oldValue != '' && oldValue == textbox.value)
{
return;
}
else
{
oldValue = textbox.value;
}
if (textbox.value != '')
{
Transport.run(url, "arg=" + textbox.value, this.show, 'get', 'json');
}
else
{
var layer = document.getElementById('AC_layer');
if (layer)
{
layer.style.display = 'none';
}
}
}
var _ac = this;
this.show = function(result)
{
var obj = result;
var layer = null;
if (document.getElementById('AC_layer'))
{
layer = document.getElementById('AC_layer');
layer.innerHTML = '';
layer.style.display = 'block';
}
else
{
layer = document.createElement('DIV');
layer.id = 'AC_layer';
document.body.appendChild(layer);
}
pos = getPosition();
layer.style.left = pos.x + 'px';
layer.style.top = pos.y + 'px';
layer.style.width = textbox.clientWidth + 'px';
layer.style.position = 'absolute';
layer.style.border = _ac.borderStyle;
layer.style.background = _ac.background;
createMenuItem(obj, layer);
textbox.onkeyup = function(e)
{
var evt = fixEvent(e);
if (evt.keyCode == '38')
{
highlightItem('prev');
}
if (evt.keyCode == '40')
{
highlightItem('next');
}
}
textbox.onblur = function()
{
var layer = document.getElementById('AC_layer');
if (layer)
{
layer.style.display = 'none';
}
}
}
var createMenuItem = function(obj, layer)
{
var lst = document.createElement('UL');
lst.style.listStyle = 'none';
lst.style.margin = '0';
lst.style.padding = '1px';
lst.style.display = 'block';
for (i = 0; i < obj.length; i ++ )
{
if (typeof(obj[i].key) === "undefined" || typeof(obj[i].val) === "undefined")
{
throw new Error('Error data.');
break;
}
else
{
var listItem = document.createElement('LI');
listItem.id = obj[i].key;
listItem.innerHTML = obj[i].val;
listItem.title = obj[i].val;
listItem.style.cursor = "default";
listItem.style.pointer = "default";
listItem.style.margin = '0px';
listItem.style.padding = '0px';
listItem.style.display = 'block';
listItem.style.width = '100%';
listItem.style.height = '16px';
listItem.style.overflow = 'hidden';
listItem.onmouseover = function(e)
{
for (i = 0; i < this.parentNode.childNodes.length;
i ++ )
{
this.parentNode.childNodes[i].style.backgroundColor = '';
this.parentNode.childNodes[i].style.color = '';
}
this.style.backgroundColor = _ac.highlight;
this.style.color = _ac.highlightText;
assign(this);
}
;
listItem.onmouseout = function(e)
{
this.style.backgroundColor = '';
this.style.color = '';
}
;
lst.appendChild(listItem);
}
}
layer.appendChild(lst);
}
var getPosition = function()
{
var obj = textbox;
var pos =
{
"x" : 0, "y" : 0
}
pos.x = document.body.offsetLeft;
pos.y = document.body.offsetTop + textbox.clientHeight + 3;
do
{
pos.x += obj.offsetLeft;
pos.y += obj.offsetTop;
obj = obj.offsetParent;
}
while (obj.tagName.toUpperCase() != 'BODY')
return pos;
}
var fixEvent = function(e)
{
return (typeof e == "undefined") ? window.event : e;
}
var highlightItem = function(direction)
{
var layer = document.getElementById('AC_layer');
var list = null;
var item = null;
if (layer)
{
list = layer.childNodes[0];
}
if (list)
{
for (i = 0; i < list.childNodes.length; i ++ )
{
if (list.childNodes[i].style.backgroundColor == _ac.highlight)
{
if (direction == 'prev')
{
item = (i > 0) ? list.childNodes[i - 1] : list.lastChild;
}
else
{
item = (i < list.childNodes.length) ? list.childNodes[i + 1] : list.childNodes[0];
}
}
list.childNodes[i].style.backgroundColor = '';
list.childNodes[i].style.color = '';
}
}
if ( ! item)
{
item = (direction == 'prev') ? list.lastChild : list.childNodes[0];
}
item.style.backgroundColor = _ac.highlight;
item.style.color = _ac.highlightText
assign(item);
}
var assign = function(item)
{
flag = true;
textbox.value = item.innerHTML;
if (typeof hidden == 'object')
{
hidden.value = item.id;
}
if (typeof callback == 'function')
{
callback.call(_ac, item.id, textbox.value);
}
}
var debug = function()
{
// document.getElementById('foo').innerHTML = textbox.value;
}
}
| JavaScript |
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose)
{
// member variables
this.activeDiv = null;
this.currentDateEl = null;
this.getDateStatus = null;
this.getDateToolTip = null;
this.getDateText = null;
this.timeout = null;
this.onSelected = onSelected || null;
this.onClose = onClose || null;
this.dragging = false;
this.hidden = false;
this.minYear = 1970;
this.maxYear = 2050;
this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
this.isPopup = true;
this.weekNumbers = true;
this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
this.showsOtherMonths = false;
this.dateStr = dateStr;
this.ar_days = null;
this.showsTime = false;
this.time24 = true;
this.yearStep = 2;
this.hiliteToday = true;
this.multiple = null;
// HTML elements
this.table = null;
this.element = null;
this.tbody = null;
this.firstdayname = null;
// Combo boxes
this.monthsCombo = null;
this.yearsCombo = null;
this.hilitedMonth = null;
this.activeMonth = null;
this.hilitedYear = null;
this.activeYear = null;
// Information
this.dateClicked = false;
// one-time initializations
if (typeof Calendar._SDN == "undefined") {
// table of short day names
if (typeof Calendar._SDN_len == "undefined")
Calendar._SDN_len = 3;
var ar = new Array();
for (var i = 8; i > 0;) {
ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
}
Calendar._SDN = ar;
// table of short month names
if (typeof Calendar._SMN_len == "undefined")
Calendar._SMN_len = 3;
ar = new Array();
for (var i = 12; i > 0;) {
ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
}
Calendar._SMN = ar;
}
};
// ** constants
/// "static", needed for event handlers.
Calendar._C = null;
/// detect a special case of "web browser"
Calendar.is_ie = ( /msie/i.test(navigator.userAgent) &&
!/opera/i.test(navigator.userAgent) );
Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );
/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);
/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
// library, at some point.
Calendar.getAbsolutePos = function(el) {
var SL = 0, ST = 0;
var is_div = /^div$/i.test(el.tagName);
if (is_div && el.scrollLeft)
SL = el.scrollLeft;
if (is_div && el.scrollTop)
ST = el.scrollTop;
var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
if (el.offsetParent) {
var tmp = this.getAbsolutePos(el.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
Calendar.isRelated = function (el, evt) {
var related = evt.relatedTarget;
if (!related) {
var type = evt.type;
if (type == "mouseover") {
related = evt.fromElement;
} else if (type == "mouseout") {
related = evt.toElement;
}
}
while (related) {
if (related == el) {
return true;
}
related = related.parentNode;
}
return false;
};
Calendar.removeClass = function(el, className) {
if (!(el && el.className)) {
return;
}
var cls = el.className.split(" ");
var ar = new Array();
for (var i = cls.length; i > 0;) {
if (cls[--i] != className) {
ar[ar.length] = cls[i];
}
}
el.className = ar.join(" ");
};
Calendar.addClass = function(el, className) {
Calendar.removeClass(el, className);
el.className += " " + className;
};
// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
Calendar.getElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
while (f.nodeType != 1 || /^div$/i.test(f.tagName))
f = f.parentNode;
return f;
};
Calendar.getTargetElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.target;
while (f.nodeType != 1)
f = f.parentNode;
return f;
};
Calendar.stopEvent = function(ev) {
ev || (ev = window.event);
if (Calendar.is_ie) {
ev.cancelBubble = true;
ev.returnValue = false;
} else {
ev.preventDefault();
ev.stopPropagation();
}
return false;
};
Calendar.addEvent = function(el, evname, func) {
if (el.attachEvent) { // IE
el.attachEvent("on" + evname, func);
} else if (el.addEventListener) { // Gecko / W3C
el.addEventListener(evname, func, true);
} else {
el["on" + evname] = func;
}
};
Calendar.removeEvent = function(el, evname, func) {
if (el.detachEvent) { // IE
el.detachEvent("on" + evname, func);
} else if (el.removeEventListener) { // Gecko / W3C
el.removeEventListener(evname, func, true);
} else {
el["on" + evname] = null;
}
};
Calendar.createElement = function(type, parent) {
var el = null;
if (document.createElementNS) {
// use the XHTML namespace; IE won't normally get here unless
// _they_ "fix" the DOM2 implementation.
el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
} else {
el = document.createElement(type);
}
if (typeof parent != "undefined") {
parent.appendChild(el);
}
return el;
};
// END: UTILITY FUNCTIONS
// BEGIN: CALENDAR STATIC FUNCTIONS
/** Internal -- adds a set of events to make some element behave like a button. */
Calendar._add_evs = function(el) {
with (Calendar) {
addEvent(el, "mouseover", dayMouseOver);
addEvent(el, "mousedown", dayMouseDown);
addEvent(el, "mouseout", dayMouseOut);
if (is_ie) {
addEvent(el, "dblclick", dayMouseDblClick);
el.setAttribute("unselectable", true);
}
}
};
Calendar.findMonth = function(el) {
if (typeof el.month != "undefined") {
return el;
} else if (typeof el.parentNode.month != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.findYear = function(el) {
if (typeof el.year != "undefined") {
return el;
} else if (typeof el.parentNode.year != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.showMonthsCombo = function () {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var mc = cal.monthsCombo;
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
if (cal.activeMonth) {
Calendar.removeClass(cal.activeMonth, "active");
}
var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
Calendar.addClass(mon, "active");
cal.activeMonth = mon;
var s = mc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var mcw = mc.offsetWidth;
if (typeof mcw == "undefined")
// Konqueror brain-dead techniques
mcw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
};
Calendar.showYearsCombo = function (fwd) {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var yc = cal.yearsCombo;
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
if (cal.activeYear) {
Calendar.removeClass(cal.activeYear, "active");
}
cal.activeYear = null;
var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
var yr = yc.firstChild;
var show = false;
for (var i = 12; i > 0; --i) {
if (Y >= cal.minYear && Y <= cal.maxYear) {
yr.innerHTML = Y;
yr.year = Y;
yr.style.display = "block";
show = true;
} else {
yr.style.display = "none";
}
yr = yr.nextSibling;
Y += fwd ? cal.yearStep : -cal.yearStep;
}
if (show) {
var s = yc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var ycw = yc.offsetWidth;
if (typeof ycw == "undefined")
// Konqueror brain-dead techniques
ycw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
}
};
// event handlers
Calendar.tableMouseUp = function(ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
if (cal.timeout) {
clearTimeout(cal.timeout);
}
var el = cal.activeDiv;
if (!el) {
return false;
}
var target = Calendar.getTargetElement(ev);
ev || (ev = window.event);
Calendar.removeClass(el, "active");
if (target == el || target.parentNode == el) {
Calendar.cellClick(el, ev);
}
var mon = Calendar.findMonth(target);
var date = null;
if (mon) {
date = new Date(cal.date);
if (mon.month != date.getMonth()) {
date.setMonth(mon.month);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
} else {
var year = Calendar.findYear(target);
if (year) {
date = new Date(cal.date);
if (year.year != date.getFullYear()) {
date.setFullYear(year.year);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
}
}
with (Calendar) {
removeEvent(document, "mouseup", tableMouseUp);
removeEvent(document, "mouseover", tableMouseOver);
removeEvent(document, "mousemove", tableMouseOver);
cal._hideCombos();
_C = null;
return stopEvent(ev);
}
};
Calendar.tableMouseOver = function (ev) {
var cal = Calendar._C;
if (!cal) {
return;
}
var el = cal.activeDiv;
var target = Calendar.getTargetElement(ev);
if (target == el || target.parentNode == el) {
Calendar.addClass(el, "hilite active");
Calendar.addClass(el.parentNode, "rowhilite");
} else {
if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
Calendar.removeClass(el, "active");
Calendar.removeClass(el, "hilite");
Calendar.removeClass(el.parentNode, "rowhilite");
}
ev || (ev = window.event);
if (el.navtype == 50 && target != el) {
var pos = Calendar.getAbsolutePos(el);
var w = el.offsetWidth;
var x = ev.clientX;
var dx;
var decrease = true;
if (x > pos.x + w) {
dx = x - pos.x - w;
decrease = false;
} else
dx = pos.x - x;
if (dx < 0) dx = 0;
var range = el._range;
var current = el._current;
var count = Math.floor(dx / 10) % range.length;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
while (count-- > 0)
if (decrease) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
}
var mon = Calendar.findMonth(target);
if (mon) {
if (mon.month != cal.date.getMonth()) {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
Calendar.addClass(mon, "hilite");
cal.hilitedMonth = mon;
} else if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
} else {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
var year = Calendar.findYear(target);
if (year) {
if (year.year != cal.date.getFullYear()) {
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
Calendar.addClass(year, "hilite");
cal.hilitedYear = year;
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
}
return Calendar.stopEvent(ev);
};
Calendar.tableMouseDown = function (ev) {
if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
return Calendar.stopEvent(ev);
}
};
Calendar.calDragIt = function (ev) {
var cal = Calendar._C;
if (!(cal && cal.dragging)) {
return false;
}
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posX = ev.pageX;
posY = ev.pageY;
}
cal.hideShowCovered();
var st = cal.element.style;
st.left = (posX - cal.xOffs) + "px";
st.top = (posY - cal.yOffs) + "px";
return Calendar.stopEvent(ev);
};
Calendar.calDragEnd = function (ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
cal.dragging = false;
with (Calendar) {
removeEvent(document, "mousemove", calDragIt);
removeEvent(document, "mouseup", calDragEnd);
tableMouseUp(ev);
}
cal.hideShowCovered();
};
Calendar.dayMouseDown = function(ev) {
var el = Calendar.getElement(ev);
if (el.disabled) {
return false;
}
var cal = el.calendar;
cal.activeDiv = el;
Calendar._C = cal;
if (el.navtype != 300) with (Calendar) {
if (el.navtype == 50) {
el._current = el.innerHTML;
addEvent(document, "mousemove", tableMouseOver);
} else
addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
addClass(el, "hilite active");
addEvent(document, "mouseup", tableMouseUp);
} else if (cal.isPopup) {
cal._dragStart(ev);
}
if (el.navtype == -1 || el.navtype == 1) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
} else if (el.navtype == -2 || el.navtype == 2) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
} else {
cal.timeout = null;
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseDblClick = function(ev) {
Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
if (Calendar.is_ie) {
document.selection.empty();
}
};
Calendar.dayMouseOver = function(ev) {
var el = Calendar.getElement(ev);
if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
return false;
}
if (el.ttip) {
if (el.ttip.substr(0, 1) == "_") {
el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
}
el.calendar.tooltips.innerHTML = el.ttip;
}
if (el.navtype != 300) {
Calendar.addClass(el, "hilite");
if (el.caldate) {
Calendar.addClass(el.parentNode, "rowhilite");
}
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseOut = function(ev) {
with (Calendar) {
var el = getElement(ev);
if (isRelated(el, ev) || _C || el.disabled)
return false;
removeClass(el, "hilite");
if (el.caldate)
removeClass(el.parentNode, "rowhilite");
if (el.calendar)
el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
return stopEvent(ev);
}
};
/**
* A generic "click" handler :) handles all types of buttons defined in this
* calendar.
*/
Calendar.cellClick = function(el, ev) {
var cal = el.calendar;
var closing = false;
var newdate = false;
var date = null;
if (typeof el.navtype == "undefined") {
if (cal.currentDateEl) {
Calendar.removeClass(cal.currentDateEl, "selected");
Calendar.addClass(el, "selected");
closing = (cal.currentDateEl == el);
if (!closing) {
cal.currentDateEl = el;
}
}
cal.date.setDateOnly(el.caldate);
date = cal.date;
var other_month = !(cal.dateClicked = !el.otherMonth);
if (!other_month && !cal.currentDateEl)
cal._toggleMultipleDate(new Date(date));
else
newdate = !el.disabled;
// a date was clicked
if (other_month)
cal._init(cal.firstDayOfWeek, date);
} else {
if (el.navtype == 200) {
Calendar.removeClass(el, "hilite");
cal.callCloseHandler();
return;
}
date = new Date(cal.date);
if (el.navtype == 0)
date.setDateOnly(new Date()); // TODAY
// unless "today" was clicked, we assume no date was clicked so
// the selected handler will know not to close the calenar when
// in single-click mode.
// cal.dateClicked = (el.navtype == 0);
cal.dateClicked = false;
var year = date.getFullYear();
var mon = date.getMonth();
function setMonth(m) {
var day = date.getDate();
var max = date.getMonthDays(m);
if (day > max) {
date.setDate(max);
}
date.setMonth(m);
};
switch (el.navtype) {
case 400:
Calendar.removeClass(el, "hilite");
var text = Calendar._TT["ABOUT"];
if (typeof text != "undefined") {
text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
} else {
// FIXME: this should be removed as soon as lang files get updated!
text = "Help and about box text is not translated into this language.\n" +
"If you know this language and you feel generous please update\n" +
"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" +
"Thank you!\n" +
"http://dynarch.com/mishoo/calendar.epl\n";
}
alert(text);
return;
case -2:
if (year > cal.minYear) {
date.setFullYear(year - 1);
}
break;
case -1:
if (mon > 0) {
setMonth(mon - 1);
} else if (year-- > cal.minYear) {
date.setFullYear(year);
setMonth(11);
}
break;
case 1:
if (mon < 11) {
setMonth(mon + 1);
} else if (year < cal.maxYear) {
date.setFullYear(year + 1);
setMonth(0);
}
break;
case 2:
if (year < cal.maxYear) {
date.setFullYear(year + 1);
}
break;
case 100:
cal.setFirstDayOfWeek(el.fdow);
return;
case 50:
var range = el._range;
var current = el.innerHTML;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
if (ev && ev.shiftKey) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
return;
case 0:
// TODAY will bring us here
if ((typeof cal.getDateStatus == "function") &&
cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
return false;
}
break;
}
if (!date.equalsTo(cal.date)) {
cal.setDate(date);
newdate = true;
} else if (el.navtype == 0)
newdate = closing = true;
}
if (newdate) {
ev && cal.callHandler();
}
if (closing) {
Calendar.removeClass(el, "hilite");
ev && cal.callCloseHandler();
}
};
// END: CALENDAR STATIC FUNCTIONS
// BEGIN: CALENDAR OBJECT FUNCTIONS
/**
* This function creates the calendar inside the given parent. If _par is
* null than it creates a popup calendar inside the BODY element. If _par is
* an element, be it BODY, then it creates a non-popup calendar (still
* hidden). Some properties need to be set before calling this function.
*/
Calendar.prototype.create = function (_par) {
var parent = null;
if (! _par) {
// default parent is the document body, in which case we create
// a popup calendar.
parent = document.getElementsByTagName("body")[0];
this.isPopup = true;
} else {
parent = _par;
this.isPopup = false;
}
this.date = this.dateStr ? new Date(this.dateStr) : new Date();
var table = Calendar.createElement("table");
this.table = table;
table.cellSpacing = 0;
table.cellPadding = 0;
table.calendar = this;
Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);
var div = Calendar.createElement("div");
this.element = div;
div.className = "calendar";
if (this.isPopup) {
div.style.position = "absolute";
div.style.display = "none";
}
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (document.body.filters))
{
div.innerHTML = '<iframe src="javascript:false" id="compareFrame" style=" position:absolute; top:0px; left:0px;width:245px; visibility:inherit;height:172px; z-index:-1;filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";></iframe>';
}
div.appendChild(table);
var thead = Calendar.createElement("thead", table);
var cell = null;
var row = null;
var cal = this;
var hh = function (text, cs, navtype) {
cell = Calendar.createElement("td", row);
cell.colSpan = cs;
cell.className = "button";
if (navtype != 0 && Math.abs(navtype) <= 2)
cell.className += " nav";
Calendar._add_evs(cell);
cell.calendar = cal;
cell.navtype = navtype;
cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
return cell;
};
row = Calendar.createElement("tr", thead);
var title_length = 6;
(this.isPopup) && --title_length;
(this.weekNumbers) && ++title_length;
hh("?", 1, 400).ttip = Calendar._TT["INFO"];
this.title = hh("", title_length, 300);
this.title.className = "title";
if (this.isPopup) {
this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
this.title.style.cursor = "move";
hh("×", 1, 200).ttip = Calendar._TT["CLOSE"];
}
row = Calendar.createElement("tr", thead);
row.className = "headrow";
this._nav_py = hh("«", 1, -2);
this._nav_py.ttip = Calendar._TT["PREV_YEAR"];
this._nav_pm = hh("‹", 1, -1);
this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];
this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
this._nav_now.ttip = Calendar._TT["GO_TODAY"];
this._nav_nm = hh("›", 1, 1);
this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];
this._nav_ny = hh("»", 1, 2);
this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
// day names
row = Calendar.createElement("tr", thead);
row.className = "daynames";
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
cell.className = "name wn";
cell.innerHTML = Calendar._TT["WK"];
}
for (var i = 7; i > 0; --i) {
cell = Calendar.createElement("td", row);
if (!i) {
cell.navtype = 100;
cell.calendar = this;
Calendar._add_evs(cell);
}
}
this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
this._displayWeekdays();
var tbody = Calendar.createElement("tbody", table);
this.tbody = tbody;
for (i = 6; i > 0; --i) {
row = Calendar.createElement("tr", tbody);
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
}
for (var j = 7; j > 0; --j) {
cell = Calendar.createElement("td", row);
cell.calendar = this;
Calendar._add_evs(cell);
}
}
if (this.showsTime) {
row = Calendar.createElement("tr", tbody);
row.className = "time";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
cell.innerHTML = Calendar._TT["TIME"] || " ";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = this.weekNumbers ? 4 : 3;
(function(){
function makeTimePart(className, init, range_start, range_end) {
var part = Calendar.createElement("span", cell);
part.className = className;
part.innerHTML = init;
part.calendar = cal;
part.ttip = Calendar._TT["TIME_PART"];
part.navtype = 50;
part._range = [];
if (typeof range_start != "number")
part._range = range_start;
else {
for (var i = range_start; i <= range_end; ++i) {
var txt;
if (i < 10 && range_end >= 10) txt = '0' + i;
else txt = '' + i;
part._range[part._range.length] = txt;
}
}
Calendar._add_evs(part);
return part;
};
var hrs = cal.date.getHours();
var mins = cal.date.getMinutes();
var t12 = !cal.time24;
var pm = (hrs > 12);
if (t12 && pm) hrs -= 12;
var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
var span = Calendar.createElement("span", cell);
span.innerHTML = ":";
span.className = "colon";
var M = makeTimePart("minute", mins, 0, 59);
var AP = null;
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
if (t12)
AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
else
cell.innerHTML = " ";
cal.onSetTime = function() {
var pm, hrs = this.date.getHours(),
mins = this.date.getMinutes();
if (t12) {
pm = (hrs >= 12);
if (pm) hrs -= 12;
if (hrs == 0) hrs = 12;
AP.innerHTML = pm ? "pm" : "am";
}
H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
};
cal.onUpdateTime = function() {
var date = this.date;
var h = parseInt(H.innerHTML, 10);
if (t12) {
if (/pm/i.test(AP.innerHTML) && h < 12)
h += 12;
else if (/am/i.test(AP.innerHTML) && h == 12)
h = 0;
}
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
date.setHours(h);
date.setMinutes(parseInt(M.innerHTML, 10));
date.setFullYear(y);
date.setMonth(m);
date.setDate(d);
this.dateClicked = false;
this.callHandler();
};
})();
} else {
this.onSetTime = this.onUpdateTime = function() {};
}
var tfoot = Calendar.createElement("tfoot", table);
row = Calendar.createElement("tr", tfoot);
row.className = "footrow";
cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
cell.className = "ttip";
if (this.isPopup) {
cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
cell.style.cursor = "move";
}
this.tooltips = cell;
div = Calendar.createElement("div", this.element);
this.monthsCombo = div;
div.className = "combo";
for (i = 0; i < Calendar._MN.length; ++i) {
var mn = Calendar.createElement("div");
mn.className = Calendar.is_ie ? "label-IEfix" : "label";
mn.month = i;
mn.innerHTML = Calendar._SMN[i];
div.appendChild(mn);
}
div = Calendar.createElement("div", this.element);
this.yearsCombo = div;
div.className = "combo";
for (i = 12; i > 0; --i) {
var yr = Calendar.createElement("div");
yr.className = Calendar.is_ie ? "label-IEfix" : "label";
div.appendChild(yr);
}
this._init(this.firstDayOfWeek, this.date);
parent.appendChild(this.element);
};
/** keyboard navigation, only for popup calendars */
Calendar._keyEvent = function(ev) {
var cal = window._dynarch_popupCalendar;
if (!cal || cal.multiple)
return false;
(Calendar.is_ie) && (ev = window.event);
var act = (Calendar.is_ie || ev.type == "keypress"),
K = ev.keyCode;
if (ev.ctrlKey) {
switch (K) {
case 37: // KEY left
act && Calendar.cellClick(cal._nav_pm);
break;
case 38: // KEY up
act && Calendar.cellClick(cal._nav_py);
break;
case 39: // KEY right
act && Calendar.cellClick(cal._nav_nm);
break;
case 40: // KEY down
act && Calendar.cellClick(cal._nav_ny);
break;
default:
return false;
}
} else switch (K) {
case 32: // KEY space (now)
Calendar.cellClick(cal._nav_now);
break;
case 27: // KEY esc
act && cal.callCloseHandler();
break;
case 37: // KEY left
case 38: // KEY up
case 39: // KEY right
case 40: // KEY down
if (act) {
var prev, x, y, ne, el, step;
prev = K == 37 || K == 38;
step = (K == 37 || K == 39) ? 1 : 7;
function setVars() {
el = cal.currentDateEl;
var p = el.pos;
x = p & 15;
y = p >> 4;
ne = cal.ar_days[y][x];
};setVars();
function prevMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() - step);
cal.setDate(date);
};
function nextMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() + step);
cal.setDate(date);
};
while (1) {
switch (K) {
case 37: // KEY left
if (--x >= 0)
ne = cal.ar_days[y][x];
else {
x = 6;
K = 38;
continue;
}
break;
case 38: // KEY up
if (--y >= 0)
ne = cal.ar_days[y][x];
else {
prevMonth();
setVars();
}
break;
case 39: // KEY right
if (++x < 7)
ne = cal.ar_days[y][x];
else {
x = 0;
K = 40;
continue;
}
break;
case 40: // KEY down
if (++y < cal.ar_days.length)
ne = cal.ar_days[y][x];
else {
nextMonth();
setVars();
}
break;
}
break;
}
if (ne) {
if (!ne.disabled)
Calendar.cellClick(ne);
else if (prev)
prevMonth();
else
nextMonth();
}
}
break;
case 13: // KEY enter
if (act)
Calendar.cellClick(cal.currentDateEl, ev);
break;
default:
return false;
}
return Calendar.stopEvent(ev);
};
/**
* (RE)Initializes the calendar to the given date and firstDayOfWeek
*/
Calendar.prototype._init = function (firstDayOfWeek, date) {
var today = new Date(),
TY = today.getFullYear(),
TM = today.getMonth(),
TD = today.getDate();
this.table.style.visibility = "hidden";
var year = date.getFullYear();
if (year < this.minYear) {
year = this.minYear;
date.setFullYear(year);
} else if (year > this.maxYear) {
year = this.maxYear;
date.setFullYear(year);
}
this.firstDayOfWeek = firstDayOfWeek;
this.date = new Date(date);
var month = date.getMonth();
var mday = date.getDate();
var no_days = date.getMonthDays();
// calendar voodoo for computing the first day that would actually be
// displayed in the calendar, even if it's from the previous month.
// WARNING: this is magic. ;-)
date.setDate(1);
var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
if (day1 < 0)
day1 += 7;
date.setDate(-day1);
date.setDate(date.getDate() + 1);
var row = this.tbody.firstChild;
var MN = Calendar._SMN[month];
var ar_days = this.ar_days = new Array();
var weekend = Calendar._TT["WEEKEND"];
var dates = this.multiple ? (this.datesCells = {}) : null;
for (var i = 0; i < 6; ++i, row = row.nextSibling) {
var cell = row.firstChild;
if (this.weekNumbers) {
cell.className = "day wn";
cell.innerHTML = date.getWeekNumber();
cell = cell.nextSibling;
}
row.className = "daysrow";
var hasdays = false, iday, dpos = ar_days[i] = [];
for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
iday = date.getDate();
var wday = date.getDay();
cell.className = "day";
cell.pos = i << 4 | j;
dpos[j] = cell;
var current_month = (date.getMonth() == month);
if (!current_month) {
if (this.showsOtherMonths) {
cell.className += " othermonth";
cell.otherMonth = true;
} else {
cell.className = "emptycell";
cell.innerHTML = " ";
cell.disabled = true;
continue;
}
} else {
cell.otherMonth = false;
hasdays = true;
}
cell.disabled = false;
cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
if (dates)
dates[date.print("%Y%m%d")] = cell;
if (this.getDateStatus) {
var status = this.getDateStatus(date, year, month, iday);
if (this.getDateToolTip) {
var toolTip = this.getDateToolTip(date, year, month, iday);
if (toolTip)
cell.title = toolTip;
}
if (status === true) {
cell.className += " disabled";
cell.disabled = true;
} else {
if (/disabled/i.test(status))
cell.disabled = true;
cell.className += " " + status;
}
}
if (!cell.disabled) {
cell.caldate = new Date(date);
cell.ttip = "_";
if (!this.multiple && current_month
&& iday == mday && this.hiliteToday) {
cell.className += " selected";
this.currentDateEl = cell;
}
if (date.getFullYear() == TY &&
date.getMonth() == TM &&
iday == TD) {
cell.className += " today";
cell.ttip += Calendar._TT["PART_TODAY"];
}
if (weekend.indexOf(wday.toString()) != -1)
cell.className += cell.otherMonth ? " oweekend" : " weekend";
}
}
if (!(hasdays || this.showsOtherMonths))
row.className = "emptyrow";
}
this.title.innerHTML = Calendar._MN[month] + ", " + year;
this.onSetTime();
this.table.style.visibility = "visible";
this._initMultipleDates();
// PROFILE
// this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};
Calendar.prototype._initMultipleDates = function() {
if (this.multiple) {
for (var i in this.multiple) {
var cell = this.datesCells[i];
var d = this.multiple[i];
if (!d)
continue;
if (cell)
cell.className += " selected";
}
}
};
Calendar.prototype._toggleMultipleDate = function(date) {
if (this.multiple) {
var ds = date.print("%Y%m%d");
var cell = this.datesCells[ds];
if (cell) {
var d = this.multiple[ds];
if (!d) {
Calendar.addClass(cell, "selected");
this.multiple[ds] = date;
} else {
Calendar.removeClass(cell, "selected");
delete this.multiple[ds];
}
}
}
};
Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
this.getDateToolTip = unaryFunction;
};
/**
* Calls _init function above for going to a certain date (but only if the
* date is different than the currently selected one).
*/
Calendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this._init(this.firstDayOfWeek, date);
}
};
/**
* Refreshes the calendar. Useful if the "disabledHandler" function is
* dynamic, meaning that the list of disabled date can change at runtime.
* Just * call this function if you think that the list of disabled dates
* should * change.
*/
Calendar.prototype.refresh = function () {
this._init(this.firstDayOfWeek, this.date);
};
/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
this._init(firstDayOfWeek, this.date);
this._displayWeekdays();
};
/**
* Allows customization of what dates are enabled. The "unaryFunction"
* parameter must be a function object that receives the date (as a JS Date
* object) and returns a boolean value. If the returned value is true then
* the passed date will be marked as disabled.
*/
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
this.getDateStatus = unaryFunction;
};
/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
this.minYear = a;
this.maxYear = z;
};
/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
if (this.onSelected) {
this.onSelected(this, this.date.print(this.dateFormat));
}
};
/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
if (this.onClose) {
this.onClose(this);
}
this.hideShowCovered();
};
/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
var el = this.element.parentNode;
el.removeChild(this.element);
Calendar._C = null;
window._dynarch_popupCalendar = null;
};
/**
* Moves the calendar element to a different section in the DOM tree (changes
* its parent).
*/
Calendar.prototype.reparent = function (new_parent) {
var el = this.element;
el.parentNode.removeChild(el);
new_parent.appendChild(el);
};
// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown. If the click was outside the open
// calendar this function closes it.
Calendar._checkCalendar = function(ev) {
var calendar = window._dynarch_popupCalendar;
if (!calendar) {
return false;
}
var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
for (; el != null && el != calendar.element; el = el.parentNode);
if (el == null) {
// calls closeHandler which should hide the calendar.
window._dynarch_popupCalendar.callCloseHandler();
return Calendar.stopEvent(ev);
}
};
/** Shows the calendar. */
Calendar.prototype.show = function () {
var rows = this.table.getElementsByTagName("tr");
for (var i = rows.length; i > 0;) {
var row = rows[--i];
Calendar.removeClass(row, "rowhilite");
var cells = row.getElementsByTagName("td");
for (var j = cells.length; j > 0;) {
var cell = cells[--j];
Calendar.removeClass(cell, "hilite");
Calendar.removeClass(cell, "active");
}
}
this.element.style.display = "block";
this.hidden = false;
if (this.isPopup) {
window._dynarch_popupCalendar = this;
Calendar.addEvent(document, "keydown", Calendar._keyEvent);
Calendar.addEvent(document, "keypress", Calendar._keyEvent);
Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
}
this.hideShowCovered();
};
/**
* Hides the calendar. Also removes any "hilite" from the class of any TD
* element.
*/
Calendar.prototype.hide = function () {
if (this.isPopup) {
Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
}
this.element.style.display = "none";
this.hidden = true;
this.hideShowCovered();
};
/**
* Shows the calendar at a given absolute position (beware that, depending on
* the calendar element style -- position property -- this might be relative
* to the parent's containing rectangle).
*/
Calendar.prototype.showAt = function (x, y) {
var s = this.element.style;
s.left = x + "px";
s.top = y + "px";
this.show();
};
/** Shows the calendar near a given element. */
Calendar.prototype.showAtElement = function (el, opts) {
var self = this;
var p = Calendar.getAbsolutePos(el);
if (!opts || typeof opts != "string") {
this.showAt(p.x, p.y + el.offsetHeight);
return true;
}
function fixPosition(box) {
if (box.x < 0)
box.x = 0;
if (box.y < 0)
box.y = 0;
var cp = document.createElement("div");
var s = cp.style;
s.position = "absolute";
s.right = s.bottom = s.width = s.height = "0px";
document.body.appendChild(cp);
var br = Calendar.getAbsolutePos(cp);
document.body.removeChild(cp);
if (Calendar.is_ie) {
br.y += document.body.scrollTop;
br.x += document.body.scrollLeft;
} else {
br.y += window.scrollY;
br.x += window.scrollX;
}
var tmp = box.x + box.width - br.x;
if (tmp > 0) box.x -= tmp;
tmp = box.y + box.height - br.y;
if (tmp > 0) box.y -= tmp;
};
this.element.style.display = "block";
Calendar.continuation_for_the_fucking_khtml_browser = function() {
var w = self.element.offsetWidth;
var h = self.element.offsetHeight;
self.element.style.display = "none";
var valign = opts.substr(0, 1);
var halign = "l";
if (opts.length > 1) {
halign = opts.substr(1, 1);
}
// vertical alignment
switch (valign) {
case "T": p.y -= h; break;
case "B": p.y += el.offsetHeight; break;
case "C": p.y += (el.offsetHeight - h) / 2; break;
case "t": p.y += el.offsetHeight - h; break;
case "b": break; // already there
}
// horizontal alignment
switch (halign) {
case "L": p.x -= w; break;
case "R": p.x += el.offsetWidth; break;
case "C": p.x += (el.offsetWidth - w) / 2; break;
case "l": p.x += el.offsetWidth - w; break;
case "r": break; // already there
}
p.width = w;
p.height = h + 40;
self.monthsCombo.style.display = "none";
//fixPosition(p);
self.showAt(p.x, p.y);
};
if (Calendar.is_khtml)
setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
else
Calendar.continuation_for_the_fucking_khtml_browser();
};
/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
this.dateFormat = str;
};
/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
this.ttDateFormat = str;
};
/**
* Tries to identify the date represented in a string. If successful it also
* calls this.setDate which moves the calendar to the given date.
*/
Calendar.prototype.parseDate = function(str, fmt) {
if (!fmt)
fmt = this.dateFormat;
this.setDate(Date.parseDate(str, fmt));
};
Calendar.prototype.hideShowCovered = function () {
if (!Calendar.is_ie && !Calendar.is_opera)
return;
function getVisib(obj){
var value = obj.style.visibility;
if (!value) {
if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
if (!Calendar.is_khtml)
value = document.defaultView.
getComputedStyle(obj, "").getPropertyValue("visibility");
else
value = '';
} else if (obj.currentStyle) { // IE
value = obj.currentStyle.visibility;
} else
value = '';
}
return value;
};
var tags = new Array("applet", "select");
var el = this.element;
var p = Calendar.getAbsolutePos(el);
var EX1 = p.x;
var EX2 = el.offsetWidth + EX1;
var EY1 = p.y;
var EY2 = el.offsetHeight + EY1;
for (var k = tags.length; k > 0; ) {
var ar = document.getElementsByTagName(tags[--k]);
var cc = null;
for (var i = ar.length; i > 0;) {
cc = ar[--i];
p = Calendar.getAbsolutePos(cc);
var CX1 = p.x;
var CX2 = cc.offsetWidth + CX1;
var CY1 = p.y;
var CY2 = cc.offsetHeight + CY1;
if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = cc.__msh_save_visibility;
} else {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = "hidden";
}
}
}
};
/** Internal function; it displays the bar with the names of the weekday. */
Calendar.prototype._displayWeekdays = function () {
var fdow = this.firstDayOfWeek;
var cell = this.firstdayname;
var weekend = Calendar._TT["WEEKEND"];
for (var i = 0; i < 7; ++i) {
cell.className = "day name";
var realday = (i + fdow) % 7;
if (i) {
cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
cell.navtype = 100;
cell.calendar = this;
cell.fdow = realday;
Calendar._add_evs(cell);
}
if (weekend.indexOf(realday.toString()) != -1) {
Calendar.addClass(cell, "weekend");
}
cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
cell = cell.nextSibling;
}
};
/** Internal function. Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
this.monthsCombo.style.display = "none";
this.yearsCombo.style.display = "none";
};
/** Internal function. Starts dragging the element. */
Calendar.prototype._dragStart = function (ev) {
if (this.dragging) {
return;
}
this.dragging = true;
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posY = ev.clientY + window.scrollY;
posX = ev.clientX + window.scrollX;
}
var st = this.element.style;
this.xOffs = posX - parseInt(st.left);
this.yOffs = posY - parseInt(st.top);
with (Calendar) {
addEvent(document, "mousemove", calDragIt);
addEvent(document, "mouseup", calDragEnd);
}
};
// BEGIN: DATE OBJECT PATCHES
/** Adds the number of days array to the Date object. */
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR = 60 * Date.MINUTE;
Date.DAY = 24 * Date.HOUR;
Date.WEEK = 7 * Date.DAY;
Date.parseDate = function(str, fmt) {
var today = new Date();
var y = 0;
var m = -1;
var d = 0;
var a = str.split(/\W+/);
var b = fmt.match(/%./g);
var i = 0, j = 0;
var hr = 0;
var min = 0;
for (i = 0; i < a.length; ++i) {
if (!a[i])
continue;
switch (b[i]) {
case "%d":
case "%e":
d = parseInt(a[i], 10);
break;
case "%m":
m = parseInt(a[i], 10) - 1;
break;
case "%Y":
case "%y":
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
break;
case "%b":
case "%B":
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
}
break;
case "%H":
case "%I":
case "%k":
case "%l":
hr = parseInt(a[i], 10);
break;
case "%P":
case "%p":
if (/pm/i.test(a[i]) && hr < 12)
hr += 12;
else if (/am/i.test(a[i]) && hr >= 12)
hr -= 12;
break;
case "%M":
min = parseInt(a[i], 10);
break;
}
}
if (isNaN(y)) y = today.getFullYear();
if (isNaN(m)) m = today.getMonth();
if (isNaN(d)) d = today.getDate();
if (isNaN(hr)) hr = today.getHours();
if (isNaN(min)) min = today.getMinutes();
if (y != 0 && m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
y = 0; m = -1; d = 0;
for (i = 0; i < a.length; ++i) {
if (a[i].search(/[a-zA-Z]+/) != -1) {
var t = -1;
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
}
if (t != -1) {
if (m != -1) {
d = m+1;
}
m = t;
}
} else if (parseInt(a[i], 10) <= 12 && m == -1) {
m = a[i]-1;
} else if (parseInt(a[i], 10) > 31 && y == 0) {
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
} else if (d == 0) {
d = a[i];
}
}
if (y == 0)
y = today.getFullYear();
if (m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
return today;
};
/** Returns the number of days in the current month */
Date.prototype.getMonthDays = function(month) {
var year = this.getFullYear();
if (typeof month == "undefined") {
month = this.getMonth();
}
if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
return 29;
} else {
return Date._MD[month];
}
};
/** Returns the number of day in the year. */
Date.prototype.getDayOfYear = function() {
var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / Date.DAY);
};
/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var DoW = d.getDay();
d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
var ms = d.valueOf(); // GMT
d.setMonth(0);
d.setDate(4); // Thu in Week 1
return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};
/** Checks date and time equality */
Date.prototype.equalsTo = function(date) {
return ((this.getFullYear() == date.getFullYear()) &&
(this.getMonth() == date.getMonth()) &&
(this.getDate() == date.getDate()) &&
(this.getHours() == date.getHours()) &&
(this.getMinutes() == date.getMinutes()));
};
/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function(date) {
var tmp = new Date(date);
this.setDate(1);
this.setFullYear(tmp.getFullYear());
this.setMonth(tmp.getMonth());
this.setDate(tmp.getDate());
};
/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
var m = this.getMonth();
var d = this.getDate();
var y = this.getFullYear();
var wn = this.getWeekNumber();
var w = this.getDay();
var s = {};
var hr = this.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = this.getDayOfYear();
if (ir == 0)
ir = 12;
var min = this.getMinutes();
var sec = this.getSeconds();
s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
s["%A"] = Calendar._DN[w]; // full weekday name
s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = Calendar._MN[m]; // full month name
// FIXME: %c : preferred date and time representation for the current locale
s["%C"] = 1 + Math.floor(y / 100); // the century number
s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
s["%e"] = d; // the day of the month (range 1 to 31)
// FIXME: %D : american date style: %m/%d/%y
// FIXME: %E, %F, %G, %g, %h (man strftime)
s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
s["%k"] = hr; // hour, range 0 to 23 (24h format)
s["%l"] = ir; // hour, range 1 to 12 (12h format)
s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
s["%n"] = "\n"; // a newline character
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
// FIXME: %r : the time in am/pm notation %I:%M:%S %p
// FIXME: %R : the time in 24-hour notation %H:%M
s["%s"] = Math.floor(this.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
s["%t"] = "\t"; // a tab character
// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN)
// FIXME: %x : preferred date representation for the current locale without the time
// FIXME: %X : preferred time representation for the current locale without the date
s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
s["%Y"] = y; // year with the century
s["%%"] = "%"; // a literal '%' character
var re = /%./g;
if (!Calendar.is_ie5 && !Calendar.is_khtml)
return str.replace(re, function (par) { return s[par] || par; });
var a = str.match(re);
for (var i = 0; i < a.length; i++) {
var tmp = s[a[i]];
if (tmp) {
re = new RegExp(a[i], 'g');
str = str.replace(re, tmp);
}
}
return str;
};
Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
var d = new Date(this);
d.__msh_oldSetFullYear(y);
if (d.getMonth() != this.getMonth())
this.setDate(28);
this.__msh_oldSetFullYear(y);
};
// END: DATE OBJECT PATCHES
// global object that remembers the calendar
window._dynarch_popupCalendar = null;
//var calendar = null;
var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
if (oldLink) oldLink.style.fontWeight = 'normal';
oldLink = link;
link.style.fontWeight = 'bold';
return false;
}
// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
cal.sel.value = date; // just update the date in the input field.
if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
// if we add this call we close the calendar on single-click.
// just to exemplify both cases, we are using this only for the 1st
// and the 3rd field, while 2nd and 4th will still require double-click.
cal.callCloseHandler();
}
// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button. It just hides the calendar without
// destroying it.
function closeHandler(cal) {
cal.hide(); // hide the calendar
// cal.destroy();
_dynarch_popupCalendar = null;
}
// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths, selbtn) {
var el = typeof(id) == "object" ? id : document.getElementById(id);
if (selbtn == '')
{
selbtn = 'selbtn';
}
var btn_el = typeof(selbtn) == "object" ? selbtn : document.getElementById(selbtn);;
if (_dynarch_popupCalendar != null) {
// we already have some calendar created
_dynarch_popupCalendar.hide(); // so we hide it first.
} else {
// first-time call, create the calendar.
var cal = new Calendar(1, null, selected, closeHandler);
// uncomment the following line to hide the week numbers
// cal.weekNumbers = false;
if (typeof showsTime == "string") {
cal.showsTime = true;
cal.time24 = (showsTime == "24");
}
if (showsOtherMonths) {
cal.showsOtherMonths = true;
}
_dynarch_popupCalendar = cal; // remember it in the global var
cal.setRange(1900, 2070); // min/max year allowed.
cal.create();
//alert(cal.table.parentNode.parentNode.innerHTML);
}
_dynarch_popupCalendar.setDateFormat(format); // set the specified date format
_dynarch_popupCalendar.parseDate(el.value); // try to parse the text in field
_dynarch_popupCalendar.sel = el; // inform it what input field we use
//_dynarch_popupCalendar.btn = btn_el; //
// the reference element that we pass to showAtElement is the button that
// triggers the calendar. In this example we align the calendar bottom-right
// to the button.
//_dynarch_popupCalendar.showAtElement(el.nextSibling, "Br"); // show the calendar
_dynarch_popupCalendar.showAtElement(btn_el, "Br");
return false;
}
var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;
// If this handler returns true then the "date" given as
// parameter will be disabled. In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here. However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
var today = new Date();
return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}
function flatSelected(cal, date) {
var el = document.getElementById("preview");
el.innerHTML = date;
}
function showFlatCalendar() {
var parent = document.getElementById("display");
// construct a calendar giving only the "selected" handler.
var cal = new Calendar(0, null, flatSelected);
// hide week numbers
cal.weekNumbers = false;
// We want some dates to be disabled; see function isDisabled above
cal.setDisabledHandler(isDisabled);
cal.setDateFormat("%A, %B %e");
// this call must be the last as it might use data initialized above; if
// we specify a parent, as opposite to the "showCalendar" function above,
// then we create a flat calendar -- not popup. Hidden, though, but...
cal.create(parent);
// ... we can show it here.
cal.show();
}
// full day names
Calendar._DN = new Array('"' + Sunday + '"', '"' + Monday + '"', '"' + Tuesday + '"', '"' + Wednesday + '"', '"' + Thursday + '"', '"' + Friday + '"', '"' + Saturday + '"', '"' + Sunday + '"');
// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary. We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
// Calendar._SDN_len = N; // short day name length
// Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.
// short day names
Calendar._SDN = new Array('"' + Sun + '"', '"' + Mon + '"', '"' + Tue + '"', '"' + Wed + '"', '"' + Thu + '"', '"' + Fri + '"', '"' + Sat + '"', '"' + Sun + '"');
// full month names
Calendar._MN = new Array('"' + January + '"', '"' + February + '"', '"' + March + '"', '"' + April + '"', '"' + May + '"', '"' + June + '"', '"' + July + '"', '"' + Aguest + '"', '"' + September + '"', '"' + October + '"', '"' + November + '"', '"' + December + '"');
// short month names
Calendar._SMN = new Array('"' + Jan + '"', '"' + Feb + '"', '"' + Mar + '"', '"' + Apr + '"', '"' + May + '"', '"' + Jun + '"', '"' + Jul + '"', '"' + Agu + '"', '"' + Sep + '"', '"' + Oct + '"', '"' + Nov + '"', '"' + Dec + '"');
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = calendar_help;
Calendar._TT["ABOUT"] = calendar_about1 + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + calendar_about2;
Calendar._TT["ABOUT_TIME"] = calendar_about_time;
Calendar._TT["PREV_YEAR"] = prev_year;
Calendar._TT["PREV_MONTH"] = prev_month;
Calendar._TT["GO_TODAY"] = go_today;
Calendar._TT["NEXT_MONTH"] = next_month;
Calendar._TT["NEXT_YEAR"] = next_year;
Calendar._TT["SEL_DATE"] = sel_date;
Calendar._TT["DRAG_TO_MOVE"] = drag_to_move;
Calendar._TT["PART_TODAY"] = part_today;
// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = day_first + "%s";
// This may be locale-dependent. It specifies the week-end days, as an array
// of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = calendar_close;
Calendar._TT["TODAY"] = calendar_today;
Calendar._TT["TIME_PART"] = time_part;
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %b %e" + calendar_day;
Calendar._TT["WK"] = calendar_wk;
Calendar._TT["TIME"] = calendar_time + ":"; | JavaScript |
/* $Id : myship.js 4865 2007-01-31 14:04:10Z Hackfan $ */
/* *
* 检查收货地址信息表单中填写的内容
*/
function checkForm(frm)
{
var msg = new Array();
var err = false;
if (frm.elements['country'].value == 0)
{
msg.push(country_not_null);
err = true;
}
if (frm.elements['province'].value == 0 && frm.elements['province'].length > 1)
{
err = true;
msg.push(province_not_null);
}
if (frm.elements['city'].value == 0 && frm.elements['city'].length > 1)
{
err = true;
msg.push(city_not_null);
}
if (frm.elements['district'].length > 1)
{
if (frm.elements['district'].value == 0)
{
err = true;
msg.push(district_not_null);
}
}
if (err)
{
message = msg.join("\n");
alert(message);
}
return ! err;
}
| JavaScript |
/* $Id: showdiv.js 15469 2008-12-19 06:34:44Z testyang $ */
//创建显示层
var swtemp = 0;
var timer = null;
//显示层
function showdiv(obj)
{
var inputid = obj.id;
if (swtemp == 1)
{
hidediv("messagediv");
}
if (!getobj("messagediv"))
{
//若尚未创建就创建层
crertdiv("" , "div" , "messagediv" , "messagediv");//创建层"messagediv"
crertdiv("messagediv" , "li" , "messageli" , "messageli");//创建"请刷新"li
getobj("messageli").innerHTML = show_div_text;
crertdiv("messagediv" , "a" , "messagea" , "");//创建"关闭"a
getobj("messagea").innerHTML = show_div_exit;
getobj("messagea").onclick = function(){hidediv("messagediv");};
}
var newdiv = getobj("messagediv");
newdiv.style.left = (getAbsoluteLeft(obj) - 50) + "px";
newdiv.style.top = (getAbsoluteTop(obj) - 65) + "px";
newdiv.style.display = "block";
timer = setTimeout(function(){hidediv("messagediv");} , 3000);
swtemp = 1;
}
//创建层
function crertdiv(parent , element , id , css)
{
var newObj = document.createElement(element);
if(id && id != "")
{
newObj.id = id;
}
if(css && css != "")
{
newObj.className = css;
}
if(parent && parent!="")
{
var theObj = getobj(parent);
var parent = theObj.parentNode;
if(parent.lastChild == theObj)
{
theObj.appendChild(newObj);
}
else
{
theObj.insertBefore(newObj, theObj.nextSibling);
}
}
else
{
document.body.appendChild(newObj);
}
}
//隐藏层
function hidediv(objid)
{
getobj(objid).style.display = "none";
swtemp = 0;
clearTimeout(timer);
}
//获取对象
function getobj(obj)
{
return document.getElementById(obj);
}
function getAbsoluteHeight(obj)
{
return obj.offsetHeight;
}
function getAbsoluteWidth(obj)
{
return obj.offsetWidth;
}
function getAbsoluteLeft(obj)
{
var s_el = 0;
var el = obj;
while(el)
{
s_el = s_el + el.offsetLeft;
el = el.offsetParent;
}
return s_el;
}
function getAbsoluteTop(obj)
{
var s_el = 0;
var el = obj;
while(el)
{
s_el = s_el + el.offsetTop;
el = el.offsetParent;
}
return s_el;
} | JavaScript |
/* $Id : region.js 4865 2007-01-31 14:04:10Z paulgao $ */
var region = new Object();
region.isAdmin = false;
region.loadRegions = function(parent, type, target)
{
Ajax.call(region.getFileName(), 'type=' + type + '&target=' + target + "&parent=" + parent , region.response, "GET", "JSON");
}
/* *
* 载入指定的国家下所有的省份
*
* @country integer 国家的编号
* @selName string 列表框的名称
*/
region.loadProvinces = function(country, selName)
{
var objName = (typeof selName == "undefined") ? "selProvinces" : selName;
region.loadRegions(country, 1, objName);
}
/* *
* 载入指定的省份下所有的城市
*
* @province integer 省份的编号
* @selName string 列表框的名称
*/
region.loadCities = function(province, selName)
{
var objName = (typeof selName == "undefined") ? "selCities" : selName;
region.loadRegions(province, 2, objName);
}
/* *
* 载入指定的城市下的区 / 县
*
* @city integer 城市的编号
* @selName string 列表框的名称
*/
region.loadDistricts = function(city, selName)
{
var objName = (typeof selName == "undefined") ? "selDistricts" : selName;
region.loadRegions(city, 3, objName);
}
/* *
* 处理下拉列表改变的函数
*
* @obj object 下拉列表
* @type integer 类型
* @selName string 目标列表框的名称
*/
region.changed = function(obj, type, selName)
{
var parent = obj.options[obj.selectedIndex].value;
region.loadRegions(parent, type, selName);
}
region.response = function(result, text_result)
{
var sel = document.getElementById(result.target);
sel.length = 1;
sel.selectedIndex = 0;
sel.style.display = (result.regions.length == 0 && ! region.isAdmin && result.type + 0 == 3) ? "none" : '';
if (document.all)
{
sel.fireEvent("onchange");
}
else
{
var evt = document.createEvent("HTMLEvents");
evt.initEvent('change', true, true);
sel.dispatchEvent(evt);
}
if (result.regions)
{
for (i = 0; i < result.regions.length; i ++ )
{
var opt = document.createElement("OPTION");
opt.value = result.regions[i].region_id;
opt.text = result.regions[i].region_name;
sel.options.add(opt);
}
}
}
region.getFileName = function()
{
if (region.isAdmin)
{
return "../region.php";
}
else
{
return "region.php";
}
}
| JavaScript |
/* $Id : utils.js 5052 2007-02-03 10:30:13Z weberliu $ */
var Browser = new Object();
Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument != 'undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != - 1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != - 1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != - 1);
var Utils = new Object();
Utils.htmlEncode = function(text)
{
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
Utils.trim = function( text )
{
if (typeof(text) == "string")
{
return text.replace(/^\s*|\s*$/g, "");
}
else
{
return text;
}
}
Utils.isEmpty = function( val )
{
switch (typeof(val))
{
case 'string':
return Utils.trim(val).length == 0 ? true : false;
break;
case 'number':
return val == 0;
break;
case 'object':
return val == null;
break;
case 'array':
return val.length == 0;
break;
default:
return true;
}
}
Utils.isNumber = function(val)
{
var reg = /^[\d|\.|,]+$/;
return reg.test(val);
}
Utils.isInt = function(val)
{
if (val == "")
{
return false;
}
var reg = /\D+/;
return !reg.test(val);
}
Utils.isEmail = function( email )
{
var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;
return reg1.test( email );
}
Utils.isTel = function ( tel )
{
var reg = /^[\d|\-|\s|\_]+$/; //只允许使用数字-空格等
return reg.test( tel );
}
Utils.fixEvent = function(e)
{
var evt = (typeof e == "undefined") ? window.event : e;
return evt;
}
Utils.srcElement = function(e)
{
if (typeof e == "undefined") e = window.event;
var src = document.all ? e.srcElement : e.target;
return src;
}
Utils.isTime = function(val)
{
var reg = /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/;
return reg.test(val);
}
Utils.x = function(e)
{ //当前鼠标X坐标
return Browser.isIE?event.x + document.documentElement.scrollLeft - 2:e.pageX;
}
Utils.y = function(e)
{ //当前鼠标Y坐标
return Browser.isIE?event.y + document.documentElement.scrollTop - 2:e.pageY;
}
Utils.request = function(url, item)
{
var sValue=url.match(new RegExp("[\?\&]"+item+"=([^\&]*)(\&?)","i"));
return sValue?sValue[1]:sValue;
}
Utils.$ = function(name)
{
return document.getElementById(name);
}
function rowindex(tr)
{
if (Browser.isIE)
{
return tr.rowIndex;
}
else
{
table = tr.parentNode.parentNode;
for (i = 0; i < table.rows.length; i ++ )
{
if (table.rows[i] == tr)
{
return i;
}
}
}
}
document.getCookie = function(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return decodeURIComponent(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
document.setCookie = function(sName, sValue, sExpires)
{
var sCookie = sName + "=" + encodeURIComponent(sValue);
if (sExpires != null)
{
sCookie += "; expires=" + sExpires;
}
document.cookie = sCookie;
}
document.removeCookie = function(sName,sValue)
{
document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}
function getPosition(o)
{
var t = o.offsetTop;
var l = o.offsetLeft;
while(o = o.offsetParent)
{
t += o.offsetTop;
l += o.offsetLeft;
}
var pos = {top:t,left:l};
return pos;
}
function cleanWhitespace(element)
{
var element = element;
for (var i = 0; i < element.childNodes.length; i++) {
var node = element.childNodes[i];
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
}
} | JavaScript |
/* $Id : lefttime.js 4865 2007-01-31 14:04:10Z paulgao $ */
/* *
* 给定一个剩余时间(s)动态显示一个剩余时间.
* 当大于一天时。只显示还剩几天。小于一天时显示剩余多少小时,多少分钟,多少秒。秒数每秒减1 *
*/
// 初始化变量
var auctionDate = 0;
var _GMTEndTime = 0;
var showTime = "leftTime";
var _day = 'day';
var _hour = 'hour';
var _minute = 'minute';
var _second = 'second';
var _end = 'end';
var cur_date = new Date();
var startTime = cur_date.getTime();
var Temp;
var timerID = null;
var timerRunning = false;
function showtime()
{
now = new Date();
var ts = parseInt((startTime - now.getTime()) / 1000) + auctionDate;
var dateLeft = 0;
var hourLeft = 0;
var minuteLeft = 0;
var secondLeft = 0;
var hourZero = '';
var minuteZero = '';
var secondZero = '';
if (ts < 0)
{
ts = 0;
CurHour = 0;
CurMinute = 0;
CurSecond = 0;
}
else
{
dateLeft = parseInt(ts / 86400);
ts = ts - dateLeft * 86400;
hourLeft = parseInt(ts / 3600);
ts = ts - hourLeft * 3600;
minuteLeft = parseInt(ts / 60);
secondLeft = ts - minuteLeft * 60;
}
if (hourLeft < 10)
{
hourZero = '0';
}
if (minuteLeft < 10)
{
minuteZero = '0';
}
if (secondLeft < 10)
{
secondZero = '0';
}
if (dateLeft > 0)
{
Temp = dateLeft + _day + hourZero + hourLeft + _hour + minuteZero + minuteLeft + _minute + secondZero + secondLeft + _second;
}
else
{
if (hourLeft > 0)
{
Temp = hourLeft + _hour + minuteZero + minuteLeft + _minute + secondZero + secondLeft + _second;
}
else
{
if (minuteLeft > 0)
{
Temp = minuteLeft + _minute + secondZero + secondLeft + _second;
}
else
{
if (secondLeft > 0)
{
Temp = secondLeft + _second;
}
else
{
Temp = '';
}
}
}
}
if (auctionDate <= 0 || Temp == '')
{
Temp = "<strong>" + _end + "</strong>";
stopclock();
}
if (document.getElementById(showTime))
{
document.getElementById(showTime).innerHTML = Temp;
}
timerID = setTimeout("showtime()", 1000);
timerRunning = true;
}
var timerID = null;
var timerRunning = false;
function stopclock()
{
if (timerRunning)
{
clearTimeout(timerID);
}
timerRunning = false;
}
function macauclock()
{
stopclock();
showtime();
}
function onload_leftTime(now_time)
{
/* 第一次运行时初始化语言项目 */
try
{
_GMTEndTime = gmt_end_time;
// 剩余时间
_day = day;
_hour = hour;
_minute = minute;
_second = second;
_end = end;
}
catch (e)
{
}
if (_GMTEndTime > 0)
{
if (now_time == undefined)
{
var tmp_val = parseInt(_GMTEndTime) - parseInt(cur_date.getTime() / 1000 + cur_date.getTimezoneOffset() * 60);
}
else
{
var tmp_val = parseInt(_GMTEndTime) - now_time;
}
if (tmp_val > 0)
{
auctionDate = tmp_val;
}
}
macauclock();
try
{
initprovcity();
}
catch (e)
{
}
}
| JavaScript |
/* $Id: index.js 15469 2008-12-19 06:34:44Z testyang $ */
var best_str = new Object();
var new_str = new Object();
var hot_str = new Object();
function init_rec_data()
{
best_str[0] = document.getElementById("show_best_area") == null ? '' : document.getElementById("show_best_area").innerHTML;
new_str[0] = document.getElementById("show_new_area") == null ? '' : document.getElementById("show_new_area").innerHTML;
hot_str[0] = document.getElementById("show_hot_area") == null ? '' : document.getElementById("show_hot_area").innerHTML;
}
function get_cat_recommend(rec_type, cat_id)
{
if (rec_type == 1)
{
if (typeof(best_str[cat_id]) == "string")
{
document.getElementById("show_best_area").innerHTML = best_str[cat_id];
return;
}
}
else if (rec_type == 2)
{
if (typeof(new_str[cat_id]) == "string")
{
document.getElementById("show_new_area").innerHTML = new_str[cat_id];
return;
}
}
else
{
if (typeof(hot_str[cat_id]) == "string")
{
document.getElementById("show_hot_area").innerHTML = hot_str[cat_id];
return;
}
}
Ajax.call('index.php?act=cat_rec', 'rec_type=' + rec_type + '&cid=' + cat_id, cat_rec_response, "POST", "TEXT");
}
function cat_rec_response(result)
{
var res = result.parseJSON();
if (res.type == 1)
{
var ele = document.getElementById("show_best_area");
best_str[res.cat_id] = res.content;
}
else if (res.type == 2)
{
var ele = document.getElementById("show_new_area");
new_str[res.cat_id] = res.content;
}
else
{
var ele = document.getElementById("show_hot_area");
hot_str[res.cat_id] = res.content;
}
ele.innerHTML = res.content;
}
if (document.all)
{
window.attachEvent("onload", init_rec_data);
}
else
{
window.addEventListener("load", init_rec_data, false);
}
function change_tab_style(item, elem, obj)
{
elem = elem.toUpperCase();
var itemObj = document.getElementById(item);
var elems = itemObj.getElementsByTagName(elem);
var _o = obj.parentNode;
while(_o.nodeName != elem)
{
_o = _o.parentNode;
}
for (var i=0,l=elems.length; i<l; i++)
{
elems[i].className = 'h2bg';
}
_o.className = '';
} | JavaScript |
/* $Id: global.js 15469 2008-12-19 06:34:44Z testyang $ */
Object.extend = function(destination, source)
{
for (property in source) {
destination[property] = source[property];
}
return destination;
}
Object.prototype.extend = function(object)
{
return Object.extend.apply(this, [this, object]);
}
//封装getEelementById函数
function $()
{
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
//创建元素
function $ce(tagName)
{
return document.createElement(tagName);
}
//定义类类型
var Class = {
create : function()
{
return function()
{
this.initialize.apply(this, arguments);
}
}
}
//对象绑定
Function.prototype.bind = function(object) {
var __method = this;
return function()
{
__method.apply(object, arguments);
}
}
if (!window.Event) {
var Event = new Object();
}
Object.extend(Event, {
element: function(event) {
return event.target || event.srcElement;
},
pointerX: function(event) {
return event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft));
},
pointerY: function(event) {
return event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop));
},
stop: function(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
} else {
event.returnValue = false;
}
},
position: function(element)
{
var t = element.offsetTop;
var l = element.offsetLeft;
while(element = element.offsetParent)
{
t += element.offsetTop;
l += element.offsetLeft;
}
var pos={top:t,left:l};
return pos;
} ,
observers: false,
_observeAndCache: function(element, name, observer, useCapture) {
if (!this.observers) this.observers = [];
if (element.addEventListener) {
this.observers.push([element, name, observer, useCapture]);
element.addEventListener(name, observer, useCapture);
} else if (element.attachEvent) {
this.observers.push([element, name, observer, useCapture]);
element.attachEvent('on' + name, observer);
}
},
observe: function(element, name, observer, useCapture) {
var element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
((navigator.appVersion.indexOf('AppleWebKit') > 0)
|| element.attachEvent))
name = 'keydown';
this._observeAndCache(element, name, observer, useCapture);
},
stopObserving: function(element, name, observer, useCapture) {
var element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
((navigator.appVersion.indexOf('AppleWebKit') > 0)
|| element.detachEvent))
name = 'keydown';
if (element.removeEventListener) {
element.removeEventListener(name, observer, useCapture);
} else if (element.detachEvent) {
element.detachEvent('on' + name, observer);
}
}
});
| JavaScript |
/* $Id : shopping_flow.js 4865 2007-01-31 14:04:10Z paulgao $ */
var selectedShipping = null;
var selectedPayment = null;
var selectedPack = null;
var selectedCard = null;
var selectedSurplus = '';
var selectedBonus = 0;
var selectedIntegral = 0;
var selectedOOS = null;
var alertedSurplus = false;
var groupBuyShipping = null;
var groupBuyPayment = null;
/* *
* 改变配送方式
*/
function selectShipping(obj)
{
if (selectedShipping == obj)
{
return;
}
else
{
selectedShipping = obj;
}
var supportCod = obj.attributes['supportCod'].value + 0;
var theForm = obj.form;
for (i = 0; i < theForm.elements.length; i ++ )
{
if (theForm.elements[i].name == 'payment' && theForm.elements[i].attributes['isCod'].value == '1')
{
if (supportCod == 0)
{
theForm.elements[i].checked = false;
theForm.elements[i].disabled = true;
}
else
{
theForm.elements[i].disabled = false;
}
}
}
if (obj.attributes['insure'].value + 0 == 0)
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = true;
}
else
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = false;
}
var now = new Date();
Ajax.call('flow.php?step=select_shipping', 'shipping=' + obj.value, orderShippingSelectedResponse, 'GET', 'JSON');
}
/**
*
*/
function orderShippingSelectedResponse(result)
{
if (result.need_insure)
{
try
{
document.getElementById('ECS_NEEDINSURE').checked = true;
}
catch (ex)
{
alert(ex.message);
}
}
try
{
if (document.getElementById('ECS_CODFEE') != undefined)
{
document.getElementById('ECS_CODFEE').innerHTML = result.cod_fee;
}
}
catch (ex)
{
alert(ex.message);
}
orderSelectedResponse(result);
}
/* *
* 改变支付方式
*/
function selectPayment(obj)
{
if (selectedPayment == obj)
{
return;
}
else
{
selectedPayment = obj;
}
Ajax.call('flow.php?step=select_payment', 'payment=' + obj.value, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 团购购物流程 --> 改变配送方式
*/
function handleGroupBuyShipping(obj)
{
if (groupBuyShipping == obj)
{
return;
}
else
{
groupBuyShipping = obj;
}
var supportCod = obj.attributes['supportCod'].value + 0;
var theForm = obj.form;
for (i = 0; i < theForm.elements.length; i ++ )
{
if (theForm.elements[i].name == 'payment' && theForm.elements[i].attributes['isCod'].value == '1')
{
if (supportCod == 0)
{
theForm.elements[i].checked = false;
theForm.elements[i].disabled = true;
}
else
{
theForm.elements[i].disabled = false;
}
}
}
if (obj.attributes['insure'].value + 0 == 0)
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = true;
}
else
{
document.getElementById('ECS_NEEDINSURE').checked = false;
document.getElementById('ECS_NEEDINSURE').disabled = false;
}
Ajax.call('group_buy.php?act=select_shipping', 'shipping=' + obj.value, orderSelectedResponse, 'GET');
}
/* *
* 团购购物流程 --> 改变支付方式
*/
function handleGroupBuyPayment(obj)
{
if (groupBuyPayment == obj)
{
return;
}
else
{
groupBuyPayment = obj;
}
Ajax.call('group_buy.php?act=select_payment', 'payment=' + obj.value, orderSelectedResponse, 'GET');
}
/* *
* 改变商品包装
*/
function selectPack(obj)
{
if (selectedPack == obj)
{
return;
}
else
{
selectedPack = obj;
}
Ajax.call('flow.php?step=select_pack', 'pack=' + obj.value, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 改变祝福贺卡
*/
function selectCard(obj)
{
if (selectedCard == obj)
{
return;
}
else
{
selectedCard = obj;
}
Ajax.call('flow.php?step=select_card', 'card=' + obj.value, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 选定了配送保价
*/
function selectInsure(needInsure)
{
needInsure = needInsure ? 1 : 0;
Ajax.call('flow.php?step=select_insure', 'insure=' + needInsure, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 团购购物流程 --> 选定了配送保价
*/
function handleGroupBuyInsure(needInsure)
{
needInsure = needInsure ? 1 : 0;
Ajax.call('group_buy.php?act=select_insure', 'insure=' + needInsure, orderSelectedResponse, 'GET', 'JSON');
}
/* *
* 回调函数
*/
function orderSelectedResponse(result)
{
if (result.error)
{
alert(result.error);
location.href = './';
}
try
{
var layer = document.getElementById("ECS_ORDERTOTAL");
layer.innerHTML = (typeof result == "object") ? result.content : result;
if (result.payment != undefined)
{
var surplusObj = document.forms['theForm'].elements['surplus'];
if (surplusObj != undefined)
{
surplusObj.disabled = result.pay_code == 'balance';
}
}
}
catch (ex) { }
}
/* *
* 改变余额
*/
function changeSurplus(val)
{
if (selectedSurplus == val)
{
return;
}
else
{
selectedSurplus = val;
}
Ajax.call('flow.php?step=change_surplus', 'surplus=' + val, changeSurplusResponse, 'GET', 'JSON');
}
/* *
* 改变余额回调函数
*/
function changeSurplusResponse(obj)
{
if (obj.error)
{
try
{
document.getElementById("ECS_SURPLUS_NOTICE").innerHTML = obj.error;
document.getElementById('ECS_SURPLUS').value = '0';
document.getElementById('ECS_SURPLUS').focus();
}
catch (ex) { }
}
else
{
try
{
document.getElementById("ECS_SURPLUS_NOTICE").innerHTML = '';
}
catch (ex) { }
orderSelectedResponse(obj.content);
}
}
/* *
* 改变积分
*/
function changeIntegral(val)
{
if (selectedIntegral == val)
{
return;
}
else
{
selectedIntegral = val;
}
Ajax.call('flow.php?step=change_integral', 'points=' + val, changeIntegralResponse, 'GET', 'JSON');
}
/* *
* 改变积分回调函数
*/
function changeIntegralResponse(obj)
{
if (obj.error)
{
try
{
document.getElementById('ECS_INTEGRAL_NOTICE').innerHTML = obj.error;
document.getElementById('ECS_INTEGRAL').value = '0';
document.getElementById('ECS_INTEGRAL').focus();
}
catch (ex) { }
}
else
{
try
{
document.getElementById('ECS_INTEGRAL_NOTICE').innerHTML = '';
}
catch (ex) { }
orderSelectedResponse(obj.content);
}
}
/* *
* 改变红包
*/
function changeBonus(val)
{
if (selectedBonus == val)
{
return;
}
else
{
selectedBonus = val;
}
Ajax.call('flow.php?step=change_bonus', 'bonus=' + val, changeBonusResponse, 'GET', 'JSON');
}
/* *
* 改变红包的回调函数
*/
function changeBonusResponse(obj)
{
if (obj.error)
{
alert(obj.error);
try
{
document.getElementById('ECS_BONUS').value = '0';
}
catch (ex) { }
}
else
{
orderSelectedResponse(obj.content);
}
}
/**
* 验证红包序列号
* @param string bonusSn 红包序列号
*/
function validateBonus(bonusSn)
{
Ajax.call('flow.php?step=validate_bonus', 'bonus_sn=' + bonusSn, validateBonusResponse, 'GET', 'JSON');
}
function validateBonusResponse(obj)
{
if (obj.error)
{
alert(obj.error);
try
{
document.getElementById('ECS_BONUSN').value = '0';
}
catch (ex) { }
}
else
{
orderSelectedResponse(obj.content);
}
}
/* *
* 改变发票的方式
*/
function changeNeedInv()
{
var obj = document.getElementById('ECS_NEEDINV');
var objType = document.getElementById('ECS_INVTYPE');
var objPayee = document.getElementById('ECS_INVPAYEE');
var objContent = document.getElementById('ECS_INVCONTENT');
var needInv = obj.checked ? 1 : 0;
var invType = obj.checked ? (objType != undefined ? objType.value : '') : '';
var invPayee = obj.checked ? objPayee.value : '';
var invContent = obj.checked ? objContent.value : '';
objType.disabled = objPayee.disabled = objContent.disabled = ! obj.checked;
if(objType != null)
{
objType.disabled = ! obj.checked;
}
Ajax.call('flow.php?step=change_needinv', 'need_inv=' + needInv + '&inv_type=' + encodeURIComponent(invType) + '&inv_payee=' + encodeURIComponent(invPayee) + '&inv_content=' + encodeURIComponent(invContent), orderSelectedResponse, 'GET');
}
/* *
* 改变发票的方式
*/
function groupBuyChangeNeedInv()
{
var obj = document.getElementById('ECS_NEEDINV');
var objPayee = document.getElementById('ECS_INVPAYEE');
var objContent = document.getElementById('ECS_INVCONTENT');
var needInv = obj.checked ? 1 : 0;
var invPayee = obj.checked ? objPayee.value : '';
var invContent = obj.checked ? objContent.value : '';
objPayee.disabled = objContent.disabled = ! obj.checked;
Ajax.call('group_buy.php?act=change_needinv', 'need_idv=' + needInv + '&payee=' + invPayee + '&content=' + invContent, null, 'GET');
}
/* *
* 改变缺货处理时的处理方式
*/
function changeOOS(obj)
{
if (selectedOOS == obj)
{
return;
}
else
{
selectedOOS = obj;
}
Ajax.call('flow.php?step=change_oos', 'oos=' + obj.value, null, 'GET');
}
/* *
* 检查提交的订单表单
*/
function checkOrderForm(frm)
{
var paymentSelected = false;
var shippingSelected = false;
// 检查是否选择了支付配送方式
for (i = 0; i < frm.elements.length; i ++ )
{
if (frm.elements[i].name == 'shipping' && frm.elements[i].checked)
{
shippingSelected = true;
}
if (frm.elements[i].name == 'payment' && frm.elements[i].checked)
{
paymentSelected = true;
}
}
if ( ! shippingSelected)
{
alert(flow_no_shipping);
return false;
}
if ( ! paymentSelected)
{
alert(flow_no_payment);
return false;
}
// 检查用户输入的余额
if (document.getElementById("ECS_SURPLUS"))
{
var surplus = document.getElementById("ECS_SURPLUS").value;
var error = Utils.trim(Ajax.call('flow.php?step=check_surplus', 'surplus=' + surplus, null, 'GET', 'TEXT', false));
if (error)
{
try
{
document.getElementById("ECS_SURPLUS_NOTICE").innerHTML = error;
}
catch (ex)
{
}
return false;
}
}
// 检查用户输入的积分
if (document.getElementById("ECS_INTEGRAL"))
{
var integral = document.getElementById("ECS_INTEGRAL").value;
var error = Utils.trim(Ajax.call('flow.php?step=check_integral', 'integral=' + integral, null, 'GET', 'TEXT', false));
if (error)
{
return false;
try
{
document.getElementById("ECS_INTEGRAL_NOTICE").innerHTML = error;
}
catch (ex)
{
}
}
}
frm.action = frm.action + '?step=done';
return true;
}
/* *
* 检查收货地址信息表单中填写的内容
*/
function checkConsignee(frm)
{
var msg = new Array();
var err = false;
if (frm.elements['country'] && frm.elements['country'].value == 0)
{
msg.push(country_not_null);
err = true;
}
if (frm.elements['province'] && frm.elements['province'].value == 0 && frm.elements['province'].length > 1)
{
err = true;
msg.push(province_not_null);
}
if (frm.elements['city'] && frm.elements['city'].value == 0 && frm.elements['city'].length > 1)
{
err = true;
msg.push(city_not_null);
}
if (frm.elements['district'] && frm.elements['district'].length > 1)
{
if (frm.elements['district'].value == 0)
{
err = true;
msg.push(district_not_null);
}
}
if (Utils.isEmpty(frm.elements['consignee'].value))
{
err = true;
msg.push(consignee_not_null);
}
if ( ! Utils.isEmail(frm.elements['email'].value))
{
err = true;
msg.push(invalid_email);
}
if (frm.elements['address'] && Utils.isEmpty(frm.elements['address'].value))
{
err = true;
msg.push(address_not_null);
}
if (frm.elements['zipcode'] && frm.elements['zipcode'].value.length > 0 && (!Utils.isNumber(frm.elements['zipcode'].value)))
{
err = true;
msg.push(zip_not_num);
}
if (Utils.isEmpty(frm.elements['tel'].value))
{
err = true;
msg.push(tele_not_null);
}
else
{
if (!Utils.isTel(frm.elements['tel'].value))
{
err = true;
msg.push(tele_invaild);
}
}
if (frm.elements['mobile'] && frm.elements['mobile'].value.length > 0 && (!Utils.isTel(frm.elements['mobile'].value)))
{
err = true;
msg.push(mobile_invaild);
}
if (err)
{
message = msg.join("\n");
alert(message);
}
return ! err;
}
| JavaScript |
/* $Id: compare.js 15469 2008-12-19 06:34:44Z testyang $ */
var Compare = new Object();
Compare = {
add : function(goodsId, goodsName, type)
{
var count = 0;
for (var k in this.data)
{
if (typeof(this.data[k]) == "function")
continue;
if (this.data[k].t != type) {
alert(goods_type_different.replace("%s", goodsName));
return;
}
count++;
}
if (this.data[goodsId])
{
alert(exist.replace("%s",goodsName));
return;
}
else
{
this.data[goodsId] = {n:goodsName,t:type};
}
this.save();
this.init();
},
relocation : function()
{
if (this.compareBox.style.display != "") return;
var diffY = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
var percent = .2*(diffY - this.lastScrollY);
if(percent > 0)
percent = Math.ceil(percent);
else
percent = Math.floor(percent);
this.compareBox.style.top = parseInt(this.compareBox.style.top)+ percent + "px";
this.lastScrollY = this.lastScrollY + percent;
},
init : function(){
this.data = new Object();
var cookieValue = document.getCookie("compareItems");
if (cookieValue != null) {
this.data = cookieValue.parseJSON();
}
if (!this.compareBox)
{
this.compareBox = document.createElement("DIV");
var submitBtn = document.createElement("INPUT");
this.compareList = document.createElement("UL");
this.compareBox.id = "compareBox";
this.compareBox.style.display = "none";
this.compareBox.style.top = "200px";
this.compareBox.align = "center";
this.compareList.id = "compareList";
submitBtn.type = "button";
submitBtn.value = button_compare;
this.compareBox.appendChild(this.compareList);
this.compareBox.appendChild(submitBtn);
submitBtn.onclick = function() {
var cookieValue = document.getCookie("compareItems");
var obj = cookieValue.parseJSON();
var url = document.location.href;
url = url.substring(0,url.lastIndexOf('/')+1) + "compare.php";
var i = 0;
for(var k in obj)
{
if(typeof(obj[k])=="function")
continue;
if(i==0)
url += "?goods[]=" + k;
else
url += "&goods[]=" + k;
i++;
}
if(i<2)
{
alert(compare_no_goods);
return ;
}
document.location.href = url;
}
document.body.appendChild(this.compareBox);
}
this.compareList.innerHTML = "";
var self = this;
for (var key in this.data)
{
if(typeof(this.data[key]) == "function")
continue;
var li = document.createElement("LI");
var span = document.createElement("SPAN");
span.style.overflow = "hidden";
span.style.width = "100px";
span.style.height = "20px";
span.style.display = "block";
span.innerHTML = this.data[key].n;
li.appendChild(span);
li.style.listStyle = "none";
var delBtn = document.createElement("IMG");
delBtn.src = "themes/default/images/drop.gif";
delBtn.className = key;
delBtn.onclick = function(){
document.getElementById("compareList").removeChild(this.parentNode);
delete self.data[this.className];
self.save();
self.init();
}
li.insertBefore(delBtn,li.childNodes[0]);
this.compareList.appendChild(li);
}
if (this.compareList.childNodes.length > 0)
{
this.compareBox.style.display = "";
this.timer = window.setInterval(this.relocation.bind(this), 50);
}
else
{
this.compareBox.style.display = "none";
window.clearInterval(this.timer);
this.timer = 0;
}
},
save : function()
{
var date = new Date();
date.setTime(date.getTime() + 99999999);
document.setCookie("compareItems", this.data.toJSONString());
},
lastScrollY : 0
} | JavaScript |
/**
* @file transport.js
* @description 用于支持AJAX的传输类。
* @author ECShop R&D Team ( http://www.ecshop.com/ )
* @date 2007-03-08 Wednesday
* @license Licensed under the Academic Free License 2.1 http://www.opensource.org/licenses/afl-2.1.php
* @version 1.0.20070308
**/
var Transport =
{
/* *
* 存储本对象所在的文件名。
*
* @static
*/
filename : "transport.js",
/* *
* 存储是否进入调试模式的开关,打印调试消息的方式,换行符,调试用的容器的ID。
*
* @private
*/
debugging :
{
isDebugging : 0,
debuggingMode : 0,
linefeed : "",
containerId : 0
},
/* *
* 设置调试模式以及打印调试消息方式的方法。
*
* @public
* @param {int} 是否打开调试模式 0:关闭,1:打开
* @param {int} 打印调试消息的方式 0:alert,1:innerHTML
*
*/
debug : function (isDebugging, debuggingMode)
{
this.debugging =
{
"isDebugging" : isDebugging,
"debuggingMode" : debuggingMode,
"linefeed" : debuggingMode ? "<br />" : "\n",
"containerId" : "dubugging-container" + new Date().getTime()
};
},
/* *
* 传输完毕后自动调用的方法,优先级比用户从run()方法中传入的回调函数高。
*
* @public
*/
onComplete : function ()
{
},
/* *
* 传输过程中自动调用的方法。
*
* @public
*/
onRunning : function ()
{
},
/* *
* 调用此方法发送HTTP请求。
*
* @public
* @param {string} url 请求的URL地址
* @param {mix} params 发送参数
* @param {Function} callback 回调函数
* @param {string} ransferMode 请求的方式,有"GET"和"POST"两种
* @param {string} responseType 响应类型,有"JSON"、"XML"和"TEXT"三种
* @param {boolean} asyn 是否异步请求的方式
* @param {boolean} quiet 是否安静模式请求
*/
run : function (url, params, callback, transferMode, responseType, asyn, quiet)
{
/* 处理用户在调用该方法时输入的参数 */
params = this.parseParams(params);
transferMode = typeof(transferMode) === "string"
&& transferMode.toUpperCase() === "GET"
? "GET"
: "POST";
if (transferMode === "GET")
{
var d = new Date();
url += params ? (url.indexOf("?") === - 1 ? "?" : "&") + params : "";
url = encodeURI(url) + (url.indexOf("?") === - 1 ? "?" : "&") + d.getTime() + d.getMilliseconds();
params = null;
}
responseType = typeof(responseType) === "string" && ((responseType = responseType.toUpperCase()) === "JSON" || responseType === "XML") ? responseType : "TEXT";
asyn = asyn === false ? false : true;
/* 处理HTTP请求和响应 */
var xhr = this.createXMLHttpRequest();
try
{
var self = this;
if (typeof(self.onRunning) === "function" && !quiet)
{
self.onRunning();
}
xhr.open(transferMode, url, asyn);
if (transferMode === "POST")
{
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if (asyn)
{
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
switch ( xhr.status )
{
case 0:
case 200: // OK!
/*
* If the request was to create a new resource
* (such as post an item to the database)
* You could instead return a status code of '201 Created'
*/
if (typeof(self.onComplete) === "function")
{
self.onComplete();
}
if (typeof(callback) === "function")
{
callback.call(self, self.parseResult(responseType, xhr), xhr.responseText);
}
break;
case 304: // Not Modified
/*
* This would be used when your Ajax widget is
* checking for updated content,
* such as the Twitter interface.
*/
break;
case 400: // Bad Request
/*
* A bit like a safety net for requests by your JS interface
* that aren't supported on the server.
* "Your browser made a request that the server cannot understand"
*/
alert("XmlHttpRequest status: [400] Bad Request");
break;
case 404: // Not Found
alert("XmlHttpRequest status: [404] \nThe requested URL "+url+" was not found on this server.");
break;
case 409: // Conflict
/*
* Perhaps your JavaScript request attempted to
* update a Database record
* but failed due to a conflict
* (eg: a field that must be unique)
*/
break;
case 503: // Service Unavailable
/*
* A resource that this request relies upon
* is currently unavailable
* (eg: a file is locked by another process)
*/
alert("XmlHttpRequest status: [503] Service Unavailable");
break;
default:
alert("XmlHttpRequest status: [" + xhr.status + "] Unknow status.");
}
xhr = null;
}
}
if (xhr != null) xhr.send(params);
}
else
{
if (typeof(self.onRunning) === "function")
{
self.onRunning();
}
xhr.send(params);
var result = self.parseResult(responseType, xhr);
//xhr = null;
if (typeof(self.onComplete) === "function")
{
self.onComplete();
}
if (typeof(callback) === "function")
{
callback.call(self, result, xhr.responseText);
}
return result;
}
}
catch (ex)
{
if (typeof(self.onComplete) === "function")
{
self.onComplete();
}
alert(this.filename + "/run() error:" + ex.description);
}
},
/* *
* 如果开启了调试模式,该方法会打印出相应的信息。
*
* @private
* @param {string} info 调试信息
* @param {string} type 信息类型
*/
displayDebuggingInfo : function (info, type)
{
if ( ! this.debugging.debuggingMode)
{
alert(info);
}
else
{
var id = this.debugging.containerId;
if ( ! document.getElementById(id))
{
div = document.createElement("DIV");
div.id = id;
div.style.position = "absolute";
div.style.width = "98%";
div.style.border = "1px solid #f00";
div.style.backgroundColor = "#eef";
var pageYOffset = document.body.scrollTop
|| window.pageYOffset
|| 0;
div.style.top = document.body.clientHeight * 0.6
+ pageYOffset
+ "px";
document.body.appendChild(div);
div.innerHTML = "<div></div>"
+ "<hr style='height:1px;border:1px dashed red;'>"
+ "<div></div>";
}
var subDivs = div.getElementsByTagName("DIV");
if (type === "param")
{
subDivs[0].innerHTML = info;
}
else
{
subDivs[1].innerHTML = info;
}
}
},
/* *
* 创建XMLHttpRequest对象的方法。
*
* @private
* @return 返回一个XMLHttpRequest对象
* @type Object
*/
createXMLHttpRequest : function ()
{
var xhr = null;
if (window.ActiveXObject)
{
var versions = ['Microsoft.XMLHTTP', 'MSXML6.XMLHTTP', 'MSXML5.XMLHTTP', 'MSXML4.XMLHTTP', 'MSXML3.XMLHTTP', 'MSXML2.XMLHTTP', 'MSXML.XMLHTTP'];
for (var i = 0; i < versions.length; i ++ )
{
try
{
xhr = new ActiveXObject(versions[i]);
break;
}
catch (ex)
{
continue;
}
}
}
else
{
xhr = new XMLHttpRequest();
}
return xhr;
},
/* *
* 当传输过程发生错误时将调用此方法。
*
* @private
* @param {Object} xhr XMLHttpRequest对象
* @param {String} url HTTP请求的地址
*/
onXMLHttpRequestError : function (xhr, url)
{
throw "URL: " + url + "\n"
+ "readyState: " + xhr.readyState + "\n"
+ "state: " + xhr.status + "\n"
+ "headers: " + xhr.getAllResponseHeaders();
},
/* *
* 对将要发送的参数进行格式化。
*
* @private
* @params {mix} params 将要发送的参数
* @return 返回合法的参数
* @type string
*/
parseParams : function (params)
{
var legalParams = "";
params = params ? params : "";
if (typeof(params) === "string")
{
legalParams = params;
}
else if (typeof(params) === "object")
{
try
{
legalParams = "JSON=" + params.toJSONString();
}
catch (ex)
{
alert("Can't stringify JSON!");
return false;
}
}
else
{
alert("Invalid parameters!");
return false;
}
if (this.debugging.isDebugging)
{
var lf = this.debugging.linefeed,
info = "[Original Parameters]" + lf + params + lf + lf
+ "[Parsed Parameters]" + lf + legalParams;
this.displayDebuggingInfo(info, "param");
}
return legalParams;
},
/* *
* 对返回的HTTP响应结果进行过滤。
*
* @public
* @params {mix} result HTTP响应结果
* @return 返回过滤后的结果
* @type string
*/
preFilter : function (result)
{
return result.replace(/\xEF\xBB\xBF/g, "");
},
/* *
* 对返回的结果进行格式化。
*
* @private
* @return 返回特定格式的数据结果
* @type mix
*/
parseResult : function (responseType, xhr)
{
var result = null;
switch (responseType)
{
case "JSON" :
result = this.preFilter(xhr.responseText);
try
{
result = result.parseJSON();
}
catch (ex)
{
throw this.filename + "/parseResult() error: can't parse to JSON.\n\n" + xhr.responseText;
}
break;
case "XML" :
result = xhr.responseXML;
break;
case "TEXT" :
result = this.preFilter(xhr.responseText);
break;
default :
throw this.filename + "/parseResult() error: unknown response type:" + responseType;
}
if (this.debugging.isDebugging)
{
var lf = this.debugging.linefeed,
info = "[Response Result of " + responseType + " Format]" + lf
+ result;
if (responseType === "JSON")
{
info = "[Response Result of TEXT Format]" + lf
+ xhr.responseText + lf + lf
+ info;
}
this.displayDebuggingInfo(info, "result");
}
return result;
}
};
/* 定义两个别名 */
var Ajax = Transport;
Ajax.call = Transport.run;
/*
json.js
2007-03-06
Public Domain
This file adds these methods to JavaScript:
array.toJSONString()
boolean.toJSONString()
date.toJSONString()
number.toJSONString()
object.toJSONString()
string.toJSONString()
These methods produce a JSON text from a JavaScript value.
It must not contain any cyclical references. Illegal values
will be excluded.
The default conversion for dates is to an ISO string. You can
add a toJSONString method to any date object to get a different
representation.
string.parseJSON(filter)
This method parses a JSON text to produce an object or
array. It can throw a SyntaxError exception.
The optional filter parameter is a function which can filter and
transform the results. It receives each of the keys and values, and
its return value is used instead of the original value. If it
returns what it received, then structure is not modified. If it
returns undefined then the member is deleted.
Example:
// Parse the text. If a key contains the string 'date' then
// convert the value to a date.
myData = text.parseJSON(function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
});
It is expected that these methods will formally become part of the
JavaScript Programming Language in the Fourth Edition of the
ECMAScript standard in 2008.
*/
// Augment the basic prototypes if they have not already been augmented.
if ( ! Object.prototype.toJSONString) {
Array.prototype.toJSONString = function () {
var a = ['['], // The array holding the text fragments.
b, // A boolean indicating that a comma is required.
i, // Loop counter.
l = this.length,
v; // The value to be stringified.
function p(s) {
// p accumulates text fragments in an array. It inserts a comma before all
// except the first fragment.
if (b) {
a.push(',');
}
a.push(s);
b = true;
}
// For each value in this array...
for (i = 0; i < l; i ++) {
v = this[i];
switch (typeof v) {
// Values without a JSON representation are ignored.
case 'undefined':
case 'function':
case 'unknown':
break;
// Serialize a JavaScript object value. Ignore objects thats lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.
case 'object':
if (v) {
if (typeof v.toJSONString === 'function') {
p(v.toJSONString());
}
} else {
p("null");
}
break;
// Otherwise, serialize the value.
default:
p(v.toJSONString());
}
}
// Join all of the fragments together and return.
a.push(']');
return a.join('');
};
Boolean.prototype.toJSONString = function () {
return String(this);
};
Date.prototype.toJSONString = function () {
// Ultimately, this method will be equivalent to the date.toISOString method.
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return '"' + this.getFullYear() + '-' +
f(this.getMonth() + 1) + '-' +
f(this.getDate()) + 'T' +
f(this.getHours()) + ':' +
f(this.getMinutes()) + ':' +
f(this.getSeconds()) + '"';
};
Number.prototype.toJSONString = function () {
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(this) ? String(this) : "null";
};
Object.prototype.toJSONString = function () {
var a = ['{'], // The array holding the text fragments.
b, // A boolean indicating that a comma is required.
k, // The current key.
v; // The current value.
function p(s) {
// p accumulates text fragment pairs in an array. It inserts a comma before all
// except the first fragment pair.
if (b) {
a.push(',');
}
a.push(k.toJSONString(), ':', s);
b = true;
}
// Iterate through all of the keys in the object, ignoring the proto chain.
for (k in this) {
if (this.hasOwnProperty(k)) {
v = this[k];
switch (typeof v) {
// Values without a JSON representation are ignored.
case 'undefined':
case 'function':
case 'unknown':
break;
// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.
case 'object':
if (v) {
if (typeof v.toJSONString === 'function') {
p(v.toJSONString());
}
} else {
p("null");
}
break;
default:
p(v.toJSONString());
}
}
}
// Join all of the fragments together and return.
a.push('}');
return a.join('');
};
(function (s) {
// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.
// m is a table of character substitutions.
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
s.parseJSON = function (filter) {
// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.
try {
if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
test(this)) {
// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
var j = eval('(' + this + ')');
// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.
if (typeof filter === 'function') {
function walk(k, v) {
if (v && typeof v === 'object') {
for (var i in v) {
if (v.hasOwnProperty(i)) {
v[i] = walk(i, v[i]);
}
}
}
return filter(k, v);
}
j = walk('', j);
}
return j;
}
} catch (e) {
// Fall through if the regexp test fails.
}
throw new SyntaxError("parseJSON");
};
s.toJSONString = function () {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.
// add by weberliu @ 2007-4-2
var _self = this.replace("&", "%26");
if (/["\\\x00-\x1f]/.test(this)) {
return '"' + _self.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + _self + '"';
};
})(String.prototype);
}
Ajax.onRunning = showLoader;
Ajax.onComplete = hideLoader;
/* *
* 显示载入信息
*/
function showLoader()
{
document.getElementsByTagName('body').item(0).style.cursor = "wait";
if (top.frames['header-frame'])
{
top.frames['header-frame'].document.getElementById("load-div").style.display = "block";
}
else
{
var obj = document.getElementById('loader');
if ( ! obj && process_request)
{
obj = document.createElement("DIV");
obj.id = "loader";
obj.innerHTML = process_request;
document.body.appendChild(obj);
}
}
}
/* *
* 隐藏载入信息
*/
function hideLoader()
{
document.getElementsByTagName('body').item(0).style.cursor = "auto";
if (top.frames['header-frame'])
{
setTimeout(function(){top.frames['header-frame'].document.getElementById("load-div").style.display = "none"}, 10);
}
else
{
try
{
var obj = document.getElementById("loader");
obj.style.display = 'none';
document.body.removeChild(obj);
}
catch (ex)
{}
}
}
| JavaScript |
var pos;
var MSIE=navigator.userAgent.indexOf("MSIE");
var Fire=navigator.userAgent.indexOf("Fire");
var OPER=navigator.userAgent.indexOf("Opera");
var bdy = (document.documentElement && document.documentElement.clientWidth)?document.documentElement:document.body;
onscroll = function()
{
if (Fire > 0)
{
pos = window.pageYOffset;
}
else
{
pos = bdy.scrollTop;
}
var ele_top = 100;
document.getElementById('tag_box').style.top = (pos + ele_top) + 'px';
} | JavaScript |
imgUrl1="data/afficheimg/20081027angsif.jpg";
imgtext1="";
imgLink1=escape("http://www.ecshop.com");
imgUrl2="data/afficheimg/20081027xuorxj.jpg";
imgtext2="";
imgLink2=escape("http://www.maifou.net/");
var pics=imgUrl1+"|"+imgUrl2;
var links=imgLink1+"|"+imgLink2;
var texts=imgtext1+"|"+imgtext2; | JavaScript |
/*
Flash Name: Dynamic Focus
Description: 动感聚焦Flash图片轮播
*/
document.write('<div id="flash_cycle_image"></div>');
$importjs = (function()
{
var uid = 0;
var curr = 0;
var remove = function(id)
{
var head = document.getElementsByTagName('head')[0];
head.removeChild( document.getElementById('jsInclude_'+id) );
};
return function(file,callback)
{
var callback;
var id = ++uid;
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src',file);
js.setAttribute('id','jsInclude_'+id);
if( document.all )
{
js.onreadystatechange = function()
{
if(/(complete|loaded)/.test(this.readyState))
{
try
{
callback(id);remove(id);
}
catch(e)
{
setTimeout(function(){remove(id);include_js(file,callback)},2000);
}
}
};
}
else
{
js.onload = function(){callback(id); remove(id); };
}
head.appendChild(js);
return uid;
};
}
)();
function show_flash()
{
var button_pos=4; //按扭位置 1左 2右 3上 4下
var stop_time=3000; //图片停留时间(1000为1秒钟)
var show_text=1; //是否显示文字标签 1显示 0不显示
var txtcolor="000000"; //文字色
var bgcolor="DDDDDD"; //背景色
var text_height = 18;
var focus_width = swf_width;
var focus_height = swf_height - text_height;
var total_height = focus_height + text_height;
document.getElementById('flash_cycle_image').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cabversion=6,0,0,0" width="'+ focus_width +'" height="'+ total_height +'">'+'<param name="movie" value="data/flashdata/dynfocus/dynfocus.swf">'+'<param name="quality" value="high"><param name="wmode" value="opaque">'+'<param name="FlashVars" value="pics='+pics+'&links='+links+'&texts='+texts+'&pic_width='+focus_width+'&pic_height='+total_height+'&show_text='+show_text+'&txtcolor='+txtcolor+'&bgcolor='+bgcolor+'&button_pos='+button_pos+'&stop_time='+stop_time+'">'+'<embed src="data/flashdata/dynfocus/dynfocus.swf" FlashVars="pics='+pics+'&links='+links+'&texts='+texts+'&pic_width='+focus_width+'&pic_height='+total_height+'&show_text='+show_text+'&txtcolor='+txtcolor+'&bgcolor='+bgcolor+'&button_pos='+button_pos+'&stop_time='+stop_time+'" quality="high" width="'+ focus_width +'" height="'+ total_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>'+'</object>';
}
$importjs('data/flashdata/dynfocus/data.js', show_flash); | JavaScript |
imgUrl1="data/afficheimg/20081027angsif.jpg";
imgtext1="";
imgLink1=escape("http://www.ecshop.com");
imgUrl2="data/afficheimg/20081027xuorxj.jpg";
imgtext2="";
imgLink2=escape("http://www.maifou.net/");
var pics=imgUrl1+"|"+imgUrl2;
var links=imgLink1+"|"+imgLink2;
var texts=imgtext1+"|"+imgtext2; | JavaScript |
/*
Flash Name: Pink Focus
Description: 粉红聚焦Flash图片轮播
*/
document.write('<div id="flash_cycle_image"></div>');
$importjs = (function()
{
var uid = 0;
var curr = 0;
var remove = function(id)
{
var head = document.getElementsByTagName('head')[0];
head.removeChild( document.getElementById('jsInclude_'+id) );
};
return function(file,callback)
{
var callback;
var id = ++uid;
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src',file);
js.setAttribute('id','jsInclude_'+id);
if( document.all )
{
js.onreadystatechange = function()
{
if(/(complete|loaded)/.test(this.readyState))
{
try
{
callback(id);remove(id);
}
catch(e)
{
setTimeout(function(){remove(id);include_js(file,callback)},2000);
}
}
};
}
else
{
js.onload = function(){callback(id); remove(id); };
}
head.appendChild(js);
return uid;
};
}
)();
function show_flash()
{
var text_height = 0;
var focus_width = swf_width;
var focus_height = swf_height - text_height;
var total_height = focus_height + text_height;
document.getElementById('flash_cycle_image').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ focus_width +'" height="'+ total_height +'">'+'<param name="allowScriptAccess" value="sameDomain"><param name="movie" value="data/flashdata/pinkfocus/pinkfocus.swf"><param name="quality" value="high"><param name="bgcolor" value="#F0F0F0">'+'<param name="menu" value="false"><param name=wmode value="opaque">'+'<param name="FlashVars" value="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'">'+'<embed src="data/flashdata/pinkfocus/pinkfocus.swf" FlashVars="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'" quality="high" width="'+ focus_width +'" height="'+ total_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>'+'</object>';
}
$importjs('data/flashdata/pinkfocus/data.js', show_flash); | JavaScript |
imgUrl1="data/afficheimg/20081027angsif.jpg";
imgtext1="开源/免费/强大/简便";
imgLink1=escape("http://www.ecshop.com");
imgUrl2="data/afficheimg/20081027xuorxj.jpg";
imgtext2="";
imgLink2=escape("http://www.maifou.net/");
var pics=imgUrl1+"|"+imgUrl2;
var links=imgLink1+"|"+imgLink2;
var texts=imgtext1+"|"+imgtext2; | JavaScript |
/*
Flash Name: Red Focus
Description: 红色聚焦Flash图片轮播
*/
document.write('<div id="flash_cycle_image"></div>');
$importjs = (function()
{
var uid = 0;
var curr = 0;
var remove = function(id)
{
var head = document.getElementsByTagName('head')[0];
head.removeChild( document.getElementById('jsInclude_'+id) );
};
return function(file,callback)
{
var callback;
var id = ++uid;
var head = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src',file);
js.setAttribute('id','jsInclude_'+id);
if( document.all )
{
js.onreadystatechange = function()
{
if(/(complete|loaded)/.test(this.readyState))
{
try
{
callback(id);remove(id);
}
catch(e)
{
setTimeout(function(){remove(id);include_js(file,callback)},2000);
}
}
};
}
else
{
js.onload = function(){callback(id); remove(id); };
}
head.appendChild(js);
return uid;
};
}
)();
function show_flash()
{
var text_height = 0;
var focus_width = swf_width;
var focus_height = swf_height - text_height;
var total_height = focus_height + text_height;
document.getElementById('flash_cycle_image').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ focus_width +'" height="'+ total_height +'">'+'<param name="allowScriptAccess" value="sameDomain"><param name="movie" value="data/flashdata/redfocus/redfocus.swf"><param name="quality" value="high"><param name="bgcolor" value="#F0F0F0">'+'<param name="menu" value="false"><param name=wmode value="opaque">'+'<param name="FlashVars" value="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'">'+'<embed src="data/flashdata/redfocus/redfocus.swf" FlashVars="pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'" quality="high" width="'+ focus_width +'" height="'+ total_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>'+'</object>';
}
$importjs('data/flashdata/redfocus/data.js', show_flash); | JavaScript |
/*
Flash Name: Default
Description: The default flash cycle.
*/
// 0xffffff:文字颜色|1:文字位置|0x0066ff:文字背景颜色|60:文字背景透明度|0xffffff:按键文字颜色|0x0066ff:按键默认颜色|0x000033:按键当前颜色|8:自动播放时间(秒)|2:图片过渡效果|1:是否显示按钮|_blank:打开窗口
var swf_config = "|2|||0xFFFFFF|0xFF6600||4|3|1|_blank"
document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ swf_width +'" height="'+ swf_height +'">');
document.write('<param name="movie" value="data/flashdata/default/bcastr.swf?bcastr_xml_url=data/flashdata/default/data.xml"><param name="quality" value="high">');
document.write('<param name="menu" value="false"><param name=wmode value="opaque">');
document.write('<param name="FlashVars" value="bcastr_config='+swf_config+'">');
document.write('<embed src="data/flashdata/default/bcastr.swf?bcastr_xml_url=data/flashdata/default/data.xml" wmode="opaque" FlashVars="bcastr_config='+swf_config+'" menu="false" quality="high" width="'+ swf_width +'" height="'+ swf_height +'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent"/>');
document.write('</object>'); | JavaScript |
/* $Id : common.js 4824 2007-01-31 08:23:56Z paulgao $ */
/* 检查新订单的时间间隔 */
var NEW_ORDER_INTERVAL = 180000;
/* *
* 开始检查新订单;
*/
function startCheckOrder()
{
checkOrder()
window.setInterval("checkOrder()", NEW_ORDER_INTERVAL);
}
/*
* 检查订单
*/
function checkOrder()
{
var lastCheckOrder = new Date(document.getCookie('ECS_LastCheckOrder'));
var today = new Date();
if (lastCheckOrder == null || today-lastCheckOrder >= NEW_ORDER_INTERVAL)
{
document.setCookie('ECS_LastCheckOrder', today.toGMTString());
try
{
Ajax.call('index.php?is_ajax=1&act=check_order','', checkOrderResponse, 'GET', 'JSON');
}
catch (e) { }
}
}
/* *
* 处理检查订单的反馈信息
*/
function checkOrderResponse(result)
{
//出错屏蔽
if (result.error != 0 || (result.new_orders == 0 && result.new_paid == 0))
{
return;
}
try
{
document.getElementById('spanNewOrder').innerHTML = result.new_orders;
document.getElementById('spanNewPaid').innerHTML = result.new_paid;
Message.show();
}
catch (e) { }
}
/**
* 确认后跳转到指定的URL
*/
function confirm_redirect(msg, url)
{
if (confirm(msg))
{
location.href=url;
}
}
/* *
* 设置页面宽度
*/
function set_size(w)
{
var y_width = document.body.clientWidth
var s_width = screen.width
var agent = navigator.userAgent.toLowerCase();
if (y_width < w)
{
if (agent.indexOf("msie") != - 1)
{
document.body.style.width = w + "px";
}
else
{
document.getElementById("bd").style.width = (w - 10) + 'px';
}
}
}
/* *
* 显示隐藏图片
* @param id div的id
* @param show | hide
*/
function showImg(id, act)
{
if (act == 'show')
{
document.getElementById(id).style.visibility = 'visible';
}
else
{
document.getElementById(id).style.visibility = 'hidden';
}
}
/*
* 气泡式提示信息
*/
var Message = Object();
Message.bottom = 0;
Message.count = 0;
Message.elem = "popMsg";
Message.mvTimer = null;
Message.show = function()
{
try
{
Message.controlSound('msgBeep');
document.getElementById(Message.elem).style.visibility = "visible"
document.getElementById(Message.elem).style.display = "block"
Message.bottom = 0 - parseInt(document.getElementById(Message.elem).offsetHeight);
Message.mvTimer = window.setInterval("Message.move()", 10);
document.getElementById(Message.elem).style.bottom = Message.bottom + "px";
}
catch (e)
{
alert(e);
}
}
Message.move = function()
{
try
{
if (Message.bottom == 0)
{
window.clearInterval(Message.mvTimer)
Message.mvTimer = window.setInterval("Message.close()", 10000)
}
Message.bottom ++ ;
document.getElementById(Message.elem).style.bottom = Message.bottom + "px";
}
catch (e)
{
alert(e);
}
}
Message.close = function()
{
document.getElementById(Message.elem).style.visibility = 'hidden';
document.getElementById(Message.elem).style.display = 'none';
if (Message.mvTimer) window.clearInterval(Message.mvTimer)
}
Message.controlSound = function(_sndObj)
{
sndObj = document.getElementById(_sndObj);
try
{
sndObj.Play();
}
catch (e) { }
}
var listZone = new Object();
/* *
* 显示正在载入
*/
listZone.showLoader = function()
{
listZone.toggleLoader(true);
}
listZone.hideLoader = function()
{
listZone.toggleLoader(false);
}
listZone.toggleLoader = function(disp)
{
document.getElementsByTagName('body').item(0).style.cursor = (disp) ? "wait" : 'auto';
try
{
var doc = top.frames['header-frame'].document;
var loader = doc.getElementById("load-div");
if (typeof loader == 'object') loader.style.display = disp ? "block" : "none";
}
catch (ex) { }
}
function $import(path,type,title){
var s,i;
if(type == "js"){
var ss = document.getElementsByTagName("script");
for(i =0;i < ss.length; i++)
{
if(ss[i].src && ss[i].src.indexOf(path) != -1)return ss[i];
}
s = document.createElement("script");
s.type = "text/javascript";
s.src =path;
}
else if(type == "css")
{
var ls = document.getElementsByTagName("link");
for(i = 0; i < ls.length; i++)
{
if(ls[i].href && ls[i].href.indexOf(path)!=-1)return ls[i];
}
s = document.createElement("link");
s.rel = "alternate stylesheet";
s.type = "text/css";
s.href = path;
s.title = title;
s.disabled = false;
}
else return;
var head = document.getElementsByTagName("head")[0];
head.appendChild(s);
return s;
} | JavaScript |
/**
* 标签上鼠标移动事件的处理函数
* @return
*/
document.getElementById("tabbar-div").onmouseover = function(e)
{
var obj = Utils.srcElement(e);
if (obj.className == "tab-back")
{
obj.className = "tab-hover";
}
}
document.getElementById("tabbar-div").onmouseout = function(e)
{
var obj = Utils.srcElement(e);
if (obj.className == "tab-hover")
{
obj.className = "tab-back";
}
}
/**
* 处理点击标签的事件的函数
* @param : e FireFox 事件句柄
*
* @return
*/
document.getElementById("tabbar-div").onclick = function(e)
{
var obj = Utils.srcElement(e);
if (obj.className == "tab-front" || obj.className == '' || obj.tagName.toLowerCase() != 'span')
{
return;
}
else
{
objTable = obj.id.substring(0, obj.id.lastIndexOf("-")) + "-table";
var tables = document.getElementsByTagName("table");
var spans = document.getElementsByTagName("span");
for (i = 0; i < tables.length; i ++ )
{
if (tables[i].id == objTable)
{
tables[i].style.display = (Browser.isIE) ? "block" : "table";
}
else
{
var tblId = tables[i].id.match(/-table$/);
if (tblId == "-table")
{
tables[i].style.display = "none";
}
}
}
for (i = 0; spans.length; i ++ )
{
if (spans[i].className == "tab-front")
{
spans[i].className = "tab-back";
obj.className = "tab-front";
break;
}
}
}
}
| JavaScript |
var Todolist = Class.create();
Todolist.prototype = {
initialize:function(adminid)
{
this.box = $ce("DIV");
this.container = $ce("DIV");
this.head = $ce("DIV");
this.buttons = $ce("DIV");
this.middle = $ce("DIV");
this.bottom = $ce("DIV");
this.bottomLeft = $ce("DIV");
this.virtualBox = $ce("DIV");
this.bottomRight = $ce("DIV");
this.minBtn = $ce("IMG");
this.closeBtn = $ce("IMG");
this.saveBtn = $ce("INPUT");
this.clearBtn = $ce("INPUT");
this.textBox = $ce("TEXTAREA");
this.tempFun = new Object();
this.tempFun.draging = this.draging.bind(this);
this.tempFun.startDrag = this.startDrag.bind(this);
this.tempFun.endDrag = this.endDrag.bind(this);
this.tempFun.startSetSize = this.startSetSize.bind(this)
this.tempFun.setSize = this.setSize.bind(this);
this.tempFun.endSetSize = this.endSetSize.bind(this);
this.tempFun.save = this.save.bind(this);
this.myTimer;
this.lastContentHash;
var self = this;
this.innerWidth = Math.min(document.body.scrollWidth, self.innerWidth||document.body.clientWidth);
if (window.self.innerHeight)
{
this.innerHeight = Math.max(window.self.innerHeight,document.body.scrollHeight);
}
else
{
if (document.documentElement && document.documentElement.clientHeight)
{
this.innerHeight = Math.max(document.documentElement.clientHeight,document.documentElement.scrollHeight);
}
else if (document.body)
{
this.innerHeight = Math.max(document.body.clientHeight,document.body.scrollHeight);
}
}
this.md5 = hex_md5;
this.adminid = adminid;
this.closeBtn.src = "images/btn_close.gif";
this.closeBtn.onclick = this.close.bind(this);
this.minBtn.src = "images/btn_minimize.gif";
this.minBtn.onclick = function()
{
if (self.Maxed)
{
self.toMin();
}
else
{
self.toMax()
}
}
this.buttons.className = "buttons";
this.buttons.appendChild(this.minBtn);
this.buttons.appendChild(this.closeBtn);
this.head.className = "head";
this.head.style.cursor = "move";
this.head.innerHTML = todolist_caption ;
this.head.appendChild(this.buttons);
this.textBox.style.height = "100px";
this.textBox.style.width = "293px";
this.clearBtn.type = "button"
this.clearBtn.value = todolist_clear;
this.clearBtn.className = "button";
this.clearBtn.onclick = this.clear.bind(this);
this.saveBtn.type = "button";
this.saveBtn.value = todolist_save;
this.saveBtn.className = "button";
this.saveBtn.onclick = this.save.bind(this);
this.bottom.className = "bottom";
this.bottomLeft.className = "bottomLeft";
this.bottomLeft.innerHTML += "<label><input type=\"checkbox\" value=\"1\" name=\"remember\" />" + todolist_autosave + "</label>"
this.bottomLeft.appendChild(this.saveBtn);
this.bottomLeft.appendChild(this.clearBtn);
this.bottom.appendChild(this.bottomLeft);
this.bottom.appendChild(this.bottomRight);
this.middle.className = "middle";
this.middle.appendChild(this.textBox);
this.container.className = "container"
this.container.appendChild(this.head);
this.container.appendChild(this.middle);
this.container.appendChild(this.bottom);
this.box.className = "todolist-box";
this.box.style.height = "auto";
this.box.style.left = "1px";
this.box.style.top = "1px";
this.box.style.display = "none";
this.box.appendChild(this.container);
this.autoSaveCheckbox = this.bottomLeft.getElementsByTagName('input')[0];
this.autoSaveCheckbox.checked = document.getCookie("todolist_notautosave_" + this.adminid) == null ? true : false;
if (this.autoSaveCheckbox.checked)
{
this.autoSave();
}
this.bottomRight.className = "bottomRight";
this.bottomRight.style.cursor = "se-resize";
this.virtualBox.style.display = "none";
this.virtualBox.className = "virtualBox";
document.body.appendChild(this.box);
document.body.appendChild(this.virtualBox);
this.LastX = 0;
this.LastY = 0;
this.LastLeft = 0;
this.LastTop = 0;
this.moveing = false;
this.visibility = false;
this.Maxed = true;
Event.observe(this.head, "selectstart", this.falseFunction);
Event.observe(this.head, "mousedown", this.tempFun.startDrag);
Event.observe(this.bottomRight, "mousedown", this.tempFun.startSetSize);
Event.observe(this.autoSaveCheckbox, "click", this.autoSave.bind(this));
window.onbeforeunload = function()
{
if (self.lastContentHash == self.md5(self.textBox.value)) return;
if (confirm(todolist_confirm_save))
{
Ajax.call('index.php?is_ajax=1&act=save_todolist', 'content=' + encodeURIComponent(self.textBox.value), null, 'POST', 'TEXT', false);
}
}
this.head.ondblclick = function()
{
if (!self.Maxed)
self.toMax();
else
self.toMin();
return false;
}
var posObj = document.getCookie("todolist_position_" + this.adminid);
if (posObj != null)
{
posObj = eval(posObj);
this.box.style.left = posObj.X;
this.box.style.top = posObj.Y;
}
this.loadData.call(this);
},
loadData : function()
{
Ajax.call('index.php?is_ajax=1&act=get_todolist', '' , this.loadDataResponse.bind(this) , 'POST', 'TEXT');
},
loadDataResponse : function(result)
{
this.textBox.value = result;
this.lastContentHash = this.md5(this.textBox.value);
},
startDrag : function(event)
{
Event.observe(document.body, "selectstart", this.falseFunction);
Event.observe(document, "mousemove", this.tempFun.draging);
Event.observe(document, "mouseup", this.tempFun.endDrag);
var element = Event.element(event||window.event);
this.LastX = Event.pointerX(event||window.event);
this.LastY = Event.pointerY(event||window.event);
this.LastLeft = this.box.style.left;
this.LastTop = this.box.style.top;
},
draging : function(event)
{
var X = Event.pointerX(event||window.event);
var Y = Event.pointerY(event||window.event);
var tX = parseInt(this.LastLeft) + X - this.LastX;
var tY = parseInt(this.LastTop) + Y - this.LastY;
if (tX <= 0)
{
tX = 0;
}
if (tY <= 0)
{
tY = 0;
}
if ((tX + parseInt(this.box.offsetWidth)) >= parseInt(this.innerWidth))
{
tX = parseInt(this.innerWidth) - parseInt(this.box.offsetWidth);
}
if ((tY + parseInt(this.box.offsetHeight)) >= parseInt(this.innerHeight))
{
tY = parseInt(this.innerHeight) - parseInt(this.box.offsetHeight);
}
this.box.style.left = tX + "px";
this.box.style.top = tY + "px";
},
endDrag : function()
{
var date = new Date();
date.setTime(date.getTime() + 99999999);
document.setCookie("todolist_position_" + this.adminid, "({X:'" + this.box.style.left + "',Y:'" + this.box.style.top + "'})", date.toGMTString());
Event.stopObserving(document.body, "selectstart", this.falseFunction);
Event.stopObserving(document, "mousemove", this.tempFun.draging);
Event.stopObserving(document, "mouseup", this.tempFun.endDrag);
},
toMax : function()
{
this.middle.style.display = "";
this.bottom.style.display = "";
this.Maxed = true;
this.minBtn.src = "images/btn_minimize.gif";
},
toMin : function()
{
this.middle.style.display = "none";
this.bottom.style.display = "none";
this.box.style.height = "";
this.Maxed = false;
this.minBtn.src = "images/btn_maximize.gif";
},
show : function()
{
this.loadData();
this.box.style.display = "";
if (Browser.isFirefox)
{
this.middle.style.paddingRight = "5px";
}
if (parseInt(this.box.style.top) + parseInt(this.box.offsetHeight) > this.innerHeight)
{
var top = this.innerHeight - this.box.offsetHeight;
this.box.style.top = top + "px";
}
if (parseInt(this.box.style.top) <= 0)
{
this.box.style.top = "1px";
}
this.visibility = true;
},
hide : function()
{
this.box.style.display = "none";
this.visibility = false;
},
falseFunction : function()
{
return false;
},
startSetSize : function(event)
{
var pos = Event.position(this.box);
this.virtualBox.style.display = "";
this.virtualBox.style.top = pos.top + "px";
this.virtualBox.style.left = pos.left + "px";
this.virtualBox.style.height = this.box.offsetHeight + "px";
this.virtualBox.style.width = this.box.offsetWidth + "px";
document.body.style.cursor = "se-resize";
Event.observe(document, "mousemove", this.tempFun.setSize);
Event.observe(document, "mouseup", this.tempFun.endSetSize);
Event.observe(document.body, "selectstart", this.falseFunction);
},
setSize : function(event)
{
var pos = Event.position(this.box);
var tX = Event.pointerX(event||window.event);
var tY = Event.pointerY(event||window.event);
var height = tY - (parseInt(pos.top) - this.box.offsetHeight) - parseInt(this.box.offsetHeight);
var width = tX - (parseInt(pos.left) - this.box.offsetWidth) - parseInt(this.box.offsetWidth);
if (height >= 95)
this.virtualBox.style.height = height + "px";
if (width >= 301)
this.virtualBox.style.width = width + "px";
},
endSetSize : function(event)
{
Event.stopObserving(document,"mousemove",this.tempFun.setSize);
Event.stopObserving(document,"mouseup",this.tempFun.endSetSize);
Event.stopObserving(document.body,"selectstart",this.falseFunction);
document.body.style.cursor='';
if (parseInt(this.virtualBox.style.height) >= 95)
{
this.box.style.height = this.virtualBox.style.height ;
}
if (parseInt(this.virtualBox.style.width) >= 301)
{
this.box.style.width = this.virtualBox.style.width;
}
this.textBox.style.width = parseInt(this.box.style.width) - 7 + "px";
this.textBox.style.height = parseInt(this.box.style.height) - parseInt(this.head.offsetHeight) - parseInt(this.bottom.offsetHeight) + "px";
if (this.container.offsetHeight > this.box.offsetHeight)
{
var span = this.container.offsetHeight - this.box.offsetHeight;
this.textBox.style.height = parseInt(this.textBox.style.height) - span - 4 + "px";
}
this.virtualBox.style.display = "none";
},
save : function()
{
if (this.lastContentHash == this.md5(this.textBox.value)) return false;
this.saveBtn.disabled = true;
this.clearBtn.disabled = true;
this.textBox.disabled = true;
var content = encodeURIComponent(this.textBox.value);
var self = this;
Ajax.call('index.php?is_ajax=1&act=save_todolist', 'content=' + content, function(result)
{
self.saveBtn.disabled = false;
self.textBox.disabled = false;
self.clearBtn.disabled = false;
self.lastContentHash = self.md5(self.textBox.value);
}, 'POST', 'TEXT');
},
autoSave : function()
{
if (this.autoSaveCheckbox.checked)
{
document.removeCookie("todolist_notautosave_" + this.adminid);
this.myTimer = window.setInterval(this.save.bind(this), 60000);
Event.observe(this.textBox, "blur", this.tempFun.save);
}
else
{
Event.stopObserving(this.textBox, "blur", this.tempFun.save);
var date = new Date();
date.setTime(date.getTime() + 99999999);
document.setCookie("todolist_notautosave_" + this.adminid, "1", date.toGMTString());
window.clearInterval(this.myTimer);
this.myTimer = false;
}
},
close : function()
{
if (this.lastContentHash != this.md5(this.textBox.value))
{
if (!this.autoSaveCheckbox.checked)
{
if (confirm(todolist_confirm_save))
{
this.save();
}
}
}
this.hide()
},
clear : function()
{
if (confirm(todolist_confirm_clear))
{
this.textBox.value = "";
}
}
} | JavaScript |
var ColorSelecter = new Object();
ColorSelecter.Show = function(sender)
{
if(ColorSelecter.box)
{
if (ColorSelecter.box.style.display = "none")
ColorSelecter.box.style.display = "";
}
else
{
ColorSelecter.box = document.createElement("Div");
ColorSelecter.box.id = "ColorSelectertBox";
var table = "<table width='93' border='1' cellpadding='0' cellspacing='0' bordercolor='#BDBBBC' style='border:2px #C5D9FE solid'><tr><td bgcolor='#FFFFFF'> </td><td bgcolor='#C0C0C0'> </td><td bgcolor='#969696'> </td><td bgcolor='#808080'> </td><td bgcolor='#333333'> </td></tr><tr><td bgcolor='#CC99FE'> </td><td bgcolor='#993365'> </td><td bgcolor='#81007F'> </td><td bgcolor='#6766CC'> </td><td bgcolor='#343399'> </td></tr><tr><td bgcolor='#BBBBBB'> </td><td bgcolor='#00CCFF'> </td><td bgcolor='#3366FF'> </td><td bgcolor='#0000FE'> </td><td bgcolor='#010080'> </td></tr><tr><td bgcolor='#CDFFFF'> </td><td bgcolor='#01FFFF'> </td><td bgcolor='#33CBCC'> </td><td bgcolor='#008081'> </td><td bgcolor='#003265'> </td></tr><tr><td bgcolor='#CDFFCC'> </td><td bgcolor='#00FF01'> </td><td bgcolor='#339967'> </td><td bgcolor='#008002'> </td><td bgcolor='#013300'> </td></tr><tr><td bgcolor='#FFFE99'> </td><td bgcolor='#FFFE03'> </td><td bgcolor='#99CD00'> </td><td bgcolor='#807F01'> </td><td bgcolor='#333301'> </td></tr><tr><td bgcolor='#FFCB99'> </td><td bgcolor='#FFCD00'> </td><td bgcolor='#FF9900'> </td><td bgcolor='#FD6600'> </td><td bgcolor='#993400'> </td></tr><tr><td bgcolor='#FF99CB'> </td><td bgcolor='#FF00FE'> </td><td bgcolor='#FE0000'> </td><td bgcolor='#800000'> </td><td bgcolor='#000000'> </td></tr></table>";
ColorSelecter.box.innerHTML = table;
document.body.appendChild(ColorSelecter.box);
var myTable = ColorSelecter.box.childNodes[0];
for (var i = 0; i<myTable.rows.length; i++)
{
for (var j = 0; j < myTable.rows[i].cells.length; j++)
{
myTable.rows[i].cells[j].style.border = "#BDBBBC 1px solid";
myTable.rows[i].cells[j].onmousemove = function()
{
this.style.border = "#fff 1px solid";
}
myTable.rows[i].cells[j].onmouseout = function()
{
this.style.border = "#BDBBBC 1px solid";
}
myTable.rows[i].cells[j].onmousedown = function()
{
document.getElementById("font_color").style.backgroundColor = this.bgColor;
document.getElementById("goods_name_color").value = this.bgColor;
document.getElementsByName("goods_name").item(0).style.color = this.bgColor;
ColorSelecter.box.style.display = "none";
}
}
}
}
var pos = getPosition(sender);
ColorSelecter.box.style.top = pos.top + 18 + "px";
ColorSelecter.box.style.left = pos.left + "px";
document.onmousedown = function()
{
ColorSelecter.box.style.display = "none";
}
}
| JavaScript |
var persistclose = 0 // set to 0 or 1. 1 means once the bar is manually closed, it will remain closed for browser session
var startX = 3 // set x offset of bar in pixels
var startY = 3 // set y offset of bar in pixels
function iecompattest()
{
return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
}
function get_cookie(Name)
{
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0)
{
offset = document.cookie.indexOf(search)
if (offset != - 1)
{
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == - 1)
{
end = document.cookie.length;
}
returnvalue = unescape(document.cookie.substring(offset, end));
}
}
return returnvalue;
}
var verticalpos = "fromtop";
function closebar()
{
if (persistclose)
{
document.cookie = "remainclosed=1";
}
document.getElementById("topbar").style.visibility = "hidden";
}
function staticbar()
{
var ns = (navigator.appName.indexOf("Netscape") != - 1);
var d = document;
function ml(id)
{
var el = d.getElementById(id);
if ( ! persistclose || persistclose && get_cookie("remainclosed") == "")
{
el.style.visibility = "visible";
}
if (d.layers)
{
el.style = el;
}
el.sP = function(x, y)
{
this.style.left = x + "px";
this.style.top = y + "px";
}
;
el.x = startX;
if (verticalpos == "fromtop")
{
el.y = startY;
}
else
{
el.y = ns ? pageYOffset + innerHeight : iecompattest().scrollTop + iecompattest().clientHeight;
el.y -= startY;
}
return el;
}
window.stayTopLeft = function()
{
if (verticalpos == "fromtop")
{
var pY = ns ? pageYOffset : iecompattest().scrollTop;
ftlObj.y += (pY + startY - ftlObj.y) / 8;
}
else
{
var pY = ns ? pageYOffset + innerHeight : iecompattest().scrollTop + iecompattest().clientHeight;
ftlObj.y += (pY - startY - ftlObj.y) / 8;
}
ftlObj.sP(ftlObj.x, ftlObj.y);
setTimeout("stayTopLeft()", 10);
}
ftlObj = ml("topbar");
stayTopLeft();
}
| JavaScript |
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
| JavaScript |
var SelectBox = Class.create();
SelectBox.prototype = {
initialize:function (src, dst)
{
this.dst_options = new Array();
this.src_obj = document.getElementById(src);
this.dst_obj = document.getElementById(dst);
this.copy_method = (typeof (arguments[2]) != 'undefined')?true:false;
},
addItem:function ()
{
var all = (typeof (arguments[0]) != 'undefined')?arguments[0]:false;
var src_options = this.fetch_options(this.src_obj, all);
if (src_options.length > 0)
{
this.copy_options(this.dst_obj, src_options);
}
},
delItem:function ()
{
var all = (typeof (arguments[0]) != 'undefined')?arguments[0]:false;
var dst_options = this.fetch_options(this.dst_obj, all);
if (dst_options.length > 0)
{
this.del_options(this.dst_obj, dst_options);
}
},
moveItem:function (direction)
{
var dst_options = this.fetch_options(this.dst_obj);
var insert_position = new Object;
if (direction == 'up')
{
if (dst_options[0] === this.dst_obj.options[0])
{
return;
}
insert_position = dst_options[0].previousSibling;
}
else
{
if (dst_options[dst_options.length-1] === this.dst_obj.options[this.dst_obj.options.length-1])
{
return;
}
insert_position = dst_options[dst_options.length-1].nextSibling.nextSibling;
}
this.move_options(this.dst_obj, insert_position, dst_options);
},
fetch_options:function (o)
{
var sel_options = [];
var c = 0;
var all = (typeof (arguments[1]) != 'undefined')?arguments[1]:false;
for (var i=0,l=o.options.length; i<l; i++)
{
if (all === false)
{
if (o.options[i].selected)
{
sel_options[c++] = o.options[i];
}
}
else
{
sel_options[c++] = o.options[i];
}
}
return sel_options;
},
del_options:function (o, arr)
{
for (var i=0,l=arr.length; i<l; i++)
{
if (this.copy_method === false)
{
o.removeChild(arr[i]);
}
else
{
this.src_obj.appendChild(arr[i]);
}
this.dst_options = this.delete_array(arr[i].value, this.dst_options);
}
},
copy_options:function (o, arr)
{
for (var i=0,l=arr.length; i<l; i++)
{
if (!this.in_array(arr[i].value, this.dst_options))
{
if (this.copy_method === false)
{
new_opt = this.clone_option(arr[i]);
}
else
{
new_opt = arr[i];
}
o.appendChild(new_opt);
this.dst_options[this.dst_options.length] = arr[i].value;
}
}
},
move_options:function (o, p, arr)
{
for (var i=0,l=arr.length; i<l; i++)
{
o.insertBefore(arr[i], p);
}
},
clone_option:function (o)
{
var new_opt = document.createElement('OPTION');
new_opt.value = o.value;
new_opt.innerHTML = o.innerHTML;
return new_opt;
},
in_array:function (elem, array)
{
var re = new RegExp('\\\|' + elem + '\\\|');
return re.test('|' + array.join('|') + '|');
},
delete_array:function (elem, array)
{
var re = new RegExp( elem + '\\\|');
var _str = (array.join('|') + '|').replace(re, '');
return _str.split('|');
}
} | JavaScript |
/* *
* ECSHOP 表单验证类
* ============================================================================
* 版权所有 (C) 2005-2007 康盛创想(北京)科技有限公司,并保留所有权利。
* 网站地址 : http : // www.ecshop.com
* ----------------------------------------------------------------------------
* 这是一个免费开源的软件;这意味着您可以在不用于商业目的的前提下对程序代码
* 进行修改和再发布。
* ============================================================================
* $Author : paulgao $
* $Date : 2007-01-31 16:23:56 +0800 (星期三, 31 一月 2007) $
* $Id : validator.js 4824 2007-01-31 08:23:56Z paulgao $
*//* *
* 表单验证类
*
* @author : weber liu
* @version : v1.1
*/
var Validator = function(name)
{
this.formName = name;
this.errMsg = new Array();
/* *
* 检查用户是否输入了内容
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
*/
this.required = function(controlId, msg)
{
var obj = document.forms[this.formName].elements[controlId];
if (typeof(obj) == "undefined" || Utils.trim(obj.value) == "")
{
this.addErrorMsg(msg);
}
}
;
/* *
* 检查用户输入的是否为合法的邮件地址
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isEmail = function(controlId, msg, required)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if ( ! required && obj.value == '')
{
return;
}
if ( ! Utils.isEmail(obj.value))
{
this.addErrorMsg(msg);
}
}
/* *
* 检查两个表单元素的值是否相等
*
* @param : fstControl 表单元素的ID
* @param : sndControl 表单元素的ID
* @param : msg 错误提示信息
*/
this.eqaul = function(fstControl, sndControl, msg)
{
var fstObj = document.forms[this.formName].elements[fstControl];
var sndObj = document.forms[this.formName].elements[sndControl];
if (fstObj != null && sndObj != null)
{
if (fstObj.value == '' || fstObj.value != sndObj.value)
{
this.addErrorMsg(msg);
}
}
}
/* *
* 检查前一个表单元素是否大于后一个表单元素
*
* @param : fstControl 表单元素的ID
* @param : sndControl 表单元素的ID
* @param : msg 错误提示信息
*/
this.gt = function(fstControl, sndControl, msg)
{
var fstObj = document.forms[this.formName].elements[fstControl];
var sndObj = document.forms[this.formName].elements[sndControl];
if (fstObj != null && sndObj != null) {
if (Utils.isNumber(fstObj.value) && Utils.isNumber(sndObj.value)) {
var v1 = parseFloat(fstObj.value) + 0;
var v2 = parseFloat(sndObj.value) + 0;
} else {
var v1 = fstObj.value;
var v2 = sndObj.value;
}
if (v1 <= v2) this.addErrorMsg(msg);
}
}
/* *
* 检查输入的内容是否是一个数字
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isNumber = function(controlId, msg, required)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if (obj.value == '' && ! required)
{
return;
}
else
{
if ( ! Utils.isNumber(obj.value))
{
this.addErrorMsg(msg);
}
}
}
/* *
* 检查输入的内容是否是一个整数
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isInt = function(controlId, msg, required)
{
if (document.forms[this.formName].elements[controlId])
{
var obj = document.forms[this.formName].elements[controlId];
}
else
{
return;
}
obj.value = Utils.trim(obj.value);
if (obj.value == '' && ! required)
{
return;
}
else
{
if ( ! Utils.isInt(obj.value)) this.addErrorMsg(msg);
}
}
/* *
* 检查输入的内容是否是为空
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isNullOption = function(controlId, msg)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if (obj.value > '0' )
{
return;
}
else
{
this.addErrorMsg(msg);
}
}
/* *
* 检查输入的内容是否是"2006-11-12 12:00:00"格式
*
* @param : controlId 表单元素的ID
* @param : msg 错误提示信息
* @param : required 是否必须
*/
this.isTime = function(controlId, msg, required)
{
var obj = document.forms[this.formName].elements[controlId];
obj.value = Utils.trim(obj.value);
if (obj.value == '' && ! required)
{
return;
}
else
{
if ( ! Utils.isTime(obj.value)) this.addErrorMsg(msg);
}
}
/* *
* 检查前一个表单元素是否小于后一个表单元素(日期判断)
*
* @param : controlIdStart 表单元素的ID
* @param : controlIdEnd 表单元素的ID
* @param : msg 错误提示信息
*/
this.islt = function(controlIdStart, controlIdEnd, msg)
{
var start = document.forms[this.formName].elements[controlIdStart];
var end = document.forms[this.formName].elements[controlIdEnd];
start.value = Utils.trim(start.value);
end.value = Utils.trim(end.value);
if(start.value <= end.value)
{
return;
}
else
{
this.addErrorMsg(msg);
}
}
/* *
* 检查指定的checkbox是否选定
*
* @param : controlId 表单元素的name
* @param : msg 错误提示信息
*/
this.requiredCheckbox = function(chk, msg)
{
var obj = document.forms[this.formName].elements[controlId];
var checked = false;
for (var i = 0; i < objects.length; i ++ )
{
if (objects[i].type.toLowerCase() != "checkbox") continue;
if (objects[i].checked)
{
checked = true;
break;
}
}
if ( ! checked) this.addErrorMsg(msg);
}
this.passed = function()
{
if (this.errMsg.length > 0)
{
var msg = "";
for (i = 0; i < this.errMsg.length; i ++ )
{
msg += "- " + this.errMsg[i] + "\n";
}
alert(msg);
return false;
}
else
{
return true;
}
}
/* *
* 增加一个错误信息
*
* @param : str
*/
this.addErrorMsg = function(str)
{
this.errMsg.push(str);
}
}
/* *
* 帮助信息的显隐函数
*/
function showNotice(objId)
{
var obj = document.getElementById(objId);
if (obj)
{
if (obj.style.display != "block")
{
obj.style.display = "block";
}
else
{
obj.style.display = "none";
}
}
}
/* *
* add one option of a select to another select.
*
* @author Chunsheng Wang < wwccss@263.net >
*/
function addItem(src, dst)
{
for (var x = 0; x < src.length; x ++ )
{
var opt = src.options[x];
if (opt.selected && opt.value != '')
{
var newOpt = opt.cloneNode(true);
newOpt.className = '';
newOpt.text = newOpt.innerHTML.replace(/^\s+|\s+$| /g, '');
dst.appendChild(newOpt);
}
}
src.selectedIndex = -1;
}
/* *
* move one selected option from a select.
*
* @author Chunsheng Wang < wwccss@263.net >
*/
function delItem(ItemList)
{
for (var x = ItemList.length - 1; x >= 0; x -- )
{
var opt = ItemList.options[x];
if (opt.selected)
{
ItemList.options[x] = null;
}
}
}
/* *
* join items of an select with ",".
*
* @author Chunsheng Wang < wwccss@263.net >
*/
function joinItem(ItemList)
{
var OptionList = new Array();
for (var i = 0; i < ItemList.length; i ++ )
{
OptionList[OptionList.length] = ItemList.options[i].text + "|" + ItemList.options[i].value;
}
return OptionList.join(",");
}
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.