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','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','sk',{devTools:{title:'Informácie o prvku',dialogName:'Názov okna dialógu',tabName:'Názov záložky',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','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 */ /* 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 */ /* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'devtools', 'ku', { 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','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-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html 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('videoforpc',{requires:['iframedialog'],init:function(a){var b=300,c=660;CKEDITOR.dialog.addIframe('MyVideoDialog','从视频库插入视频','index.php?m=video&c=video_for_ck&a=init',c,b,function(){},{onOk:function(){}});a.addCommand('MyVideo',new CKEDITOR.dialogCommand('MyVideoDialog'));a.ui.addButton('MyVideo',{label:'插入视频/上传视频',command:'MyVideo',icon:this.path+'v.png'});}});
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'specialchar', 'fa', { euro: 'نشان یورو', lsquo: 'علامت نقل قول تکی چپ', rsquo: 'علامت نقل قول تکی راست', ldquo: 'علامت دوتایی نقل قول چپ', rdquo: 'علامت دوتایی نقل قول راست', ndash: 'En dash', // MISSING mdash: 'Em dash', // MISSING iexcl: 'علامت گذاری به عنوان علامت تعجب وارونه', cent: 'نشان سنت', pound: 'نشان پوند', curren: 'نشان ارز', yen: 'نشان ین', brvbar: 'نوار شکسته', sect: 'نشان بخش', uml: 'Diaeresis', // MISSING copy: 'نشان کپی رایت', ordf: 'Feminine ordinal indicator', // MISSING laquo: 'Left-pointing double angle quotation mark', // MISSING not: 'علامت ثبت نشده', reg: 'علامت ثبت شده', macr: 'Macron', // MISSING deg: 'نشان درجه', sup2: 'بالانویس دو', sup3: 'بالانویس سه', acute: 'لهجه غلیظ', micro: 'نشان مایکرو', para: 'Pilcrow sign', // MISSING middot: 'نقطه میانی', cedil: 'Cedilla', // MISSING sup1: 'Superscript one', // MISSING ordm: 'Masculine ordinal indicator', // MISSING raquo: 'نشان زاویهدار دوتایی نقل قول راست چین', frac14: 'Vulgar fraction one quarter', // MISSING frac12: 'Vulgar fraction one half', // MISSING frac34: 'Vulgar fraction three quarters', // MISSING iquest: 'Inverted question mark', // MISSING Agrave: 'Latin capital letter A with grave accent', // MISSING Aacute: 'Latin capital letter A with acute accent', // MISSING Acirc: 'Latin capital letter A with circumflex', // MISSING Atilde: 'Latin capital letter A with tilde', // MISSING Auml: 'Latin capital letter A with diaeresis', // MISSING Aring: 'Latin capital letter A with ring above', // MISSING AElig: 'Latin Capital letter Æ', // MISSING Ccedil: 'Latin capital letter C with cedilla', // MISSING Egrave: 'Latin capital letter E with grave accent', // MISSING Eacute: 'Latin capital letter E with acute accent', // MISSING Ecirc: 'Latin capital letter E with circumflex', // MISSING Euml: 'Latin capital letter E with diaeresis', // MISSING Igrave: 'Latin capital letter I with grave accent', // MISSING Iacute: 'Latin capital letter I with acute accent', // MISSING Icirc: 'Latin capital letter I with circumflex', // MISSING Iuml: 'Latin capital letter I with diaeresis', // MISSING ETH: 'Latin capital letter Eth', // MISSING Ntilde: 'Latin capital letter N with tilde', // MISSING Ograve: 'Latin capital letter O with grave accent', // MISSING Oacute: 'Latin capital letter O with acute accent', // MISSING Ocirc: 'Latin capital letter O with circumflex', // MISSING Otilde: 'Latin capital letter O with tilde', // MISSING Ouml: 'Latin capital letter O with diaeresis', // MISSING times: 'Multiplication sign', // MISSING Oslash: 'Latin capital letter O with stroke', // MISSING Ugrave: 'Latin capital letter U with grave accent', // MISSING Uacute: 'Latin capital letter U with acute accent', // MISSING Ucirc: 'Latin capital letter U with circumflex', // MISSING Uuml: 'Latin capital letter U with diaeresis', // MISSING Yacute: 'Latin capital letter Y with acute accent', // MISSING THORN: 'Latin capital letter Thorn', // MISSING szlig: 'Latin small letter sharp s', // MISSING agrave: 'Latin small letter a with grave accent', // MISSING aacute: 'Latin small letter a with acute accent', // MISSING acirc: 'Latin small letter a with circumflex', // MISSING atilde: 'Latin small letter a with tilde', // MISSING auml: 'Latin small letter a with diaeresis', // MISSING aring: 'Latin small letter a with ring above', // MISSING aelig: 'Latin small letter æ', // MISSING ccedil: 'Latin small letter c with cedilla', // MISSING egrave: 'Latin small letter e with grave accent', // MISSING eacute: 'Latin small letter e with acute accent', // MISSING ecirc: 'Latin small letter e with circumflex', // MISSING euml: 'Latin small letter e with diaeresis', // MISSING igrave: 'Latin small letter i with grave accent', // MISSING iacute: 'Latin small letter i with acute accent', // MISSING icirc: 'Latin small letter i with circumflex', // MISSING iuml: 'Latin small letter i with diaeresis', // MISSING eth: 'Latin small letter eth', // MISSING ntilde: 'Latin small letter n with tilde', // MISSING ograve: 'Latin small letter o with grave accent', // MISSING oacute: 'Latin small letter o with acute accent', // MISSING ocirc: 'Latin small letter o with circumflex', // MISSING otilde: 'Latin small letter o with tilde', // MISSING ouml: 'Latin small letter o with diaeresis', // MISSING divide: 'Division sign', // MISSING oslash: 'Latin small letter o with stroke', // MISSING ugrave: 'Latin small letter u with grave accent', // MISSING uacute: 'Latin small letter u with acute accent', // MISSING ucirc: 'Latin small letter u with circumflex', // MISSING uuml: 'Latin small letter u with diaeresis', // MISSING yacute: 'Latin small letter y with acute accent', // MISSING thorn: 'Latin small letter thorn', // MISSING yuml: 'Latin small letter y with diaeresis', // MISSING OElig: 'Latin capital ligature OE', // MISSING oelig: 'Latin small ligature oe', // MISSING '372': 'Latin capital letter W with circumflex', // MISSING '374': 'Latin capital letter Y with circumflex', // MISSING '373': 'Latin small letter w with circumflex', // MISSING '375': 'Latin small letter y with circumflex', // MISSING sbquo: 'Single low-9 quotation mark', // MISSING '8219': 'Single high-reversed-9 quotation mark', // MISSING bdquo: 'Double low-9 quotation mark', // MISSING hellip: 'Horizontal ellipsis', // MISSING trade: 'Trade mark sign', // MISSING '9658': 'Black right-pointing pointer', // MISSING bull: 'Bullet', // MISSING rarr: 'Rightwards arrow', // MISSING rArr: 'Rightwards double arrow', // MISSING hArr: 'جهتنمای دوتایی چپ به راست', diams: 'Black diamond suit', // MISSING asymp: 'تقریبا برابر با' });
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'specialchar', 'ku', { euro: 'نیشانه‌ی یۆرۆ', lsquo: 'نیشانه‌ی فاریزه‌ی سه‌رووژێری تاکی چه‌پ', rsquo: 'نیشانه‌ی فاریزه‌ی سه‌رووژێری تاکی ڕاست', ldquo: 'نیشانه‌ی فاریزه‌ی سه‌رووژێری دووهێنده‌ی چه‌پ', rdquo: 'نیشانه‌ی فاریزه‌ی سه‌رووژێری دووهێنده‌ی ڕاست', ndash: 'ته‌قه‌ڵی کورت', mdash: 'ته‌قه‌ڵی درێژ', iexcl: 'نیشانه‌ی هه‌ڵه‌وگێڕی سه‌رسوڕمێنه‌ر', cent: 'نیشانه‌ی سه‌نت', pound: 'نیشانه‌ی پاوه‌ند', curren: 'نیشانه‌ی دراو', yen: 'نیشانه‌ی یه‌نی ژاپۆنی', brvbar: 'شریتی ئه‌ستوونی پچڕاو', sect: 'نیشانه‌ی دوو s له‌سه‌ریه‌ك', uml: 'خاڵ', copy: 'نیشانه‌ی مافی چاپ', ordf: 'هێڵ له‌سه‌ر پیتی a', laquo: 'دوو تیری به‌دووایه‌کی چه‌پ', not: 'نیشانه‌ی نه‌خێر', reg: 'نیشانه‌ی R له‌ناو بازنه‌دا', macr: 'ماکڕوون', deg: 'نیشانه‌ی پله', sup2: 'سه‌رنووسی دوو', sup3: 'سه‌رنووسی سێ', acute: 'لاری تیژ', micro: 'نیشانه‌ی u لق درێژی چه‌پی خواروو', para: 'نیشانه‌یپه‌ڕه‌گراف', middot: 'ناوه‌ڕاستی خاڵ', cedil: 'نیشانه‌ی c ژێر چووکره‌', sup1: 'سه‌رنووسی یه‌ك', ordm: 'هێڵ له‌ژێر پیتی o', raquo: 'دوو تیری به‌دووایه‌کی ڕاست', frac14: 'یه‌ك له‌سه‌ر چووار', frac12: 'یه‌ك له‌سه‌ر دوو', frac34: 'سێ له‌سه‌ر چووار', iquest: 'هێمای هه‌ڵه‌وگێری پرسیار', Agrave: 'پیتی لاتینی A-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری لار', Aacute: 'پیتی لاتینی A-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری تیژ', Acirc: 'پیتی لاتینی A-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Atilde: 'پیتی لاتینی A-ی گه‌وره‌ له‌گه‌ڵ زه‌ڕه‌', Auml: 'پیتی لاتینی A-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Aring: 'پیتی لاتینی گه‌وره‌ی Å', AElig: 'پیتی لاتینی گه‌وره‌ی Æ', Ccedil: 'پیتی لاتینی C-ی گه‌وره‌ له‌گه‌ڵ ژێر چووکره‌', Egrave: 'پیتی لاتینی E-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری لار', Eacute: 'پیتی لاتینی E-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری تیژ', Ecirc: 'پیتی لاتینی E-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Euml: 'پیتی لاتینی E-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Igrave: 'پیتی لاتینی I-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری لار', Iacute: 'پیتی لاتینی I-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری تیژ', Icirc: 'پیتی لاتینی I-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Iuml: 'پیتی لاتینی I-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', ETH: 'پیتی لاتینی E-ی گه‌وره‌ی', Ntilde: 'پیتی لاتینی N-ی گه‌وره‌ له‌گه‌ڵ زه‌ڕه‌', Ograve: 'پیتی لاتینی O-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری لار', Oacute: 'پیتی لاتینی O-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری تیژ', Ocirc: 'پیتی لاتینی O-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Otilde: 'پیتی لاتینی O-ی گه‌وره‌ له‌گه‌ڵ زه‌ڕه‌', Ouml: 'پیتی لاتینی O-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', times: 'نیشانه‌ی لێکدان', Oslash: 'پیتی لاتینی گه‌وره‌ی Ø له‌گه‌ڵ هێمای دڵ وه‌ستان', Ugrave: 'پیتی لاتینی U-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری لار', Uacute: 'پیتی لاتینی U-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری تیژ', Ucirc: 'پیتی لاتینی U-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Uuml: 'پیتی لاتینی U-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', Yacute: 'پیتی لاتینی Y-ی گه‌وره‌ له‌گه‌ڵ ڕوومه‌تداری تیژ', THORN: 'پیتی لاتینی دڕکی گه‌وره', szlig: 'پیتی لاتنی نووك تیژی s', agrave: 'پیتی لاتینی a-ی بچووك له‌گه‌ڵ ڕوومه‌تداری لار', aacute: 'پیتی لاتینی a-ی بچووك له‌گه‌ڵ ڕوومه‌تداری تیژ', acirc: 'پیتی لاتینی a-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', atilde: 'پیتی لاتینی a-ی بچووك له‌گه‌ڵ زه‌ڕه‌', auml: 'پیتی لاتینی a-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', aring: 'پیتی لاتینی å-ی بچووك', aelig: 'پیتی لاتینی æ-ی بچووك', ccedil: 'پیتی لاتینی c-ی بچووك له‌گه‌ڵ ژێر چووکره‌', egrave: 'پیتی لاتینی e-ی بچووك له‌گه‌ڵ ڕوومه‌تداری لار', eacute: 'پیتی لاتینی e-ی بچووك له‌گه‌ڵ ڕوومه‌تداری تیژ', ecirc: 'پیتی لاتینی e-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', euml: 'پیتی لاتینی e-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', igrave: 'پیتی لاتینی i-ی بچووك له‌گه‌ڵ ڕوومه‌تداری لار', iacute: 'پیتی لاتینی i-ی بچووك له‌گه‌ڵ ڕوومه‌تداری تیژ', icirc: 'پیتی لاتینی i-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', iuml: 'پیتی لاتینی i-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', eth: 'پیتی لاتینی e-ی بچووك', ntilde: 'پیتی لاتینی n-ی بچووك له‌گه‌ڵ زه‌ڕه‌', ograve: 'پیتی لاتینی o-ی بچووك له‌گه‌ڵ ڕوومه‌تداری لار', oacute: 'پیتی لاتینی o-ی بچووك له‌گه‌ڵ ڕوومه‌تداری تیژ', ocirc: 'پیتی لاتینی o-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', otilde: 'پیتی لاتینی o-ی بچووك له‌گه‌ڵ زه‌ڕه‌', ouml: 'پیتی لاتینی o-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', divide: 'نیشانه‌ی دابه‌ش', oslash: 'پیتی لاتینی گه‌وره‌ی ø له‌گه‌ڵ هێمای دڵ وه‌ستان', ugrave: 'پیتی لاتینی u-ی بچووك له‌گه‌ڵ ڕوومه‌تداری لار', uacute: 'پیتی لاتینی u-ی بچووك له‌گه‌ڵ ڕوومه‌تداری تیژ', ucirc: 'پیتی لاتینی u-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', uuml: 'پیتی لاتینی u-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', yacute: 'پیتی لاتینی y-ی بچووك له‌گه‌ڵ ڕوومه‌تداری تیژ', thorn: 'پیتی لاتینی دڕکی بچووك', yuml: 'پیتی لاتینی y-ی بچووك له‌گه‌ڵ نیشانه‌ له‌سه‌ری', OElig: 'پیتی لاتینی گه‌وره‌ی پێکه‌وه‌نووسراوی OE', oelig: 'پیتی لاتینی بچووکی پێکه‌وه‌نووسراوی oe', '372': 'پیتی لاتینی W-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', '374': 'پیتی لاتینی Y-ی گه‌وره‌ له‌گه‌ڵ نیشانه‌ له‌سه‌ری', '373': 'پیتی لاتینی w-ی بچووکی له‌گه‌ڵ نیشانه‌ له‌سه‌ری', '375': 'پیتی لاتینی y-ی بچووکی له‌گه‌ڵ نیشانه‌ له‌سه‌ری', sbquo: 'نیشانه‌ی فاریزه‌ی نزم', '8219': 'نیشانه‌ی فاریزه‌ی به‌رزی پێچه‌وانه', bdquo: 'دوو فاریزه‌ی ته‌نیش یه‌ك', hellip: 'ئاسۆیی بازنه', trade: 'نیشانه‌ی بازرگانی', '9658': 'ئاراسته‌ی ڕه‌شی ده‌ستی ڕاست', bull: 'فیشه‌ك', rarr: 'تیری ده‌ستی ڕاست', rArr: 'دووتیری ده‌ستی ڕاست', hArr: 'دوو تیری ڕاست و چه‌پ', diams: 'ڕه‌شی پاقڵاوه‌یی', asymp: 'نیشانه‌ی یه‌کسانه' });
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-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'fa', { accessibilityHelp : { title : 'دستورالعملهای دسترسی', contents : 'راهنمای فهرست مطالب. برای بستن این کادر محاورهای ESC را فشار دهید.', legend : [ { name : 'عمومی', items : [ { name : 'نوار ابزار ویرایشگر', legend: '${toolbarFocus} را برای باز کردن نوار ابزار بفشارید. با کلید Tab و Shif-Tab در مجموعه نوار ابزار بعدی و قبلی حرکت کنید. برای حرکت در کلید نوار ابزار قبلی و بعدی با کلید جهتنمای راست و چپ جابجا شوید. کلید Space یا Enter را برای فعال کردن کلید نوار ابزار بفشارید.' }, { name : 'پنجره محاورهای ویرایشگر', legend : 'در داخل یک پنجره محاورهای، کلید Tab را بفشارید تا به پنجرهی بعدی بروید، Shift+Tab برای حرکت به فیلد قبلی، فشردن Enter برای ثبت اطلاعات پنجره، فشردن Esc برای لغو پنجره محاورهای و برای پنجرههایی که چندین برگه دارند، فشردن Alt+F10 جهت رفتن به Tab-List. در نهایت حرکت به برگه بعدی با Tab یا کلید جهتنمای راست. حرکت به برگه قبلی با Shift+Tab یا کلید جهتنمای چپ. فشردن Space یا Enter برای انتخاب یک برگه.' }, { name : 'منوی متنی ویرایشگر', legend : '${contextMenu} یا کلید برنامههای کاربردی را برای باز کردن منوی متن را بفشارید. سپس میتوانید برای حرکت به گزینه بعدی منو با کلید Tab و یا کلید جهتنمای پایین جابجا شوید. حرکت به گزینه قبلی با Shift+Tab یا کلید جهتنمای بالا. فشردن Space یا Enter برای انتخاب یک گزینه از منو. باز کردن زیر شاخه گزینه منو جاری با کلید Space یا Enter و یا کلید جهتنمای راست و چپ. بازگشت به منوی والد با کلید Esc یا کلید جهتنمای چپ. بستن منوی متن با Esc.' }, { name : 'جعبه فهرست ویرایشگر', legend : 'در داخل جعبه لیست، قلم دوم از اقلام لیست بعدی را با TAB و یا Arrow Down حرکت دهید. انتقال به قلم دوم از اقلام لیست قبلی را با SHIFT + TAB یا UP ARROW. کلید Space یا ENTER را برای انتخاب گزینه لیست بفشارید. کلید ESC را برای بستن جعبه لیست بفشارید.' }, { name : 'ویرایشگر عنصر نوار راه', legend : 'برای رفتن به مسیر عناصر ${elementsPathFocus} را بفشارید. حرکت به کلید عنصر بعدی با کلید Tab یا کلید جهتنمای راست. برگشت به کلید قبلی با Shift+Tab یا کلید جهتنمای چپ. فشردن Space یا Enter برای انتخاب یک عنصر در ویرایشگر.' } ] }, { name : 'فرمانها', items : [ { name : 'بازگشت فرمان', legend : 'فشردن ${undo}' }, { name : 'انجام مجدد فرمان', legend : 'فشردن ${redo}' }, { name : 'فرمان متن درشت', legend : 'فشردن ${bold}' }, { name : 'فرمان متن کج', legend : 'فشردن ${italic}' }, { name : 'فرمان متن زیرخطدار', legend : 'فشردن ${underline}' }, { name : 'فرمان پیوند', legend : 'فشردن ${link}' }, { name : 'بستن نوار ابزار فرمان', legend : 'فشردن ${toolbarCollapse}' }, { name : 'راهنمای دسترسی', legend : 'فشردن ${a11yHelp}' } ] } ] } });
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'ku', { accessibilityHelp : { title : 'ڕێنمای لەبەردەستدابوون', contents : 'پێکهاتەی یارمەتی. کلیك ESC بۆ داخستنی ئەم دیالۆگه.', legend : [ { name : 'گشتی', items : [ { name : 'تووڵامرازی ده‌ستكاریكه‌ر', legend: 'کلیك ${toolbarFocus} بۆ ڕابەری تووڵامراز. بۆ گواستنەوەی پێشوو داهاتووی گرووپی تووڵامرازی داگرتنی کلیلی TAB له‌گه‌ڵ‌ SHIFT-TAB. بۆ گواستنەوەی پێشوو داهاتووی دووگمەی تووڵامرازی لەڕێی کلیلی تیری دەستی ڕاست یان کلیلی تیری دەستی چەپ. کلیکی کلیلی SPACE یان ENTER بۆ چالاککردنی دووگمەی تووڵامراز.' }, { name : 'دیالۆگی ده‌ستكاریكه‌ر', legend : 'لەهەمانکاتدا کەتۆ لەدیالۆگی, کلیکی کلیلی TAB بۆ ڕابەری خانەی دیالۆگێکی تر, داگرتنی کلیلی SHIFT + TAB بۆ گواستنەوەی بۆ خانەی پێشووتر, کلیكی کلیلی ENTER بۆ ڕازیکردنی دیالۆگەکە, کلیكی کلیلی ESC بۆ هەڵوەشاندنەوەی دیالۆگەکە. بۆ دیالۆگی لەبازدەری (تابی) زیاتر, کلیكی کلیلی ALT + F10 بۆ ڕابه‌ری لیستی بازده‌ره‌کان. بۆ چوونه‌ بازده‌ری تابی داهاتوو کلیكی کلیلی TAB یان کلیلی تیری ده‌ستی ڕاست. بۆچوونه‌ بازده‌ری تابی پێشوو داگرتنی کلیلی SHIFT + TAB یان کلیلی تیری ده‌ستی چه‌پ. کلیی کلیلی SPACE یان ENTER بۆ هه‌ڵبژاردنی بازده‌ر (تاب).' }, { name : 'پێڕستی سه‌رنووسه‌ر', legend : 'کلیك ${contextMenu} یان دوگمه‌ی لیسته‌(Menu) بۆ کردنه‌وه‌ی لیسته‌ی ده‌ق. بۆ چوونه‌ هه‌ڵبژارده‌یه‌کی تر له‌ لیسته‌ کلیکی کلیلی TAB یان کلیلی تیری ڕوو له‌خواره‌وه‌ بۆ چوون بۆ هه‌ڵبژارده‌ی پێشوو کلیکی کلیلی SHIFT+TAB یان کلیلی تیری ڕوو له‌ سه‌ره‌وه. داگرتنی کلیلی SPACE یان ENTER بۆ هه‌ڵبژاردنی هه‌ڵبژارده‌ی لیسته‌. بۆ کردنه‌وه‌ی لقی ژێر لیسته‌ له‌هه‌ڵبژارده‌ی لیسته‌ کلیکی کلیلی SPACE یان ENTER یان کلیلی تیری ده‌ستی ڕاست. بۆ گه‌ڕانه‌وه بۆ سه‌ره‌وه‌ی لیسته‌ کلیکی کلیلی ESC یان کلیلی تیری ده‌ستی چه‌پ. بۆ داخستنی لیسته‌ کلیكی کلیلی ESC بکه.' }, { name : 'لیستی سنووقی سه‌رنووسه‌ر', legend : 'له‌ناو سنوقی لیست, چۆن بۆ هه‌ڵنبژارده‌ی لیستێکی تر کلیکی کلیلی TAB یان کلیلی تیری ڕوو له‌خوار. چوون بۆ هه‌ڵبژارده‌ی لیستی پێشوو کلیکی کلیلی SHIFT + TAB یان کلیلی تیری ڕوو له‌سه‌ره‌وه‌. کلیکی کلیلی SPACE یان ENTER بۆ دیاریکردنی ‌هه‌ڵبژارده‌ی لیست. کلیکی کلیلی ESC بۆ داخستنی سنوقی لیست.' }, { name : 'تووڵامرازی توخم', legend : 'کلیك ${elementsPathFocus} بۆ ڕابه‌ری تووڵامرازی توخمه‌کان. چوون بۆ دوگمه‌ی توخمێکی تر کلیکی کلیلی TAB یان کلیلی تیری ده‌ستی ڕاست. چوون بۆ دوگمه‌ی توخمی پێشوو کلیلی SHIFT+TAB یان کلیکی کلیلی تیری ده‌ستی چه‌پ. داگرتنی کلیلی SPACE یان ENTER بۆ دیاریکردنی توخمه‌که‌ له‌سه‌رنووسه.' } ] }, { name : 'فه‌رمانه‌کان', items : [ { name : 'فه‌رمانی پووچکردنه‌وه', legend : 'کلیك ${undo}' }, { name : 'فه‌رمانی هه‌ڵگه‌ڕانه‌وه', legend : 'کلیك ${redo}' }, { name : 'فه‌رمانی ده‌قی قه‌ڵه‌و', legend : 'کلیك ${bold}' }, { name : 'فه‌رمانی ده‌قی لار', legend : 'کلیك ${italic}' }, { name : 'فه‌رمانی ژێرهێڵ', legend : 'کلیك ${underline}' }, { name : 'فه‌رمانی به‌سته‌ر', legend : 'کلیك ${link}' }, { name : 'شارده‌نه‌وه‌ی تووڵامراز', legend : 'کلیك ${toolbarCollapse}' }, { name : 'ده‌ستپێگه‌یشتنی یارمه‌تی', legend : 'کلیك ${a11yHelp}' } ] } ] } });
JavaScript
$(document).ready(function() { $("#q").suggest("?m=search&c=index&a=public_get_suggest_keyword&url="+encodeURIComponent('http://www.google.cn/complete/search?hl=zh-CN&q='+$("#q").val()), { onSelect: function() { alert(this.value); } }); }); var google={ ac:{ h:function(results){ if(results[1].length > 0) { var data = '<ul>'; for (var i=0;i<results[1].length;i++) { if(results[1][i]==null || typeof(results[1][i])=='undefined') { } else { data += '<li><a href="javascript:;" onmousedown="s(\''+results[1][i][0]+'\')">'+results[1][i][0]+'</a></li>'; } } data += '</ul>'; $("#sr_infos").html(data); } else { $("#sr_infos").hide(); } } } }; function s(name) { $("#q").val(name); window.location.href='?m=search&c=index&a=init&q='+name; }
JavaScript
$(document).ready(function(){ //获取锚点即当前图片id var picid = location.hash; picid = picid.substring(1); if(isNaN(picid) || picid=='' || picid==null) { picid = 1; } picid = parseInt(picid); //图集图片总数 var totalnum = $("#pictureurls li").length; //如果当前图片id大于图片数,显示第一张图片 if(picid > totalnum || picid < 1) { picid = 1; next_picid = 1; //下一张图片id } else { next_picid = picid + 1; } url = $("#pictureurls li:nth-child("+picid+") img").attr("rel"); $("#big-pic").html("<img src='"+url+"' onload='loadpic("+next_picid+")'>"); $('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel')); $("#picnum").html("("+picid+"/"+totalnum+")"); $("#picinfo").html($("#pictureurls li:nth-child("+picid+") img").attr("alt")); $("#pictureurls li").click(function(){ i = $(this).index() + 1; showpic(i); }); //加载时图片滚动到中间 var _w = $('.cont li').width()*$('.cont li').length; if(picid>2) { movestep = picid - 3; } else { movestep = 0; } $(".cont ul").css({"left":-+$('.cont li').width()*movestep}); //点击图片滚动 $('.cont ul').width(_w); $(".cont li").click( function () { if($(this).index()>2){ movestep = $(this).index() - 2; $(".cont ul").css({"left":-+$('.cont li').width()*movestep}); } }); //当前缩略图添加样式 $("#pictureurls li:nth-child("+picid+")").addClass("on"); }); $(document).keyup(function(e) { var currKey=0,e=e||event; currKey=e.keyCode||e.which||e.charCode; switch(currKey) { case 37: // left showpic('pre'); break; case 39: // up showpic('next'); break; case 13: // enter var nextpicurl = $('#nextPicsBut').attr('href'); if(nextpicurl !== '' || nextpicurl !== 'null') { window.location=nextpicurl; } break; } }); function showpic(type, replay) { //隐藏重复播放div $("#endSelect").hide(); //图集图片总数 var totalnum = $("#pictureurls li").length; if(type=='next' || type=='pre') { //获取锚点即当前图片id var picid = location.hash; picid = picid.substring(1); if(isNaN(picid) || picid=='' || picid==null) { picid = 1; } picid = parseInt(picid); if(type=='next') { i = picid + 1; //如果是最后一张图片,指针指向第一张 if(i > totalnum) { $("#endSelect").show(); i=1; next_picid=1; //重新播放 if(replay!=1) { return false; } else { $("#endSelect").hide(); } } else { next_picid = parseInt(i) + 1; } } else if (type=='pre') { i = picid - 1; //如果是第一张图片,指针指向最后一张 if(i < 1) { i=totalnum; next_picid = totalnum; } else { next_picid = parseInt(i) - 1; } } url = $("#pictureurls li:nth-child("+i+") img").attr("rel"); $("#big-pic").html("<img src='"+url+"' onload='loadpic("+next_picid+")'>"); $('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel')); $("#picnum").html("("+i+"/"+totalnum+")"); $("#picinfo").html($("#pictureurls li:nth-child("+i+") img").attr("alt")); //更新锚点 location.hash = i; type = i; //点击图片滚动 var _w = $('.cont li').width()*$('.cont li').length; if(i>2) { movestep = i - 3; } else { movestep = 0; } $(".cont ul").css({"left":-+$('.cont li').width()*movestep}); } else if(type=='big') { //获取锚点即当前图片id var picid = location.hash; picid = picid.substring(1); if(isNaN(picid) || picid=='' || picid==null) { picid = 1; } picid = parseInt(picid); url = $("#pictureurls li:nth-child("+picid+") img").attr("rel"); window.open(url); } else { url = $("#pictureurls li:nth-child("+type+") img").attr("rel"); $("#big-pic").html("<img src='"+url+"'>"); $('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel')); $("#picnum").html("("+type+"/"+totalnum+")"); $("#picinfo").html($("#pictureurls li:nth-child("+type+") img").attr("alt")); location.hash = type; } $("#pictureurls li").each(function(i){ j = i+1; if(j==type) { $("#pictureurls li:nth-child("+j+")").addClass("on"); } else { $("#pictureurls li:nth-child("+j+")").removeClass(); } }); } //预加载图片 function loadpic(id) { url = $("#pictureurls li:nth-child("+id+") img").attr("rel"); $("#load_pic").html("<img src='"+url+"'>"); }
JavaScript
var regexEnum = { intege:"^-?[1-9]\\d*$", //整数 intege1:"^[1-9]\\d*$", //正整数 intege2:"^-[1-9]\\d*$", //负整数 num:"^([+-]?)\\d*\\.?\\d+$", //数字 num1:"^[1-9]\\d*|0$", //正数(正整数 + 0) num2:"^-[1-9]\\d*|0$", //负数(负整数 + 0) decmal:"^([+-]?)\\d*\\.\\d+$", //浮点数 decmal1:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$",   //正浮点数 decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$",  //负浮点数 decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$",  //浮点数 decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$",   //非负浮点数(正浮点数 + 0) decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$",  //非正浮点数(负浮点数 + 0) email:"^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件 color:"^[a-fA-F0-9]{6}$", //颜色 url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", //仅中文 ascii:"^[\\x00-\\xFF]+$", //仅ACSII字符 zipcode:"^\\d{6}$", //邮编 mobile:"^(1)[0-9]{10}$", //手机 ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$", //ip地址 notempty:"^\\S+$", //非空 picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片 rar:"(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件 date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期 qq:"^[1-9]*[1-9][0-9]*$", //QQ号码 tel:"^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", //电话号码的函数(包括验证国内区号,国际区号,分机号) username:"^\\w+$", //用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串 letter:"^[A-Za-z]+$", //字母 letter_u:"^[A-Z]+$", //大写字母 letter_l:"^[a-z]+$", //小写字母 idcard:"^[1-9]([0-9]{14}|[0-9]{17})$", //身份证 ps_username:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D_\\w]+$" //中文、字母、数字 _ } function isCardID(sId){ var iSum=0 ; var info="" ; if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误"; sId=sId.replace(/x$/i,"a"); if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法"; sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); var d=new Date(sBirthday.replace(/-/g,"/")) ; if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法"; for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ; if(iSum%11!=1) return "你输入的身份证号非法"; return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女") } //短时间,形如 (13:04:06) function isTime(str) { var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/); if (a == null) {return false} if (a[1]>24 || a[3]>60 || a[4]>60) { return false; } return true; } //短日期,形如 (2003-12-05) function isDate(str) { var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); if(r==null)return false; var d= new Date(r[1], r[3]-1, r[4]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]); } //长时间,形如 (2003-12-05 13:04:06) function isDateTime(str) { var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/; var r = str.match(reg); if(r==null) return false; var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]); }
JavaScript
$(document).ready(function(){ //获取锚点即当前图片id //var picid = location.hash; //picid = picid.substring(1); if(isNaN(picid) || picid=='' || picid==null) { picid = 1; } picid = parseInt(picid); //图集图片总数 var totalnum = $("#pictureurls li").length; //如果当前图片id大于图片数,显示第一张图片 if(picid > totalnum || picid < 1) { picid = 1; next_picid = 1; //下一张图片id } else { next_picid = picid + 1; } url = $("#pictureurls li:nth-child("+picid+") img").attr("rel"); $("#big-pic").html("<img src='"+url+"' onload='loadpic("+next_picid+")'>"); $('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel')); $("#picnum").html("("+picid+"/"+totalnum+")"); $("#picinfo").html($("#pictureurls li:nth-child("+picid+") img").attr("alt")); $("#pictureurls li").click(function(){ i = $(this).index() + 1; showpic(i); }); //加载时图片滚动到中间 var _w = $('.cont li').width()*$('.cont li').length; if(picid>2) { movestep = picid - 3; } else { movestep = 0; } $(".cont ul").css({"left":-+$('.cont li').width()*movestep}); //点击图片滚动 $('.cont ul').width(_w); $(".cont li").click( function () { if($(this).index()>2){ movestep = $(this).index() - 2; $(".cont ul").css({"left":-+$('.cont li').width()*movestep}); } }); //当前缩略图添加样式 $("#pictureurls li:nth-child("+picid+")").addClass("on"); }); $(document).keyup(function(e) { var currKey=0,e=e||event; currKey=e.keyCode||e.which||e.charCode; switch(currKey) { case 37: // left showpic('pre'); break; case 39: // up showpic('next'); break; case 13: // enter var nextpicurl = $('#nextPicsBut').attr('href'); if(nextpicurl !== '' || nextpicurl !== 'null') { window.location=nextpicurl; } break; } }); function showpic(type, replay) { //隐藏重复播放div $("#endSelect").hide(); //图集图片总数 var totalnum = $("#pictureurls li").length; if(type=='next' || type=='pre') { //获取锚点即当前图片id var picid = location.hash; picid = picid.substring(1); if(isNaN(picid) || picid=='' || picid==null) { picid = 1; } picid = parseInt(picid); if(type=='next') { i = picid + 1; //如果是最后一张图片,指针指向第一张 if(i > totalnum) { $("#endSelect").show(); i=1; next_picid=1; //重新播放 if(replay!=1) { return false; } else { $("#endSelect").hide(); } } else { next_picid = parseInt(i) + 1; } } else if (type=='pre') { i = picid - 1; //如果是第一张图片,指针指向最后一张 if(i < 1) { i=totalnum; next_picid = totalnum; } else { next_picid = parseInt(i) - 1; } } url = $("#pictureurls li:nth-child("+i+") img").attr("rel"); $("#big-pic").html("<img src='"+url+"' onload='loadpic("+next_picid+")'>"); $('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel')); $("#picnum").html("("+i+"/"+totalnum+")"); $("#picinfo").html($("#pictureurls li:nth-child("+i+") img").attr("alt")); //更新锚点 location.hash = i; type = i; //点击图片滚动 var _w = $('.cont li').width()*$('.cont li').length; if(i>2) { movestep = i - 3; } else { movestep = 0; } $(".cont ul").css({"left":-+$('.cont li').width()*movestep}); } else if(type=='big') { //获取锚点即当前图片id var picid = location.hash; picid = picid.substring(1); if(isNaN(picid) || picid=='' || picid==null) { picid = 1; } picid = parseInt(picid); url = $("#pictureurls li:nth-child("+picid+") img").attr("rel"); window.open(url); } else { url = $("#pictureurls li:nth-child("+type+") img").attr("rel"); $("#big-pic").html("<img src='"+url+"'>"); $('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel')); $("#picnum").html("("+type+"/"+totalnum+")"); $("#picinfo").html($("#pictureurls li:nth-child("+type+") img").attr("alt")); location.hash = type; } $("#pictureurls li").each(function(i){ j = i+1; if(j==type) { $("#pictureurls li:nth-child("+j+")").addClass("on"); } else { $("#pictureurls li:nth-child("+j+")").removeClass(); } }); } //预加载图片 function loadpic(id) { url = $("#pictureurls li:nth-child("+id+") img").attr("rel"); $("#load_pic").html("<img src='"+url+"'>"); }
JavaScript
/*! * artDialog 4.1.6 * Date: 2012-07-16 22:57 * http://code.google.com/p/artdialog/ * (c) 2009-2012 TangBin, http://www.planeArt.cn * * This is licensed under the GNU LGPL, version 2.1 or later. * For details, see: http://creativecommons.org/licenses/LGPL/2.1/ */ ;(function (window, undefined) { //if (window.jQuery) return jQuery; var $ = window.art = function (selector, context) { return new $.fn.init(selector, context); }, readyBound = false, readyList = [], DOMContentLoaded, isOpacity = 'opacity' in document.documentElement.style, quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, rclass = /[\n\t]/g, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/; if (window.$ === undefined) window.$ = $; $.fn = $.prototype = { constructor: $, /** * DOM 就绪 * @param {Function} 回调函数 */ ready: function (callback) { $.bindReady(); if ($.isReady) { callback.call(document, $); } else if (readyList) { readyList.push(callback); }; return this; }, /** * 判断样式类是否存在 * @param {String} 名称 * @return {Boolean} */ hasClass: function (name) { var className = ' ' + name + ' '; if ((' ' + this[0].className + ' ').replace(rclass, ' ') .indexOf(className) > -1) return true; return false; }, /** * 添加样式类 * @param {String} 名称 */ addClass: function (name) { if (!this.hasClass(name)) this[0].className += ' ' + name; return this; }, /** * 移除样式类 * @param {String} 名称 */ removeClass: function (name) { var elem = this[0]; if (!name) { elem.className = ''; } else if (this.hasClass(name)) { elem.className = elem.className.replace(name, ' '); }; return this; }, /** * 读写样式<br /> * css(name) 访问第一个匹配元素的样式属性<br /> * css(properties) 把一个"名/值对"对象设置为所有匹配元素的样式属性<br /> * css(name, value) 在所有匹配的元素中,设置一个样式属性的值<br /> */ css: function (name, value) { var i, elem = this[0], obj = arguments[0]; if (typeof name === 'string') { if (value === undefined) { return $.css(elem, name); } else { name === 'opacity' ? $.opacity.set(elem, value) : elem.style[name] = value; }; } else { for (i in obj) { i === 'opacity' ? $.opacity.set(elem, obj[i]) : elem.style[i] = obj[i]; }; }; return this; }, /** 显示元素 */ show: function () { return this.css('display', 'block'); }, /** 隐藏元素 */ hide: function () { return this.css('display', 'none'); }, /** * 获取相对文档的坐标 * @return {Object} 返回left、top的数值 */ offset: function () { var elem = this[0], box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || docElem.scrollTop) - clientTop, left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft; return { left: left, top: top }; }, /** * 读写HTML - (不支持文本框) * @param {String} 内容 */ html: function (content) { var elem = this[0]; if (content === undefined) return elem.innerHTML; $.cleanData(elem.getElementsByTagName('*')); elem.innerHTML = content; return this; }, /** * 移除节点 */ remove: function () { var elem = this[0]; $.cleanData(elem.getElementsByTagName('*')); $.cleanData([elem]); elem.parentNode.removeChild(elem); return this; }, /** * 事件绑定 * @param {String} 类型 * @param {Function} 要绑定的函数 */ bind: function (type, callback) { $.event.add(this[0], type, callback); return this; }, /** * 移除事件 * @param {String} 类型 * @param {Function} 要卸载的函数 */ unbind: function(type, callback) { $.event.remove(this[0], type, callback); return this; } }; $.fn.init = function (selector, context) { var match, elem; context = context || document; if (!selector) return this; if (selector.nodeType) { this[0] = selector; return this; }; if (selector === 'body' && context.body) { this[0] = context.body; return this; }; if (selector === 'head' || selector === 'html') { this[0] = context.getElementsByTagName(selector)[0]; return this; }; if (typeof selector === 'string') { match = quickExpr.exec(selector); if (match && match[2]) { elem = context.getElementById(match[2]); if (elem && elem.parentNode) this[0] = elem; return this; }; }; if (typeof selector === 'function') return $(document).ready(selector); this[0] = selector; return this; }; $.fn.init.prototype = $.fn; /** 空函数 */ $.noop = function () {}; /** 检测window */ $.isWindow = function (obj) { return obj && typeof obj === 'object' && 'setInterval' in obj; }; /** 数组判定 */ $.isArray = function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; /** * 搜索子元素 * 注意:只支持nodeName或.className的形式,并且只返回第一个元素 * @param {String} */ $.fn.find = function (expr) { var value, elem = this[0], className = expr.split('.')[1]; if (className) { if (document.getElementsByClassName) { value = elem.getElementsByClassName(className); } else { value = getElementsByClassName(className, elem); }; } else { value = elem.getElementsByTagName(expr); }; return $(value[0]); }; function getElementsByClassName (className, node, tag) { node = node || document; tag = tag || '*'; var i = 0, j = 0, classElements = [], els = node.getElementsByTagName(tag), elsLen = els.length, pattern = new RegExp("(^|\\s)" + className + "(\\s|$)"); for (; i < elsLen; i ++) { if (pattern.test(els[i].className)) { classElements[j] = els[i]; j ++; }; }; return classElements; }; /** * 遍历 * @param {Object} * @param {Function} */ $.each = function (obj, callback) { var name, i = 0, length = obj.length, isObj = length === undefined; if (isObj) { for (name in obj) { if (callback.call(obj[name], name, obj[name]) === false) break; }; } else { for (var value = obj[0]; i < length && callback.call(value, i, value) !== false; value = obj[++i]) {}; }; return obj; }; /** * 读写缓存 * @param {HTMLElement} 元素 * @param {String} 缓存名称 * @param {Any} 数据 * @return {Any} 如果无参数data则返回缓存数据 */ $.data = function (elem, name, data) { var cache = $.cache, id = uuid(elem); if (name === undefined) return cache[id]; if (!cache[id]) cache[id] = {}; if (data !== undefined) cache[id][name] = data; return cache[id][name]; }; /** * 删除缓存 * @param {HTMLElement} 元素 * @param {String} 缓存名称 */ $.removeData = function (elem, name) { var empty = true, expando = $.expando, cache = $.cache, id = uuid(elem), thisCache = id && cache[id]; if (!thisCache) return; if (name) { delete thisCache[name]; for (var n in thisCache) empty = false; if (empty) delete $.cache[id]; } else { delete cache[id]; if (elem.removeAttribute) { elem.removeAttribute(expando); } else { elem[expando] = null; }; }; }; $.uuid = 0; $.cache = {}; $.expando = '@cache' + + new Date // 标记元素唯一身份 function uuid (elem) { var expando = $.expando, id = elem === window ? 0 : elem[expando]; if (id === undefined) elem[expando] = id = ++ $.uuid; return id; }; /** * 事件机制 * @namespace * @requires [$.data, $.removeData] */ $.event = { /** * 添加事件 * @param {HTMLElement} 元素 * @param {String} 事件类型 * @param {Function} 要添加的函数 */ add: function (elem, type, callback) { var cache, listeners, that = $.event, data = $.data(elem, '@events') || $.data(elem, '@events', {}); cache = data[type] = data[type] || {}; listeners = cache.listeners = cache.listeners || []; listeners.push(callback); if (!cache.handler) { cache.elem = elem; cache.handler = that.handler(cache); elem.addEventListener ? elem.addEventListener(type, cache.handler, false) : elem.attachEvent('on' + type, cache.handler); }; }, /** * 卸载事件 * @param {HTMLElement} 元素 * @param {String} 事件类型 * @param {Function} 要卸载的函数 */ remove: function (elem, type, callback) { var i, cache, listeners, that = $.event, empty = true, data = $.data(elem, '@events'); if (!data) return; if (!type) { for (i in data) that.remove(elem, i); return; }; cache = data[type]; if (!cache) return; listeners = cache.listeners; if (callback) { for (i = 0; i < listeners.length; i ++) { listeners[i] === callback && listeners.splice(i--, 1); }; } else { cache.listeners = []; }; if (cache.listeners.length === 0) { elem.removeEventListener ? elem.removeEventListener(type, cache.handler, false) : elem.detachEvent('on' + type, cache.handler); delete data[type]; cache = $.data(elem, '@events'); for (var n in cache) empty = false; if (empty) $.removeData(elem, '@events'); }; }, /** @inner 事件句柄 */ handler: function (cache) { return function (event) { event = $.event.fix(event || window.event); for (var i = 0, list = cache.listeners, fn; fn = list[i++];) { if (fn.call(cache.elem, event) === false) { event.preventDefault(); event.stopPropagation(); }; }; }; }, /** @inner Event对象兼容处理 */ fix: function (event) { if (event.target) return event; var event2 = { target: event.srcElement || document, preventDefault: function () {event.returnValue = false}, stopPropagation: function () {event.cancelBubble = true} }; // IE6/7/8 在原生window.event对象写入数据会导致内存无法回收,应当采用拷贝 for (var i in event) event2[i] = event[i]; return event2; } }; /** * 清理元素集的事件与缓存 * @requires [$.removeData, $.event] * @param {HTMLCollection} 元素集 */ $.cleanData = function (elems) { var i = 0, elem, len = elems.length, removeEvent = $.event.remove, removeData = $.removeData; for (; i < len; i ++) { elem = elems[i]; removeEvent(elem); removeData(elem); }; }; // DOM就绪事件 $.isReady = false; $.ready = function () { if (!$.isReady) { if (!document.body) return setTimeout($.ready, 13); $.isReady = true; if (readyList) { var fn, i = 0; while ((fn = readyList[i++])) { fn.call(document, $); }; readyList = null; }; }; }; $.bindReady = function () { if (readyBound) return; readyBound = true; if (document.readyState === 'complete') { return $.ready(); }; if (document.addEventListener) { document.addEventListener('DOMContentLoaded', DOMContentLoaded, false); window.addEventListener('load', $.ready, false); } else if (document.attachEvent) { document.attachEvent('onreadystatechange', DOMContentLoaded); window.attachEvent('onload', $.ready); var toplevel = false; try { toplevel = window.frameElement == null; } catch (e) {}; if (document.documentElement.doScroll && toplevel) { doScrollCheck(); }; }; }; if (document.addEventListener) { DOMContentLoaded = function () { document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false); $.ready(); }; } else if (document.attachEvent) { DOMContentLoaded = function () { if (document.readyState === 'complete') { document.detachEvent('onreadystatechange', DOMContentLoaded); $.ready(); }; }; }; function doScrollCheck () { if ($.isReady) return; try { document.documentElement.doScroll('left'); } catch (e) { setTimeout(doScrollCheck, 1); return; }; $.ready(); }; // 获取css $.css = 'defaultView' in document && 'getComputedStyle' in document.defaultView ? function (elem, name) { return document.defaultView.getComputedStyle(elem, false)[name]; } : function (elem, name) { var ret = name === 'opacity' ? $.opacity.get(elem) : elem.currentStyle[name]; return ret || ''; }; // 跨浏览器处理opacity $.opacity = { get: function (elem) { return isOpacity ? document.defaultView.getComputedStyle(elem, false).opacity : ropacity.test((elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || '') ? (parseFloat(RegExp.$1) / 100) + '' : 1; }, set: function (elem, value) { if (isOpacity) return elem.style.opacity = value; var style = elem.style; style.zoom = 1; var opacity = 'alpha(opacity=' + value * 100 + ')', filter = style.filter || ''; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : style.filter + ' ' + opacity; } }; /** * 获取滚动条位置 - [不支持写入] * $.fn.scrollLeft, $.fn.scrollTop * @example 获取文档垂直滚动条:$(document).scrollTop() * @return {Number} 返回滚动条位置 */ $.each(['Left', 'Top'], function (i, name) { var method = 'scroll' + name; $.fn[method] = function () { var elem = this[0], win; win = getWindow(elem); return win ? ('pageXOffset' in win) ? win[i ? 'pageYOffset' : 'pageXOffset'] : win.document.documentElement[method] || win.document.body[method] : elem[method]; }; }); function getWindow (elem) { return $.isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; }; /** * 获取窗口或文档尺寸 - [只支持window与document读取] * @example 获取文档宽度:$(document).width() 获取可视范围:$(window).width() * @return {Number} */ $.each(['Height', 'Width'], function (i, name) { var type = name.toLowerCase(); $.fn[type] = function (size) { var elem = this[0]; if (!elem) { return size == null ? null : this; }; return $.isWindow(elem) ? elem.document.documentElement['client' + name] || elem.document.body['client' + name] : (elem.nodeType === 9) ? Math.max( elem.documentElement['client' + name], elem.body['scroll' + name], elem.documentElement['scroll' + name], elem.body['offset' + name], elem.documentElement['offset' + name] ) : null; }; }); /** * 简单ajax支持 * @example * $.ajax({ * url: url, * success: callback, * cache: cache * }); */ $.ajax = function (config) { var ajax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'), url = config.url; if (config.cache === false) { var ts = + new Date, ret = url.replace(/([?&])_=[^&]*/, "$1_=" + ts ); url = ret + ((ret === url) ? (/\?/.test(url) ? "&" : "?") + "_=" + ts : ""); }; ajax.onreadystatechange = function() { if (ajax.readyState === 4 && ajax.status === 200) { config.success && config.success(ajax.responseText); ajax.onreadystatechange = $.noop; }; }; ajax.open('GET', url, 1); ajax.send(null); }; /** 动画引擎 - [不支持链式列队操作] */ $.fn.animate = function (prop, speed, easing, callback) { speed = speed || 400; if (typeof easing === 'function') callback = easing; easing = easing && $.easing[easing] ? easing : 'swing'; var elem = this[0], overflow, fx, parts, start, end, unit, opt = { speed: speed, easing: easing, callback: function () { if (overflow != null) elem.style.overflow = ''; callback && callback(); } }; opt.curAnim = {}; $.each(prop, function (name, val) { opt.curAnim[name] = val; }); $.each(prop, function (name, val) { fx = new $.fx(elem, opt, name); parts = rfxnum.exec(val); start = parseFloat(name === 'opacity' || (elem.style && elem.style[name] != null) ? $.css(elem, name) : elem[name]); end = parseFloat(parts[2]); unit = parts[3]; if (name === 'height' || name === 'width') { end = Math.max(0, end); overflow = [elem.style.overflow, elem.style.overflowX, elem.style.overflowY]; }; fx.custom(start, end, unit); }); if (overflow != null) elem.style.overflow = 'hidden'; return this; }; $.timers = []; $.fx = function (elem, options, prop) { this.elem = elem; this.options = options; this.prop = prop; }; $.fx.prototype = { custom: function (from, to, unit) { var that = this; that.startTime = $.fx.now(); that.start = from; that.end = to; that.unit = unit; that.now = that.start; that.state = that.pos = 0; function t() { return that.step(); }; t.elem = that.elem; t(); $.timers.push(t); if (!$.timerId) $.timerId = setInterval($.fx.tick, 13); }, step: function () { var that = this, t = $.fx.now(), done = true; if (t >= that.options.speed + that.startTime) { that.now = that.end; that.state = that.pos = 1; that.update(); that.options.curAnim[that.prop] = true; for (var i in that.options.curAnim) { if (that.options.curAnim[i] !== true) { done = false; }; }; if (done) that.options.callback.call(that.elem); return false; } else { var n = t - that.startTime; that.state = n / that.options.speed; that.pos = $.easing[that.options.easing](that.state, n, 0, 1, that.options.speed); that.now = that.start + ((that.end - that.start) * that.pos); that.update(); return true; }; }, update: function () { var that = this; if (that.prop === 'opacity') { $.opacity.set(that.elem, that.now); } else if (that.elem.style && that.elem.style[that.prop] != null) { that.elem.style[that.prop] = that.now + that.unit; } else { that.elem[that.prop] = that.now; }; } }; $.fx.now = function () { return + new Date; }; $.easing = { linear: function (p, n, firstNum, diff) { return firstNum + diff * p; }, swing: function (p, n, firstNum, diff) { return ((-Math.cos(p * Math.PI) / 2) + 0.5) * diff + firstNum; } }; $.fx.tick = function () { var timers = $.timers; for (var i = 0; i < timers.length; i++) { !timers[i]() && timers.splice(i--, 1); }; !timers.length && $.fx.stop(); }; $.fx.stop = function () { clearInterval($.timerId); $.timerId = null; }; $.fn.stop = function () { var timers = $.timers; for (var i = timers.length - 1; i >= 0; i--) { if (timers[i].elem === this[0]) timers.splice(i, 1); }; return this; }; //-------------end return $}(window)); //------------------------------------------------ // 对话框模块 //------------------------------------------------ ;(function ($, window, undefined) { $.noop = $.noop || function () {}; // jQuery 1.3.2 var _box, _thisScript, _skin, _path, _count = 0, _$window = $(window), _$document = $(document), _$html = $('html'), _elem = document.documentElement, _isIE6 = window.VBArray && !window.XMLHttpRequest, _isMobile = 'createTouch' in document && !('onmousemove' in _elem) || /(iPhone|iPad|iPod)/i.test(navigator.userAgent), _expando = 'artDialog' + + new Date; var artDialog = function (config, ok, cancel) { config = config || {}; if (typeof config === 'string' || config.nodeType === 1) { config = {content: config, fixed: !_isMobile}; }; var api, defaults = artDialog.defaults, elem = config.follow = this.nodeType === 1 && this || config.follow; // 合并默认配置 for (var i in defaults) { if (config[i] === undefined) config[i] = defaults[i]; }; // 兼容v4.1.0之前的参数,未来版本将删除此 $.each({ok:"yesFn",cancel:"noFn",close:"closeFn",init:"initFn",okVal:"yesText",cancelVal:"noText"}, function(i,o){config[i]=config[i]!==undefined?config[i]:config[o]}); // 返回跟随模式或重复定义的ID if (typeof elem === 'string') elem = $(elem)[0]; config.id = elem && elem[_expando + 'follow'] || config.id || _expando + _count; api = artDialog.list[config.id]; if (elem && api) return api.follow(elem).zIndex().focus(); art.PHPCMS_API = art.PHPCMS_API || []; var that_Api = art.PHPCMS_API[config.id]; if (typeof that_Api == 'object' && api) { api.data = {}; api.data.iframe = that_Api }; if (api) return api.zIndex().focus(); // 目前主流移动设备对fixed支持不好 if (_isMobile) config.fixed = false; // 按钮队列 if (!$.isArray(config.button)) { config.button = config.button ? [config.button] : []; }; if (ok !== undefined) config.ok = ok; if (cancel !== undefined) config.cancel = cancel; config.ok && config.button.push({ name: config.okVal, callback: config.ok, focus: true }); config.cancel && config.button.push({ name: config.cancelVal, callback: config.cancel }); // zIndex全局配置 artDialog.defaults.zIndex = config.zIndex; _count ++; return artDialog.list[config.id] = _box ? _box._init(config) : new artDialog.fn._init(config); }; artDialog.fn = artDialog.prototype = { version: '4.1.6', closed: true, _init: function (config) { var that = this, DOM, icon = config.icon, iconBg = icon && (_isIE6 ? {png: 'icons/' + icon + '.png'} : {backgroundImage: 'url(\'' + config.path + '/skins/icons/' + icon + '.png\')'}); that.closed = false; that.config = config; that.DOM = DOM = that.DOM || that._getDOM(); DOM.wrap.addClass(config.skin); DOM.close[config.cancel === false ? 'hide' : 'show'](); DOM.icon[0].style.display = icon ? '' : 'none'; DOM.iconBg.css(iconBg || {background: 'none'}); DOM.se.css('cursor', config.resize ? 'se-resize' : 'auto'); DOM.title.css('cursor', config.drag ? 'move' : 'auto'); DOM.content.css('padding', config.padding); that[config.show ? 'show' : 'hide'](true) that.button(config.button) .title(config.title) .content(config.content, config.iframe) .size(config.width, config.height) .time(config.time); config.follow ? that.follow(config.follow) : that.position(config.left, config.top); that.zIndex().focus(); config.lock && that.lock(); that._addEvent(); that._ie6PngFix(); _box = null; config.init && config.init.call(that, window); return that; }, /** * 设置内容 * @param {String, HTMLElement} 内容 (可选) * @return {this, HTMLElement} 如果无参数则返回内容容器DOM对象 */ content: function (msg,url) { var prev, next, parent, display, that = this, DOM = that.DOM, wrap = DOM.wrap[0], width = wrap.offsetWidth, height = wrap.offsetHeight, left = parseInt(wrap.style.left), top = parseInt(wrap.style.top), cssWidth = wrap.style.width, $content = DOM.content, content = $content[0]; that._reset(1); iframe = null, isIframe = typeof url == 'string' && url != '', iframrId = 'atrDialogIframe_' + that.config.id; if (isIframe) { if (typeof pc_hash == 'string') url += (url.indexOf('?') > -1 ? '&': '?') + 'pc_hash=' + pc_hash; iframe = document.createElement('iframe'); iframe.setAttribute("frameborder", 0, 0); iframe.setAttribute("width", that.config.width); iframe.setAttribute("height", that.config.height); iframe.setAttribute("padding", '0'); iframe.setAttribute("id", iframrId); iframe.src = url; that.DOM.content.css('padding', "5px 0px"); that.DOM.content.css('height', that.config.height); msg = iframe; }; that._elemBack && that._elemBack(); wrap.style.width = 'auto'; if (msg === undefined) return content; if (typeof msg === 'string') { $content.html(msg); } else if (msg && msg.nodeType === 1) { // 让传入的元素在对话框关闭后可以返回到原来的地方 display = msg.style.display; prev = msg.previousSibling; next = msg.nextSibling; parent = msg.parentNode; that._elemBack = function () { if (prev && prev.parentNode) { prev.parentNode.insertBefore(msg, prev.nextSibling); } else if (next && next.parentNode) { next.parentNode.insertBefore(msg, next); } else if (parent) { parent.appendChild(msg); }; msg.style.display = display; that._elemBack = null; }; $content.html(''); content.appendChild(msg); msg.style.display = 'block'; //content.focus(); //alert('1'); if (isIframe) art.PHPCMS_API[that.config.id] = msg.contentWindow }; // 新增内容后调整位置 if (!arguments[1]) { if (that.config.follow) { that.follow(that.config.follow); } else { width = wrap.offsetWidth - width; height = wrap.offsetHeight - height; left = left - width / 2; top = top - height / 2; wrap.style.left = Math.max(left, 0) + 'px'; wrap.style.top = Math.max(top, 0) + 'px'; }; if (cssWidth && cssWidth !== 'auto') { wrap.style.width = wrap.offsetWidth + 'px'; }; that._autoPositionType(); }; that._ie6SelectFix(); that._runScript(content); return that; }, /** * 设置标题 * @param {String, Boolean} 标题内容. 为false则隐藏标题栏 * @return {this, HTMLElement} 如果无参数则返回内容器DOM对象 */ title: function (text) { var DOM = this.DOM, wrap = DOM.wrap, title = DOM.title, className = 'aui_state_noTitle'; if (text === undefined) return title[0]; if (text === false) { title.hide().html(''); wrap.addClass(className); } else { title.show().html(text || ''); wrap.removeClass(className); }; return this; }, /** * 位置(相对于可视区域) * @param {Number, String} * @param {Number, String} */ position: function (left, top) { var that = this, config = that.config, wrap = that.DOM.wrap[0], isFixed = _isIE6 ? false : config.fixed, ie6Fixed = _isIE6 && that.config.fixed, docLeft = _$document.scrollLeft(), docTop = _$document.scrollTop(), dl = isFixed ? 0 : docLeft, dt = isFixed ? 0 : docTop, ww = _$window.width(), wh = _$window.height(), ow = wrap.offsetWidth, oh = wrap.offsetHeight, style = wrap.style; if (left || left === 0) { that._left = left.toString().indexOf('%') !== -1 ? left : null; left = that._toNumber(left, ww - ow); if (typeof left === 'number') { left = ie6Fixed ? (left += docLeft) : left + dl; style.left = Math.max(left, dl) + 'px'; } else if (typeof left === 'string') { style.left = left; }; }; if (top || top === 0) { that._top = top.toString().indexOf('%') !== -1 ? top : null; top = that._toNumber(top, wh - oh); if (typeof top === 'number') { top = ie6Fixed ? (top += docTop) : top + dt; style.top = Math.max(top, dt) + 'px'; } else if (typeof top === 'string') { style.top = top; }; }; if (left !== undefined && top !== undefined) { that._follow = null; that._autoPositionType(); }; return that; }, /** * 尺寸 * @param {Number, String} 宽度 * @param {Number, String} 高度 */ size: function (width, height) { var maxWidth, maxHeight, scaleWidth, scaleHeight, that = this, config = that.config, DOM = that.DOM, wrap = DOM.wrap, main = DOM.main, wrapStyle = wrap[0].style, style = main[0].style; if (width) { that._width = width.toString().indexOf('%') !== -1 ? width : null; maxWidth = _$window.width() - wrap[0].offsetWidth + main[0].offsetWidth; scaleWidth = that._toNumber(width, maxWidth); width = scaleWidth; if (typeof width === 'number') { wrapStyle.width = 'auto'; style.width = Math.max(that.config.minWidth, width) + 'px'; wrapStyle.width = wrap[0].offsetWidth + 'px'; // 防止未定义宽度的表格遇到浏览器右边边界伸缩 } else if (typeof width === 'string') { style.width = width; width === 'auto' && wrap.css('width', 'auto'); }; }; if (height) { that._height = height.toString().indexOf('%') !== -1 ? height : null; maxHeight = _$window.height() - wrap[0].offsetHeight + main[0].offsetHeight; scaleHeight = that._toNumber(height, maxHeight); height = scaleHeight; //alert(height); if (typeof height === 'number') { style.height = Math.max(that.config.minHeight, height) + 'px'; } else if (typeof height === 'string') { style.height = height; //height === 'auto' && wrap.css('height', 'auto'); }; }; that._ie6SelectFix(); return that; }, /** * 跟随元素 * @param {HTMLElement, String} */ follow: function (elem) { var $elem, that = this, config = that.config; if (typeof elem === 'string' || elem && elem.nodeType === 1) { $elem = $(elem); elem = $elem[0]; }; // 隐藏元素不可用 if (!elem || !elem.offsetWidth && !elem.offsetHeight) { return that.position(that._left, that._top); }; var expando = _expando + 'follow', winWidth = _$window.width(), winHeight = _$window.height(), docLeft = _$document.scrollLeft(), docTop = _$document.scrollTop(), offset = $elem.offset(), width = elem.offsetWidth, height = elem.offsetHeight, isFixed = _isIE6 ? false : config.fixed, left = isFixed ? offset.left - docLeft : offset.left, top = isFixed ? offset.top - docTop : offset.top, wrap = that.DOM.wrap[0], style = wrap.style, wrapWidth = wrap.offsetWidth, wrapHeight = wrap.offsetHeight, setLeft = left - (wrapWidth - width) / 2, setTop = top + height, dl = isFixed ? 0 : docLeft, dt = isFixed ? 0 : docTop; setLeft = setLeft < dl ? left : (setLeft + wrapWidth > winWidth) && (left - wrapWidth > dl) ? left - wrapWidth + width : setLeft; setTop = (setTop + wrapHeight > winHeight + dt) && (top - wrapHeight > dt) ? top - wrapHeight : setTop; style.left = setLeft + 'px'; style.top = setTop + 'px'; that._follow && that._follow.removeAttribute(expando); that._follow = elem; elem[expando] = config.id; that._autoPositionType(); return that; }, /** * 自定义按钮 * @example button({ name: 'login', callback: function () {}, disabled: false, focus: true }, .., ..) */ button: function () { var that = this, ags = arguments, DOM = that.DOM, buttons = DOM.buttons, elem = buttons[0], strongButton = 'aui_state_highlight', listeners = that._listeners = that._listeners || {}, list = $.isArray(ags[0]) ? ags[0] : [].slice.call(ags); if (ags[0] === undefined) return elem; $.each(list, function (i, val) { var name = val.name, isNewButton = !listeners[name], button = !isNewButton ? listeners[name].elem : document.createElement('button'); if (!listeners[name]) listeners[name] = {}; if (val.callback) listeners[name].callback = val.callback; if (val.className) button.className = val.className; if (val.focus) { that._focus && that._focus.removeClass(strongButton); that._focus = $(button).addClass(strongButton); that.focus(); }; // Internet Explorer 的默认类型是 "button", // 而其他浏览器中(包括 W3C 规范)的默认值是 "submit" // @see http://www.w3school.com.cn/tags/att_button_type.asp button.setAttribute('type', 'button'); button[_expando + 'callback'] = name; button.disabled = !!val.disabled; if (isNewButton) { button.innerHTML = name; listeners[name].elem = button; elem.appendChild(button); }; }); buttons[0].style.display = list.length ? '' : 'none'; that._ie6SelectFix(); return that; }, /** 显示对话框 */ show: function () { this.DOM.wrap.show(); !arguments[0] && this._lockMaskWrap && this._lockMaskWrap.show(); return this; }, /** 隐藏对话框 */ hide: function () { this.DOM.wrap.hide(); !arguments[0] && this._lockMaskWrap && this._lockMaskWrap.hide(); return this; }, /** 关闭对话框 */ close: function () { if (this.closed) return this; var that = this, DOM = that.DOM, wrap = DOM.wrap, list = artDialog.list, fn = that.config.close, follow = that.config.follow; that.time(); if (typeof fn === 'function' && fn.call(that, window) === false) { return that; }; that.unlock(); // 置空内容 that._elemBack && that._elemBack(); wrap[0].className = wrap[0].style.cssText = ''; DOM.title.html(''); DOM.content.html(''); DOM.buttons.html(''); if (artDialog.focus === that) artDialog.focus = null; if (follow) follow.removeAttribute(_expando + 'follow'); delete list[that.config.id]; that._removeEvent(); that.hide(true)._setAbsolute(); // 清空除this.DOM之外临时对象,恢复到初始状态,以便使用单例模式 for (var i in that) { if (that.hasOwnProperty(i)) delete that[i]; }; // 移除HTMLElement或重用 _box ? wrap.remove() : _box = that; return that; }, /** * 定时关闭 * @param {Number} 单位为秒, 无参数则停止计时器 */ time: function (second) { var that = this, cancel = that.config.cancelVal, timer = that._timer; timer && clearTimeout(timer); if (second) { that._timer = setTimeout(function(){ that._click(cancel); }, 1000 * second); }; return that; }, /** 设置焦点 */ focus: function () { try { var elem = this._focus && this._focus[0] || this.DOM.close[0]; elem && elem.focus(); } catch (e) {}; // IE对不可见元素设置焦点会报错 return this; }, /** 置顶对话框 */ zIndex: function () { var that = this, DOM = that.DOM, wrap = DOM.wrap, top = artDialog.focus, index = artDialog.defaults.zIndex ++; // 设置叠加高度 wrap.css('zIndex', index); that._lockMask && that._lockMask.css('zIndex', index - 1); // 设置最高层的样式 top && top.DOM.wrap.removeClass('aui_state_focus'); artDialog.focus = that; wrap.addClass('aui_state_focus'); return that; }, /** 设置屏锁 */ lock: function () { if (this._lock) return this; var that = this, index = artDialog.defaults.zIndex - 1, wrap = that.DOM.wrap, config = that.config, docWidth = _$document.width(), docHeight = _$document.height(), lockMaskWrap = that._lockMaskWrap || $(document.body.appendChild(document.createElement('div'))), lockMask = that._lockMask || $(lockMaskWrap[0].appendChild(document.createElement('div'))), domTxt = '(document).documentElement', sizeCss = _isMobile ? 'width:' + docWidth + 'px;height:' + docHeight + 'px' : 'width:100%;height:100%', ie6Css = _isIE6 ? 'position:absolute;left:expression(' + domTxt + '.scrollLeft);top:expression(' + domTxt + '.scrollTop);width:expression(' + domTxt + '.clientWidth);height:expression(' + domTxt + '.clientHeight)' : ''; that.zIndex(); wrap.addClass('aui_state_lock'); lockMaskWrap[0].style.cssText = sizeCss + ';position:fixed;z-index:' + index + ';top:0;left:0;overflow:hidden;' + ie6Css; lockMask[0].style.cssText = 'height:100%;background:' + config.background + ';filter:alpha(opacity=0);opacity:0'; // 让IE6锁屏遮罩能够盖住下拉控件 if (_isIE6) lockMask.html( '<iframe src="about:blank" style="width:100%;height:100%;position:absolute;' + 'top:0;left:0;z-index:-1;filter:alpha(opacity=0)"></iframe>'); lockMask.stop(); lockMask.bind('click', function () { that._reset(); }).bind('dblclick', function () { that._click(that.config.cancelVal); }); if (config.duration === 0) { lockMask.css({opacity: config.opacity}); } else { lockMask.animate({opacity: config.opacity}, config.duration); }; that._lockMaskWrap = lockMaskWrap; that._lockMask = lockMask; that._lock = true; return that; }, /** 解开屏锁 */ unlock: function () { var that = this, lockMaskWrap = that._lockMaskWrap, lockMask = that._lockMask; if (!that._lock) return that; var style = lockMaskWrap[0].style; var un = function () { if (_isIE6) { style.removeExpression('width'); style.removeExpression('height'); style.removeExpression('left'); style.removeExpression('top'); }; style.cssText = 'display:none'; _box && lockMaskWrap.remove(); }; lockMask.stop().unbind(); that.DOM.wrap.removeClass('aui_state_lock'); if (!that.config.duration) {// 取消动画,快速关闭 un(); } else { lockMask.animate({opacity: 0}, that.config.duration, un); }; that._lock = false; return that; }, // 获取元素 _getDOM: function () { var wrap = document.createElement('div'), body = document.body; wrap.style.cssText = 'position:absolute;left:0;top:0'; wrap.innerHTML = artDialog._templates; body.insertBefore(wrap, body.firstChild); var name, i = 0, DOM = {wrap: $(wrap)}, els = wrap.getElementsByTagName('*'), elsLen = els.length; for (; i < elsLen; i ++) { name = els[i].className.split('aui_')[1]; if (name) DOM[name] = $(els[i]); }; return DOM; }, // px与%单位转换成数值 (百分比单位按照最大值换算) // 其他的单位返回原值 _toNumber: function (thisValue, maxValue) { if (!thisValue && thisValue !== 0 || typeof thisValue === 'number') { return thisValue; }; var last = thisValue.length - 1; if (thisValue.lastIndexOf('px') === last) { thisValue = parseInt(thisValue); } else if (thisValue.lastIndexOf('%') === last) { thisValue = parseInt(maxValue * thisValue.split('%')[0] / 100); }; return thisValue; }, // 让IE6 CSS支持PNG背景 _ie6PngFix: _isIE6 ? function () { var i = 0, elem, png, pngPath, runtimeStyle, path = artDialog.defaults.path + '/skins/', list = this.DOM.wrap[0].getElementsByTagName('*'); for (; i < list.length; i ++) { elem = list[i]; png = elem.currentStyle['png']; if (png) { pngPath = path + png; runtimeStyle = elem.runtimeStyle; runtimeStyle.backgroundImage = 'none'; runtimeStyle.filter = "progid:DXImageTransform.Microsoft." + "AlphaImageLoader(src='" + pngPath + "',sizingMethod='crop')"; }; }; } : $.noop, // 强制覆盖IE6下拉控件 _ie6SelectFix: _isIE6 ? function () { var $wrap = this.DOM.wrap, wrap = $wrap[0], expando = _expando + 'iframeMask', iframe = $wrap[expando], width = wrap.offsetWidth, height = wrap.offsetHeight; width = width + 'px'; height = height + 'px'; if (iframe) { iframe.style.width = width; iframe.style.height = height; } else { iframe = wrap.appendChild(document.createElement('iframe')); $wrap[expando] = iframe; iframe.src = 'about:blank'; iframe.style.cssText = 'position:absolute;z-index:-1;left:0;top:0;' + 'filter:alpha(opacity=0);width:' + width + ';height:' + height; }; } : $.noop, // 解析HTML片段中自定义类型脚本,其this指向artDialog内部 // <script type="text/dialog">/* [code] */</script> _runScript: function (elem) { var fun, i = 0, n = 0, tags = elem.getElementsByTagName('script'), length = tags.length, script = []; for (; i < length; i ++) { if (tags[i].type === 'text/dialog') { script[n] = tags[i].innerHTML; n ++; }; }; if (script.length) { script = script.join(''); fun = new Function(script); fun.call(this); }; }, // 自动切换定位类型 _autoPositionType: function () { this[this.config.fixed ? '_setFixed' : '_setAbsolute']();///////////// }, // 设置静止定位 // IE6 Fixed @see: http://www.planeart.cn/?p=877 _setFixed: (function () { _isIE6 && $(function () { var bg = 'backgroundAttachment'; if (_$html.css(bg) !== 'fixed' && $('body').css(bg) !== 'fixed') { _$html.css({ zoom: 1,// 避免偶尔出现body背景图片异常的情况 backgroundImage: 'url(about:blank)', backgroundAttachment: 'fixed' }); }; }); return function () { var $elem = this.DOM.wrap, style = $elem[0].style; if (_isIE6) { var left = parseInt($elem.css('left')), top = parseInt($elem.css('top')), sLeft = _$document.scrollLeft(), sTop = _$document.scrollTop(), txt = '(document.documentElement)'; this._setAbsolute(); style.setExpression('left', 'eval(' + txt + '.scrollLeft + ' + (left - sLeft) + ') + "px"'); style.setExpression('top', 'eval(' + txt + '.scrollTop + ' + (top - sTop) + ') + "px"'); } else { style.position = 'fixed'; }; }; }()), // 设置绝对定位 _setAbsolute: function () { var style = this.DOM.wrap[0].style; if (_isIE6) { style.removeExpression('left'); style.removeExpression('top'); }; style.position = 'absolute'; }, // 按钮回调函数触发 _click: function (name) { var that = this, fn = that._listeners[name] && that._listeners[name].callback; return typeof fn !== 'function' || fn.call(that, window) !== false ? that.close() : that; }, // 重置位置与尺寸 _reset: function (test) { var newSize, that = this, oldSize = that._winSize || _$window.width() * _$window.height(), elem = that._follow, width = that._width, height = that._height, left = that._left, top = that._top; if (test) { // IE6~7 window.onresize bug newSize = that._winSize = _$window.width() * _$window.height(); if (oldSize === newSize) return; }; if (width || height) that.size(width, height); if (elem) { that.follow(elem); } else if (left || top) { that.position(left, top); }; }, // 事件代理 _addEvent: function () { var resizeTimer, that = this, config = that.config, isIE = 'CollectGarbage' in window, DOM = that.DOM; // 窗口调节事件 that._winResize = function () { resizeTimer && clearTimeout(resizeTimer); resizeTimer = setTimeout(function () { that._reset(isIE); }, 40); }; _$window.bind('resize', that._winResize); // 监听点击 DOM.wrap .bind('click', function (event) { var target = event.target, callbackID; if (target.disabled) return false; // IE BUG if (target === DOM.close[0]) { that._click(config.cancelVal); return false; } else { callbackID = target[_expando + 'callback']; callbackID && that._click(callbackID); }; that._ie6SelectFix(); }) .bind('mousedown', function () { that.zIndex(); }); }, // 卸载事件代理 _removeEvent: function () { var that = this, DOM = that.DOM; DOM.wrap.unbind(); _$window.unbind('resize', that._winResize); } }; artDialog.fn._init.prototype = artDialog.fn; $.fn.dialog = $.fn.artDialog = function () { var config = arguments; this[this.live ? 'live' : 'bind']('click', function () { artDialog.apply(this, config); return false; }); return this; }; /** 最顶层的对话框API */ artDialog.focus = null; /** 获取某对话框API */ artDialog.get = function (id) { return id === undefined ? artDialog.list : artDialog.list[id]; }; artDialog.list = {}; // 全局快捷键 _$document.bind('keydown', function (event) { var target = event.target, nodeName = target.nodeName, rinput = /^INPUT|TEXTAREA$/, api = artDialog.focus, keyCode = event.keyCode; if (!api || !api.config.esc || rinput.test(nodeName)) return; keyCode === 27 && api._click(api.config.cancelVal); }); // 获取artDialog路径 _path = window['_artDialog_path'] || (function (script, i, me) { for (i in script) { // 如果通过第三方脚本加载器加载本文件,请保证文件名含有"artDialog"字符 if (script[i].src && script[i].src.indexOf('artDialog') !== -1) me = script[i]; }; _thisScript = me || script[script.length - 1]; me = _thisScript.src.replace(/\\/g, '/'); return me.lastIndexOf('/') < 0 ? '.' : me.substring(0, me.lastIndexOf('/')); }(document.getElementsByTagName('script'))); // 无阻塞载入CSS (如"artDialog.js?skin=aero") _skin = _thisScript.src.split('skin=')[1]; if (_skin) { var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = _path + '/skins/' + _skin + '.css?' + artDialog.fn.version; _thisScript.parentNode.insertBefore(link, _thisScript); }; // 触发浏览器预先缓存背景图片 _$window.bind('load', function () { setTimeout(function () { if (_count) return; artDialog({left: '-9999em',time: 9,fixed: false,lock: false,focus: false}); }, 150); }); // 开启IE6 CSS背景图片缓存 try { document.execCommand('BackgroundImageCache', false, true); } catch (e) {}; // 使用uglifyjs压缩能够预先处理"+"号合并字符串 // uglifyjs: http://marijnhaverbeke.nl/uglifyjs artDialog._templates = '<div class="aui_outer">' + '<table class="aui_border">' + '<tbody>' + '<tr>' + '<td class="aui_nw"></td>' + '<td class="aui_n"></td>' + '<td class="aui_ne"></td>' + '</tr>' + '<tr>' + '<td class="aui_w"></td>' + '<td class="aui_c">' + '<div class="aui_inner">' + '<table class="aui_dialog">' + '<tbody>' + '<tr>' + '<td colspan="2" class="aui_header">' + '<div class="aui_titleBar">' + '<div class="aui_title"></div>' + '<a class="aui_close" href="javascript:/*artDialog*/;">' + '\xd7' + '</a>' + '</div>' + '</td>' + '</tr>' + '<tr>' + '<td class="aui_icon">' + '<div class="aui_iconBg"></div>' + '</td>' + '<td class="aui_main">' + '<div class="aui_content"></div>' + '</td>' + '</tr>' + '<tr>' + '<td colspan="2" class="aui_footer">' + '<div class="aui_buttons"></div>' + '</td>' + '</tr>' + '</tbody>' + '</table>' + '</div>' + '</td>' + '<td class="aui_e"></td>' + '</tr>' + '<tr>' + '<td class="aui_sw"></td>' + '<td class="aui_s"></td>' + '<td class="aui_se"></td>' + '</tr>' + '</tbody>' + '</table>' +'</div>'; /** * 默认配置 */ artDialog.defaults = { // 消息内容 content: '<div class="aui_loading"><span>loading..</span></div>', title: '\u6d88\u606f', // 标题. 默认'消息' button: null, // 自定义按钮 ok: null, // 确定按钮回调函数 cancel: null, // 取消按钮回调函数 init: null, // 对话框初始化后执行的函数 close: null, // 对话框关闭前执行的函数 okVal: '\u786E\u5B9A', // 确定按钮文本. 默认'确定' cancelVal: '\u53D6\u6D88', // 取消按钮文本. 默认'取消' width: 'auto', // 内容宽度 height: 'auto', // 内容高度 minWidth: 96, // 最小宽度限制 minHeight: 32, // 最小高度限制 padding: '20px 25px', // 内容与边界填充距离 skin: '', // 皮肤名(预留接口,尚未实现) icon: null, // 消息图标名称 time: null, // 自动关闭时间 esc: true, // 是否支持Esc键关闭 focus: true, // 是否支持对话框按钮自动聚焦 show: true, // 初始化后是否显示对话框 follow: null, // 跟随某元素(即让对话框在元素附近弹出) path: _path, // artDialog路径 lock: true, // 是否锁屏 background: '#000', // 遮罩颜色 opacity: .7, // 遮罩透明度 duration: 300, // 遮罩透明度渐变动画速度 fixed: false, // 是否静止定位 left: '50%', // X轴坐标 top: '38.2%', // Y轴坐标 zIndex: 1987, // 对话框叠加高度值(重要:此值不能超过浏览器最大限制) resize: true, // 是否允许用户调节尺寸 drag: true // 是否允许用户拖动位置 }; window.artDialog = $.dialog = $.artDialog = artDialog; }(this.art || this.jQuery && (this.art = jQuery), this)); //------------------------------------------------ // 对话框模块-拖拽支持(可选外置模块) //------------------------------------------------ ;(function ($) { var _dragEvent, _use, _$window = $(window), _$document = $(document), _elem = document.documentElement, _isIE6 = !('minWidth' in _elem.style), _isLosecapture = 'onlosecapture' in _elem, _isSetCapture = 'setCapture' in _elem; // 拖拽事件 artDialog.dragEvent = function () { var that = this, proxy = function (name) { var fn = that[name]; that[name] = function () { return fn.apply(that, arguments); }; }; proxy('start'); proxy('move'); proxy('end'); }; artDialog.dragEvent.prototype = { // 开始拖拽 onstart: $.noop, start: function (event) { _$document .bind('mousemove', this.move) .bind('mouseup', this.end); this._sClientX = event.clientX; this._sClientY = event.clientY; this.onstart(event.clientX, event.clientY); return false; }, // 正在拖拽 onmove: $.noop, move: function (event) { this._mClientX = event.clientX; this._mClientY = event.clientY; this.onmove( event.clientX - this._sClientX, event.clientY - this._sClientY ); return false; }, // 结束拖拽 onend: $.noop, end: function (event) { _$document .unbind('mousemove', this.move) .unbind('mouseup', this.end); this.onend(event.clientX, event.clientY); return false; } }; _use = function (event) { var limit, startWidth, startHeight, startLeft, startTop, isResize, api = artDialog.focus, //config = api.config, DOM = api.DOM, wrap = DOM.wrap, title = DOM.title, main = DOM.main; // 清除文本选择 var clsSelect = 'getSelection' in window ? function () { window.getSelection().removeAllRanges(); } : function () { try { document.selection.empty(); } catch (e) {}; }; // 对话框准备拖动 _dragEvent.onstart = function (x, y) { if (isResize) { startWidth = main[0].offsetWidth; startHeight = main[0].offsetHeight; } else { startLeft = wrap[0].offsetLeft; startTop = wrap[0].offsetTop; }; _$document.bind('dblclick', _dragEvent.end); !_isIE6 && _isLosecapture ? title.bind('losecapture', _dragEvent.end) : _$window.bind('blur', _dragEvent.end); _isSetCapture && title[0].setCapture(); wrap.addClass('aui_state_drag'); api.focus(); }; // 对话框拖动进行中 _dragEvent.onmove = function (x, y) { if (isResize) { var wrapStyle = wrap[0].style, style = main[0].style, width = x + startWidth, height = y + startHeight; wrapStyle.width = 'auto'; style.width = Math.max(0, width) + 'px'; wrapStyle.width = wrap[0].offsetWidth + 'px'; style.height = Math.max(0, height) + 'px'; } else { var style = wrap[0].style, left = Math.max(limit.minX, Math.min(limit.maxX, x + startLeft)), top = Math.max(limit.minY, Math.min(limit.maxY, y + startTop)); style.left = left + 'px'; style.top = top + 'px'; }; clsSelect(); api._ie6SelectFix(); }; // 对话框拖动结束 _dragEvent.onend = function (x, y) { _$document.unbind('dblclick', _dragEvent.end); !_isIE6 && _isLosecapture ? title.unbind('losecapture', _dragEvent.end) : _$window.unbind('blur', _dragEvent.end); _isSetCapture && title[0].releaseCapture(); _isIE6 && !api.closed && api._autoPositionType(); wrap.removeClass('aui_state_drag'); }; isResize = event.target === DOM.se[0] ? true : false; limit = (function () { var maxX, maxY, wrap = api.DOM.wrap[0], fixed = wrap.style.position === 'fixed', ow = wrap.offsetWidth, oh = wrap.offsetHeight, ww = _$window.width(), wh = _$window.height(), dl = fixed ? 0 : _$document.scrollLeft(), dt = fixed ? 0 : _$document.scrollTop(), // 坐标最大值限制 maxX = ww - ow + dl; maxY = wh - oh + dt; return { minX: dl, minY: dt, maxX: maxX, maxY: maxY }; })(); _dragEvent.start(event); }; // 代理 mousedown 事件触发对话框拖动 _$document.bind('mousedown', function (event) { var api = artDialog.focus; if (!api) return; var target = event.target, config = api.config, DOM = api.DOM; if (config.drag !== false && target === DOM.title[0] || config.resize !== false && target === DOM.se[0]) { _dragEvent = _dragEvent || new artDialog.dragEvent(); _use(event); return false;// 防止firefox与chrome滚屏 }; }); })(this.art || this.jQuery && (this.art = jQuery));
JavaScript
var phpcms_path = '/'; var cookie_pre = 'sYQDUGqqzH'; var cookie_domain = ''; var cookie_path = '/'; function getcookie(name) { name = cookie_pre+name; var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while(i < clen) { var j = i + alen; if(document.cookie.substring(i, j) == arg) return getcookieval(j); i = document.cookie.indexOf(" ", i) + 1; if(i == 0) break; } return null; } function setcookie(name, value, days) { name = cookie_pre+name; var argc = setcookie.arguments.length; var argv = setcookie.arguments; var secure = (argc > 5) ? argv[5] : false; var expire = new Date(); if(days==null || days==0) days=1; expire.setTime(expire.getTime() + 3600000*24*days); document.cookie = name + "=" + escape(value) + ("; path=" + cookie_path) + ((cookie_domain == '') ? "" : ("; domain=" + cookie_domain)) + ((secure == true) ? "; secure" : "") + ";expires="+expire.toGMTString(); } function delcookie(name) { var exp = new Date(); exp.setTime (exp.getTime() - 1); var cval = getcookie(name); name = cookie_pre+name; document.cookie = name+"="+cval+";expires="+exp.toGMTString(); } function getcookieval(offset) { var endstr = document.cookie.indexOf (";", offset); if(endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); }
JavaScript
var ColorHex=new Array('00','33','66','99','CC','FF') var SpColorHex=new Array('FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF') var current=null var colorTable='' function colorpicker(showid,fun) { for (i=0;i<2;i++) { for (j=0;j<6;j++) { colorTable=colorTable+'<tr height=12>' colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\'000\')" onclick="select_color(\''+showid+'\',\'000\','+fun+')" style="background-color:#000">' if (i==0){ colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\''+ColorHex[j]+ColorHex[j]+ColorHex[j]+'\')" onclick="select_color(\''+showid+'\',\''+ColorHex[j]+ColorHex[j]+ColorHex[j]+'\','+fun+')" style="background-color:#'+ColorHex[j]+ColorHex[j]+ColorHex[j]+'">' } else { colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\''+SpColorHex[j]+'\')" onclick="select_color(\''+showid+'\',\''+SpColorHex[j]+'\','+fun+')" style="background-color:#'+SpColorHex[j]+'">'} colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\'000\')" onclick="select_color(\''+showid+'\',\'000\','+fun+')" style="background-color:#000">' for (k=0;k<3;k++) { for (l=0;l<6;l++) { colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\''+ColorHex[k+i*3]+ColorHex[l]+ColorHex[j]+'\')" onclick="select_color(\''+showid+'\',\''+ColorHex[k+i*3]+ColorHex[l]+ColorHex[j]+'\','+fun+')" style="background-color:#'+ColorHex[k+i*3]+ColorHex[l]+ColorHex[j]+'">' } } } } colorTable='<div style="position:relative;width:253px; height:176px"><a href="javascript:;" onclick="closeBox();" class="close-own">X</a><table width=253 border="0" cellspacing="0" cellpadding="0" style="border:1px #000 solid;border-bottom:none;border-collapse: collapse" bordercolor="000000">' +'<tr height=30><td colspan=21 bgcolor=#eeeeee>' +'<table cellpadding="0" cellspacing="1" border="0" style="border-collapse: collapse">' +'<tr><td width="3"><td><input type="text" name="DisColor" size="6" id="background_colorId" disabled style="border:solid 1px #000000;background-color:#ffff00"></td>' +'<td width="3"><td><input type="text" name="HexColor" size="7" id="input_colorId" style="border:inset 1px;font-family:Arial;" value="#000000"></td><td><a href="javascript:;" onclick="clear_title();"> clear</a></td></tr></table></td></table>' +'<table border="1" cellspacing="0" cellpadding="0" style="border-collapse: collapse" bordercolor="000000" style="cursor:hand;">' +colorTable+'</table></div>'; $('#'+showid).html(colorTable); colorTable = ''; } function onmouseover_color(color) { var color = '#'+color; $('#background_colorId').css('background-color',color); $('#input_colorId').val(color); } function select_color(showid,color,fun) { var color = '#'+color; //$('#title').css('color',color); if(fun) { fun.apply(this,[color]); } $('#'+showid).html(' '); } function closeBox(){ $(".colorpanel").html(' '); } function clear_title() { $('#title').css('color',''); $('#title_colorpanel').html(' '); }
JavaScript
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject = function() { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
function checkradio(radio) { var result = false; for(var i=0; i<radio.length; i++) { if(radio[i].checked) { result = true; break; } } return result; } function checkselect(select) { var result = false; for(var i=0;i<select.length;i++) { if(select[i].selected && select[i].value!='' && select[i].value!=0) { result = true; break; } } return result; } var set_show = false; jQuery.fn.checkFormorder = function(m,func){ mode = (m==1) ? 1 : 0; var form=jQuery(this); var elements = form.find('input[require],select[require],textarea[require]'); elements.blur(function(index){ return validator.check(jQuery(this)); }); form.submit(function(){ var ok = true; var errIndex= new Array(); var n=0; elements.each(function(i){ if(validator.check(jQuery(this))==false){ ok = false; errIndex[n++]=i; }; }); if(ok==false){ elements.eq(errIndex[0]).focus().select(); return false; } if(document.getElementById('video_uploader') && !upLoading) { uploadFile(); return false; } if($('#f_filed_1') && set_show==false) { $("select[@id=catids] option").each(function() { $(this).attr('selected','selected'); }); } if($('#hava_checked').val()==0) { YP_checkform(); return false; } func(); return false; }); }
JavaScript
jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? '; path=' + options.path : ''; var domain = options.domain ? '; domain=' + options.domain : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/* *改变加入清单的图片事件和图片显示 */ function ChangStatus(){ var player_list ; var list_array= new Array(); player_list = getcookie('player_list'); if(player_list!=""){ list_array = player_list.split("|"); if(list_array.length>0){ for(var i=0;i<list_array.length;i++) { var player; player=list_array[i].split("@"); $("a[contentid='"+player[2]+"']").removeClass("j"); $("a[contentid='"+player[2]+"']").addClass("j2"); } } } } function toggle(object) { var url = $(object).attr("href"); var title = $(object).attr("title"); var id = $(object).attr("contentid"); var catid = $(object).attr("catid"); var isCookieExist; isCookieExist = getcookie('player_list'); if(!isCookieExist){ var new_player = url+'@'+title+'@'+id+'@'+catid; player_list = new_player; } else{ var player_list = getcookie('player_list'); //判断是否已经存在 if(player_list.indexOf(id)!=-1){ //已经加入播放菜单则设置COOKIE,直接跳转至播放页面 var list_array = player_list.split("|"); var player=new Array(); for(var i=0;i<list_array.length;i++) { player = list_array[i].split("@"); if(id == player[2]){ setcookie('now',i); window.open(player[0],'_blank'); } } return false; } var new_player = '|'+url+'@'+title+'@'+id+'@'+catid; player_list +=new_player; } //改变图片样式,并且去掉onclick函数 setcookie('player_list',player_list,1); $("a[contentid='"+id+"']").removeClass("j"); $("a[contentid='"+id+"']").addClass("j2"); $("a[contentid='"+id+"']").unbind("click"); return false; }
JavaScript
/* * sGallery 1.0 - simple gallery with jQuery * made by bujichong 2009-11-25 * 作者:不羁虫 2009-11-25 * http://hi.baidu.com/bujichong/ * 欢迎交流转载,但请尊重作者劳动成果,标明插件来源及作者 */ (function ($) { $.fn.sGallery = function (o) { return new $sG(this, o); //alert('do'); }; var settings = { thumbObj:null,//预览对象 titleObj:null,//标题 botLast:null,//按钮上一个 botNext:null,//按钮下一个 thumbNowClass:'now',//预览对象当前的class,默认为now slideTime:800,//平滑过渡时间 autoChange:true,//是否自动切换 changeTime:5000,//自动切换时间 delayTime:100//鼠标经过时反应的延迟时间 }; $.sGalleryLong = function(e, o) { this.options = $.extend({}, settings, o || {}); var _self = $(e); var set = this.options; var thumb; var size = _self.size(); var nowIndex = 0; //定义全局指针 var index;//定义全局指针 var startRun;//预定义自动运行参数 var delayRun;//预定义延迟运行参数 //初始化 _self.eq(0).show(); //主切换函数 function fadeAB () { if (nowIndex != index) { if (set.thumbObj!=null) { $(set.thumbObj).removeClass().eq(index).addClass(set.thumbNowClass);} _self.eq(nowIndex).stop(false,true).fadeOut(set.slideTime); _self.eq(index).stop(true,true).fadeIn(set.slideTime); $(set.titleObj).eq(nowIndex).hide();//新增加title $(set.titleObj).eq(index).show();//新增加title nowIndex = index; if (set.autoChange==true) { clearInterval(startRun);//重置自动切换函数 startRun = setInterval(runNext,set.changeTime);} } } //切换到下一个 function runNext() { index = (nowIndex+1)%size; fadeAB(); } //点击任一图片 if (set.thumbObj!=null) { thumb = $(set.thumbObj); //初始化 thumb.eq(0).addClass(set.thumbNowClass); thumb.bind("mousemove",function(event){ index = thumb.index($(this)); fadeAB(); delayRun = setTimeout(fadeAB,set.delayTime); clearTimeout(delayRun); event.stopPropagation(); }) } //点击上一个 if (set.botNext!=null) { var botNext = $(set.botNext); botNext.mousemove(function () { runNext(); return false; }); } //点击下一个 if (set.botLast!=null) { var botLast = $(set.botLast); botLast.mousemove(function () { index = (nowIndex+size-1)%size; fadeAB(); return false; }); } //自动运行 if (set.autoChange==true) { startRun = setInterval(runNext,set.changeTime); } } var $sG = $.sGalleryLong; })(jQuery); function slide(Name,Class,Width,Height,fun){ $(Name).width(Width); $(Name).height(Height); if(fun == true){ $(Name).append('<div class="title-bg"></div><div class="title"></div><div class="change"></div>') var atr = $(Name+' div.changeDiv a'); var sum = atr.length; for(i=1;i<=sum;i++){ var title = atr.eq(i-1).attr("title"); var href = atr.eq(i-1).attr("href"); $(Name+' .change').append('<i>'+i+'</i>'); $(Name+' .title').append('<a href="'+href+'">'+title+'</a>'); } $(Name+' .change i').eq(0).addClass('cur'); } $(Name+' div.changeDiv a').sGallery({//对象指向层,层内包含图片及标题 titleObj:Name+' div.title a', thumbObj:Name+' .change i', thumbNowClass:Class }); $(Name+" .title-bg").width(Width); } //缩略图 jQuery.fn.LoadImage=function(scaling,width,height,loadpic){ if(loadpic==null)loadpic="../images/msg_img/loading.gif"; return this.each(function(){ var t=$(this); var src=$(this).attr("src") var img=new Image(); img.src=src; //自动缩放图片 var autoScaling=function(){ if(scaling){ if(img.width>0 && img.height>0){ if(img.width/img.height>=width/height){ if(img.width>width){ t.width(width); t.height((img.height*width)/img.width); }else{ t.width(img.width); t.height(img.height); } } else{ if(img.height>height){ t.height(height); t.width((img.width*height)/img.height); }else{ t.width(img.width); t.height(img.height); } } } } } //处理ff下会自动读取缓存图片 if(img.complete){ autoScaling(); return; } $(this).attr("src",""); var loading=$("<img alt=\"加载中...\" title=\"图片加载中...\" src=\""+loadpic+"\" />"); t.hide(); t.after(loading); $(img).load(function(){ autoScaling(); loading.remove(); t.attr("src",this.src); t.show(); //$('.photo_prev a,.photo_next a').height($('#big-pic img').height()); }); }); } //向上滚动代码 function startmarquee(elementID,h,n,speed,delay){ var t = null; var box = '#' + elementID; $(box).hover(function(){ clearInterval(t); }, function(){ t = setInterval(start,delay); }).trigger('mouseout'); function start(){ $(box).children('ul:first').animate({marginTop: '-='+h},speed,function(){ $(this).css({marginTop:'0'}).find('li').slice(0,n).appendTo(this); }) } } //TAB切换 function SwapTab(name,title,content,Sub,cur){ $(name+' '+title).mouseover(function(){ $(this).addClass(cur).siblings().removeClass(cur); $(content+" > "+Sub).eq($(name+' '+title).index(this)).show().siblings().hide(); }); }
JavaScript
//方法 function strToJson(str){ var json = eval('(' + str + ')'); return json; } function showAuto() { n = n >=(count - 1) ? 0 : ++n; $("#banner li").eq(n).trigger('click'); } function hit_love(catid,id,hid) { var hid = hid ? hid : '#number_'; var n = 2;n++; $(hid+id).html(n); } function hit_love(catid,id,mid,hid,username){ if(username=='') { alert('您还没登陆!'); return false; } var hid = hid ? hid : '#number_'; var saveid = GetCookie('loveid'); valueid = 'l-'+id+'-'+mid; /* if (saveid == valueid) { alert("您已经喜欢过了O(∩_∩)O哈哈~"); } else{}*/ $.get("/index.php?m=content&c=love&a=love", { modelid:mid, catid: catid, id:id}, function (r){ $(hid+id).html(r); }); SetCookie('loveid',valueid,1); } function fensi(username,uid,show,n) { if(show) { alert('不能关注自己!'); return false; } $.get("/index.php?m=member&c=space&a=guanzu1", { username:encodeURIComponent(username), uid:uid, n:n}, function (r){ if(r==3) { alert('您还没登陆!'); return false; } else if(r==2) { $('#guanzhu').html('已关注!'); } else { $('#guanzhu').html(r); return false; } }); } function GetCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "=") if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";",c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start,c_end)); } } return null } function SetCookie(c_name,value,expiredays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie = c_name + "=" +escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()); //使设置的有效时间正确。增加toGMTString() } //tabs $(document).ready(function(){ var curLi; $(".outTab a").mouseover(function(){ curLi=$(this); }); $(".outTab a").hover(function(){//鼠标点击也可以切换 $(".travelShow").removeClass("travelShow"); $(".travelHide").eq($(".outTab a").index(curLi)).addClass("travelShow"); $(".hover").removeClass("hover"); curLi.addClass("hover"); }); }); //tabsdomestic $(document).ready(function(){ var curLi; $("#domestic a").mouseover(function(){ curLi=$(this); }); $("#domestic a").hover(function(){//鼠标点击也可以切换 $(".domesticShow").removeClass("domesticShow"); $(".domesticHide").eq($("#domestic a").index(curLi)).addClass("domesticShow"); $(".domesticHover").removeClass("domesticHover"); curLi.addClass("domesticHover"); }); }); //bycarTab $(document).ready(function(){ var curLi; $(".bycarTab a").mouseover(function(){ curLi=$(this); }); $(".bycarTab a").hover(function(){//鼠标点击也可以切换 $(".bycarShow").removeClass("bycarShow"); $(".bycarHide").eq($(".bycarTab a").index(curLi)).addClass("bycarShow"); $(".bycarHover").removeClass("bycarHover"); curLi.addClass("bycarHover"); }); }); //bycarTab $(document).ready(function(){ var curLi; $(".travelHot li").mouseover(function(){ curLi=$(this); }); $(".travelHot li").click(function(){//鼠标点击也可以切换 $(".yjShow").removeClass("yjShow"); $(".yjHide").eq($(".travelHot li").index(curLi)).addClass("yjShow"); $(".hoverHot").removeClass("hoverHot"); curLi.addClass("hoverHot"); }); });
JavaScript
/** * FusionCharts Free: Flash Player detection and Chart embed * * Morphed from SWFObject (http://blog.deconcept.com/swfobject/) under MIT License: * http://www.opensource.org/licenses/mit-license.php * */ if(typeof infosoftglobal == "undefined") var infosoftglobal = new Object(); if(typeof infosoftglobal.FusionChartsUtil == "undefined") infosoftglobal.FusionChartsUtil = new Object(); infosoftglobal.FusionCharts = function(swf, id, w, h, c){ if (!document.getElementById) { return; } //Flag to see whether data has been set initially this.initialDataSet = false; //Create container objects this.params = new Object(); this.variables = new Object(); this.attributes = new Array(); //Set attributes for the SWF if(swf) { this.setAttribute('swf', swf); } if(id) { this.setAttribute('id', id); } if(w) { this.setAttribute('width', w); } if(h) { this.setAttribute('height', h); } //Set background color if(c) { this.addParam('bgcolor', c); } //Set Quality this.addParam('quality', 'high'); //Add scripting access parameter this.addParam('allowScriptAccess', 'always'); this.addParam('swliveconnect', 'true'); //Pass width and height to be appended as chartWidth and chartHeight this.addVariable('chartWidth', w); this.addVariable('chartHeight', h); } infosoftglobal.FusionCharts.prototype = { setAttribute: function(name, value){ this.attributes[name] = value; }, getAttribute: function(name){ return this.attributes[name]; }, addParam: function(name, value){ this.params[name] = value; }, getParams: function(){ return this.params; }, addVariable: function(name, value){ this.variables[name] = value; }, getVariable: function(name){ return this.variables[name]; }, getVariables: function(){ return this.variables; }, getVariablePairs: function(){ var variablePairs = new Array(); var key; var variables = this.getVariables(); for(key in variables){ variablePairs.push(key +"="+ variables[key]); } return variablePairs; }, getSWFHTML: function() { var swfNode = ""; if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" '; swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" '; var params = this.getParams(); for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; } var pairs = this.getVariablePairs().join("&"); if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; } swfNode += '/>'; } else { // PC IE swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">'; swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />'; var params = this.getParams(); for(var key in params) { swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />'; } var pairs = this.getVariablePairs().join("&"); if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';} swfNode += "</object>"; } return swfNode; }, setDataURL: function(strDataURL){ //This method sets the data URL for the chart. //If being set initially if (this.initialDataSet==false){ this.addVariable('dataURL',strDataURL); //Update flag this.initialDataSet = true; }else{ //Else do nothing as FusionCharts Free doesn't support dynamic //update of dataURL. It only supports update of dataXML. } }, setDataXML: function(strDataXML){ //If being set initially if (this.initialDataSet==false){ //This method sets the data XML for the chart INITIALLY. this.addVariable('dataXML',strDataXML); //Update flag this.initialDataSet = true; }else{ //In FusionCharts Free, we use updateChartXML method to update //the data of chart. } }, render: function(elementId){ var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId; n.innerHTML = this.getSWFHTML(); return true; } } // ------------ Fix for Out of Memory Bug in IE in FP9 ---------------// /* Fix for video streaming bug */ infosoftglobal.FusionChartsUtil.cleanupSWFs = function() { if (window.opera || !document.all) return; var objects = document.getElementsByTagName("OBJECT"); for (var i=0; i < objects.length; i++) { objects[i].style.display = 'none'; for (var x in objects[i]) { if (typeof objects[i][x] == 'function') { objects[i][x] = function(){}; } } } } // Fixes bug in fp9 infosoftglobal.FusionChartsUtil.prepUnload = function() { __flash_unloadHandler = function(){}; __flash_savedUnloadHandler = function(){}; if (typeof window.onunload == 'function') { var oldUnload = window.onunload; window.onunload = function() { infosoftglobal.FusionChartsUtil.cleanupSWFs(); oldUnload(); } } else { window.onunload = infosoftglobal.FusionChartsUtil.cleanupSWFs; } } if (typeof window.onbeforeunload == 'function') { var oldBeforeUnload = window.onbeforeunload; window.onbeforeunload = function() { infosoftglobal.FusionChartsUtil.prepUnload(); oldBeforeUnload(); } } else { window.onbeforeunload = infosoftglobal.FusionChartsUtil.prepUnload; } /* Add Array.push if needed (ie5) */ if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }} /* Function to return Flash Object from ID */ infosoftglobal.FusionChartsUtil.getChartObject = function(id) { if (window.document[id]) { return window.document[id]; } if (navigator.appName.indexOf("Microsoft Internet")==-1) { if (document.embeds && document.embeds[id]) return document.embeds[id]; } else { return document.getElementById(id); } } /* Function to update chart's data at client side */ infosoftglobal.FusionChartsUtil.updateChartXML = function(chartId, strXML){ //Get reference to chart object var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(chartId); //Set dataURL to null chartObj.SetVariable("_root.dataURL",""); //Set the flag chartObj.SetVariable("_root.isNewData","1"); //Set the actual data chartObj.SetVariable("_root.newData",strXML); //Go to the required frame chartObj.TGotoLabel("/", "JavaScriptHandler"); } /* Aliases for easy usage */ var getChartFromId = infosoftglobal.FusionChartsUtil.getChartObject; var updateChartXML = infosoftglobal.FusionChartsUtil.updateChartXML; var FusionCharts = infosoftglobal.FusionCharts;
JavaScript
var regexEnum = { intege:"^-?[1-9]\\d*$", //整数 intege1:"^[1-9]\\d*$", //正整数 intege2:"^-[1-9]\\d*$", //负整数 num:"^([+-]?)\\d*\\.?\\d+$", //数字 num1:"^[1-9]\\d*|0$", //正数(正整数 + 0) num2:"^-[1-9]\\d*|0$", //负数(负整数 + 0) decmal:"^([+-]?)\\d*\\.\\d+$", //浮点数 decmal1:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$",   //正浮点数 decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$",  //负浮点数 decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$",  //浮点数 decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$",   //非负浮点数(正浮点数 + 0) decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$",  //非正浮点数(负浮点数 + 0) email:"^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件 color:"^[a-fA-F0-9]{6}$", //颜色 url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", //仅中文 ascii:"^[\\x00-\\xFF]+$", //仅ACSII字符 zipcode:"^\\d{6}$", //邮编 mobile:"^(13|15)[0-9]{9}$", //手机 ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$", //ip地址 notempty:"^\\S+$", //非空 picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片 rar:"(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件 date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期 qq:"^[1-9]*[1-9][0-9]*$", //QQ号码 tel:"^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", //电话号码的函数(包括验证国内区号,国际区号,分机号) username:"^\\w+$", //用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串 letter:"^[A-Za-z]+$", //字母 letter_u:"^[A-Z]+$", //大写字母 letter_l:"^[a-z]+$", //小写字母 idcard:"^[1-9]([0-9]{14}|[0-9]{17})$", //身份证 ps_username:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D_\\w]+$" //中文、字母、数字 _ } function isCardID(sId){ var iSum=0 ; var info="" ; if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误"; sId=sId.replace(/x$/i,"a"); if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法"; sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); var d=new Date(sBirthday.replace(/-/g,"/")) ; if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法"; for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ; if(iSum%11!=1) return "你输入的身份证号非法"; return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女") } //短时间,形如 (13:04:06) function isTime(str) { var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/); if (a == null) {return false} if (a[1]>24 || a[3]>60 || a[4]>60) { return false; } return true; } //短日期,形如 (2003-12-05) function isDate(str) { var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); if(r==null)return false; var d= new Date(r[1], r[3]-1, r[4]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]); } //长时间,形如 (2003-12-05 13:04:06) function isDateTime(str) { var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/; var r = str.match(reg); if(r==null) return false; var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]); }
JavaScript
/** * Move a block in the blocks table from one region to another via select list. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. */ Drupal.behaviors.termDrag = function(context) { var table = $('#taxonomy', context); var tableDrag = Drupal.tableDrag.taxonomy; // Get the blocks tableDrag object. var rows = $('tr', table).size(); // When a row is swapped, keep previous and next page classes set. tableDrag.row.prototype.onSwap = function(swappedRow) { $('tr.taxonomy-term-preview', table).removeClass('taxonomy-term-preview'); $('tr.taxonomy-term-divider-top', table).removeClass('taxonomy-term-divider-top'); $('tr.taxonomy-term-divider-bottom', table).removeClass('taxonomy-term-divider-bottom'); if (Drupal.settings.taxonomy.backPeddle) { for (var n = 0; n < Drupal.settings.taxonomy.backPeddle; n++) { $(table[0].tBodies[0].rows[n]).addClass('taxonomy-term-preview'); } $(table[0].tBodies[0].rows[Drupal.settings.taxonomy.backPeddle - 1]).addClass('taxonomy-term-divider-top'); $(table[0].tBodies[0].rows[Drupal.settings.taxonomy.backPeddle]).addClass('taxonomy-term-divider-bottom'); } if (Drupal.settings.taxonomy.forwardPeddle) { for (var n = rows - Drupal.settings.taxonomy.forwardPeddle - 1; n < rows - 1; n++) { $(table[0].tBodies[0].rows[n]).addClass('taxonomy-term-preview'); } $(table[0].tBodies[0].rows[rows - Drupal.settings.taxonomy.forwardPeddle - 2]).addClass('taxonomy-term-divider-top'); $(table[0].tBodies[0].rows[rows - Drupal.settings.taxonomy.forwardPeddle - 1]).addClass('taxonomy-term-divider-bottom'); } }; };
JavaScript
/** * Attach handlers to evaluate the strength of any password fields and to check * that its confirmation is correct. */ Drupal.behaviors.password = function(context) { var translate = Drupal.settings.password; $("input.password-field:not(.password-processed)", context).each(function() { var passwordInput = $(this).addClass('password-processed'); var parent = $(this).parent(); // Wait this number of milliseconds before checking password. var monitorDelay = 700; // Add the password strength layers. $(this).after('<span class="password-strength"><span class="password-title">'+ translate.strengthTitle +'</span> <span class="password-result"></span></span>').parent(); var passwordStrength = $("span.password-strength", parent); var passwordResult = $("span.password-result", passwordStrength); parent.addClass("password-parent"); // Add the password confirmation layer. var outerItem = $(this).parent().parent(); $("input.password-confirm", outerItem).after('<span class="password-confirm">'+ translate["confirmTitle"] +' <span></span></span>').parent().addClass("confirm-parent"); var confirmInput = $("input.password-confirm", outerItem); var confirmResult = $("span.password-confirm", outerItem); var confirmChild = $("span", confirmResult); // Add the description box at the end. $(confirmInput).parent().after('<div class="password-description"></div>'); var passwordDescription = $("div.password-description", $(this).parent().parent()).hide(); // Check the password fields. var passwordCheck = function () { // Remove timers for a delayed check if they exist. if (this.timer) { clearTimeout(this.timer); } // Verify that there is a password to check. if (!passwordInput.val()) { passwordStrength.css({ visibility: "hidden" }); passwordDescription.hide(); return; } // Evaluate password strength. var result = Drupal.evaluatePasswordStrength(passwordInput.val()); passwordResult.html(result.strength == "" ? "" : translate[result.strength +"Strength"]); // Map the password strength to the relevant drupal CSS class. var classMap = { low: "error", medium: "warning", high: "ok" }; var newClass = classMap[result.strength] || ""; // Remove the previous styling if any exists; add the new class. if (this.passwordClass) { passwordResult.removeClass(this.passwordClass); passwordDescription.removeClass(this.passwordClass); } passwordDescription.html(result.message); passwordResult.addClass(newClass); if (result.strength == "high") { passwordDescription.hide(); } else { passwordDescription.addClass(newClass); } this.passwordClass = newClass; // Check that password and confirmation match. // Hide the result layer if confirmation is empty, otherwise show the layer. confirmResult.css({ visibility: (confirmInput.val() == "" ? "hidden" : "visible") }); var success = passwordInput.val() == confirmInput.val(); // Remove the previous styling if any exists. if (this.confirmClass) { confirmChild.removeClass(this.confirmClass); } // Fill in the correct message and set the class accordingly. var confirmClass = success ? "ok" : "error"; confirmChild.html(translate["confirm"+ (success ? "Success" : "Failure")]).addClass(confirmClass); this.confirmClass = confirmClass; // Show the indicator and tips. passwordStrength.css({ visibility: "visible" }); passwordDescription.show(); }; // Do a delayed check on the password fields. var passwordDelayedCheck = function() { // Postpone the check since the user is most likely still typing. if (this.timer) { clearTimeout(this.timer); } // When the user clears the field, hide the tips immediately. if (!passwordInput.val()) { passwordStrength.css({ visibility: "hidden" }); passwordDescription.hide(); return; } // Schedule the actual check. this.timer = setTimeout(passwordCheck, monitorDelay); }; // Monitor keyup and blur events. // Blur must be used because a mouse paste does not trigger keyup. passwordInput.keyup(passwordDelayedCheck).blur(passwordCheck); confirmInput.keyup(passwordDelayedCheck).blur(passwordCheck); }); }; /** * Evaluate the strength of a user's password. * * Returns the estimated strength and the relevant output message. */ Drupal.evaluatePasswordStrength = function(value) { var strength = "", msg = "", translate = Drupal.settings.password; var hasLetters = value.match(/[a-zA-Z]+/); var hasNumbers = value.match(/[0-9]+/); var hasPunctuation = value.match(/[^a-zA-Z0-9]+/); var hasCasing = value.match(/[a-z]+.*[A-Z]+|[A-Z]+.*[a-z]+/); // Check if the password is blank. if (!value.length) { strength = ""; msg = ""; } // Check if length is less than 6 characters. else if (value.length < 6) { strength = "low"; msg = translate.tooShort; } // Check if password is the same as the username (convert both to lowercase). else if (value.toLowerCase() == translate.username.toLowerCase()) { strength = "low"; msg = translate.sameAsUsername; } // Check if it contains letters, numbers, punctuation, and upper/lower case. else if (hasLetters && hasNumbers && hasPunctuation && hasCasing) { strength = "high"; } // Password is not secure enough so construct the medium-strength message. else { // Extremely bad passwords still count as low. var count = (hasLetters ? 1 : 0) + (hasNumbers ? 1 : 0) + (hasPunctuation ? 1 : 0) + (hasCasing ? 1 : 0); strength = count > 1 ? "medium" : "low"; msg = []; if (!hasLetters || !hasCasing) { msg.push(translate.addLetters); } if (!hasNumbers) { msg.push(translate.addNumbers); } if (!hasPunctuation) { msg.push(translate.addPunctuation); } msg = translate.needsMoreVariation +"<ul><li>"+ msg.join("</li><li>") +"</li></ul>"; } return { strength: strength, message: msg }; }; /** * Set the client's system timezone as default values of form fields. */ Drupal.setDefaultTimezone = function() { var offset = new Date().getTimezoneOffset() * -60; $("#edit-date-default-timezone, #edit-user-register-timezone").val(offset); }; /** * On the admin/user/settings page, conditionally show all of the * picture-related form elements depending on the current value of the * "Picture support" radio buttons. */ Drupal.behaviors.userSettings = function (context) { $('div.user-admin-picture-radios input[type=radio]:not(.userSettings-processed)', context).addClass('userSettings-processed').click(function () { $('div.user-admin-picture-settings', context)[['hide', 'show'][this.value]](); }); };
JavaScript
Drupal.behaviors.comment = function (context) { var parts = new Array("name", "homepage", "mail"); var cookie = ''; for (i=0;i<3;i++) { cookie = Drupal.comment.getCookie('comment_info_' + parts[i]); if (cookie != '') { $("#comment-form input[name=" + parts[i] + "]:not(.comment-processed)", context) .val(cookie) .addClass('comment-processed'); } } }; Drupal.comment = {}; Drupal.comment.getCookie = function(name) { var search = name + '='; var returnValue = ''; if (document.cookie.length > 0) { offset = document.cookie.indexOf(search); if (offset != -1) { offset += search.length; var end = document.cookie.indexOf(';', offset); if (end == -1) { end = document.cookie.length; } returnValue = decodeURIComponent(document.cookie.substring(offset, end).replace(/\+/g, '%20')); } } return returnValue; };
JavaScript
Drupal.behaviors.openid = function (context) { var $loginElements = $("#edit-name-wrapper, #edit-pass-wrapper, li.openid-link"); var $openidElements = $("#edit-openid-identifier-wrapper, li.user-link"); // This behavior attaches by ID, so is only valid once on a page. if (!$("#edit-openid-identifier.openid-processed").size() && $("#edit-openid-identifier").val()) { $("#edit-openid-identifier").addClass('openid-processed'); $loginElements.hide(); // Use .css("display", "block") instead of .show() to be Konqueror friendly. $openidElements.css("display", "block"); } $("li.openid-link:not(.openid-processed)", context) .addClass('openid-processed') .click( function() { $loginElements.hide(); $openidElements.css("display", "block"); // Remove possible error message. $("#edit-name, #edit-pass").removeClass("error"); $("div.messages.error").hide(); // Set focus on OpenID Identifier field. $("#edit-openid-identifier")[0].focus(); return false; }); $("li.user-link:not(.openid-processed)", context) .addClass('openid-processed') .click(function() { $openidElements.hide(); $loginElements.css("display", "block"); // Clear OpenID Identifier field and remove possible error message. $("#edit-openid-identifier").val('').removeClass("error"); $("div.messages.error").css("display", "block"); // Set focus on username field. $("#edit-name")[0].focus(); return false; }); };
JavaScript
/** * Internal function to check using Ajax if clean URLs can be enabled on the * settings page. * * This function is not used to verify whether or not clean URLs * are currently enabled. */ Drupal.behaviors.cleanURLsSettingsCheck = function(context) { // This behavior attaches by ID, so is only valid once on a page. // Also skip if we are on an install page, as Drupal.cleanURLsInstallCheck will handle // the processing. if ($("#clean-url.clean-url-processed, #clean-url.install").size()) { return; } var url = Drupal.settings.basePath +"admin/settings/clean-urls/check"; $("#clean-url .description span").html('<div id="testing">'+ Drupal.t('Testing clean URLs...') +"</div>"); $("#clean-url p").hide(); $.ajax({ url: location.protocol +"//"+ location.host + url, dataType: 'json', success: function () { // Check was successful. $("#clean-url input.form-radio").attr("disabled", false); $("#clean-url .description span").append('<div class="ok">'+ Drupal.t('Your server has been successfully tested to support this feature.') +"</div>"); $("#testing").hide(); }, error: function() { // Check failed. $("#clean-url .description span").append('<div class="warning">'+ Drupal.t('Your system configuration does not currently support this feature. The <a href="http://drupal.org/node/15365">handbook page on Clean URLs</a> has additional troubleshooting information.') +"</div>"); $("#testing").hide(); } }); $("#clean-url").addClass('clean-url-processed'); }; /** * Internal function to check using Ajax if clean URLs can be enabled on the * install page. * * This function is not used to verify whether or not clean URLs * are currently enabled. */ Drupal.cleanURLsInstallCheck = function() { var url = location.protocol +"//"+ location.host + Drupal.settings.basePath +"admin/settings/clean-urls/check"; $("#clean-url .description").append('<span><div id="testing">'+ Drupal.settings.cleanURL.testing +"</div></span>"); $("#clean-url.install").css("display", "block"); $.ajax({ url: url, dataType: 'json', success: function () { // Check was successful. $("#clean-url input.form-radio").attr("disabled", false); $("#clean-url input.form-radio").attr("checked", 1); $("#clean-url .description span").append('<div class="ok">'+ Drupal.settings.cleanURL.success +"</div>"); $("#testing").hide(); }, error: function() { // Check failed. $("#clean-url .description span").append('<div class="warning">'+ Drupal.settings.cleanURL.failure +"</div>"); $("#testing").hide(); } }); $("#clean-url").addClass('clean-url-processed'); }; /** * When a field is filled out, apply its value to other fields that will likely * use the same value. In the installer this is used to populate the * administrator e-mail address with the same value as the site e-mail address. */ Drupal.behaviors.copyFieldValue = function (context) { for (var sourceId in Drupal.settings.copyFieldValue) { // Get the list of target fields. targetIds = Drupal.settings.copyFieldValue[sourceId]; if (!$('#'+ sourceId + '.copy-field-values-processed').size(), context) { // Add the behavior to update target fields on blur of the primary field. sourceField = $('#' + sourceId); sourceField.bind('blur', function() { for (var delta in targetIds) { var targetField = $('#'+ targetIds[delta]); if (targetField.val() == '') { targetField.val(this.value); } } }); sourceField.addClass('copy-field-values-processed'); } } }; /** * Show/hide custom format sections on the date-time settings page. */ Drupal.behaviors.dateTime = function(context) { // Show/hide custom format depending on the select's value. $('select.date-format:not(.date-time-processed)', context).change(function() { $(this).addClass('date-time-processed').parents("div.date-container").children("div.custom-container")[$(this).val() == "custom" ? "show" : "hide"](); }); // Attach keyup handler to custom format inputs. $('input.custom-format:not(.date-time-processed)', context).addClass('date-time-processed').keyup(function() { var input = $(this); var url = Drupal.settings.dateTime.lookup +(Drupal.settings.dateTime.lookup.match(/\?q=/) ? "&format=" : "?format=") + encodeURIComponent(input.val()); $.getJSON(url, function(data) { $("div.description span", input.parent()).html(data); }); }); // Trigger the event handler to show the form input if necessary. $('select.date-format', context).trigger('change'); };
JavaScript
/** * Add functionality to the profile drag and drop table. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. It shows and hides * a warning message when removing the last field from a profile category. */ Drupal.behaviors.profileDrag = function(context) { var table = $('#profile-fields'); var tableDrag = Drupal.tableDrag['profile-fields']; // Get the profile tableDrag object. // Add a handler for when a row is swapped, update empty categories. tableDrag.row.prototype.onSwap = function(swappedRow) { var rowObject = this; $('tr.category-message', table).each(function() { // If the dragged row is in this category, but above the message row, swap it down one space. if ($(this).prev('tr').get(0) == rowObject.element) { // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } } // This category has become empty if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').size() == 0) { $(this).removeClass('category-populated').addClass('category-empty'); } // This category has become populated. else if ($(this).is('.category-empty')) { $(this).removeClass('category-empty').addClass('category-populated'); } }); }; // Add a handler so when a row is dropped, update fields dropped into new categories. tableDrag.onDrop = function() { dragObject = this; if ($(dragObject.rowObject.element).prev('tr').is('.category-message')) { var categoryRow = $(dragObject.rowObject.element).prev('tr').get(0); var categoryNum = categoryRow.className.replace(/([^ ]+[ ]+)*category-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); var categoryField = $('select.profile-category', dragObject.rowObject.element); var weightField = $('select.profile-weight', dragObject.rowObject.element); var oldcategoryNum = weightField[0].className.replace(/([^ ]+[ ]+)*profile-weight-([^ ]+)([ ]+[^ ]+)*/, '$2'); if (!categoryField.is('.profile-category-'+ categoryNum)) { categoryField.removeClass('profile-category-' + oldcategoryNum).addClass('profile-category-' + categoryNum); weightField.removeClass('profile-weight-' + oldcategoryNum).addClass('profile-weight-' + categoryNum); categoryField.val(categoryField[0].options[categoryNum].value); } } }; };
JavaScript
Drupal.behaviors.color = function (context) { // This behavior attaches by ID, so is only valid once on a page. if ($('#color_scheme_form .color-form.color-processed').size()) { return; } var form = $('#color_scheme_form .color-form', context); var inputs = []; var hooks = []; var locks = []; var focused = null; // Add Farbtastic $(form).prepend('<div id="placeholder"></div>').addClass('color-processed'); var farb = $.farbtastic('#placeholder'); // Decode reference colors to HSL var reference = Drupal.settings.color.reference; for (i in reference) { reference[i] = farb.RGBToHSL(farb.unpack(reference[i])); } // Build preview $('#preview:not(.color-processed)') .append('<div id="gradient"></div>') .addClass('color-processed'); var gradient = $('#preview #gradient'); var h = parseInt(gradient.css('height')) / 10; for (i = 0; i < h; ++i) { gradient.append('<div class="gradient-line"></div>'); } // Fix preview background in IE6 if (navigator.appVersion.match(/MSIE [0-6]\./)) { var e = $('#preview #img')[0]; var image = e.currentStyle.backgroundImage; e.style.backgroundImage = 'none'; e.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image.substring(5, image.length - 2) + "')"; } // Set up colorscheme selector $('#edit-scheme', form).change(function () { var colors = this.options[this.selectedIndex].value; if (colors != '') { colors = colors.split(','); for (i in colors) { callback(inputs[i], colors[i], false, true); } preview(); } }); /** * Render the preview. */ function preview() { // Solid background $('#preview', form).css('backgroundColor', inputs[0].value); // Text preview $('#text', form).css('color', inputs[4].value); $('#text a, #text h2', form).css('color', inputs[1].value); // Set up gradient var top = farb.unpack(inputs[2].value); var bottom = farb.unpack(inputs[3].value); if (top && bottom) { var delta = []; for (i in top) { delta[i] = (bottom[i] - top[i]) / h; } var accum = top; // Render gradient lines $('#gradient > div', form).each(function () { for (i in accum) { accum[i] += delta[i]; } this.style.backgroundColor = farb.pack(accum); }); } } /** * Shift a given color, using a reference pair (ref in HSL). * * This algorithm ensures relative ordering on the saturation and luminance * axes is preserved, and performs a simple hue shift. * * It is also symmetrical. If: shift_color(c, a, b) == d, * then shift_color(d, b, a) == c. */ function shift_color(given, ref1, ref2) { // Convert to HSL given = farb.RGBToHSL(farb.unpack(given)); // Hue: apply delta given[0] += ref2[0] - ref1[0]; // Saturation: interpolate if (ref1[1] == 0 || ref2[1] == 0) { given[1] = ref2[1]; } else { var d = ref1[1] / ref2[1]; if (d > 1) { given[1] /= d; } else { given[1] = 1 - (1 - given[1]) * d; } } // Luminance: interpolate if (ref1[2] == 0 || ref2[2] == 0) { given[2] = ref2[2]; } else { var d = ref1[2] / ref2[2]; if (d > 1) { given[2] /= d; } else { given[2] = 1 - (1 - given[2]) * d; } } return farb.pack(farb.HSLToRGB(given)); } /** * Callback for Farbtastic when a new color is chosen. */ function callback(input, color, propagate, colorscheme) { // Set background/foreground color $(input).css({ backgroundColor: color, 'color': farb.RGBToHSL(farb.unpack(color))[2] > 0.5 ? '#000' : '#fff' }); // Change input value if (input.value && input.value != color) { input.value = color; // Update locked values if (propagate) { var i = input.i; for (j = i + 1; ; ++j) { if (!locks[j - 1] || $(locks[j - 1]).is('.unlocked')) break; var matched = shift_color(color, reference[input.key], reference[inputs[j].key]); callback(inputs[j], matched, false); } for (j = i - 1; ; --j) { if (!locks[j] || $(locks[j]).is('.unlocked')) break; var matched = shift_color(color, reference[input.key], reference[inputs[j].key]); callback(inputs[j], matched, false); } // Update preview preview(); } // Reset colorscheme selector if (!colorscheme) { resetScheme(); } } } /** * Reset the color scheme selector. */ function resetScheme() { $('#edit-scheme', form).each(function () { this.selectedIndex = this.options.length - 1; }); } // Focus the Farbtastic on a particular field. function focus() { var input = this; // Remove old bindings focused && $(focused).unbind('keyup', farb.updateValue) .unbind('keyup', preview).unbind('keyup', resetScheme) .parent().removeClass('item-selected'); // Add new bindings focused = this; farb.linkTo(function (color) { callback(input, color, true, false); }); farb.setColor(this.value); $(focused).keyup(farb.updateValue).keyup(preview).keyup(resetScheme) .parent().addClass('item-selected'); } // Initialize color fields $('#palette input.form-text', form) .each(function () { // Extract palette field name this.key = this.id.substring(13); // Link to color picker temporarily to initialize. farb.linkTo(function () {}).setColor('#000').linkTo(this); // Add lock var i = inputs.length; if (inputs.length) { var lock = $('<div class="lock"></div>').toggle( function () { $(this).addClass('unlocked'); $(hooks[i - 1]).attr('class', locks[i - 2] && $(locks[i - 2]).is(':not(.unlocked)') ? 'hook up' : 'hook' ); $(hooks[i]).attr('class', locks[i] && $(locks[i]).is(':not(.unlocked)') ? 'hook down' : 'hook' ); }, function () { $(this).removeClass('unlocked'); $(hooks[i - 1]).attr('class', locks[i - 2] && $(locks[i - 2]).is(':not(.unlocked)') ? 'hook both' : 'hook down' ); $(hooks[i]).attr('class', locks[i] && $(locks[i]).is(':not(.unlocked)') ? 'hook both' : 'hook up' ); } ); $(this).after(lock); locks.push(lock); }; // Add hook var hook = $('<div class="hook"></div>'); $(this).after(hook); hooks.push(hook); $(this).parent().find('.lock').click(); this.i = i; inputs.push(this); }) .focus(focus); $('#palette label', form); // Focus first color focus.call(inputs[0]); // Render preview preview(); };
JavaScript
/** * Move a block in the blocks table from one region to another via select list. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. */ Drupal.behaviors.blockDrag = function(context) { var table = $('table#blocks'); var tableDrag = Drupal.tableDrag.blocks; // Get the blocks tableDrag object. // Add a handler for when a row is swapped, update empty regions. tableDrag.row.prototype.onSwap = function(swappedRow) { checkEmptyRegions(table, this); }; // A custom message for the blocks page specifically. Drupal.theme.tableDragChangedWarning = function () { return '<div class="warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t("The changes to these blocks will not be saved until the <em>Save blocks</em> button is clicked.") + '</div>'; }; // Add a handler so when a row is dropped, update fields dropped into new regions. tableDrag.onDrop = function() { dragObject = this; if ($(dragObject.rowObject.element).prev('tr').is('.region-message')) { var regionRow = $(dragObject.rowObject.element).prev('tr').get(0); var regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); var regionField = $('select.block-region-select', dragObject.rowObject.element); var weightField = $('select.block-weight', dragObject.rowObject.element); var oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*block-weight-([^ ]+)([ ]+[^ ]+)*/, '$2'); if (!regionField.is('.block-region-'+ regionName)) { regionField.removeClass('block-region-' + oldRegionName).addClass('block-region-' + regionName); weightField.removeClass('block-weight-' + oldRegionName).addClass('block-weight-' + regionName); regionField.val(regionName); } } }; // Add the behavior to each region select list. $('select.block-region-select:not(.blockregionselect-processed)', context).each(function() { $(this).change(function(event) { // Make our new row and select field. var row = $(this).parents('tr:first'); var select = $(this); tableDrag.rowObject = new tableDrag.row(row); // Find the correct region and insert the row as the first in the region. $('tr.region-message', table).each(function() { if ($(this).is('.region-' + select[0].value + '-message')) { // Add the new row and remove the old one. $(this).after(row); // Manually update weights and restripe. tableDrag.updateFields(row.get(0)); tableDrag.rowObject.changed = true; if (tableDrag.oldRowElement) { $(tableDrag.oldRowElement).removeClass('drag-previous'); } tableDrag.oldRowElement = row.get(0); tableDrag.restripeTable(); tableDrag.rowObject.markChanged(); tableDrag.oldRowElement = row; $(row).addClass('drag-previous'); } }); // Modify empty regions with added or removed fields. checkEmptyRegions(table, row); // Remove focus from selectbox. select.get(0).blur(); }); $(this).addClass('blockregionselect-processed'); }); var checkEmptyRegions = function(table, rowObject) { $('tr.region-message', table).each(function() { // If the dragged row is in this region, but above the message row, swap it down one space. if ($(this).prev('tr').get(0) == rowObject.element) { // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } } // This region has become empty if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').size() == 0) { $(this).removeClass('region-populated').addClass('region-empty'); } // This region has become populated. else if ($(this).is('.region-empty')) { $(this).removeClass('region-empty').addClass('region-populated'); } }); }; };
JavaScript
Drupal.tableHeaderDoScroll = function() { if (typeof(Drupal.tableHeaderOnScroll)=='function') { Drupal.tableHeaderOnScroll(); } }; Drupal.behaviors.tableHeader = function (context) { // This breaks in anything less than IE 7. Prevent it from running. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7) { return; } // Keep track of all cloned table headers. var headers = []; $('table.sticky-enabled thead:not(.tableHeader-processed)', context).each(function () { // Clone thead so it inherits original jQuery properties. var headerClone = $(this).clone(true).insertBefore(this.parentNode).wrap('<table class="sticky-header"></table>').parent().css({ position: 'fixed', top: '0px' }); headerClone = $(headerClone)[0]; headers.push(headerClone); // Store parent table. var table = $(this).parent('table')[0]; headerClone.table = table; // Finish initialzing header positioning. tracker(headerClone); $(table).addClass('sticky-table'); $(this).addClass('tableHeader-processed'); }); // Define the anchor holding var. var prevAnchor = ''; // Track positioning and visibility. function tracker(e) { // Save positioning data. var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (e.viewHeight != viewHeight) { e.viewHeight = viewHeight; e.vPosition = $(e.table).offset().top - 4; e.hPosition = $(e.table).offset().left; e.vLength = e.table.clientHeight - 100; // Resize header and its cell widths. var parentCell = $('th', e.table); $('th', e).each(function(index) { var cellWidth = parentCell.eq(index).css('width'); // Exception for IE7. if (cellWidth == 'auto') { cellWidth = parentCell.get(index).clientWidth +'px'; } $(this).css('width', cellWidth); }); $(e).css('width', $(e.table).css('width')); } // Track horizontal positioning relative to the viewport and set visibility. var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft; var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - e.vPosition; var visState = (vOffset > 0 && vOffset < e.vLength) ? 'visible' : 'hidden'; $(e).css({left: -hScroll + e.hPosition +'px', visibility: visState}); // Check the previous anchor to see if we need to scroll to make room for the header. // Get the height of the header table and scroll up that amount. if (prevAnchor != location.hash) { if (location.hash != '') { var offset = $('td' + location.hash).offset(); if (offset) { var top = offset.top; var scrollLocation = top - $(e).height(); $('body, html').scrollTop(scrollLocation); } } prevAnchor = location.hash; } } // Only attach to scrollbars once, even if Drupal.attachBehaviors is called // multiple times. if (!$('body').hasClass('tableHeader-processed')) { $('body').addClass('tableHeader-processed'); $(window).scroll(Drupal.tableHeaderDoScroll); $(document.documentElement).scroll(Drupal.tableHeaderDoScroll); } // Track scrolling. Drupal.tableHeaderOnScroll = function() { $(headers).each(function () { tracker(this); }); }; // Track resizing. var time = null; var resize = function () { // Ensure minimum time between adjustments. if (time) { return; } time = setTimeout(function () { $('table.sticky-header').each(function () { // Force cell width calculation. this.viewHeight = 0; tracker(this); }); // Reset timer time = null; }, 250); }; $(window).resize(resize); };
JavaScript
/** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = function(context) { for (var base in Drupal.settings.tableDrag) { if (!$('#' + base + '.tabledrag-processed', context).size()) { var tableSettings = Drupal.settings.tableDrag[base]; $('#' + base).filter(':not(.tabledrag-processed)').each(function() { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, tableSettings); }); $('#' + base).addClass('tabledrag-processed'); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function(table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (group in tableSettings) { for (n in tableSettings[group]) { if (tableSettings[group][n]['relationship'] == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n]['limit'] > 0) { this.maxDepth = tableSettings[group][n]['limit']; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); // Match immediate children of the parent element to allow nesting. var testCell = $('> tbody > tr.draggable:first td:first, > tr.draggable:first td:first', table).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; $('.indentation', testCell).slice(0, 2).remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function() { self.makeDraggable(this); }); // Hide columns containing affected form elements. this.hideColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function(event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function(event) { return self.dropRow(event, self); }); }; /** * Hide the columns containing form elements according to the settings for * this tableDrag instance. */ Drupal.tableDrag.prototype.hideColumns = function(){ for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d]['target'] + ':first', this.table); if (field.size() && this.tableSettings[group][d]['hidden']) { var hidden = this.tableSettings[group][d]['hidden']; var cell = field.parents('td:first'); break; } } // Hide the column containing this field. if (hidden && cell[0] && cell.css('display') != 'none') { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; var headerIndex = $('> td:not(:hidden)', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function(){ var row = $(this); var parentTag = row.parent().get(0).tagName.toLowerCase(); var index = (parentTag == 'thead') ? headerIndex : columnIndex; // Adjust the index to take into account colspans. row.children().each(function(n) { if (n < index) { index -= (this.colSpan && this.colSpan > 1) ? this.colSpan - 1 : 0; } }); if (index > 0) { cell = row.children(':nth-child(' + index + ')'); if (cell[0].colSpan > 1) { // If this cell has a colspan, simply reduce it. cell[0].colSpan = cell[0].colSpan - 1; } else { // Hide table body cells, but remove table header cells entirely // (Safari doesn't hide properly). parentTag == 'thead' ? cell.remove() : cell.css('display', 'none'); } } }); } } }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function(group, row) { var field = $('.' + group, row); for (delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta]['target']; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = new Object(); for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function(item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).after(handle).size()) { // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).size(), self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function() { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function() { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function(event) { // Create a new dragObject recording the event information. self.dragObject = new Object(); self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = self.getPosition(self.table).y; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function() { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function() { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function(event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function(event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row.. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).size()) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () {groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight}); nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will supress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function(event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function(event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function(event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertAfter(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the position of an element by adding up parent offsets in the DOM tree. */ Drupal.tableDrag.prototype.getPosition = function(element){ var left = 0; var top = 0; // Because Safari doesn't report offsetHeight on table rows, but does on table // cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari if (element.offsetHeight == 0) { element = element.firstChild; // a table cell } while (element.offsetParent){ left += element.offsetLeft; top += element.offsetTop; element = element.offsetParent; } left += element.offsetLeft; top += element.offsetTop; return {x:left, y:top}; }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function(event){ if (event.pageX || event.pageY) { return {x:event.pageX, y:event.pageY}; } return { x:event.clientX + document.body.scrollLeft - document.body.clientLeft, y:event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Given a target element and a mouse event, get the mouse offset from that * element. To do this we need the element's position and the mouse position. */ Drupal.tableDrag.prototype.getMouseOffset = function(target, event) { var docPos = this.getPosition(target); var mousePos = this.mouseCoords(event); return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y}; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function(x, y) { var rows = this.table.tBodies[0].rows; for (var n=0; n<rows.length; n++) { var row = rows[n]; var indentDiff = 0; // Safari fix see Drupal.tableDrag.prototype.getPosition() if (row.offsetHeight == 0) { var rowY = this.getPosition(row.firstChild).y; var rowHeight = parseInt(row.firstChild.offsetHeight)/2; } // Other browsers. else { var rowY = this.getPosition(row).y; var rowHeight = parseInt(row.offsetHeight)/2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function(changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each seperately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function(changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as it's own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).size() == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).size() == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's garanteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).parents('tr:first')).size(); break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = new Array(); $('option', targetElement).each(function() { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function() { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val()) || 0; $(targetClass, siblings).each(function() { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function(sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function(cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function(scrollAmount) { var self = this; this.scrollInterval = setInterval(function() { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function() { // :even and :odd are reversed because jquery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable, > tr.draggable', this.table) .filter(':odd').filter('.odd') .removeClass('odd').addClass('even') .end().end() .filter(':even').filter('.even') .removeClass('even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function() { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function() { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function(tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = new Array(tableRow); this.groupDepth = $('.indentation', tableRow).size(); this.changed = false; this.table = $(tableRow).parents('table:first').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).size(); this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).size(), this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function(addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = new Array(); var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function(indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function(position, row) { $(row)[position](this.group); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).size() : 0; // Maximum indentation: if (!prevRow || $(this.element).is('.tabledrag-root')) { // Do not indent the first row in the table or 'root' rows.. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).size() + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return {'min':minIndent, 'max':maxIndent}; } /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function(indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { prevRow = $(this.element).prev('tr').get(0); nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function(rowSettings) { var siblings = new Array(); var directions = new Array('prev', 'next'); var rowIndentation = this.indents; for (var d in directions) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentaiton. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function() { for (n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function() { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function() { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function(swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t("Changes made in this table will not be saved until the form is submitted.") + '</div>'; };
JavaScript
Drupal.behaviors.textarea = function(context) { $('textarea.resizable:not(.textarea-processed)', context).each(function() { // Avoid non-processed teasers. if ($(this).is(('textarea.teaser:not(.teaser-processed)'))) { return false; } var textarea = $(this).addClass('textarea-processed'), staticOffset = null; // When wrapping the text area, work around an IE margin bug. See: // http://jaspan.com/ie-inherited-margin-bug-form-elements-and-haslayout $(this).wrap('<div class="resizable-textarea"><span></span></div>') .parent().append($('<div class="grippie"></div>').mousedown(startDrag)); var grippie = $('div.grippie', $(this).parent())[0]; grippie.style.marginRight = (grippie.offsetWidth - $(this)[0].offsetWidth) +'px'; function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind("mousemove", performDrag).unbind("mouseup", endDrag); textarea.css('opacity', 1); } }); };
JavaScript
/** * Toggle the visibility of a fieldset using smooth animations */ Drupal.toggleFieldset = function(fieldset) { if ($(fieldset).is('.collapsed')) { // Action div containers are processed separately because of a IE bug // that alters the default submit button behavior. var content = $('> div:not(.action)', fieldset); $(fieldset).removeClass('collapsed'); content.hide(); content.slideDown( { duration: 'fast', easing: 'linear', complete: function() { Drupal.collapseScrollIntoView(this.parentNode); this.parentNode.animating = false; $('div.action', fieldset).show(); }, step: function() { // Scroll the fieldset into view Drupal.collapseScrollIntoView(this.parentNode); } }); } else { $('div.action', fieldset).hide(); var content = $('> div:not(.action)', fieldset).slideUp('fast', function() { $(this.parentNode).addClass('collapsed'); this.parentNode.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = self.innerHeight || document.documentElement.clientHeight || $('body')[0].clientHeight || 0; var offset = self.pageYOffset || document.documentElement.scrollTop || $('body')[0].scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = function (context) { $('fieldset.collapsible > legend:not(.collapse-processed)', context).each(function() { var fieldset = $(this.parentNode); // Expand if there are errors inside if ($('input.error, textarea.error, select.error', fieldset).size() > 0) { fieldset.removeClass('collapsed'); } // Turn the legend into a clickable link and wrap the contents of the fieldset // in a div for easier animation var text = this.innerHTML; $(this).empty().append($('<a href="#">'+ text +'</a>').click(function() { var fieldset = $(this).parents('fieldset:first')[0]; // Don't animate multiple times if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; })) .after($('<div class="fieldset-wrapper"></div>') .append(fieldset.children(':not(legend):not(.action)'))) .addClass('collapse-processed'); }); };
JavaScript
/** * Auto-attach for teaser behavior. * * Note: depends on resizable textareas. */ Drupal.behaviors.teaser = function(context) { // This breaks in Konqueror. Prevent it from running. if (/KDE/.test(navigator.vendor)) { return; } $('textarea.teaser:not(.teaser-processed)', context).each(function() { var teaser = $(this).addClass('teaser-processed'); // Move teaser textarea before body, and remove its form-item wrapper. var body = $('#'+ Drupal.settings.teaser[this.id]); var checkbox = $('#'+ Drupal.settings.teaserCheckbox[this.id]).parent(); var checked = $(checkbox).children('input').attr('checked') ? true : false; var parent = teaser[0].parentNode; $(body).before(teaser); $(parent).remove(); function trim(text) { return text.replace(/^\s+/g, '').replace(/\s+$/g, ''); } // Join the teaser back to the body. function join_teaser() { if (teaser.val()) { body.val(trim(teaser.val()) +'\r\n\r\n'+ trim(body.val())); } // Empty, hide and disable teaser. teaser[0].value = ''; $(teaser).attr('disabled', 'disabled'); $(teaser).parent().slideUp('fast'); // Change label. $(this).val(Drupal.t('Split summary at cursor')); // Hide separate teaser checkbox. $(checkbox).hide(); // Force a hidden checkbox to be checked (to ensure that the body is // correctly processed on form submit when teaser/body are in joined // state), and remember the current checked status. checked = $(checkbox).children('input').attr('checked') ? true : false; $(checkbox).children('input').attr('checked', true); } // Split the teaser from the body. function split_teaser() { body[0].focus(); var selection = Drupal.getSelection(body[0]); var split = selection.start; var text = body.val(); // Note: using val() fails sometimes. jQuery bug? teaser[0].value = trim(text.slice(0, split)); body[0].value = trim(text.slice(split)); // Reveal and enable teaser $(teaser).attr('disabled', ''); $(teaser).parent().slideDown('fast'); // Change label $(this).val(Drupal.t('Join summary')); // Show separate teaser checkbox, restore checked value. $(checkbox).show().children('input').attr('checked', checked); } // Add split/join button. var button = $('<div class="teaser-button-wrapper"><input type="button" class="teaser-button" /></div>'); var include = $('#'+ this.id.substring(0, this.id.length - 2) +'include'); $(include).parent().parent().before(button); // Extract the teaser from the body, if set. Otherwise, stay in joined mode. var text = body.val().split('<!--break-->'); if (text.length >= 2) { teaser[0].value = trim(text.shift()); body[0].value = trim(text.join('<!--break-->')); $(teaser).attr('disabled', ''); $('input', button).val(Drupal.t('Join summary')).toggle(join_teaser, split_teaser); } else { $('input', button).val(Drupal.t('Split summary at cursor')).toggle(split_teaser, join_teaser); $(checkbox).hide().children('input').attr('checked', true); } // Make sure that textarea.js has done its magic to ensure proper visibility state. if (Drupal.behaviors.textarea && teaser.is(('.form-textarea:not(.textarea-processed)'))) { Drupal.behaviors.textarea(teaser.parentNode); } // Set initial visibility if ($(teaser).is(':disabled')) { $(teaser).parent().hide(); } }); };
JavaScript
/** * Attaches the batch behavior to progress bars. */ Drupal.behaviors.batch = function (context) { // This behavior attaches by ID, so is only valid once on a page. if ($('#progress.batch-processed').size()) { return; } $('#progress', context).addClass('batch-processed').each(function () { var holder = this; var uri = Drupal.settings.batch.uri; var initMessage = Drupal.settings.batch.initMessage; var errorMessage = Drupal.settings.batch.errorMessage; // Success: redirect to the summary. var updateCallback = function (progress, status, pb) { if (progress == 100) { pb.stopMonitoring(); window.location = uri+'&op=finished'; } }; var errorCallback = function (pb) { var div = document.createElement('p'); div.className = 'error'; $(div).html(errorMessage); $(holder).prepend(div); $('#wait').hide(); }; var progress = new Drupal.progressBar('updateprogress', updateCallback, "POST", errorCallback); progress.setProgress(-1, initMessage); $(holder).append(progress.element); progress.startMonitoring(uri+'&op=do', 10); }); };
JavaScript
// Farbtastic 1.2 jQuery.fn.farbtastic = function (callback) { $.farbtastic(this, callback); return this; }; jQuery.farbtastic = function (container, callback) { var container = $(container).get(0); return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); }; jQuery._farbtastic = function (container, callback) { // Store farbtastic object var fb = this; // Insert markup $(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>'); var e = $('.farbtastic', container); fb.wheel = $('.wheel', container).get(0); // Dimensions fb.radius = 84; fb.square = 100; fb.width = 194; // Fix background PNGs in IE6 if (navigator.appVersion.match(/MSIE [0-6]\./)) { $('*', e).each(function () { if (this.currentStyle.backgroundImage != 'none') { var image = this.currentStyle.backgroundImage; image = this.currentStyle.backgroundImage.substring(5, image.length - 2); $(this).css({ 'backgroundImage': 'none', 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" }); } }); } /** * Link to the given element(s) or callback. */ fb.linkTo = function (callback) { // Unbind previous nodes if (typeof fb.callback == 'object') { $(fb.callback).unbind('keyup', fb.updateValue); } // Reset color fb.color = null; // Bind callback or elements if (typeof callback == 'function') { fb.callback = callback; } else if (typeof callback == 'object' || typeof callback == 'string') { fb.callback = $(callback); fb.callback.bind('keyup', fb.updateValue); if (fb.callback.get(0).value) { fb.setColor(fb.callback.get(0).value); } } return this; }; fb.updateValue = function (event) { if (this.value && this.value != fb.color) { fb.setColor(this.value); } }; /** * Change color with HTML syntax #123456 */ fb.setColor = function (color) { var unpack = fb.unpack(color); if (fb.color != color && unpack) { fb.color = color; fb.rgb = unpack; fb.hsl = fb.RGBToHSL(fb.rgb); fb.updateDisplay(); } return this; }; /** * Change color with HSL triplet [0..1, 0..1, 0..1] */ fb.setHSL = function (hsl) { fb.hsl = hsl; fb.rgb = fb.HSLToRGB(hsl); fb.color = fb.pack(fb.rgb); fb.updateDisplay(); return this; }; ///////////////////////////////////////////////////// /** * Retrieve the coordinates of the given event relative to the center * of the widget. */ fb.widgetCoords = function (event) { var x, y; var el = event.target || event.srcElement; var reference = fb.wheel; // If the offset from the relative element is undefined calculate it. if ( typeof event.offsetX == 'undefined' && typeof event.offsetY == 'undefined' ) { var offset = $(event.target).offset(false); event.offsetX = event.pageX - offset.left; event.offsetY = event.pageY - offset.top; } // Use offset coordinates and find common offsetParent var pos = { x: event.offsetX, y: event.offsetY }; // Send the coordinates upwards through the offsetParent chain. var e = el; while (e) { e.mouseX = pos.x; e.mouseY = pos.y; pos.x += e.offsetLeft; pos.y += e.offsetTop; e = e.offsetParent; } // Look for the coordinates starting from the wheel widget. var e = reference; var offset = { x: 0, y: 0 }; while (e) { if (typeof e.mouseX != 'undefined') { x = e.mouseX - offset.x; y = e.mouseY - offset.y; break; } offset.x += e.offsetLeft; offset.y += e.offsetTop; e = e.offsetParent; } // Reset stored coordinates e = el; while (e) { e.mouseX = undefined; e.mouseY = undefined; e = e.offsetParent; } // Subtract distance to middle return { x: x - fb.width / 2, y: y - fb.width / 2 }; }; /** * Mousedown handler */ fb.mousedown = function (event) { // Capture mouse if (!document.dragging) { $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); document.dragging = true; } // Check which area is being dragged var pos = fb.widgetCoords(event); fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; // Process fb.mousemove(event); return false; }; /** * Mousemove handler */ fb.mousemove = function (event) { // Get coordinates relative to color picker center var pos = fb.widgetCoords(event); // Set new HSL parameters if (fb.circleDrag) { var hue = Math.atan2(pos.x, -pos.y) / 6.28; if (hue < 0) hue += 1; fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); } else { var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); fb.setHSL([fb.hsl[0], sat, lum]); } return false; }; /** * Mouseup handler */ fb.mouseup = function () { // Uncapture mouse $(document).unbind('mousemove', fb.mousemove); $(document).unbind('mouseup', fb.mouseup); document.dragging = false; }; /** * Update the markers and styles */ fb.updateDisplay = function () { // Markers var angle = fb.hsl[0] * 6.28; $('.h-marker', e).css({ left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' }); $('.sl-marker', e).css({ left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' }); // Saturation/Luminance gradient $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); // Linked elements or callback if (typeof fb.callback == 'object') { // Set background/foreground color $(fb.callback).css({ backgroundColor: fb.color, color: fb.hsl[2] > 0.5 ? '#000' : '#fff' }); // Change linked value $(fb.callback).each(function() { if (this.value && this.value != fb.color) { this.value = fb.color; } }); } else if (typeof fb.callback == 'function') { fb.callback.call(fb, fb.color); } }; /* Various color utility functions */ fb.pack = function (rgb) { var r = Math.round(rgb[0] * 255); var g = Math.round(rgb[1] * 255); var b = Math.round(rgb[2] * 255); return '#' + (r < 16 ? '0' : '') + r.toString(16) + (g < 16 ? '0' : '') + g.toString(16) + (b < 16 ? '0' : '') + b.toString(16); }; fb.unpack = function (color) { if (color.length == 7) { return [parseInt('0x' + color.substring(1, 3)) / 255, parseInt('0x' + color.substring(3, 5)) / 255, parseInt('0x' + color.substring(5, 7)) / 255]; } else if (color.length == 4) { return [parseInt('0x' + color.substring(1, 2)) / 15, parseInt('0x' + color.substring(2, 3)) / 15, parseInt('0x' + color.substring(3, 4)) / 15]; } }; fb.HSLToRGB = function (hsl) { var m1, m2, r, g, b; var h = hsl[0], s = hsl[1], l = hsl[2]; m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; m1 = l * 2 - m2; return [this.hueToRGB(m1, m2, h+0.33333), this.hueToRGB(m1, m2, h), this.hueToRGB(m1, m2, h-0.33333)]; }; fb.hueToRGB = function (m1, m2, h) { h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; if (h * 2 < 1) return m2; if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; return m1; }; fb.RGBToHSL = function (rgb) { var min, max, delta, h, s, l; var r = rgb[0], g = rgb[1], b = rgb[2]; min = Math.min(r, Math.min(g, b)); max = Math.max(r, Math.max(g, b)); delta = max - min; l = (min + max) / 2; s = 0; if (l > 0 && l < 1) { s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); } h = 0; if (delta > 0) { if (max == r && max != g) h += (g - b) / delta; if (max == g && max != b) h += (2 + (b - r) / delta); if (max == b && max != r) h += (4 + (r - g) / delta); h /= 6; } return [h, s, l]; }; // Install mousedown handler (the others are set on the document on-demand) $('*', e).mousedown(fb.mousedown); // Init color fb.setColor('#000000'); // Set linked elements/callback if (callback) { fb.linkTo(callback); } };
JavaScript
/** * Provides AJAX-like page updating via AHAH (Asynchronous HTML and HTTP). * * AHAH is a method of making a request via Javascript while viewing an HTML * page. The request returns a small chunk of HTML, which is then directly * injected into the page. * * Drupal uses this file to enhance form elements with #ahah[path] and * #ahah[wrapper] properties. If set, this file will automatically be included * to provide AHAH capabilities. */ /** * Attaches the ahah behavior to each ahah form element. */ Drupal.behaviors.ahah = function(context) { for (var base in Drupal.settings.ahah) { if (!$('#'+ base + '.ahah-processed').size()) { var element_settings = Drupal.settings.ahah[base]; $(element_settings.selector).each(function() { element_settings.element = this; var ahah = new Drupal.ahah(base, element_settings); }); $('#'+ base).addClass('ahah-processed'); } } }; /** * AHAH object. */ Drupal.ahah = function(base, element_settings) { // Set the properties for this object. this.element = element_settings.element; this.selector = element_settings.selector; this.event = element_settings.event; this.keypress = element_settings.keypress; this.url = element_settings.url; this.wrapper = '#'+ element_settings.wrapper; this.effect = element_settings.effect; this.method = element_settings.method; this.progress = element_settings.progress; this.button = element_settings.button || { }; if (this.effect == 'none') { this.showEffect = 'show'; this.hideEffect = 'hide'; this.showSpeed = ''; } else if (this.effect == 'fade') { this.showEffect = 'fadeIn'; this.hideEffect = 'fadeOut'; this.showSpeed = 'slow'; } else { this.showEffect = this.effect + 'Toggle'; this.hideEffect = this.effect + 'Toggle'; this.showSpeed = 'slow'; } // Record the form action and target, needed for iFrame file uploads. var form = $(this.element).parents('form'); this.form_action = form.attr('action'); this.form_target = form.attr('target'); this.form_encattr = form.attr('encattr'); // Set the options for the ajaxSubmit function. // The 'this' variable will not persist inside of the options object. var ahah = this; var options = { url: ahah.url, data: ahah.button, beforeSubmit: function(form_values, element_settings, options) { return ahah.beforeSubmit(form_values, element_settings, options); }, success: function(response, status) { // Sanity check for browser support (object expected). // When using iFrame uploads, responses must be returned as a string. if (typeof(response) == 'string') { response = Drupal.parseJson(response); } return ahah.success(response, status); }, complete: function(response, status) { if (status == 'error' || status == 'parsererror') { return ahah.error(response, ahah.url); } }, dataType: 'json', type: 'POST' }; // Bind the ajaxSubmit function to the element event. $(element_settings.element).bind(element_settings.event, function() { $(element_settings.element).parents('form').ajaxSubmit(options); return false; }); // If necessary, enable keyboard submission so that AHAH behaviors // can be triggered through keyboard input as well as e.g. a mousedown // action. if (element_settings.keypress) { $(element_settings.element).keypress(function(event) { // Detect enter key. if (event.keyCode == 13) { $(element_settings.element).trigger(element_settings.event); return false; } }); } }; /** * Handler for the form redirection submission. */ Drupal.ahah.prototype.beforeSubmit = function (form_values, element, options) { // Disable the element that received the change. $(this.element).addClass('progress-disabled').attr('disabled', true); // Insert progressbar or throbber. if (this.progress.type == 'bar') { var progressBar = new Drupal.progressBar('ahah-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback)); if (this.progress.message) { progressBar.setProgress(-1, this.progress.message); } if (this.progress.url) { progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500); } this.progress.element = $(progressBar.element).addClass('ahah-progress ahah-progress-bar'); this.progress.object = progressBar; $(this.element).after(this.progress.element); } else if (this.progress.type == 'throbber') { this.progress.element = $('<div class="ahah-progress ahah-progress-throbber"><div class="throbber">&nbsp;</div></div>'); if (this.progress.message) { $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>') } $(this.element).after(this.progress.element); } }; /** * Handler for the form redirection completion. */ Drupal.ahah.prototype.success = function (response, status) { var wrapper = $(this.wrapper); var form = $(this.element).parents('form'); // Manually insert HTML into the jQuery object, using $() directly crashes // Safari with long string lengths. http://dev.jquery.com/ticket/1152 var new_content = $('<div></div>').html(response.data); // Restore the previous action and target to the form. form.attr('action', this.form_action); this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target'); this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr'); // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } $(this.element).removeClass('progress-disabled').attr('disabled', false); // Add the new content to the page. Drupal.freezeHeight(); if (this.method == 'replace') { wrapper.empty().append(new_content); } else { wrapper[this.method](new_content); } // Immediately hide the new content if we're using any effects. if (this.showEffect != 'show') { new_content.hide(); } // Determine what effect use and what content will receive the effect, then // show the new content. For browser compatibility, Safari is excluded from // using effects on table rows. if (($.browser.safari && $("tr.ahah-new-content", new_content).size() > 0)) { new_content.show(); } else if ($('.ahah-new-content', new_content).size() > 0) { $('.ahah-new-content', new_content).hide(); new_content.show(); $(".ahah-new-content", new_content)[this.showEffect](this.showSpeed); } else if (this.showEffect != 'show') { new_content[this.showEffect](this.showSpeed); } // Attach all javascript behaviors to the new content, if it was successfully // added to the page, this if statement allows #ahah[wrapper] to be optional. if (new_content.parents('html').length > 0) { Drupal.attachBehaviors(new_content); } Drupal.unfreezeHeight(); }; /** * Handler for the form redirection error. */ Drupal.ahah.prototype.error = function (response, uri) { alert(Drupal.ahahError(response, uri)); // Resore the previous action and target to the form. $(this.element).parent('form').attr( { action: this.form_action, target: this.form_target} ); // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } // Undo hide. $(this.wrapper).show(); // Re-enable the element. $(this.element).removeClass('progess-disabled').attr('disabled', false); };
JavaScript
Drupal.behaviors.multiselectSelector = function() { // Automatically selects the right radio button in a multiselect control. $('.multiselect select:not(.multiselectSelector-processed)') .addClass('multiselectSelector-processed').change(function() { $('.multiselect input:radio[value="'+ this.id.substr(5) +'"]') .attr('checked', true); }); };
JavaScript
var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} }; /** * Set the variable that indicates if JavaScript behaviors should be applied */ Drupal.jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById; /** * Attach all registered behaviors to a page element. * * Behaviors are event-triggered actions that attach to page elements, enhancing * default non-Javascript UIs. Behaviors are registered in the Drupal.behaviors * object as follows: * @code * Drupal.behaviors.behaviorName = function () { * ... * }; * @endcode * * Drupal.attachBehaviors is added below to the jQuery ready event and so * runs on initial page load. Developers implementing AHAH/AJAX in their * solutions should also call this function after new page content has been * loaded, feeding in an element to be processed, in order to attach all * behaviors to the new content. * * Behaviors should use a class in the form behaviorName-processed to ensure * the behavior is attached only once to a given element. (Doing so enables * the reprocessing of given elements, which may be needed on occasion despite * the ability to limit behavior attachment to a particular element.) * * @param context * An element to attach behaviors to. If none is given, the document element * is used. */ Drupal.attachBehaviors = function(context) { context = context || document; if (Drupal.jsEnabled) { // Execute all of them. jQuery.each(Drupal.behaviors, function() { this(context); }); } }; /** * Encode special characters in a plain-text string for display as HTML. */ Drupal.checkPlain = function(str) { str = String(str); var replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }; for (var character in replace) { var regex = new RegExp(character, 'g'); str = str.replace(regex, replace[character]); } return str; }; /** * Translate strings to the page language or a given language. * * See the documentation of the server-side t() function for further details. * * @param str * A string containing the English string to translate. * @param args * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * Based on the first character of the key, the value is escaped and/or themed: * - !variable: inserted as is * - @variable: escape plain text to HTML (Drupal.checkPlain) * - %variable: escape text and theme as a placeholder for user-submitted * content (checkPlain + Drupal.theme('placeholder')) * @return * The translated string. */ Drupal.t = function(str, args) { // Fetch the localized version of the string. if (Drupal.locale.strings && Drupal.locale.strings[str]) { str = Drupal.locale.strings[str]; } if (args) { // Transform arguments before inserting them for (var key in args) { switch (key.charAt(0)) { // Escaped only case '@': args[key] = Drupal.checkPlain(args[key]); break; // Pass-through case '!': break; // Escaped and placeholder case '%': default: args[key] = Drupal.theme('placeholder', args[key]); break; } str = str.replace(key, args[key]); } } return str; }; /** * Format a string containing a count of items. * * This function ensures that the string is pluralized correctly. Since Drupal.t() is * called by this function, make sure not to pass already-localized strings to it. * * See the documentation of the server-side format_plural() function for further details. * * @param count * The item count to display. * @param singular * The string for the singular case. Please make sure it is clear this is * singular, to ease translation (e.g. use "1 new comment" instead of "1 new"). * Do not use @count in the singular string. * @param plural * The string for the plural case. Please make sure it is clear this is plural, * to ease translation. Use @count in place of the item count, as in "@count * new comments". * @param args * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * Based on the first character of the key, the value is escaped and/or themed: * - !variable: inserted as is * - @variable: escape plain text to HTML (Drupal.checkPlain) * - %variable: escape text and theme as a placeholder for user-submitted * content (checkPlain + Drupal.theme('placeholder')) * Note that you do not need to include @count in this array. * This replacement is done automatically for the plural case. * @return * A translated string. */ Drupal.formatPlural = function(count, singular, plural, args) { var args = args || {}; args['@count'] = count; // Determine the index of the plural form. var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1); if (index == 0) { return Drupal.t(singular, args); } else if (index == 1) { return Drupal.t(plural, args); } else { args['@count['+ index +']'] = args['@count']; delete args['@count']; return Drupal.t(plural.replace('@count', '@count['+ index +']')); } }; /** * Generate the themed representation of a Drupal object. * * All requests for themed output must go through this function. It examines * the request and routes it to the appropriate theme function. If the current * theme does not provide an override function, the generic theme function is * called. * * For example, to retrieve the HTML that is output by theme_placeholder(text), * call Drupal.theme('placeholder', text). * * @param func * The name of the theme function to call. * @param ... * Additional arguments to pass along to the theme function. * @return * Any data the theme function returns. This could be a plain HTML string, * but also a complex object. */ Drupal.theme = function(func) { for (var i = 1, args = []; i < arguments.length; i++) { args.push(arguments[i]); } return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args); }; /** * Parse a JSON response. * * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message. */ Drupal.parseJson = function (data) { if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) { return { status: 0, data: data.length ? data : Drupal.t('Unspecified error') }; } return eval('(' + data + ');'); }; /** * Freeze the current body height (as minimum height). Used to prevent * unnecessary upwards scrolling when doing DOM manipulations. */ Drupal.freezeHeight = function () { Drupal.unfreezeHeight(); var div = document.createElement('div'); $(div).css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: $('body').css('height') }).attr('id', 'freeze-height'); $('body').append(div); }; /** * Unfreeze the body height */ Drupal.unfreezeHeight = function () { $('#freeze-height').remove(); }; /** * Wrapper around encodeURIComponent() which avoids Apache quirks (equivalent of * drupal_urlencode() in PHP). This function should only be used on paths, not * on query string arguments. */ Drupal.encodeURIComponent = function (item, uri) { uri = uri || location.href; item = encodeURIComponent(item).replace(/%2F/g, '/'); return (uri.indexOf('?q=') != -1) ? item : item.replace(/%26/g, '%2526').replace(/%23/g, '%2523').replace(/\/\//g, '/%252F'); }; /** * Get the text selection in a textarea. */ Drupal.getSelection = function (element) { if (typeof(element.selectionStart) != 'number' && document.selection) { // The current selection var range1 = document.selection.createRange(); var range2 = range1.duplicate(); // Select all text. range2.moveToElementText(element); // Now move 'dummy' end point to end point of original range. range2.setEndPoint('EndToEnd', range1); // Now we can calculate start and end points. var start = range2.text.length - range1.text.length; var end = start + range1.text.length; return { 'start': start, 'end': end }; } return { 'start': element.selectionStart, 'end': element.selectionEnd }; }; /** * Build an error message from ahah response. */ Drupal.ahahError = function(xmlhttp, uri) { if (xmlhttp.status == 200) { if (jQuery.trim($(xmlhttp.responseText).text())) { var message = Drupal.t("An error occurred. \n@uri\n@text", {'@uri': uri, '@text': xmlhttp.responseText }); } else { var message = Drupal.t("An error occurred. \n@uri\n(no information available).", {'@uri': uri, '@text': xmlhttp.responseText }); } } else { var message = Drupal.t("An HTTP error @status occurred. \n@uri", {'@uri': uri, '@status': xmlhttp.status }); } return message; } // Global Killswitch on the <html> element if (Drupal.jsEnabled) { // Global Killswitch on the <html> element $(document.documentElement).addClass('js'); // 'js enabled' cookie document.cookie = 'has_js=1; path=/'; // Attach all behaviors. $(document).ready(function() { Drupal.attachBehaviors(this); }); } /** * The default themes. */ Drupal.theme.prototype = { /** * Formats text for emphasized display in a placeholder inside a sentence. * * @param str * The text to format (plain-text). * @return * The formatted text (html). */ placeholder: function(str) { return '<em>' + Drupal.checkPlain(str) + '</em>'; } };
JavaScript
/** * Attaches the autocomplete behavior to all required fields */ Drupal.behaviors.autocomplete = function (context) { var acdb = []; $('input.autocomplete:not(.autocomplete-processed)', context).each(function () { var uri = this.value; if (!acdb[uri]) { acdb[uri] = new Drupal.ACDB(uri); } var input = $('#' + this.id.substr(0, this.id.length - 13)) .attr('autocomplete', 'OFF')[0]; $(input.form).submit(Drupal.autocompleteSubmit); new Drupal.jsAC(input, acdb[uri]); $(this).addClass('autocomplete-processed'); }); }; /** * Prevents the form from submitting if the suggestions popup is open * and closes the suggestions popup when doing so. */ Drupal.autocompleteSubmit = function () { return $('#autocomplete').each(function () { this.owner.hidePopup(); }).size() == 0; }; /** * An AutoComplete object */ Drupal.jsAC = function (input, db) { var ac = this; this.input = input; this.db = db; $(this.input) .keydown(function (event) { return ac.onkeydown(this, event); }) .keyup(function (event) { ac.onkeyup(this, event); }) .blur(function () { ac.hidePopup(); ac.db.cancel(); }); }; /** * Handler for the "keydown" event */ Drupal.jsAC.prototype.onkeydown = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 40: // down arrow this.selectDown(); return false; case 38: // up arrow this.selectUp(); return false; default: // all other keys return true; } }; /** * Handler for the "keyup" event */ Drupal.jsAC.prototype.onkeyup = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 16: // shift case 17: // ctrl case 18: // alt case 20: // caps lock case 33: // page up case 34: // page down case 35: // end case 36: // home case 37: // left arrow case 38: // up arrow case 39: // right arrow case 40: // down arrow return true; case 9: // tab case 13: // enter case 27: // esc this.hidePopup(e.keyCode); return true; default: // all other keys if (input.value.length > 0) this.populatePopup(); else this.hidePopup(e.keyCode); return true; } }; /** * Puts the currently highlighted suggestion into the autocomplete field */ Drupal.jsAC.prototype.select = function (node) { this.input.value = node.autocompleteValue; }; /** * Highlights the next suggestion */ Drupal.jsAC.prototype.selectDown = function () { if (this.selected && this.selected.nextSibling) { this.highlight(this.selected.nextSibling); } else { var lis = $('li', this.popup); if (lis.size() > 0) { this.highlight(lis.get(0)); } } }; /** * Highlights the previous suggestion */ Drupal.jsAC.prototype.selectUp = function () { if (this.selected && this.selected.previousSibling) { this.highlight(this.selected.previousSibling); } }; /** * Highlights a suggestion */ Drupal.jsAC.prototype.highlight = function (node) { if (this.selected) { $(this.selected).removeClass('selected'); } $(node).addClass('selected'); this.selected = node; }; /** * Unhighlights a suggestion */ Drupal.jsAC.prototype.unhighlight = function (node) { $(node).removeClass('selected'); this.selected = false; }; /** * Hides the autocomplete suggestions */ Drupal.jsAC.prototype.hidePopup = function (keycode) { // Select item if the right key or mousebutton was pressed if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) { this.input.value = this.selected.autocompleteValue; } // Hide popup var popup = this.popup; if (popup) { this.popup = null; $(popup).fadeOut('fast', function() { $(popup).remove(); }); } this.selected = false; }; /** * Positions the suggestions popup and starts a search */ Drupal.jsAC.prototype.populatePopup = function () { // Show popup if (this.popup) { $(this.popup).remove(); } this.selected = false; this.popup = document.createElement('div'); this.popup.id = 'autocomplete'; this.popup.owner = this; $(this.popup).css({ marginTop: this.input.offsetHeight +'px', width: (this.input.offsetWidth - 4) +'px', display: 'none' }); $(this.input).before(this.popup); // Do search this.db.owner = this; this.db.search(this.input.value); }; /** * Fills the suggestion popup with any matches received */ Drupal.jsAC.prototype.found = function (matches) { // If no value in the textfield, do not show the popup. if (!this.input.value.length) { return false; } // Prepare matches var ul = document.createElement('ul'); var ac = this; for (key in matches) { var li = document.createElement('li'); $(li) .html('<div>'+ matches[key] +'</div>') .mousedown(function () { ac.select(this); }) .mouseover(function () { ac.highlight(this); }) .mouseout(function () { ac.unhighlight(this); }); li.autocompleteValue = key; $(ul).append(li); } // Show popup with matches, if any if (this.popup) { if (ul.childNodes.length > 0) { $(this.popup).empty().append(ul).show(); } else { $(this.popup).css({visibility: 'hidden'}); this.hidePopup(); } } }; Drupal.jsAC.prototype.setStatus = function (status) { switch (status) { case 'begin': $(this.input).addClass('throbbing'); break; case 'cancel': case 'error': case 'found': $(this.input).removeClass('throbbing'); break; } }; /** * An AutoComplete DataBase object */ Drupal.ACDB = function (uri) { this.uri = uri; this.delay = 300; this.cache = {}; }; /** * Performs a cached and delayed search */ Drupal.ACDB.prototype.search = function (searchString) { var db = this; this.searchString = searchString; // See if this key has been searched for before if (this.cache[searchString]) { return this.owner.found(this.cache[searchString]); } // Initiate delayed search if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(function() { db.owner.setStatus('begin'); // Ajax GET request for autocompletion $.ajax({ type: "GET", url: db.uri +'/'+ Drupal.encodeURIComponent(searchString), dataType: 'json', success: function (matches) { if (typeof matches['status'] == 'undefined' || matches['status'] != 0) { db.cache[searchString] = matches; // Verify if these are still the matches the user wants to see if (db.searchString == searchString) { db.owner.found(matches); } db.owner.setStatus('found'); } }, error: function (xmlhttp) { alert(Drupal.ahahError(xmlhttp, db.uri)); } }); }, this.delay); }; /** * Cancels the current autocomplete request */ Drupal.ACDB.prototype.cancel = function() { if (this.owner) this.owner.setStatus('cancel'); if (this.timer) clearTimeout(this.timer); this.searchString = ''; };
JavaScript
/** * A progressbar object. Initialized with the given id. Must be inserted into * the DOM afterwards through progressBar.element. * * method is the function which will perform the HTTP request to get the * progress bar state. Either "GET" or "POST". * * e.g. pb = new progressBar('myProgressBar'); * some_element.appendChild(pb.element); */ Drupal.progressBar = function (id, updateCallback, method, errorCallback) { var pb = this; this.id = id; this.method = method || "GET"; this.updateCallback = updateCallback; this.errorCallback = errorCallback; this.element = document.createElement('div'); this.element.id = id; this.element.className = 'progress'; $(this.element).html('<div class="bar"><div class="filled"></div></div>'+ '<div class="percentage"></div>'+ '<div class="message">&nbsp;</div>'); }; /** * Set the percentage and status message for the progressbar. */ Drupal.progressBar.prototype.setProgress = function (percentage, message) { if (percentage >= 0 && percentage <= 100) { $('div.filled', this.element).css('width', percentage +'%'); $('div.percentage', this.element).html(percentage +'%'); } $('div.message', this.element).html(message); if (this.updateCallback) { this.updateCallback(percentage, message, this); } }; /** * Start monitoring progress via Ajax. */ Drupal.progressBar.prototype.startMonitoring = function (uri, delay) { this.delay = delay; this.uri = uri; this.sendPing(); }; /** * Stop monitoring progress via Ajax. */ Drupal.progressBar.prototype.stopMonitoring = function () { clearTimeout(this.timer); // This allows monitoring to be stopped from within the callback this.uri = null; }; /** * Request progress data from server. */ Drupal.progressBar.prototype.sendPing = function () { if (this.timer) { clearTimeout(this.timer); } if (this.uri) { var pb = this; // When doing a post request, you need non-null data. Otherwise a // HTTP 411 or HTTP 406 (with Apache mod_security) error may result. $.ajax({ type: this.method, url: this.uri, data: '', dataType: 'json', success: function (progress) { // Display errors if (progress.status == 0) { pb.displayError(progress.data); return; } // Update display pb.setProgress(progress.percentage, progress.message); // Schedule next timer pb.timer = setTimeout(function() { pb.sendPing(); }, pb.delay); }, error: function (xmlhttp) { pb.displayError(Drupal.ahahError(xmlhttp, pb.uri)); } }); } }; /** * Display errors on the page. */ Drupal.progressBar.prototype.displayError = function (string) { var error = document.createElement('div'); error.className = 'error'; error.innerHTML = string; $(this.element).before(error).hide(); if (this.errorCallback) { this.errorCallback(this); } };
JavaScript
Drupal.behaviors.tableSelect = function (context) { $('form table:has(th.select-all):not(.tableSelect-processed)', context).each(Drupal.tableSelect); }; Drupal.tableSelect = function() { // Do not add a "Select all" checkbox if there are no rows with checkboxes in the table if ($('td input:checkbox', this).size() == 0) { return; } // Keep track of the table, which checkbox is checked and alias the settings. var table = this, checkboxes, lastChecked; var strings = { 'selectAll': Drupal.t('Select all rows in this table'), 'selectNone': Drupal.t('Deselect all rows in this table') }; var updateSelectAll = function(state) { $('th.select-all input:checkbox', table).each(function() { $(this).attr('title', state ? strings.selectNone : strings.selectAll); this.checked = state; }); }; // Find all <th> with class select-all, and insert the check all checkbox. $('th.select-all', table).prepend($('<input type="checkbox" class="form-checkbox" />').attr('title', strings.selectAll)).click(function(event) { if ($(event.target).is('input:checkbox')) { // Loop through all checkboxes and set their state to the select all checkbox' state. checkboxes.each(function() { this.checked = event.target.checked; // Either add or remove the selected class based on the state of the check all checkbox. $(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected'); }); // Update the title and the state of the check all box. updateSelectAll(event.target.checked); } }); // For each of the checkboxes within the table. checkboxes = $('td input:checkbox', table).click(function(e) { // Either add or remove the selected class based on the state of the check all checkbox. $(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected'); // If this is a shift click, we need to highlight everything in the range. // Also make sure that we are actually checking checkboxes over a range and // that a checkbox has been checked or unchecked before. if (e.shiftKey && lastChecked && lastChecked != e.target) { // We use the checkbox's parent TR to do our range searching. Drupal.tableSelectRange($(e.target).parents('tr')[0], $(lastChecked).parents('tr')[0], e.target.checked); } // If all checkboxes are checked, make sure the select-all one is checked too, otherwise keep unchecked. updateSelectAll((checkboxes.length == $(checkboxes).filter(':checked').length)); // Keep track of the last checked checkbox. lastChecked = e.target; }); $(this).addClass('tableSelect-processed'); }; Drupal.tableSelectRange = function(from, to, state) { // We determine the looping mode based on the the order of from and to. var mode = from.rowIndex > to.rowIndex ? 'previousSibling' : 'nextSibling'; // Traverse through the sibling nodes. for (var i = from[mode]; i; i = i[mode]) { // Make sure that we're only dealing with elements. if (i.nodeType != 1) { continue; } // Either add or remove the selected class based on the state of the target checkbox. $(i)[ state ? 'addClass' : 'removeClass' ]('selected'); $('input:checkbox', i).each(function() { this.checked = state; }); if (to.nodeType) { // If we are at the end of the range, stop. if (i == to) { break; } } // A faster alternative to doing $(i).filter(to).length. else if (jQuery.filter(to, [i]).r.length) { break; } } };
JavaScript
/**//**//**//**//**//**//* ** ================================================================================================== ** 类名:1k.js ** 版本:1.0 ** 功能:js类库 ** 示例: --------------------------------------------------------------------------------------------------- 文档:http://www.1kjs.com/lib/doc/ --------------------------------------------------------------------------------------------------- ** 作者:zjfeihu ** 邮件:zjfeihu@126.com ** 创建:2011/08/01 ** 更新:2011/08/27 ** 类库地址:http://www.1kjs.com/lib/ ** ================================================================================================== **/ !function(){ var $PID=1, $WIN=window, $DOC=document, $DE=$DOC.documentElement, $HEAD=$g('head')?$g('head')[0]:$g('html')[0], $Class=function(){ var initializing=0,//构造函数初始化锁定 fnTest=/\b_super\b/,//检测类中是否使用超类的方法 Class=function(){};//基类 Class.prototype={//基类的API ops:function(o1,o2){//将o1中的val映射成对象的私有属性,假如key在o2中存在,则优先使用o2中的值 o2=o2||{}; for(var key in o1){ this['_'+key]=key in o2?o2[key]:o1[key]; } } }; function _implements(source){//扩展类的API if(typeof source == "function") {//传入是类,则取类的原型 source=source.prototype; } for(var ex in source){ this.prototype[ex]=source[ex]; } return this; } Class.extend=function(prop,_static){ var _super = this.prototype;//超类的原型 initializing=1;//锁定初始化,阻止超类执行初始化 var _prototype=new this();//只是通过此来继承,而非创建类 initializing=0;//解锁初始化 function fn(name, fn) {//让子类能使用超类的方法 return function() { this._super = _super[name];//保存超类方法,此this后面通过apply改变成本体类引用,this._super是动态的,即在需要使用的时候自动指向指定的_super var ret = fn.apply(this, arguments);//执行fn方法 delete this._super;//在子类调用完毕释放this._super return ret;//返回刚才创建的方法 }; } var _mtd;//临时变量,存方法 for (var name in prop){//遍历传进来的所有原型方法 _mtd=prop[name]; _prototype[name] =(typeof _mtd=='function'&& typeof _super[name]=='function'&& fnTest.test(_mtd))?fn(name,_mtd):_mtd;//假如传进来的是函数,进行是否调用超类的检测来决定是否保存超类 } function F(arg1) {//构造函数,假如没有被初始化,并且有初始化函数,执行初始化 if(this.constructor!=Object){//让类在使用的时候前面可以省略new return new F({ FID:'JClassArguments', val:arguments }); } if (!initializing&&this.init){ if(arg1&&arg1.FID&&arg1.FID=='JClassArguments'){ this.init.apply(this, arg1.val); }else{ this.init.apply(this, arguments); } this.init=null; }; } if(_static){//类的静态方法 for(var ex in _static){ F[ex]=_static[ex]; } } F.prototype=_prototype;//创建。。。 F.constructor=F;//修正用 F.extend=arguments.callee; F.implements=_implements;//扩展api return F; }; return Class; }(), $EVENTQUEUE={}, $E_add=function(){ if($DOC.attachEvent){ return function(node,type,fn){ node.attachEvent('on'+type,fn); }; }else{ return function(node,type,fn){ node.addEventListener(type,fn,false); }; } }(), $ready=function(){ var isReady=false, //判断onDOMReady方法是否已经被执行过 readyList= [],//把需要执行的方法先暂存在这个数组里 timer,//定时器句柄 ready=function(fn) { if (isReady){ fn(); }else{ readyList.push(fn); } }, onDOMReady=function(){ for(var i=0,lg=readyList.length;i<lg;i++){ readyList[i](); } readyList = null; }, bindReady = function(evt){ if(isReady)return; isReady=true; onDOMReady(); if($DOC.removeEventListener){ $DOC.removeEventListener("DOMContentLoaded",bindReady,false); }else if($DOC.attachEvent){ $DOC.detachEvent("onreadystatechange", bindReady); if($WIN == $WIN.top){ clearInterval(timer); timer = null; } } }; if($DOC.addEventListener){ $DOC.addEventListener("DOMContentLoaded", bindReady, false); }else if($DOC.attachEvent){ $DOC.attachEvent("onreadystatechange", function(){ if((/loaded|complete/).test($DOC.readyState))bindReady(); }); if($WIN == $WIN.top){ timer = setInterval(function(){ try{ isReady||$DOC.documentElement.doScroll('left');//在IE下用能否执行doScroll判断dom是否加载完毕 }catch(e){ return; } bindReady(); },5); } } return ready; }(), //浏览器相关 $browser=function(){ var ua=navigator.userAgent.toLowerCase(), sys={}, s; (s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0; return sys; }(), $isIE6=/MSIE\s*6.0/i.test(navigator.appVersion), $XHR=function(){ return $WIN.XMLHttpRequest||function(X){ var xstr=[0,'Microsoft.XMLHTTP','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP'], i=4; while(--i){ try { X = new ActiveXObject(xstr[i]); return function(){return X;} }catch(e){ ;;;alert('ajax对象不存在!'); } } }(); }(), $scrollTop=function(){ var tr, cr=$browser.chrome; return function(y,t,tp){ var ds=cr?$DOC.body:$DE; switch(arguments.length){ case 0:return ds['scrollTop']; case 1:return ds['scrollTop']=y; default: var s0=0, s1=Math.ceil(t/16), z0=ds['scrollTop'], tp=$EASING[tp||'circOut'], zc=y-z0; !function(me){ clearTimeout(tr); me=arguments.callee; tr=setTimeout(function(){ if(s0<s1){ ds['scrollTop']=tp(s0,z0,zc,s1); me(); }else{ ds['scrollTop']=y; clearTimeout(tr); } s0++; },16); }(); } }; }(), $ANIMEQUEQU={}, $EASING={ //t:当前步数 //b:开始位置 //c:总改变量 //d:总步数 Linear: function(t,b,c,d){ return c*t/d + b; }, slowIn:function(t,b,c,d){return c*(t/=d)*t + b;}, slowOut:function(t,b,c,d){return -c *(t/=d)*(t-2) + b;}, slowBoth:function(t,b,c,d){ if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, In: function(t,b,c,d){ return c*(t/=d)*t*t*t + b; }, Out: function(t,b,c,d){ return -c * ((t=t/d-1)*t*t*t - 1) + b; }, Both: function(t,b,c,d){ if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, fastIn: function(t,b,c,d){ return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, fastOut: function(t,b,c,d){ return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, fastBoth: function(t,b,c,d){ if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, circIn: function(t,b,c,d){ return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, circOut: function(t,b,c,d){ return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, circBoth: function(t,b,c,d){ if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, elasticIn: function(t,b,c,d,a,p){ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a || a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, elasticOut: function(t,b,c,d,a,p){ if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (!a || a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b); }, elasticBoth: function(t,b,c,d,a,p){ if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (!a || a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, backIn: function(t,b,c,d,s){ if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, backOut: function(t,b,c,d,s){ if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, backBoth: function(t,b,c,d,s){ if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, bounceIn: function(t,b,c,d){ return c - $EASING.bounceOut(d-t, 0, c, d) + b; }, bounceOut: function(t,b,c,d){ if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, bounceBoth: function(t,b,c,d){ if (t < d/2) return $EASING.bounceIn(t*2, 0, c, d) * .5 + b; else return $EASING.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; } }, $DRAGQUEQU={}, $drag=$Class.extend({ init:function(node,ops){ this.node=node; this.ops({ before:0,//拖动前 after:0,//拖动完成 runing:0,//拖动中 clone:0,//是否clone节点 lockx:0,//锁定x方向 locky:0,//锁定y方向 range:-1//拖动范围控制 },ops); this.addHand(ops.hand||node); }, addHand:function(hand){ $bind(hand,'mousedown',this._beforeDrag,this); }, rmvHand:function(hand){ $bind(hand,'mousedown',this._beforeDrag,this); }, _init:function(evt){ this._hasInit=1; var node=this.node,box=node, offset=$offset(node), marginLeft=$cssnum(node,'marginLeft'), marginTop=$cssnum(node,'marginTop'); if(this._clone){ var clone=$clone(node,true); $css(clone,{ position:'absolute', zIndex:9999, left:offset.left-marginLeft, top:offset.top-marginTop, width:$cssnum(node,'width'), height:$cssnum(node,'height') }); $append($g('body')[0],clone); box=this._clone=clone; } this._style=box.style; this._offsetX=evt.clientX-box.offsetLeft+marginLeft; this._offsetY=evt.clientY-box.offsetTop+marginTop; this._before&&this._before.call(this,evt); if(this._range==-1){//限制在窗口内 this._minX=0; this._minY=0; this._maxX=$DE.clientWidth-box.offsetWidth-marginLeft-$cssnum(box,'marginRight'); this._maxY=$DE.clientHeight-box.offsetHeight-marginTop-$cssnum(box,'marginBottom'); }else if(this._range){ var range=$g(this._range), ro=$offset(range), rw=range.offsetWidth, rh=range.offsetHeight, bl=$css(range,'borderLeftWidth'), br=$css(range,'borderRightWidth'), bt=$css(range,'borderTopWidth'), bb=$css(range,'borderBottomWidth'); this._minX=ro.left+bl; this._minY=ro.top+bt; this._maxX=ro.left+rw-br-box.offsetWidth-marginLeft-$cssnum(box,'marginRight'); this._maxY=ro.top+rh-bb-box.offsetHeight-marginTop-$cssnum(box,'marginBottom'); } }, _beforeDrag:function(evt){ if(evt.mouseKey!='left')return; //evt.stopPropagation(); evt.preventDefault(); this._hasInit=0; if($browser.ie){ this._focusHand=evt.target; $bind(this._focusHand,'losecapture',this._drop,this); this._focusHand.setCapture(false); }else{ var self=this; this._win_blur=$WIN.onblur||null; $WIN.onblur=function(){ self._win_blur&&self._win_blur(); self._drop(evt); }; } $bind($DOC,'mousemove',this._draging,this); $bind($DOC,'mouseup',this._drop,this); }, _draging:function(evt){ $WIN.getSelection?$WIN.getSelection().removeAllRanges():$DOC.selection.empty(); if(!this._hasInit)this._init(evt); var left=evt.clientX-this._offsetX, top=evt.clientY-this._offsetY; if(this._range){ left=Math.min(Math.max(left,this._minX),this._maxX); top=Math.min(Math.max(top,this._minY),this._maxY); } if(!this._lockx)this._style.left=left+'px'; if(!this._locky)this._style.top=top+'px'; this._runing&&this._runing.call(this,evt); }, _drop:function(evt){ $unbind($DOC,'mousemove',this._draging,this); $unbind($DOC,'mouseup',this._drop,this); if($browser.ie){ $unbind(this._focusHand,'losecapture',this._drop,this); this._focusHand.releaseCapture(); }else{ $WIN.onblur=this._win_blur; } this._after&&this._after.call(this,evt); if(this._clone&&this._clone.parentNode){ $remove(this._clone); } }, set:function(ops){ for(var e in ops){ this[e]=ops[e]; } } }); function $1k(selector,context){ switch(typeof selector){ case 'function':; case 'string':; case 'object': if(selector==null||selector==undefined)return null; var jn = new $_1k(selector,context); return jn.node?jn:null; } } function $_1k(selector,context){ if(selector==$DOC||selector==$WIN||$isNode(selector)){ this.node=selector; }else{ var result=$g(selector,context); if(result==null)return null; if(result.nodeName){ this.node=result; }else{ this.nodes=result; this.node=result[0]; } } } function $box(func,arg1,arg2,arg3){ var result=func.call(this,this.node,arg1,arg2,arg3); if(this.nodes&&result==this){ var i=1; while(this.nodes[i]){ func.call(this,this.nodes[i],arg1,arg2,arg3); i++; } return this; }else{ return result; } } function $g(selector,context){ var root=$DOC, id, tag, cls, attr, nodes, reNodes=[]; if(typeof selector=='object')return selector;//传入节点 if(/^#[\w\-]+$/.test(selector)){ return $DOC.getElementById(selector.substr(1)); } selector=selector.match(/^(?:#([\w\-]+))?\s*(?:(\w+))?(?:\.([\w\-]+))?(?:\[(.+)\])?$/); if(selector){ id=selector[1]; tag=selector[2]; cls=selector[3]; attr=selector[4]; }else{ return null; } if(id){ root=$DOC.getElementById(id); if(!root)return null; }else if(typeof context=='object'){ root=context; } nodes=root.getElementsByTagName(tag||'*'); if(cls||attr){ if(cls){ if(!tag&&root.getElementsByClassName){ nodes=root.getElementsByClassName(cls); for(var i=0;i<nodes.length;i++){ reNodes[i]=nodes[i]; } }else{ reNodes=[]; var re=RegExp('(^|\\s)'+cls+'($|\\s)'); for(var i=0,lg=nodes.length;i<lg;i++){ re.test(nodes[i].className)&&reNodes.push(nodes[i]); } } } if(attr){ if(cls)nodes=reNodes.slice(0); reNodes=[]; attr=attr.split('='); if(attr.length==2){ var key=attr[0].split('!'), val=attr[1]||''; if(key.length>1){//=前面跟! key=key[0]; for(var i=0,l=nodes.length; i<l; i++){ nodes[i].getAttribute(key)!=val && reNodes.push(nodes[i]); } }else{ for(var i=0,l=nodes.length; i<l; i++){ nodes[i].getAttribute(key)==val && reNodes.push(nodes[i]); } } }else{ for(var i=0,l=nodes.length; i<l; i++){ nodes[i].hasAttribute(attr) && reNodes.push(nodes[i]); } } } }else{ for(var i=0,lg=nodes.length;i<lg;i++){ reNodes[i]=nodes[i]; } } return reNodes.length?reNodes:null; } function $child(node,index){ var child = [], i=0, ol = node.childNodes; while(ol[i]){ ol[i].nodeType==1 && child.push(ol[i]); i++; } if(index>-1){ child= child[index]; }else if(index<0){ child= child[child.length+index]; }else if(typeof index=='string'){ var nodes=$g(index,node), reNode=[]; $each(nodes,function(){ if(this.parentNode==node){ reNode.push(this); } }); if(reNode.length){ return reNode; } } return child; } function $sibling(node,selector){ var parent=node.parentNode, _node, nodes=selector?$g(selector,node.parentNode):node.parentNode.childNodes, re=[], i=0; while(_node=nodes[i++]){ if(_node.parentNode==parent&&node!=_node&&_node.nodeType==1)re.push(_node); } return re.length?re:null; } function $parent(node,selector){ if(selector==undefined){ return node.parentNode; }else if(selector>0){ selector++; while(selector--){ node=node.parentNode; } return node; }else{ selector=selector.match(/^(?:#([\w\-]+))?\s*(?:(\w+))?(?:.([\w\-]+))?(?:\[(.+)\])?$/); if(selector){ var id=selector[1], tag=selector[2], cls=selector[3], attr=selector[4]; tag=tag&&tag.toUpperCase(); attr=attr&&attr.split('='); }else{ return null; } if(id){ return $g(id); }else{ while(node=node.parentNode){ if( (!cls||cls&&$hcls(node,cls)) &&(!tag||node.nodeName==tag) &&(!attr||$attr(node,attr[0])==attr[1]) ){ return node; } } } } return null; } function $prev(node){ while(node=node.previousSibling){ if(node.nodeType==1){ return node; } } } function $next(node){ while(node=node.nextSibling){ if(node.nodeType==1){ return node; } } } function $node(node){ if($isNode(node))return node; if($is1k(node))return node.node; if(node.indexOf('<')>-1){//非标准创建节点 var prarent=$DOC.createElement('div'); prarent.innerHTML=node; return prarent.firstChild; }else{ return $DOC.createElement(node); } } function $append(node,newNode,index){ if($isArray(newNode)){ var root=$DOC.createDocumentFragment(); $each(newNode,function(){ root.appendChild($node(this)); }); newNode=root; }else{ newNode=$node(newNode); } if(index==undefined){ node.appendChild(newNode); return this; } var child=node.childNodes; if(!$browser.ie){//过滤非Element节点 var _child=[]; for(var i=0,lg=child.length;i<lg;i++){ if(child[i].nodeType==1)_child.push(child[i]); } child=_child; } if(index>-1){ child= child[index]; }else if(index<0){ child= child[Math.max(child.length+index+1,0)]; } if(child){ child.parentNode.insertBefore(newNode,child); }else{ node.appendChild(newNode); } return this; } function $insert(node,newNode,flag){ newNode=$node(newNode); if(flag){ while(node.nextSibling){ node=node.nextSibling; if(node.nodeType==1){ node.parentNode.insertBefore(newNode,node); return this; } } node.parentNode.appendChild(newNode); }else{ node.parentNode.insertBefore(newNode,node); } return this; } function $remove(node){ node.parentNode.removeChild(node); return this; } function $clone(node,flag){ node=node.cloneNode(flag); return node; } function $replace(node,newNode){ node.parentNode.replaceChild($node(newNode),node); return this; } function $cls(node,cls1,cls2){ if(cls2){ node.className=(' '+node.className+' ') .replace(new RegExp('\\s+'+cls2+'\\s+'),' '+cls1+' ') .replace(/^\s+|\s+$/g,''); }else{ if(!cls1){ return node.className; } var _exp=cls1.substr(0,1), _cls=cls1.substr(1); if(_exp=='+'){ if(!$hcls(node,_cls))node.className+=' '+_cls.split(',').join(' '); }else if(_exp=='-'){ node.className=(' '+node.className+' ') .replace(new RegExp('\\s+('+_cls.split(',').join('|')+')(?=\\s+)','g'),'') .replace(/^\s+|\s+$/g,''); }else if(_exp=='='){ node.className=_cls; }else if(cls1){ return $hcls(node,cls1); } } return this; } function $addpx(attr,val){ if(/width|height|left|top|right|bottom|margin|padding/.test(attr)&&/^[\-\d.]+$/.test(val)){//数值属性 return val+'px';//加px } return val; } function $rmvpx(attr,val){ if(/px$/.test(val))return parseFloat(val);//去除px return val; } function $css(node,name,value){ if(typeof value!='undefined'){ name=name.replace(/-(\w)/g,function(_,$1){ return $1.toUpperCase(); }); node.style[name]=$addpx(name,value); }else if(typeof name=='object'){ for(var key in name){ $css(node,key,name[key]); //node.style[key]=$addpx(key,name[key]); } }else{ if(name.indexOf(':')==-1){//无‘:’,比如'background:red' name=name.replace(/-(\w)/g,function(_,$1){ return $1.toUpperCase(); }); return $rmvpx(name,node.style&&node.style[name]||(node.currentStyle||$DOC.defaultView.getComputedStyle(node,null))[name]); }else{ var cssObj=name.replace(/;$/,'').split(';'), cssText; for(var i=0,lg=cssObj.length;i<lg;i++){ cssText=cssObj[i].split(':'); $css(node,cssText.shift(),cssText.join(':')); //?$css(node,cssText[0],cssText[1]);//background:url(http://www....)bug } } } return this; } function $cssnum(node,attr){ var val=+$css(node,attr)||0; if(/^width|height|left|top$/.test(attr)){ switch(attr){ case 'left':return val||node.offsetLeft-$cssnum(node,'marginLeft'); case 'top':return val||node.offsetTop-$cssnum(node,'marginTop'); case 'width':return val ||(node.offsetWidth -$cssnum(node,'paddingLeft') -$cssnum(node,'paddingRight') -$cssnum(node,'borderLeftWidth') -$cssnum(node,'borderRightWidth') ); case 'height':return val ||(node.offsetHeight -$cssnum(node,'paddingTop') -$cssnum(node,'paddingBottom') -$cssnum(node,'borderTopWidth') -$cssnum(node,'borderBottomWidth') ); } } return val; } function $left(node,value){ if(value!=undefined){ $css(node,'left',value); return this; } return $cssnum(node,'left'); } function $top(node,value){ if(value!=undefined){ $css(node,'top',value); return this; } return $cssnum(node,'top'); } function $width(node,value){ if(value!=undefined){ $css(node,'width',value); return this; } return $cssnum(node,'width'); } function $height(node,value){ if(value!=undefined){ $css(node,'height',value); return this; } return $cssnum(node,'height'); } function $offset(node){ var top = 0, left = 0; if ( "getBoundingClientRect" in $DE){ //jquery方法 var box = node.getBoundingClientRect(), body = $DOC.body, clientTop = $DE.clientTop || body.clientTop || 0, clientLeft = $DE.clientLeft || body.clientLeft || 0, top = box.top + ($WIN.pageYOffset || $DE && $DE.scrollTop || body.scrollTop ) - clientTop, left = box.left + ($WIN.pageXOffset || $DE && $DE.scrollLeft || body.scrollLeft) - clientLeft; }else{ do{ top += node.offsetTop || 0; left += node.offsetLeft || 0; node = node.offsetParent; } while (node); } return {left:left, top:top,width:node.offsetWidth,height:node.offsetHeight}; } function $opacity(node,opacity){ if($browser.ie){ if(typeof opacity=='undefined'){ var filter=$css(node,'filter'); if(filter){ return +filter.match(/(\d+)/)[0]/100; } return 1; } node.style.filter='Alpha(opacity='+opacity*100+')'; }else{ if(typeof opacity=='undefined'){ opacity=+$css(node,'opacity'); return opacity>-1?opacity:1; } node.style.opacity=opacity; } return this; } function $show(node){ node.style.display='block'; return this; } function $hide(node){ node.style.display='none'; return this; } function $hcls(node,cls){ if(new RegExp('\\s'+cls+'\\s').test(' '+node.className+' '))return !0; return !1; } function $attr(node,name,value){ if(value===null){ node.removeAttribute(name); }else if(value!=undefined){ if(typeof name=='object'){ for(var attr in name){ $attr(node,attr,name[attr]); } }else{ if(name=='style'){ node.style.cssText=value; }else{ if(node[name]!=undefined){//优先设置js属性 node[name]=value; }else{ node.setAttribute(name,value,2); } } } }else{ if(name=='style'){ return node.style.cssText; }else{ if(name=='href'&&node.nodeName=='A'){ return node.getAttribute(name,2); }else{ if(node[name]!=undefined){//优先获取js属性 return node[name]; }else{ var val=node.getAttribute(name); return val==null?void(0):val; } } } } return this; } function $html(node,html){ var type=typeof html, _html=''; if(type=='undefined'){ return node.innerHTML; }else if(type=='function'){ _html=html(); }else if(type=='object'){ $each(html,function(){ _html+=this; }); }else{ _html=html; } if(node.nodeName=='SELECT'&&type!='undefined'&&$browser.ie){ var s=document.createElement('span'); s.innerHTML='<select>'+_html+'</select>'; node.innerHTML=''; $each($g('option',s),function(){ node.appendChild(this); }); }else{ node.innerHTML=_html; } return this; } function $tag(node,nodeName){ if(typeof nodeName!='undefined'){ return nodeName==node.nodeName; } return node.nodeName; } function $contains(pnode,cnode){ if(cnode==pnode)return 1; if(pnode.contains){//ie下判断是不是属于contains容器中的节点 if(pnode.contains(cnode)){ return 2; } }else if(pnode.compareDocumentPosition){//非ie下判断 if(pnode.compareDocumentPosition(cnode)==20){ return 2; } } return 0; } function $val(node,val){ if(val==undefined)return node.value.replace(/^\s+|\s+$/g,''); node.value=val; return this; } function $Evt(evt){ var _evt={ native:evt, type:evt.type, keyCode:evt.keyCode, clientX:evt.clientX, clientY:evt.clientY, target:evt.target||evt.srcElement, fromTarget:evt.fromElement||(evt.type=='mouseover'?evt.relatedTarget:null), toTarget:evt.toElement||(evt.type=='mouseout'?evt.relatedTarget:null), stopPropagation:function(){ if(evt.stopPropagation){ evt.stopPropagation(); }else{ evt.cancelBubble=true; } }, mouseKey:($browser.ie?{1:'left',4:'middle',2:'right'}:{0:'left',1:'middle',2:'right'})[evt.button], preventDefault:function(){ if(evt.preventDefault){ evt.preventDefault(); }else{ evt.returnValue = false; } } }; return _evt; } function $bind(node,type,func,who){ if(!node.___EVENTID){//没有有事件队列 $EVENTQUEUE[node.___EVENTID=$PID++]=[]; } var EQ=$EVENTQUEUE[node.___EVENTID]; if(!EQ[type]){//无该类型的事件队列 EQ[type]=[]; $E_add(node,type,function(evt){ var Q=EQ[type].slice(0); while(Q[0]){ Q[0].func.call(Q[0].who,$Evt(evt)); Q.shift(); } }); } EQ[type].push({ func:func, who:who||node }); return this; } function $unbind(node,type,func,who){ var Q=$EVENTQUEUE[node.___EVENTID][type],i=0; while(Q[i]){ if(Q[i].func==func&&Q[i].who==(who||node)){ Q.splice(i,1);break; } i++; } return this; } function $cookie(name,value,expire){ if(typeof value!='undefined'){ var exp = new Date(); exp.setTime(exp.getTime()+(value==null?-1:(expire||2592000000))); $DOC.cookie=name+'='+escape(value)+';expires='+exp.toGMTString(); }else{ var arr = $DOC.cookie.match(new RegExp('(^| )'+name+'=([^;]*)(;|$)')); return arr!=null?unescape(arr[2]):null; } } function $each(obj,fn){ if($isArray(obj)){ for(var i=0,lg=obj.length;i<lg;i++){ if(fn.call(obj[i],i,obj[i]))break; } }else{ for(var i in obj){ if(fn.call(obj[i],i,obj[i]))break; } } } function $toJson(obj){ switch(typeof obj){ case 'object': if(obj==null){ return obj; } var E,_json=[]; if(Object.prototype.toString.apply(obj) == '[object Array]'){ for(var e=0,L=obj.length;e<L;e++){ _json[e]=arguments.callee(obj[e]); } return '['+_json.join(',')+']'; } for(e in obj){ _json.push('"'+e+'":'+arguments.callee(obj[e])); } return '{'+_json.join(',')+'}'; case 'function': obj=''+obj; case 'string': return '"'+obj.replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/\r/g,'\\r').replace(/\n/g,'\\n')+'"'; case 'number': case 'boolean': case 'undefined': return obj; } return obj; } function $param(obj,t){ var query=[]; if(typeof obj=='object'){ for(var E in obj){ if(/^e_/.test(E)){ query.push(E.substr(2)+'='+$encodeURL(obj[E])); }else{ query.push(E+'='+obj[E]); } } } if(t)query.push('t='+(+new Date)); return query.join('&'); } function $encodeHTML(str){ return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); } function $decodeHTML(str){ return str.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&'); } function $encodeURL(str){ return str .replace(/%/g,'%25') .replace(/ /g,'%20') .replace(/#/g,'%23') .replace(/&/g,'%26') .replace(/=/g,'%3D') .replace(/\//g,'%2F') .replace(/\?/g,'%3F') .replace(/\+/g,'%2B'); } function $tirm(str){ return str.replace(/^\s+|\s+$/g,''); } function $parseJson(str){ try{ return Function('return '+str)(); }catch(e){ return null; } } function $parseHash(str){ var hash = {}; str.replace(/([^=]+)=([^&=]*)&?/g,function(a,key,val){ hash[key]=val; }); return hash; } function $post(url,callback,data){ var xmlhttp=new $XHR(); xmlhttp.open('post',url,true); xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ callback&&callback(xmlhttp.responseText); }else{ callback&&callback(null); } } }; xmlhttp.send(typeof data=='object'?$param(data):data); return xmlhttp; } function $get(url,callback,data){ var xmlhttp=new $XHR(); if(data)url+='?'+(typeof data=='object'?$param(data):data); xmlhttp.open('get',url,true); xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ callback&&callback(xmlhttp.responseText); }else{ callback&&callback(null); } } }; xmlhttp.send(null); return xmlhttp; } function $img(url,callback){ var img = new Image(); img.src = url; if(img.complete){ return callback&&callback.call(img,img); } img.onload = function () { callback&&callback.call(img,img); }; return this; } function $js(url,callback,data,charset){ var s=$DOC.createElement('script'); if(data)url+='?'+(typeof data=='object'?$param(data):data); s.src=url; charset&&(s.charset=charset); $HEAD.appendChild(s); if(s.readyState){ s.onreadystatechange=function(){ if(s.readyState=='loaded'||s.readyState=='complete'){ callback&&callback(); $HEAD.removeChild(s); } }; }else{ s.onload=function(){ callback&&callback(); $HEAD.removeChild(s); }; } return this; } function $style(arg1){ if(typeof arg1=='object')arg1=arg1.join(''); if(/{[\w\W]+?}/.test(arg1)){//cssText var s=$DOC.createElement('style'); s.type='text/css'; s.styleSheet&&(s.styleSheet.cssText=arg1)||s.appendChild($DOC.createTextNode(arg1)); }else{ var s=$DOC.createElement('link'); s.rel='stylesheet'; s.href=arg1; } $HEAD.appendChild(s); return this; } function $isArray(obj){ return {}.toString.call(obj)=='[object Array]'; } function $isNode(obj){ return obj&&obj.nodeType === 1; } function $is1k(obj){ return !!(obj&&$isNode(obj.node)); } function $proxy(fn,who){ var args=[].slice.call(arguments,2); return function(){ return fn.apply(who,[].concat.apply(args,arguments)); }; } function $anime(node,args){ var ns=node.style, mc=Math.ceil, tp=$EASING[args.type||'Both'], xc=0,//x方向改变量 yc=0,//y方向改变量 wc=0,//宽度改变量 ws=0,//宽度改变比例 hc=0,//高度改变量 hs=0,//高度改变比例 o0=0,//初始透明度 oc=0,//透明度改变 mx=0,//移动x标志 my=0,//移动x标志 rw=0,//改变宽度标志 rh=0,//改变高度标志 co=0,//改变透明度标志 x0,//left初始值 y0,//top初始值 w0,//宽度初始值 h0,//高度初始值 //run,//动画核心函数 opa0, opac, s0=0,//当前步数 s1=mc((args.t||1000)/16),//总步数,普通人眼能看到1/24秒,window反应时钟16ms,这里取32ms timer, end; if($browser.ie&&$browser.ie<8){ $css(node,'zoom',1); } if(typeof args.w!='undefined'){ rw=1; w0=$width(node); if(typeof args.w=='number'){//数字参数,则为目标,字符串则为增量 wc=args.w-w0; }else{ wc=+args.w; } if(args.ws){ x0=$left(node); ws=args.ws; } } if(typeof args.h!='undefined'){ rh=1; h0=$height(node); if(typeof args.h=='number'){ hc=args.h-h0; }else{ hc=+args.h; } if(args.hs){ y0=$top(node); hs=args.hs; } } if(typeof args.x!='undefined'){ mx=1; ws=0; x0=$left(node); if(typeof args.x=='number'){ xc=args.x-x0; }else{ xc=+args.x; } } if(typeof args.y!='undefined'){ my=1; hs=0; y0=$top(node); if(typeof args.y=='number'){ yc=args.y-y0; }else{ yc=+args.y; } } if(args.o>=0){ co=1; opa0=$opacity(node); if(typeof args.o=='number'){ opac=args.o-opa0; }else{ opac=+args.o; } } if(mx||my||ws||hs){ if($css(node,'position')=='static'){ ns.position='relative'; } if($browser.ie&&$browser.ie<7&&(rw||rh)){ ns.overflow='hidden'; } } function _doing(){ if(s0<s1){ if(mx){ ns.left=mc(tp(s0,x0,xc,s1))+'px'; } if(rw){ var w=mc(tp(s0,w0,wc,s1)); ns.width = w+'px'; if(ws){ ns.left=x0+(-ws)*(w-w0)+'px'; } } if(my){ ns.top=mc(tp(s0,y0,yc,s1))+'px'; } if(rh){ var h=mc(tp(s0,h0,hc,s1)); ns.height = h+'px'; if(hs){ ns.top=y0+(-hs)*(h-h0)+'px'; } } if(co){ $opacity(node,tp(s0,opa0,opac,s1)); } s0++; timer=setTimeout(_doing,15.6); }else{ // 最终修正误差 if(mx){ ns.left=x0+xc+'px'; } if(rw){ ns.width = w0+wc+'px'; if(ws)ns.left=x0+(-ws)*(wc)+'px'; } if(my){ ns.top=y0+yc+'px'; } if(rh){ ns.height = h0+hc+'px'; if(hs){ ns.top=y0+(-hs)*(hc)+'px'; } } if(co){ $opacity(node,opa0+opac); } args.after&&args.after(); } args.running&&args.running(); } args.before&&args.before(); timer=setTimeout(_doing,16); return{ stop:function(){ if(!args.lock)clearTimeout(timer); args.stop&&args.stop(); } }; } $1k.Class=function(ops){ //;;;if(!/object|function/.test(typeof ops)||ops==null){alert('参数类型不对!');}; return $Class.extend(typeof ops=='function'?ops($1k):ops); }; $1k.extend=function(name,fn){ $_1k.prototype[name]=fn; }; $1k.widget=function(name,fn){ if(typeof fn=='function'){ $1k[name]=fn($1k); }else{ var Class=$Class.extend(fn); $1k[name]=function(ops){ return new Class(ops); }; } }; $1k.g=$g; $_1k.prototype.find=function(selector){ return $1k(selector,this.node); }; $_1k.prototype.eq=function(i){ if(i<0)i=this.nodes.length+i; return $1k(this.nodes[i]); }; $_1k.prototype.child=function(index){ return $1k($child(this.node,index)); }; $_1k.prototype.sibling=function(selector){ return $1k($sibling(this.node,selector)); }; $_1k.prototype.parent=function(index){ return $1k($parent(this.node,index)); }; $_1k.prototype.prev=function(){ return $1k($prev(this.node)); }; $_1k.prototype.next=function(){ return $1k($next(this.node)); }; $_1k.prototype.each=function(func){ if(this.nodes){ var i=0; while(this.nodes[i]){ func.call($1k(this.nodes[i]),i); i++; } }else if(this.node){ func.call(this,0); } return this; }; $1k.node=function(html){ return $1k($node(html)); }; $_1k.prototype.append=function(newNode,index){ return $box.call(this,$append,newNode,index); }; $_1k.prototype.insert=function(newNode,flag){ return $box.call(this,$insert,newNode,flag); }; $_1k.prototype.remove=function(){ return $box.call(this,$remove); }; $_1k.prototype.clone=function(flag){ return $1k($clone(this.node,flag)); }; $_1k.prototype.replace=function(newNode){ return $box.call(this,$replace,newNode); }; $_1k.prototype.cls=function(cls1,cls2){ return $box.call(this,$cls,cls1,cls2); }; $_1k.prototype.css=function(name,value){ return $box.call(this,$css,name,value); }; $_1k.prototype.px=function(name){ return $cssnum(this.node,name); }; $_1k.prototype.left=function(value){ return $box.call(this,$left,value); }; $_1k.prototype.top=function(value){ return $box.call(this,$top,value); }; $_1k.prototype.width=function(value){ return $box.call(this,$width,value); }; $_1k.prototype.height=function(value){ return $box.call(this,$height,value); }; $_1k.prototype.offsetLeft=function(){ return $offset(this.node).left; }; $_1k.prototype.offsetTop=function(){ return $offset(this.node).top; }; $_1k.prototype.offset=function(){ return $offset(this.node); }; $_1k.prototype.offsetWidth=function(){ return this.node.offsetWidth; }; $_1k.prototype.offsetHeight=function(){ return this.node.offsetHeight; }; $_1k.prototype.opacity=function(opacity){ return $box.call(this,$opacity,opacity); }; $_1k.prototype.show=function(){ return $box.call(this,$show); }; $_1k.prototype.hide=function(){ return $box.call(this,$hide); }; $_1k.prototype.attr=function(name,value){ return $box.call(this,$attr,name,value); }; $_1k.prototype.html=function(html){ return $box.call(this,$html,html); }; $_1k.prototype.tag=function(nodeName){ return $tag(this.node,nodeName); }; $_1k.prototype.contains=function(cnode){ return $contains(this.node,cnode); }; $_1k.prototype.val=function(value){ return $box.call(this,$val,value); }; $_1k.prototype.length=function(){ return this.nodes.length||1; }; $1k.ready=$ready; $_1k.prototype.on=function(type,func,who){ var result=$bind.call(this,this.node,type,func,who||this.node); if(this.nodes&&result==this){ var i=1; while(this.nodes[i]){ $bind.call(this,this.nodes[i],type,func,who||this.nodes[i]); i++; } return this; }else{ return result; } }; $_1k.prototype.un=function(type,func,who){ var result=$unbind.call(this,this.node,type,func,who||this.node); if(this.nodes&&result==this){ var i=1; while(this.nodes[i]){ $unbind.call(this,this.nodes[i],type,func,who||this.nodes[i]); i++; } return this; }else{ return result; } }; $_1k.prototype.click=function(func,who){ var result=$bind.call(this,this.node,'click',func,who||$1k(this.node)); if(this.nodes&&result==this){ var i=1; while(this.nodes[i]){ $bind.call(this,this.nodes[i],'click',func,who||this.eq(i)); i++; } return this; }else{ return result; } }; $_1k.prototype.hover=function(hover,out,who){ var node, self=this; if(this.nodes){ var i=0; while(node=this.nodes[i]){ ~function(_who){ var node=_who.node; $bind(node,'mouseover',function(evt){ if(evt.fromTarget&&!$contains(node,evt.fromTarget))hover.call(who||_who,evt); },who||_who); $bind(node,'mouseout',function(evt){ if(!evt.toTarget||!$contains(node,evt.toTarget))out.call(who||_who,evt); },who||_who); }(this.eq(i)); i++; } }else{ node=this.node; $bind(node,'mouseover',function(evt){ if(evt.fromTarget&&!$contains(node,evt.fromTarget))hover.call(who||self,evt); },who||self); $bind(node,'mouseout',function(evt){ if(!evt.toTarget||!$contains(node,evt.toTarget))out.call(who||self,evt); },who||self); } return this; }; $1k.browser=$browser; $1k.isIE6=$isIE6; $1k.cookie=$cookie; $1k.each=$each; $1k.toJson=$toJson; $1k.param=$param; $1k.tirm=$tirm; $1k.encodeURL=$encodeURL; $1k.encodeHTML=$encodeHTML; $1k.decodeHTML=$decodeHTML; $1k.parseJson=$parseJson; $1k.parseHash=$parseHash; $1k.post=$post; $1k.get=$get; $1k.img=$img; $1k.js=$js; $1k.css=$style; $1k.isArray=$isArray; $1k.isNode=$isNode; $1k.docWidth=function(){ return $DE.clientWidth; }; $1k.docHeight=function(){ return $DE.clientHeight; }; $1k.scrollWidth=function(){ return $DE.scrollWidth; }; $1k.scrollHeight=function(){ return Math.max($DE.scrollHeight,$DOC.body.scrollHeight); }; $1k.scrollTop=function(){ return $scrollTop.apply(this,arguments); }; $1k.scrollLeft=function(){ return $DE.scrollLeft+$DOC.body.scrollLeft; }; $1k.proxy=$proxy; $1k.echo=function(){}; $_1k.prototype.anime=function(args){ if(!this.node.___ANIMEID){ var pid=this.node.___ANIMEID=$PID; $PID++; args=args||{}; $ANIMEQUEQU[pid]=$anime(this.node,args); }else{ var pid=this.node.___ANIMEID; $ANIMEQUEQU[pid].stop(); $ANIMEQUEQU[pid]=$anime(this.node,args); } return $ANIMEQUEQU[pid]; }; $_1k.prototype.drag=function(ops){ if(!this.node.___DRAGID){ var pid=this.node.___DRAGID=$PID; $PID++; $DRAGQUEQU[pid]=$drag(this.node,ops||{}); } return $DRAGQUEQU[this.node.___DRAGID]; }; this.$1k=$1k; }();
JavaScript
// ==ClosureCompiler== // @compilation_level ADVANCED_OPTIMIZATIONS // @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3_3.js // ==/ClosureCompiler== /** * @name MarkerClusterer for Google Maps v3 * @version version 1.0 * @author Luke Mahe * @fileoverview * The library creates and manages per-zoom-level clusters for large amounts of * markers. * <br/> * This is a v3 implementation of the * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/" * >v2 MarkerClusterer</a>. */ /** * 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 Marker Clusterer that clusters markers. * * @param {google.maps.Map} map The Google map to attach to. * @param {Array.<google.maps.Marker>=} opt_markers Optional markers to add to * the cluster. * @param {Object=} opt_options support the following options: * 'gridSize': (number) The grid size of a cluster in pixels. * 'maxZoom': (number) The maximum zoom level that a marker can be part of a * cluster. * 'zoomOnClick': (boolean) Whether the default behaviour of clicking on a * cluster is to zoom into it. * 'averageCenter': (boolean) Wether the center of each cluster should be * the average of all markers in the cluster. * 'minimumClusterSize': (number) The minimum number of markers to be in a * cluster before the markers are hidden and a count * is shown. * 'styles': (object) An object that has style properties: * 'url': (string) The image url. * 'height': (number) The image height. * 'width': (number) The image width. * 'anchor': (Array) The anchor position of the label text. * 'textColor': (string) The text color. * 'textSize': (number) The text size. * 'backgroundPosition': (string) The position of the backgound x, y. * @constructor * @extends google.maps.OverlayView */ function MarkerClusterer(map, opt_markers, opt_options) { // MarkerClusterer implements google.maps.OverlayView interface. We use the // extend function to extend MarkerClusterer with google.maps.OverlayView // because it might not always be available when the code is defined so we // look for it at the last possible moment. If it doesn't exist now then // there is no point going ahead :) this.extend(MarkerClusterer, google.maps.OverlayView); this.map_ = map; /** * @type {Array.<google.maps.Marker>} * @private */ this.markers_ = []; /** * @type {Array.<Cluster>} */ this.clusters_ = []; this.sizes = [53, 56, 66, 78, 90]; /** * @private */ this.styles_ = []; /** * @type {boolean} * @private */ this.ready_ = false; var options = opt_options || {}; /** * @type {number} * @private */ this.gridSize_ = options['gridSize'] || 60; /** * @private */ this.minClusterSize_ = options['minimumClusterSize'] || 2; /** * @type {?number} * @private */ this.maxZoom_ = options['maxZoom'] || null; this.styles_ = options['styles'] || []; /** * @type {string} * @private */ this.imagePath_ = options['imagePath'] || this.MARKER_CLUSTER_IMAGE_PATH_; /** * @type {string} * @private */ this.imageExtension_ = options['imageExtension'] || this.MARKER_CLUSTER_IMAGE_EXTENSION_; /** * @type {boolean} * @private */ this.zoomOnClick_ = true; if (options['zoomOnClick'] != undefined) { this.zoomOnClick_ = options['zoomOnClick']; } /** * @type {boolean} * @private */ this.averageCenter_ = false; if (options['averageCenter'] != undefined) { this.averageCenter_ = options['averageCenter']; } this.setupStyles_(); this.setMap(map); /** * @type {number} * @private */ this.prevZoom_ = this.map_.getZoom(); // Add the map event listeners var that = this; google.maps.event.addListener(this.map_, 'zoom_changed', function() { var zoom = that.map_.getZoom(); if (that.prevZoom_ != zoom) { that.prevZoom_ = zoom; that.resetViewport(); } }); google.maps.event.addListener(this.map_, 'idle', function() { that.redraw(); }); // Finally, add the markers if (opt_markers && opt_markers.length) { this.addMarkers(opt_markers, false); } } /** * The marker cluster image path. * * @type {string} * @private */ MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_ = 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/' + 'images/m'; /** * The marker cluster image path. * * @type {string} * @private */ MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_EXTENSION_ = 'png'; /** * Extends a objects prototype by anothers. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function(obj1, obj2) { return (function(object) { for (var property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * Implementaion of the interface method. * @ignore */ MarkerClusterer.prototype.onAdd = function() { this.setReady_(true); }; /** * Implementaion of the interface method. * @ignore */ MarkerClusterer.prototype.draw = function() {}; /** * Sets up the styles object. * * @private */ MarkerClusterer.prototype.setupStyles_ = function() { if (this.styles_.length) { return; } for (var i = 0, size; size = this.sizes[i]; i++) { this.styles_.push({ url: this.imagePath_ + (i + 1) + '.' + this.imageExtension_, height: size, width: size }); } }; /** * Fit the map to the bounds of the markers in the clusterer. */ MarkerClusterer.prototype.fitMapToMarkers = function() { var markers = this.getMarkers(); var bounds = new google.maps.LatLngBounds(); for (var i = 0, marker; marker = markers[i]; i++) { bounds.extend(marker.getPosition()); } this.map_.fitBounds(bounds); }; /** * Sets the styles. * * @param {Object} styles The style to set. */ MarkerClusterer.prototype.setStyles = function(styles) { this.styles_ = styles; }; /** * Gets the styles. * * @return {Object} The styles object. */ MarkerClusterer.prototype.getStyles = function() { return this.styles_; }; /** * Whether zoom on click is set. * * @return {boolean} True if zoomOnClick_ is set. */ MarkerClusterer.prototype.isZoomOnClick = function() { return this.zoomOnClick_; }; /** * Whether average center is set. * * @return {boolean} True if averageCenter_ is set. */ MarkerClusterer.prototype.isAverageCenter = function() { return this.averageCenter_; }; /** * Returns the array of markers in the clusterer. * * @return {Array.<google.maps.Marker>} The markers. */ MarkerClusterer.prototype.getMarkers = function() { return this.markers_; }; /** * Returns the number of markers in the clusterer * * @return {Number} The number of markers. */ MarkerClusterer.prototype.getTotalMarkers = function() { return this.markers_.length; }; /** * Sets the max zoom for the clusterer. * * @param {number} maxZoom The max zoom level. */ MarkerClusterer.prototype.setMaxZoom = function(maxZoom) { this.maxZoom_ = maxZoom; }; /** * Gets the max zoom for the clusterer. * * @return {number} The max zoom level. */ MarkerClusterer.prototype.getMaxZoom = function() { return this.maxZoom_; }; /** * The function for calculating the cluster icon image. * * @param {Array.<google.maps.Marker>} markers The markers in the clusterer. * @param {number} numStyles The number of styles available. * @return {Object} A object properties: 'text' (string) and 'index' (number). * @private */ MarkerClusterer.prototype.calculator_ = function(markers, numStyles) { var index = 0; var count = markers.length; var dv = count; while (dv !== 0) { dv = parseInt(dv / 10, 10); index++; } index = Math.min(index, numStyles); return { text: count, index: index }; }; /** * Set the calculator function. * * @param {function(Array, number)} calculator The function to set as the * calculator. The function should return a object properties: * 'text' (string) and 'index' (number). * */ MarkerClusterer.prototype.setCalculator = function(calculator) { this.calculator_ = calculator; }; /** * Get the calculator function. * * @return {function(Array, number)} the calculator function. */ MarkerClusterer.prototype.getCalculator = function() { return this.calculator_; }; /** * Add an array of markers to the clusterer. * * @param {Array.<google.maps.Marker>} markers The markers to add. * @param {boolean=} opt_nodraw Whether to redraw the clusters. */ MarkerClusterer.prototype.addMarkers = function(markers, opt_nodraw) { for (var i = 0, marker; marker = markers[i]; i++) { this.pushMarkerTo_(marker); } if (!opt_nodraw) { this.redraw(); } }; /** * Pushes a marker to the clusterer. * * @param {google.maps.Marker} marker The marker to add. * @private */ MarkerClusterer.prototype.pushMarkerTo_ = function(marker) { marker.isAdded = false; if (marker['draggable']) { // If the marker is draggable add a listener so we update the clusters on // the drag end. var that = this; google.maps.event.addListener(marker, 'dragend', function() { marker.isAdded = false; that.repaint(); }); } this.markers_.push(marker); }; /** * Adds a marker to the clusterer and redraws if needed. * * @param {google.maps.Marker} marker The marker to add. * @param {boolean=} opt_nodraw Whether to redraw the clusters. */ MarkerClusterer.prototype.addMarker = function(marker, opt_nodraw) { this.pushMarkerTo_(marker); if (!opt_nodraw) { this.redraw(); } }; /** * Removes a marker and returns true if removed, false if not * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not * @private */ MarkerClusterer.prototype.removeMarker_ = function(marker) { var index = -1; if (this.markers_.indexOf) { index = this.markers_.indexOf(marker); } else { for (var i = 0, m; m = this.markers_[i]; i++) { if (m == marker) { index = i; break; } } } if (index == -1) { // Marker is not in our list of markers. return false; } marker.setMap(null); this.markers_.splice(index, 1); return true; }; /** * Remove a marker from the cluster. * * @param {google.maps.Marker} marker The marker to remove. * @param {boolean=} opt_nodraw Optional boolean to force no redraw. * @return {boolean} True if the marker was removed. */ MarkerClusterer.prototype.removeMarker = function(marker, opt_nodraw) { var removed = this.removeMarker_(marker); if (!opt_nodraw && removed) { this.resetViewport(); this.redraw(); return true; } else { return false; } }; /** * Removes an array of markers from the cluster. * * @param {Array.<google.maps.Marker>} markers The markers to remove. * @param {boolean=} opt_nodraw Optional boolean to force no redraw. */ MarkerClusterer.prototype.removeMarkers = function(markers, opt_nodraw) { var removed = false; for (var i = 0, marker; marker = markers[i]; i++) { var r = this.removeMarker_(marker); removed = removed || r; } if (!opt_nodraw && removed) { this.resetViewport(); this.redraw(); return true; } }; /** * Sets the clusterer's ready state. * * @param {boolean} ready The state. * @private */ MarkerClusterer.prototype.setReady_ = function(ready) { if (!this.ready_) { this.ready_ = ready; this.createClusters_(); } }; /** * Returns the number of clusters in the clusterer. * * @return {number} The number of clusters. */ MarkerClusterer.prototype.getTotalClusters = function() { return this.clusters_.length; }; /** * Returns the google map that the clusterer is associated with. * * @return {google.maps.Map} The map. */ MarkerClusterer.prototype.getMap = function() { return this.map_; }; /** * Sets the google map that the clusterer is associated with. * * @param {google.maps.Map} map The map. */ MarkerClusterer.prototype.setMap = function(map) { this.map_ = map; }; /** * Returns the size of the grid. * * @return {number} The grid size. */ MarkerClusterer.prototype.getGridSize = function() { return this.gridSize_; }; /** * Sets the size of the grid. * * @param {number} size The grid size. */ MarkerClusterer.prototype.setGridSize = function(size) { this.gridSize_ = size; }; /** * Returns the min cluster size. * * @return {number} The grid size. */ MarkerClusterer.prototype.getMinClusterSize = function() { return this.minClusterSize_; }; /** * Sets the min cluster size. * * @param {number} size The grid size. */ MarkerClusterer.prototype.setMinClusterSize = function(size) { this.minClusterSize_ = size; }; /** * Extends a bounds object by the grid size. * * @param {google.maps.LatLngBounds} bounds The bounds to extend. * @return {google.maps.LatLngBounds} The extended bounds. */ MarkerClusterer.prototype.getExtendedBounds = function(bounds) { var projection = this.getProjection(); // Turn the bounds into latlng. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()); var bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()); // Convert the points to pixels and the extend out by the grid size. var trPix = projection.fromLatLngToDivPixel(tr); trPix.x += this.gridSize_; trPix.y -= this.gridSize_; var blPix = projection.fromLatLngToDivPixel(bl); blPix.x -= this.gridSize_; blPix.y += this.gridSize_; // Convert the pixel points back to LatLng var ne = projection.fromDivPixelToLatLng(trPix); var sw = projection.fromDivPixelToLatLng(blPix); // Extend the bounds to contain the new bounds. bounds.extend(ne); bounds.extend(sw); return bounds; }; /** * Determins if a marker is contained in a bounds. * * @param {google.maps.Marker} marker The marker to check. * @param {google.maps.LatLngBounds} bounds The bounds to check against. * @return {boolean} True if the marker is in the bounds. * @private */ MarkerClusterer.prototype.isMarkerInBounds_ = function(marker, bounds) { return bounds.contains(marker.getPosition()); }; /** * Clears all clusters and markers from the clusterer. */ MarkerClusterer.prototype.clearMarkers = function() { this.resetViewport(true); // Set the markers a empty array. this.markers_ = []; }; /** * Clears all existing clusters and recreates them. * @param {boolean} opt_hide To also hide the marker. */ MarkerClusterer.prototype.resetViewport = function(opt_hide) { // Remove all the clusters for (var i = 0, cluster; cluster = this.clusters_[i]; i++) { cluster.remove(); } // Reset the markers to not be added and to be invisible. for (var i = 0, marker; marker = this.markers_[i]; i++) { marker.isAdded = false; if (opt_hide) { marker.setMap(null); } } this.clusters_ = []; }; /** * */ MarkerClusterer.prototype.repaint = function() { var oldClusters = this.clusters_.slice(); this.clusters_.length = 0; this.resetViewport(); this.redraw(); // Remove the old clusters. // Do it in a timeout so the other clusters have been drawn first. window.setTimeout(function() { for (var i = 0, cluster; cluster = oldClusters[i]; i++) { cluster.remove(); } }, 0); }; /** * Redraws the clusters. */ MarkerClusterer.prototype.redraw = function() { this.createClusters_(); }; /** * Calculates the distance between two latlng locations in km. * @see http://www.movable-type.co.uk/scripts/latlong.html * * @param {google.maps.LatLng} p1 The first lat lng point. * @param {google.maps.LatLng} p2 The second lat lng point. * @return {number} The distance between the two points in km. * @private */ MarkerClusterer.prototype.distanceBetweenPoints_ = function(p1, p2) { if (!p1 || !p2) { return 0; } var R = 6371; // Radius of the Earth in km var dLat = (p2.lat() - p1.lat()) * Math.PI / 180; var dLon = (p2.lng() - p1.lng()) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; /** * Add a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. * @private */ MarkerClusterer.prototype.addToClosestCluster_ = function(marker) { var distance = 40000; // Some large number var clusterToAddTo = null; var pos = marker.getPosition(); for (var i = 0, cluster; cluster = this.clusters_[i]; i++) { var center = cluster.getCenter(); if (center) { var d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { var cluster = new Cluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Creates the clusters. * * @private */ MarkerClusterer.prototype.createClusters_ = function() { if (!this.ready_) { return; } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. var mapBounds = new google.maps.LatLngBounds(this.map_.getBounds().getSouthWest(), this.map_.getBounds().getNorthEast()); var bounds = this.getExtendedBounds(mapBounds); for (var i = 0, marker; marker = this.markers_[i]; i++) { if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { this.addToClosestCluster_(marker); } } }; /** * A cluster that contains markers. * * @param {MarkerClusterer} markerClusterer The markerclusterer that this * cluster is associated with. * @constructor * @ignore */ function Cluster(markerClusterer) { this.markerClusterer_ = markerClusterer; this.map_ = markerClusterer.getMap(); this.gridSize_ = markerClusterer.getGridSize(); this.minClusterSize_ = markerClusterer.getMinClusterSize(); this.averageCenter_ = markerClusterer.isAverageCenter(); this.center_ = null; this.markers_ = []; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, markerClusterer.getStyles(), markerClusterer.getGridSize()); } /** * Determins if a marker is already added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker is already added. */ Cluster.prototype.isMarkerAlreadyAdded = function(marker) { if (this.markers_.indexOf) { return this.markers_.indexOf(marker) != -1; } else { for (var i = 0, m; m = this.markers_[i]; i++) { if (m == marker) { return true; } } } return false; }; /** * Add a marker the cluster. * * @param {google.maps.Marker} marker The marker to add. * @return {boolean} True if the marker was added. */ Cluster.prototype.addMarker = function(marker) { if (this.isMarkerAlreadyAdded(marker)) { return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l-1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l-1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); var len = this.markers_.length; if (len < this.minClusterSize_ && marker.getMap() != this.map_) { // Min cluster size not reached so show the marker. marker.setMap(this.map_); } if (len == this.minClusterSize_) { // Hide the markers that were showing. for (var i = 0; i < len; i++) { this.markers_[i].setMap(null); } } if (len >= this.minClusterSize_) { marker.setMap(null); } this.updateIcon(); return true; }; /** * Returns the marker clusterer that the cluster is associated with. * * @return {MarkerClusterer} The associated marker clusterer. */ Cluster.prototype.getMarkerClusterer = function() { return this.markerClusterer_; }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. */ Cluster.prototype.getBounds = function() { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers(); for (var i = 0, marker; marker = markers[i]; i++) { bounds.extend(marker.getPosition()); } return bounds; }; /** * Removes the cluster */ Cluster.prototype.remove = function() { this.clusterIcon_.remove(); this.markers_.length = 0; delete this.markers_; }; /** * Returns the center of the cluster. * * @return {number} The cluster center. */ Cluster.prototype.getSize = function() { return this.markers_.length; }; /** * Returns the center of the cluster. * * @return {Array.<google.maps.Marker>} The cluster center. */ Cluster.prototype.getMarkers = function() { return this.markers_; }; /** * Returns the center of the cluster. * * @return {google.maps.LatLng} The cluster center. */ Cluster.prototype.getCenter = function() { return this.center_; }; /** * Calculated the extended bounds of the cluster with the grid. * * @private */ Cluster.prototype.calculateBounds_ = function() { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds); }; /** * Determines if a marker lies in the clusters bounds. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker lies in the bounds. */ Cluster.prototype.isMarkerInClusterBounds = function(marker) { return this.bounds_.contains(marker.getPosition()); }; /** * Returns the map that the cluster is associated with. * * @return {google.maps.Map} The map. */ Cluster.prototype.getMap = function() { return this.map_; }; /** * Updates the cluster icon */ Cluster.prototype.updateIcon = function() { var zoom = this.map_.getZoom(); var mz = this.markerClusterer_.getMaxZoom(); if (mz && zoom > mz) { // The zoom is greater than our max zoom so show all the markers in cluster. for (var i = 0, marker; marker = this.markers_[i]; i++) { marker.setMap(this.map_); } return; } if (this.markers_.length < this.minClusterSize_) { // Min cluster size not yet reached. this.clusterIcon_.hide(); return; } var numStyles = this.markerClusterer_.getStyles().length; var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles); this.clusterIcon_.setCenter(this.center_); this.clusterIcon_.setSums(sums); this.clusterIcon_.show(); }; /** * A cluster icon * * @param {Cluster} cluster The cluster to be associated with. * @param {Object} styles An object that has style properties: * 'url': (string) The image url. * 'height': (number) The image height. * 'width': (number) The image width. * 'anchor': (Array) The anchor position of the label text. * 'textColor': (string) The text color. * 'textSize': (number) The text size. * 'backgroundPosition: (string) The background postition x, y. * @param {number=} opt_padding Optional padding to apply to the cluster icon. * @constructor * @extends google.maps.OverlayView * @ignore */ function ClusterIcon(cluster, styles, opt_padding) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.styles_ = styles; this.padding_ = opt_padding || 0; this.cluster_ = cluster; this.center_ = null; this.map_ = cluster.getMap(); this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(this.map_); } /** * Triggers the clusterclick event and zoom's if the option is set. */ ClusterIcon.prototype.triggerClusterClick = function() { var markerClusterer = this.cluster_.getMarkerClusterer(); // Trigger the clusterclick event. google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_); if (markerClusterer.isZoomOnClick()) { // Zoom into the cluster. this.map_.fitBounds(this.cluster_.getBounds()); } }; /** * Adding the cluster icon to the dom. * @ignore */ ClusterIcon.prototype.onAdd = function() { this.div_ = document.createElement('DIV'); if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); this.div_.innerHTML = this.sums_.text; } var panes = this.getPanes(); panes.overlayMouseTarget.appendChild(this.div_); var that = this; google.maps.event.addDomListener(this.div_, 'click', function() { that.triggerClusterClick(); }); }; /** * Returns the position to place the div dending on the latlng. * * @param {google.maps.LatLng} latlng The position in latlng. * @return {google.maps.Point} The position in pixels. * @private */ ClusterIcon.prototype.getPosFromLatLng_ = function(latlng) { var pos = this.getProjection().fromLatLngToDivPixel(latlng); pos.x -= parseInt(this.width_ / 2, 10); pos.y -= parseInt(this.height_ / 2, 10); return pos; }; /** * Draw the icon. * @ignore */ ClusterIcon.prototype.draw = function() { if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.top = pos.y + 'px'; this.div_.style.left = pos.x + 'px'; } }; /** * Hide the icon. */ ClusterIcon.prototype.hide = function() { if (this.div_) { this.div_.style.display = 'none'; } this.visible_ = false; }; /** * Position and show the icon. */ ClusterIcon.prototype.show = function() { if (this.div_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); this.div_.style.display = ''; } this.visible_ = true; }; /** * Remove the icon from the map */ ClusterIcon.prototype.remove = function() { this.setMap(null); }; /** * Implementation of the onRemove interface. * @ignore */ ClusterIcon.prototype.onRemove = function() { if (this.div_ && this.div_.parentNode) { this.hide(); this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Set the sums of the icon. * * @param {Object} sums The sums containing: * 'text': (string) The text to display in the icon. * 'index': (number) The style index of the icon. */ ClusterIcon.prototype.setSums = function(sums) { this.sums_ = sums; this.text_ = sums.text; this.index_ = sums.index; if (this.div_) { this.div_.innerHTML = sums.text; } this.useStyle(); }; /** * Sets the icon to the the styles. */ ClusterIcon.prototype.useStyle = function() { var index = Math.max(0, this.sums_.index - 1); index = Math.min(this.styles_.length - 1, index); var style = this.styles_[index]; this.url_ = style['url']; this.height_ = style['height']; this.width_ = style['width']; this.textColor_ = style['textColor']; this.anchor_ = style['anchor']; this.textSize_ = style['textSize']; this.backgroundPosition_ = style['backgroundPosition']; }; /** * Sets the center of the icon. * * @param {google.maps.LatLng} center The latlng to set as the center. */ ClusterIcon.prototype.setCenter = function(center) { this.center_ = center; }; /** * Create the css text based on the position of the icon. * * @param {google.maps.Point} pos The position. * @return {string} The css style text. */ ClusterIcon.prototype.createCss = function(pos) { var style = []; style.push('background-image:url(' + this.url_ + ');'); var backgroundPosition = this.backgroundPosition_ ? this.backgroundPosition_ : '0 0'; style.push('background-position:' + backgroundPosition + ';'); if (typeof this.anchor_ === 'object') { if (typeof this.anchor_[0] === 'number' && this.anchor_[0] > 0 && this.anchor_[0] < this.height_) { style.push('height:' + (this.height_ - this.anchor_[0]) + 'px; padding-top:' + this.anchor_[0] + 'px;'); } else { style.push('height:' + this.height_ + 'px; line-height:' + this.height_ + 'px;'); } if (typeof this.anchor_[1] === 'number' && this.anchor_[1] > 0 && this.anchor_[1] < this.width_) { style.push('width:' + (this.width_ - this.anchor_[1]) + 'px; padding-left:' + this.anchor_[1] + 'px;'); } else { style.push('width:' + this.width_ + 'px; text-align:center;'); } } else { style.push('height:' + this.height_ + 'px; line-height:' + this.height_ + 'px; width:' + this.width_ + 'px; text-align:center;'); } var txtColor = this.textColor_ ? this.textColor_ : 'black'; var txtSize = this.textSize_ ? this.textSize_ : 11; style.push('cursor:pointer; top:' + pos.y + 'px; left:' + pos.x + 'px; color:' + txtColor + '; position:absolute; font-size:' + txtSize + 'px; font-family:Arial,sans-serif; font-weight:bold'); return style.join(''); }; // Export Symbols for Closure // If you are not going to compile with closure then you can remove the // code below. window['MarkerClusterer'] = MarkerClusterer; MarkerClusterer.prototype['addMarker'] = MarkerClusterer.prototype.addMarker; MarkerClusterer.prototype['addMarkers'] = MarkerClusterer.prototype.addMarkers; MarkerClusterer.prototype['clearMarkers'] = MarkerClusterer.prototype.clearMarkers; MarkerClusterer.prototype['fitMapToMarkers'] = MarkerClusterer.prototype.fitMapToMarkers; MarkerClusterer.prototype['getCalculator'] = MarkerClusterer.prototype.getCalculator; MarkerClusterer.prototype['getGridSize'] = MarkerClusterer.prototype.getGridSize; MarkerClusterer.prototype['getExtendedBounds'] = MarkerClusterer.prototype.getExtendedBounds; MarkerClusterer.prototype['getMap'] = MarkerClusterer.prototype.getMap; MarkerClusterer.prototype['getMarkers'] = MarkerClusterer.prototype.getMarkers; MarkerClusterer.prototype['getMaxZoom'] = MarkerClusterer.prototype.getMaxZoom; MarkerClusterer.prototype['getStyles'] = MarkerClusterer.prototype.getStyles; MarkerClusterer.prototype['getTotalClusters'] = MarkerClusterer.prototype.getTotalClusters; MarkerClusterer.prototype['getTotalMarkers'] = MarkerClusterer.prototype.getTotalMarkers; MarkerClusterer.prototype['redraw'] = MarkerClusterer.prototype.redraw; MarkerClusterer.prototype['removeMarker'] = MarkerClusterer.prototype.removeMarker; MarkerClusterer.prototype['removeMarkers'] = MarkerClusterer.prototype.removeMarkers; MarkerClusterer.prototype['resetViewport'] = MarkerClusterer.prototype.resetViewport; MarkerClusterer.prototype['repaint'] = MarkerClusterer.prototype.repaint; MarkerClusterer.prototype['setCalculator'] = MarkerClusterer.prototype.setCalculator; MarkerClusterer.prototype['setGridSize'] = MarkerClusterer.prototype.setGridSize; MarkerClusterer.prototype['setMaxZoom'] = MarkerClusterer.prototype.setMaxZoom; MarkerClusterer.prototype['onAdd'] = MarkerClusterer.prototype.onAdd; MarkerClusterer.prototype['draw'] = MarkerClusterer.prototype.draw; Cluster.prototype['getCenter'] = Cluster.prototype.getCenter; Cluster.prototype['getSize'] = Cluster.prototype.getSize; Cluster.prototype['getMarkers'] = Cluster.prototype.getMarkers; ClusterIcon.prototype['onAdd'] = ClusterIcon.prototype.onAdd; ClusterIcon.prototype['draw'] = ClusterIcon.prototype.draw; ClusterIcon.prototype['onRemove'] = ClusterIcon.prototype.onRemove;
JavaScript
// JavaScript Document //<![CDATA[ // Latitude and Longitude math routines are from: http://www.fcc.gov/mb/audio/bickel/DDDMMSS-decimal.html var map = null; var geocoder = null; var latsgn = 1; var lgsgn = 1; var zm = 0; var marker = null; var posset = 0; function xz() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map")); map.setCenter(new GLatLng(18.646245, 77.343750), 2); map.setMapType(G_NORMAL_MAP); map.addControl(new GLargeMapControl()); map.addControl(new MapTypeControl()); map.addControl(new GScaleControl()); map.enableScrollWheelZoom(); map.disableDoubleClickZoom(); geocoder = new GClientGeocoder(); marker = new GMarker(new GLatLng(18.646245, 77.343750), {draggable: true}); map.addOverlay(marker); GEvent.addListener(map, 'click', function(overlay,point) { if (overlay) { } else { posset = 1; fc( point) ; //marker.setPoint(point); if (zm == 0) {map.setCenter(point,7); zm = 1;} else {map.setCenter(point);} computepos(point); } }); GEvent.addListener(map, 'singlerightclick', function(point,src,overlay) { if (overlay) { if (overlay != marker) { map.removeOverlay(overlay) document.getElementById("latbox").value=''; document.getElementById("latboxm").value=''; document.getElementById("latboxmd").value=''; document.getElementById("latboxms").value=''; document.getElementById("lonbox").value=''; document.getElementById("lonboxm").value=''; document.getElementById("lonboxmd").value=''; document.getElementById("lonboxms").value=''; } } else {} }); GEvent.addListener(marker, "dragend", function() { var point = marker.getLatLng(); posset = 1; marker.closeInfoWindow(); if (zm == 0) {map.setCenter(point,7); zm = 1;} else {map.setCenter(point);} computepos(point); }); GEvent.addListener(marker, "click", function() { var point = marker.getLatLng(); marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6)); computepos (point); }); }} function computepos (point) { var latA = Math.abs(Math.round(value=point.y * 1000000.)); var lonA = Math.abs(Math.round(value=point.x * 1000000.)); if(value=point.y < 0) { var ls = '-' + Math.floor((latA / 1000000)); } else { var ls = Math.floor((latA / 1000000)); } var lm = Math.floor(((latA/1000000) - Math.floor(latA/1000000)) * 60); var ld = ( Math.floor(((((latA/1000000) - Math.floor(latA/1000000)) * 60) - Math.floor(((latA/1000000) - Math.floor(latA/1000000)) * 60)) * 100000) *60/100000 ); if(value=point.x < 0) { var lgs = '-' + Math.floor((lonA / 1000000)); } else { var lgs = Math.floor((lonA / 1000000)); } var lgm = Math.floor(((lonA/1000000) - Math.floor(lonA/1000000)) * 60); var lgd = ( Math.floor(((((lonA/1000000) - Math.floor(lonA/1000000)) * 60) - Math.floor(((lonA/1000000) - Math.floor(lonA/1000000)) * 60)) * 100000) *60/100000 ); document.getElementById("latbox").value=point.y.toFixed(6); document.getElementById("latboxm").value=ls; document.getElementById("latboxmd").value=lm; document.getElementById("latboxms").value=ld; document.getElementById("lonbox").value=point.x.toFixed(6); document.getElementById("lonboxm").value=lgs; document.getElementById("lonboxmd").value=lgm; document.getElementById("lonboxms").value=lgd; } function showAddress(address) { if (geocoder) { geocoder.getLatLng( address, function(point) { if (!point) { alert(address + " not found"); } else { posset = 1; map.setMapType(G_HYBRID_MAP); map.setCenter(point,16); zm = 1; marker.setPoint(point); GEvent.trigger(marker, "click"); } } ); } } function showLatLong(latitude, longitude) { if (isNaN(latitude)) {alert(' Latitude must be a number. e.g. Use +/- instead of N/S'); return false;} if (isNaN(longitude)) {alert(' Longitude must be a number. e.g. Use +/- instead of E/W'); return false;} latitude1 = Math.abs( Math.round(latitude * 1000000.)); if(latitude1 > (90 * 1000000)) { alert(' Latitude must be between -90 to 90. '); document.getElementById("latbox1").value=''; return;} longitude1 = Math.abs( Math.round(longitude * 1000000.)); if(longitude1 > (180 * 1000000)) { alert(' Longitude must be between -180 to 180. '); document.getElementById("lonbox1").value=''; return;} var point = new GLatLng(latitude,longitude); posset = 1; if (zm == 0) { map.setMapType(G_HYBRID_MAP); map.setCenter(point,16); zm = 1; } else { map.setCenter(point); } var html = ""; html += html + "Latitude, Longitude<br>" + point.toUrlValue(6); var baseIcon = new GIcon(); baseIcon.iconSize=new GSize(32,32); baseIcon.shadowSize=new GSize(56,32); baseIcon.iconAnchor=new GPoint(16,32); baseIcon.infoWindowAnchor=new GPoint(16,0); var thisicon = new GIcon(baseIcon, "http://itouchmap.com/i/blue-dot.png", null, "http://itouchmap.com/i/msmarker.shadow.png"); var marker = new GMarker(point,thisicon); GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);}); map.addOverlay(marker); GEvent.trigger(marker, "click"); } function showLatLong1(latitude, latitudem,latitudes, longitude, longitudem, longitudes) { if (isNaN(latitude)) {alert(' Latitude must be a number. e.g. Use +/- instead of N/S'); return false;} if (isNaN(latitudem)) {alert(' Latitude must be a number. e.g. Use +/- instead of N/S'); return false;} if (isNaN(latitudes)) {alert(' Latitude must be a number. e.g. Use +/- instead of N/S'); return false;} if (isNaN(longitude)) {alert(' Longitude must be a number. e.g. Use +/- instead of E/W'); return false;} if (isNaN(longitudem)) {alert(' Longitude must be a number. e.g. Use +/- instead of E/W'); return false;} if (isNaN(longitudes)) {alert(' Longitude must be a number. e.g. Use +/- instead of E/W'); return false;} if(latitude < 0) { latsgn = -1; } alat = Math.abs( Math.round(latitude * 1000000.)); if(alat > (90 * 1000000)) { alert(' Degrees Latitude must be between -90 to 90. '); document.getElementById("latbox1m").value=''; document.getElementById("latbox1md").value=''; document.getElementById("latbox1ms").value=''; return; } latitudem = Math.abs(Math.round(latitudem * 1000000.)/1000000); //integer absmlat = Math.abs(Math.round(latitudem * 1000000.)); //integer if(absmlat >= (60 * 1000000)) { alert(' Minutes Latitude must be between 0 to 59. '); document.getElementById("latbox1md").value=''; document.getElementById("latbox1ms").value=''; return;} latitudes = Math.abs(Math.round(latitudes * 1000000.)/1000000); absslat = Math.abs(Math.round(latitudes * 1000000.)); if(absslat > (59.99999999 * 1000000)) { alert(' Seconds Latitude must be between 0 and 59.99. '); document.getElementById("latbox1ms").value=''; return; } if(longitude < 0) { lgsgn = -1; } alon = Math.abs( Math.round(longitude * 1000000.)); if(alon > (180 * 1000000)) { alert(' Degrees Longitude must be between -180 to 180. '); document.getElementById("lonbox1m").value=''; document.getElementById("lonbox1md").value=''; document.getElementById("lonbox1ms").value=''; return;} longitudem = Math.abs(Math.round(longitudem * 1000000.)/1000000); absmlon = Math.abs(Math.round(longitudem * 1000000)); if(absmlon >= (60 * 1000000)) { alert(' Minutes Longitude must be between 0 to 59. '); document.getElementById("lonbox1md").value=''; document.getElementById("lonbox1ms").value=''; return;} longitudes = Math.abs(Math.round(longitudes * 1000000.)/1000000); absslon = Math.abs(Math.round(longitudes * 1000000.)); if(absslon > (59.99999999 * 1000000)) { alert(' Seconds Longitude must be between 0 and 59.99. '); document.getElementById("lonbox1ms").value=''; return;} latitude = Math.round(alat + (absmlat/60.) + (absslat/3600.) ) * latsgn/1000000; longitude = Math.round(alon + (absmlon/60) + (absslon/3600) ) * lgsgn/1000000; var point = new GLatLng(latitude,longitude); posset = 1; if (zm == 0) { map.setMapType(G_HYBRID_MAP); map.setCenter(point,16); zm = 1; } else { map.setCenter(point); } var html = ""; html += html + "Latitude, Longitude<br>" + point.toUrlValue(6); var baseIcon = new GIcon(); baseIcon.iconSize=new GSize(32,32); baseIcon.shadowSize=new GSize(56,32); baseIcon.iconAnchor=new GPoint(16,32); baseIcon.infoWindowAnchor=new GPoint(16,0); var thisicon = new GIcon(baseIcon, "http://itouchmap.com/i/blue-dot.png", null, "http://itouchmap.com/i/msmarker.shadow.png"); var marker = new GMarker(point,thisicon); GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);}); map.addOverlay(marker); GEvent.trigger(marker, "click"); } function streetview() { if (posset == 0) { alert("Position Not Set. Please click on the spot on the map to set the street view point."); return; } var point = map.getCenter(); var t1 = String(point); t1 = t1.replace(/[() ]+/g,""); var str = "http://www.streetviews.co?e=" + t1; var popup = window.open(str, "streetview"); popup.focus(); } function googleearth() { if (posset == 0) { alert("Position Not Set. Please click on the spot on the map to set the Google Earth map point."); return; } var point = map.getCenter(); var gearth_str = "http://gmap3d.com?r=3dmap&mt=Latitude-Longitude Point&ml=" + point.y+ "&mg=" + point.x; var popup = window.open(gearth_str, "googleearth"); popup.focus(); } function pictures() { if (posset == 0) { alert("Position Not Set. Please click on the spot on the map to set the photograph point."); return; } var point = map.getCenter(); var pictures_str = "http://ipicture.mobi?r=pictures&mt=Latitude-Longitude Point&ml=" + point.y+ "&mg=" + point.x; var popup = window.open(pictures_str, "pictures"); popup.focus(); } function lotsize() { if (posset == 0) { alert("Position Not Set. Please click on the spot on the map to set the lot size map point."); return; } var point = map.getCenter(); var t1 = String(point); t1 = t1.replace(/[() ]+/g,""); var vpike_str = "http://viewofhouse.com?e=" + t1 + "::findlotsize:"; var popup = window.open(vpike_str, "lotsize"); popup.focus(); } function getaddress() { if (posset == 0) { alert("Position Not Set. Please click on the spot on the map to set the get address map point."); return; } var point = map.getCenter(); var t1 = String(point); t1 = t1.replace(/[() ]+/g,""); var getaddr_str = "http://www.getaddress.net?latlng=" + t1; var popup = window.open(getaddr_str, "getaddress"); popup.focus(); } function fc( point ) { var html = ""; html += html + "Latitude, Longitude<br>" + point.toUrlValue(6); var baseIcon = new GIcon(); baseIcon.iconSize=new GSize(32,32); baseIcon.shadowSize=new GSize(56,32); baseIcon.iconAnchor=new GPoint(16,32); baseIcon.infoWindowAnchor=new GPoint(16,0); var thisicon = new GIcon(baseIcon, "http://itouchmap.com/i/blue-dot.png", null, "http://itouchmap.com/i/msmarker.shadow.png"); var marker = new GMarker(point,thisicon); GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);}); map.addOverlay(marker); } function createMarker(point, html) { var marker = new GMarker(point); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); }); return marker; } function reset() { map.clearOverlays(); document.getElementById("latbox").value=''; document.getElementById("latboxm").value=''; document.getElementById("latboxmd").value=''; document.getElementById("latboxms").value=''; document.getElementById("lonbox").value=''; document.getElementById("lonboxm").value=''; document.getElementById("lonboxmd").value=''; document.getElementById("lonboxms").value=''; marker = new GMarker(new GLatLng(20.0, -10.0), {draggable: true}); map.addOverlay(marker); marker.setPoint(map.getCenter()); GEvent.addListener(marker, "dragend", function() { var point = marker.getLatLng(); posset = 0; if (zm == 0) {map.setCenter(point,7); zm = 1;} else {map.setCenter(point);} computepos(point); }); GEvent.addListener(marker, "click", function() { var point = marker.getLatLng(); marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6)); computepos (point); }); } function reset1() { marker.setPoint(map.getCenter()); } //]]>
JavaScript
function MapTypeControl(opt_opts) { this.options = opt_opts || {}; } MapTypeControl.prototype = new GControl(); MapTypeControl.prototype.initialize = function(map) { var container = document.createElement("div"); var me = this; var mapDiv = me.createButton_("Map"); var satDiv = me.createButton_("Satellite"); var hybDiv = me.createButton_("Hybrid"); var phyDiv = me.createButton_("Terrain"); me.assignButtonEvent_(mapDiv, map, G_NORMAL_MAP, [phyDiv, satDiv, hybDiv]); me.assignButtonEvent_(phyDiv, map, G_PHYSICAL_MAP, [mapDiv, satDiv, hybDiv]); me.assignButtonEvent_(satDiv, map, G_SATELLITE_MAP, [phyDiv, mapDiv, hybDiv]); me.assignButtonEvent_(hybDiv, map, G_HYBRID_MAP, [phyDiv, satDiv, mapDiv]); GEvent.addListener(map, "maptypechanged", function() { if (map.getCurrentMapType() == G_NORMAL_MAP) { GEvent.trigger(mapDiv, "click"); } else if (map.getCurrentMapType() == G_PHYSICAL_MAP) { GEvent.trigger(phyDiv, "click"); } else if (map.getCurrentMapType() == G_SATELLITE_MAP) { GEvent.trigger(satDiv, "click"); } else if (map.getCurrentMapType() == G_HYBRID_MAP) { GEvent.trigger(hybDiv, "click"); } }); container.appendChild(mapDiv); container.appendChild(satDiv); container.appendChild(hybDiv); container.appendChild(phyDiv); map.getContainer().appendChild(container); GEvent.trigger(map, "maptypechanged"); return container; } MapTypeControl.prototype.createButton_ = function(text) { var buttonDiv = document.createElement("div"); this.setButtonStyle_(buttonDiv); buttonDiv.style.cssFloat = "left"; buttonDiv.style.styleFloat = "left"; var textDiv = document.createElement("div"); textDiv.appendChild(document.createTextNode(text)); textDiv.style.width = "6em"; buttonDiv.appendChild(textDiv); return buttonDiv; } MapTypeControl.prototype.assignButtonEvent_ = function(div, map, mapType, otherDivs) { var me = this; GEvent.addDomListener(div, "click", function() { for (var i = 0; i < otherDivs.length; i++) { me.toggleButton_(otherDivs[i].firstChild, false); } me.toggleButton_(div.firstChild, true); map.setMapType(mapType); }); } MapTypeControl.prototype.toggleButton_ = function(div, boolCheck) { div.style.fontWeight = boolCheck ? "bold" : ""; div.style.border = "1px solid white"; var shadows = boolCheck ? ["Top", "Left"] : ["Bottom", "Right"]; for (var j = 0; j < shadows.length; j++) { div.style["border" + shadows[j]] = "1px solid #b0b0b0"; } } MapTypeControl.prototype.getDefaultPosition = function() { return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7)); } MapTypeControl.prototype.setButtonStyle_ = function(button) { button.style.color = "#000000"; button.style.backgroundColor = "white"; button.style.font = "small Arial"; button.style.border = "1px solid black"; button.style.padding = "0px"; button.style.margin= "0px"; button.style.textAlign = "center"; button.style.fontSize = "12px"; button.style.cursor = "pointer"; }
JavaScript
// set area's id to hidden field(id:school_area_id) function select_area(dom_id, id, title, notice_msg) { $(dom_id).val(id); var notice = $('#areas-list-notice'); notice.html(notice_msg + title) $('#area-title').html(title); school_title_input = $('#school_title'); school_title_input.val(title + school_title_input.val()); notice.show(); $('#areas-list-spinner').hide(); $('#areas-list').hide(); } // ajax活动指示器 $(function() { var $indicator = $('.spinner'); $(document).ajaxSend(function() { $indicator .hide() .show(); }); $(document).ajaxStop(function() { $indicator.hide(); }); });
JavaScript
/* * jQuery Form Plugin * version: 2.12 (06/07/2008) * @requires jQuery v1.2.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id$ */ (function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function() { $(this).ajaxSubmit({ target: '#output' }); return false; // <-- important! }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') options = { success: options }; options = $.extend({ url: this.attr('action') || window.location.toString(), type: this.attr('method') || 'GET' }, options || {}); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } var a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (var n in options.data) a.push( { name: n, value: options.data[n] } ); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else options.data = q; // data is the query string for 'post' var $form = this, callbacks = []; if (options.resetForm) callbacks.push(function() { $form.resetForm(); }); if (options.clearForm) callbacks.push(function() { $form.clearForm(); }); // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { $(options.target).html(data).each(oldSuccess, arguments); }); } else if (options.success) callbacks.push(options.success); options.success = function(data, status) { for (var i=0, max=callbacks.length; i < max; i++) callbacks[i](data, status, $form); }; // are there files to upload? var files = $('input:file', this).fieldValue(); var found = false; for (var j=0; j < files.length; j++) if (files[j]) found = true; // options.iframe allows user to force iframe mode if (options.iframe || found) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if ($.browser.safari && options.closeKeepAlive) $.get(options.closeKeepAlive, fileUpload); else fileUpload(); } else $.ajax(options); // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[@name=submit]', form).length) { alert('Error: Form elements must not be named "submit".'); return; } var opts = $.extend({}, $.ajaxSettings, options); var id = 'jqFormIO' + (new Date().getTime()); var $io = $('<iframe id="' + id + '" name="' + id + '" />'); var io = $io[0]; if ($.browser.msie || $.browser.opera) io.src = 'javascript:false;document.write("");'; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {} }; var g = opts.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) $.event.trigger("ajaxStart"); if (g) $.event.trigger("ajaxSend", [xhr, opts]); var cbInvoked = 0; var timedOut = 0; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { options.extraData = options.extraData || {}; options.extraData[n] = sub.value; if (sub.type == "image") { options.extraData[name+'.x'] = form.clk_x; options.extraData[name+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts setTimeout(function() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); $form.attr({ target: id, encoding: 'multipart/form-data', enctype: 'multipart/form-data', method: 'POST', action: opts.url }); // support timout if (opts.timeout) setTimeout(function() { timedOut = true; cb(); }, opts.timeout); // add "extra" data to form if provided in options var extraInputs = []; try { if (options.extraData) for (var n in options.extraData) extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />') .appendTo(form)[0]); // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.submit(); } finally { // reset attrs and remove "extra" input elements $form.attr('action', a); t ? $form.attr('target', t) : $form.removeAttr('target'); $(extraInputs).remove(); } }, 10); function cb() { if (cbInvoked++) return; io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var operaHack = 0; var ok = true; try { if (timedOut) throw 'timeout'; // extract the server response from the iframe var data, doc; doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if (doc.body == null && !operaHack && $.browser.opera) { // In Opera 9.2.x the iframe DOM is not always traversable when // the onload callback fires so we give Opera 100ms to right itself operaHack = 1; cbInvoked--; setTimeout(cb, 100); return; } xhr.responseText = doc.body ? doc.body.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; xhr.getResponseHeader = function(header){ var headers = {'content-type': opts.dataType}; return headers[header]; }; if (opts.dataType == 'json' || opts.dataType == 'script') { var ta = doc.getElementsByTagName('textarea')[0]; xhr.responseText = ta ? ta.value : xhr.responseText; } else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = $.httpData(xhr, opts.dataType); } catch(e){ ok = false; $.handleError(opts, xhr, 'error', e); } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { opts.success(data, 'success'); if (g) $.event.trigger("ajaxSuccess", [xhr, opts]); } if (g) $.event.trigger("ajaxComplete", [xhr, opts]); if (g && ! --$.active) $.event.trigger("ajaxStop"); if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error'); // clean up setTimeout(function() { $io.remove(); xhr.responseXML = null; }, 100); }; function toXml(s, doc) { if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else doc = (new DOMParser()).parseFromString(s, 'text/xml'); return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null; }; }; }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { return this.ajaxFormUnbind().bind('submit.form-plugin',function() { $(this).ajaxSubmit(options); return false; }).each(function() { // store options in hash $(":submit,input:image", this).bind('click.form-plugin',function(e) { var $form = this.form; $form.clk = this; if (this.type == 'image') { if (e.offsetX != undefined) { $form.clk_x = e.offsetX; $form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $(this).offset(); $form.clk_x = e.pageX - offset.left; $form.clk_y = e.pageY - offset.top; } else { $form.clk_x = e.pageX - this.offsetLeft; $form.clk_y = e.pageY - this.offsetTop; } } // clear form vars setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10); }); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { this.unbind('submit.form-plugin'); return this.each(function() { $(":submit,input:image", this).unbind('click.form-plugin'); }); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length == 0) return a; var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) return a; for(var i=0, max=els.length; i < max; i++) { var el = els[i]; var n = el.name; if (!n) continue; if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); continue; } var v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(var j=0, jmax=v.length; j < jmax; j++) a.push({name: n, value: v[j]}); } else if (v !== null && typeof v != 'undefined') a.push({name: n, value: v}); } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle them here var inputs = form.getElementsByTagName("input"); for(var i=0, max=inputs.length; i < max; i++) { var input = inputs[i]; var n = input.name; if(n && !input.disabled && input.type == "image" && form.clk == input) a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) return; var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) a.push({name: n, value: v[i]}); } else if (v !== null && typeof v != 'undefined') a.push({name: this.name, value: v}); }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) continue; v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (typeof successful == 'undefined') successful = true; if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) return null; if (tag == 'select') { var index = el.selectedIndex; if (index < 0) return null; var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { // extra pain for IE... var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value; if (one) return v; a.push(v); } } return a; } return el.value; }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') this.value = ''; else if (t == 'checkbox' || t == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) this.reset(); }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b == undefined) b = true; return this.each(function() { this.disabled = !b }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.select = function(select) { if (select == undefined) select = true; return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') this.checked = select; else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').select(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug && window.console && window.console.log) window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,'')); }; })(jQuery);
JavaScript
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var tb_pathToImage = "/images/loadingAnimation.gif"; /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init $(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ $(domChunk).click(function(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; }); } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 $("body","html").css({height: "100%", width: "100%"}); $("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page $('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = $("a[@rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; $("#TB_window").append("<a href='' id='TB_ImageOff' title='关闭'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='关闭'>关闭</a></div>"); $("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);} $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } $("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } $("#TB_next").click(goNext); } document.onkeydown = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } else if(keycode == 190){ // display previous image if(!(TB_NextHTML == "")){ document.onkeydown = ""; goNext(); } } else if(keycode == 188){ // display next image if(!(TB_PrevHTML == "")){ document.onkeydown = ""; goPrev(); } } }; tb_position(); $("#TB_load").remove(); $("#TB_ImageOff").click(tb_remove); $("#TB_window").css({display:"block"}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); $("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='关闭'>关闭</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>"); }else{//iframe modal $("#TB_overlay").unbind(); $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>"); } }else{// not an iframe, ajax if($("#TB_window").css("display") != "block"){ if(params['modal'] != "true"){//ajax no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>关闭</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal $("#TB_overlay").unbind(); $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; $("#TB_ajaxContent")[0].scrollTop = 0; $("#TB_ajaxWindowTitle").html(caption); } } $("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ $("#TB_ajaxContent").append($('#' + params['inlineId']).children()); $("#TB_window").unload(function () { $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); $("#TB_load").remove(); $("#TB_window").css({display:"block"}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if($.browser.safari){//safari needs help because it will not fire iframe onload $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } }else{ $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); $("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); $("#TB_window").css({display:"block"}); }); } } if(!params['modal']){ document.onkeyup = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } }; } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } function tb_remove() { $("#TB_imageOff").unbind("click"); $("#TB_closeWindowButton").unbind("click"); $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();}); $("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 $("body","html").css({height: "auto", width: "auto"}); $("html").css("overflow",""); } document.onkeydown = ""; document.onkeyup = ""; return false; } function tb_position() { $("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6 $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
JavaScript
function getTxt(s) { switch(s) { case "Cannot delete Asset Base Folder.":return "\u4e0d\u80fd\u5220\u9664\u6b64\u8d44\u6599\u5939 ."; case "Delete this file ?":return "\u5220\u9664\u6b64\u6863\u6848 ?"; case "Uploading...":return "\u4e0a\u8f7d\u4e2d ..."; case "File already exists. Do you want to replace it?":return "\u6863\u6848\u5df2\u5b58\u5728\uff0c\u8981\u50a8\u5b58\u5e76\u66ff\u4ee3\u65e7\u6709\u6863\u6848\u5417 ?"; case "Files": return "\u6863\u6848 "; case "del": return "\u5220\u9664 "; case "Empty...": return "\u7a7a\u767d ..."; } } function loadTxt() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "\u65b0\u589e\u8d44\u6599\u5939 "; txtLang[1].innerHTML = "\u5220\u9664\u8d44\u6599\u5939 "; txtLang[2].innerHTML = "\u4e0a\u8f7d\u6863\u6848 "; var optLang = document.getElementsByName("optLang"); optLang[0].text = "\u5168\u90e8\u6863\u6848 "; optLang[1].text = "\u591a\u5a92\u4f53\u6863\u6848 "; optLang[2].text = "\u5f71\u50cf "; optLang[3].text = "Flash"; document.getElementById("btnOk").value = " \u786e\u8ba4 "; document.getElementById("btnUpload").value = "\u4e0a\u8f7d "; } function writeTitle() { document.write("<title>Asset manager</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder deleted.": return "\u8d44\u6599\u5939\u5df1\u5220\u9664 ."; case "Folder does not exist.": return "\u8d44\u6599\u5939\u4e0d\u5b58\u5728 ."; case "Cannot delete Asset Base Folder.": return "\u4e0d\u80fd\u5220\u9664\u6b64\u8d44\u6599\u5939 ."; } } function loadTxt() { document.getElementById("btnCloseAndRefresh").value = "\u5173\u95ed\u53ca\u66f4\u65b0 "; } function writeTitle() { document.write("<title>\u5220\u9664\u8d44\u6599\u5939 </title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder already exists.": return "\u8d44\u6599\u5939\u5df2\u5b58\u5728 ."; case "Folder created.": return "\u8d44\u6599\u5939\u5df1\u5efa\u7acb ."; case "Invalid input.": return "\u8f93\u5165\u4e0d\u6b63\u786e ."; } } function loadTxt() { document.getElementById("txtLang").innerHTML = "\u65b0\u589e\u8d44\u6599\u5939\u540d\u79f0 "; document.getElementById("btnCloseAndRefresh").value = "\u5173\u95ed\u53ca\u66f4\u65b0 "; document.getElementById("btnCreate").value = "\u5efa\u7acb "; } function writeTitle() { document.write("<title>\u5efa\u7acb\u8d44\u6599\u5939 </title>") }
JavaScript
function loadTxt() { document.getElementById("txtLang").innerHTML = "\u786e\u5b9a\u5220\u9664\u6b64\u8d44\u6599\u5939 ?"; document.getElementById("btnClose").value = "\u5173\u95ed "; document.getElementById("btnDelete").value = "\u5220\u9664 "; } function writeTitle() { document.write("<title>Delete Folder</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Cannot delete Asset Base Folder.":return "Der Hauptordner kann nicht gel\u00F6scht werden."; case "Delete this file ?":return "Soll diese Datei gel\u00F6scht werden ?"; case "Uploading...":return "Es wird hochgeladen..."; case "File already exists. Do you want to replace it?":return "Datei existiert bereits. Soll sie ersetzt werden?" case "Files": return "Dateien"; case "del": return "l&ouml;schen"; case "Empty...": return "Empty..."; } } function loadTxt() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "Neuer&nbsp;Ordner"; txtLang[1].innerHTML = "Ordner&nbsp;l&ouml;schen"; txtLang[2].innerHTML = "Datei hochladen"; var optLang = document.getElementsByName("optLang"); optLang[0].text = "alle Dateien"; optLang[1].text = "Media"; optLang[2].text = "Bilder"; optLang[3].text = "Flash"; document.getElementById("btnOk").value = " OK "; document.getElementById("btnUpload").value = "hochladen"; } function writeTitle() { document.write("<title>Asset manager</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder deleted.": return "Ordner gel&ouml;scht."; case "Folder does not exist.": return "Ordner existiert nicht."; case "Cannot delete Asset Base Folder.": return "Der Basisordner kann nicht gel&ouml;scht werden."; } } function loadTxt() { document.getElementById("btnCloseAndRefresh").value = "schlie\u00DFen & aktualisieren"; } function writeTitle() { document.write("<title>"+"Ordner l\u00F6schen"+"</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder already exists.": return "Der Ordner existiert bereits."; case "Folder created.": return "Ordner wurde angelegt."; case "Invalid input.":return "Falsche Eingabe"; } } function loadTxt() { document.getElementById("txtLang").innerHTML = "Neuer Ordnername"; document.getElementById("btnCloseAndRefresh").value = "schlie\u00DFen & aktualisieren"; document.getElementById("btnCreate").value = "erstellen"; } function writeTitle() { document.write("<title>Ordner anlegen</title>") }
JavaScript
function loadTxt() { document.getElementById("txtLang").innerHTML = "Wollen Sie diesen Ordner wirklich l\u00F6schen?"; document.getElementById("btnClose").value = "schlie\u00DFen"; document.getElementById("btnDelete").value = "l\u00F6schen"; } function writeTitle() { document.write("<title>"+"Ordner l\u00F6schen"+"</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Cannot delete Asset Base Folder.":return "No se puede borrar la carpeta raiz."; case "Delete this file ?":return "Borrar el archivo?"; case "Uploading...":return "Subiendo el archivo..."; case "File already exists. Do you want to replace it?":return "El archivo ya existe. Quiere reemplazarlo?" case "Files": return "Archivos"; case "del": return "Borrar"; case "Empty...": return "Vacio..."; } } function loadTxt() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "Nueva carpeta"; txtLang[1].innerHTML = "Borrar carpeta"; txtLang[2].innerHTML = "Subir archivo"; var optLang = document.getElementsByName("optLang"); optLang[0].text = "Todos"; optLang[1].text = "Multimedia"; optLang[2].text = "Imagenes"; optLang[3].text = "Flash"; document.getElementById("btnOk").value = " Aceptar "; document.getElementById("btnUpload").value = "Subir"; } function writeTitle() { document.write("<title>Administrador de archivos</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder deleted.": return "Carpeta borrada."; case "Folder does not exist.": return "La carpeta no existe."; case "Cannot delete Asset Base Folder.": return "No se puede borrar la carpeta."; } } function loadTxt() { document.getElementById("btnCloseAndRefresh").value = "Cerrar y actualizar"; } function writeTitle() { document.write("<title>Borrar Carpeta</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder already exists.": return "La carpeta ya existe."; case "Folder created.": return "Carpeta creada."; case "Invalid input.":return "Nombre no valido."; } } function loadTxt() { document.getElementById("txtLang").innerHTML = "Nombre nueva carpeta"; document.getElementById("btnCloseAndRefresh").value = "Cerrar y actualizar"; document.getElementById("btnCreate").value = "Crear"; } function writeTitle() { document.write("<title>Crear Carpeta</title>") }
JavaScript
function loadTxt() { document.getElementById("txtLang").innerHTML = "Est\u00E1 seguro que quiere borrar la carpeta?"; document.getElementById("btnClose").value = "Cerrar"; document.getElementById("btnDelete").value = "Borrar"; } function writeTitle() { document.write("<title>Borrar Carpeta</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Cannot delete Asset Base Folder.":return "Du kan ikke slette fil rodmappen."; case "Delete this file ?":return "Vil du slette filen ?"; case "Uploading...":return "Oploader...";//or "Sender..." case "File already exists. Do you want to replace it?":return "Fil eksisterer allerede. \u00D8nsker du at overskrive den?"; case "Files": return "Filer" case "del": return "Slet" case "Empty...": return "Tom..." } } function loadTxt() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "Opret&nbsp;mappe"; txtLang[1].innerHTML = "Slet&nbsp;mappe"; txtLang[2].innerHTML = "Send fil"; var optLang = document.getElementsByName("optLang"); optLang[0].text = "Alle filer"; optLang[1].text = "Medier"; optLang[2].text = "Billeder"; optLang[3].text = "Flash"; document.getElementById("btnOk").value = " ok "; document.getElementById("btnUpload").value = "Upload"; } function writeTitle() { document.write("<title>Filmanager</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder deleted.": return "Mappen er slettet."; case "Folder does not exist.": return "Mappen eksisterer ikke."; case "Cannot delete Asset Base Folder.": return "Rodmappen kan ikke slettes."; } } function loadTxt() { document.getElementById("btnCloseAndRefresh").value = "Luk og opdater"; } function writeTitle() { document.write("<title>Slet mappe</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder already exists.": return "Mappen eksisterer allerede."; case "Folder created.": return "Mappen er oprettet."; case "Invalid input.": return "Indtastningen indeholder ugyldige karakterer."; } } function loadTxt() { document.getElementById("txtLang").innerHTML = "Nyt mappe navn"; document.getElementById("btnCloseAndRefresh").value = "Luk og opdater"; document.getElementById("btnCreate").value = "Opret"; } function writeTitle() { document.write("<title>Opret mappe</title>") }
JavaScript
function loadTxt() { document.getElementById("txtLang").innerHTML = "Vil du slette denne mappe?"; document.getElementById("btnClose").value = "Annuler"; document.getElementById("btnDelete").value = "Slet"; } function writeTitle() { document.write("<title>Slet mappe</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Cannot delete Asset Base Folder.":return "Impossible d'effacer le r\u00E9pertoire racine."; case "Delete this file ?":return "Voulez vous effacer ce fichier ?"; case "Uploading...":return "publication en cours..."; case "File already exists. Do you want to replace it?":return "File already exists. Do you want to replace it?" case "Files": return "Fichiers"; case "del": return "Effacer"; case "Empty...": return "Empty..."; } } function loadTxt() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "Nouveau r\u00E9pertoire"; txtLang[1].innerHTML = "Effacer le r\u00E9pertoire"; txtLang[2].innerHTML = "Publier un fichier"; var optLang = document.getElementsByName("optLang"); optLang[0].text = "Tous les fichiers"; optLang[1].text = "Media"; optLang[2].text = "Images"; optLang[3].text = "Flash"; document.getElementById("btnOk").value = " ok "; document.getElementById("btnUpload").value = "publier"; } function writeTitle() { document.write("<title>Gestionnaire de fichiers</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder deleted.": return "R&eacute;pertoire effac&eacute;."; case "Folder does not exist.": return "Le r&eacute;pertoire n'existe pas."; case "Cannot delete Asset Base Folder.": return "Impossible d'effacer le r&eacute;pertoire racine."; } } function loadTxt() { document.getElementById("btnCloseAndRefresh").value = "fermer & actualiser"; } function writeTitle() { document.write("<title>Effacer les r\u00E9pertoires</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Folder already exists.": return "Le r&eacute;pertoire existe d&eacute;j&agrave;."; case "Folder created.": return "Le r&eacute;pertoire a &eacute;t&eacute; cr&eacute;&eacute;"; case "Invalid input.":return "La valeur entr\u00E9e ne convient pas.";//"La valeur entr&eacute;e ne convient pas." } } function loadTxt() { document.getElementById("txtLang").innerHTML = "Nom du nouveau r\u00E9pertoire"; document.getElementById("btnCloseAndRefresh").value = "fermer et actualiser"; document.getElementById("btnCreate").value = "Cr\u00E9er"; } function writeTitle() { document.write("<title>Cr\u00E9ation de r\u00E9pertoire</title>") }
JavaScript
function loadTxt() { document.getElementById("txtLang").innerHTML = "Etes vous sur de vouloir effacer ce r\u00E9pertoire ?"; document.getElementById("btnClose").value = "fermer"; document.getElementById("btnDelete").value = "effacer"; } function writeTitle() { document.write("<title>Suppression de r\u00E9pertoires</title>") }
JavaScript
function getTxt(s) { switch(s) { case "Cannot delete Asset Base Folder.":return "Cannot delete Asset Base Folder."; case "Delete this file ?":return "Delete this file ?"; case "Uploading...":return "Uploading..."; case "File already exists. Do you want to replace it?":return "File already exists. Do you want to replace it?"; case "Files": return "Files"; case "del": return "del"; case "Empty...": return "Empty..."; } } function loadTxt() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "New&nbsp;Folder"; txtLang[1].innerHTML = "Del&nbsp;Folder"; txtLang[2].innerHTML = "Upload File"; var optLang = document.getElementsByName("optLang"); optLang[0].text = "All Files"; optLang[1].text = "Media"; optLang[2].text = "Images"; optLang[3].text = "Flash"; document.getElementById("btnOk").value = " ok "; document.getElementById("btnUpload").value = "upload"; } function writeTitle() { document.write("<title>Asset manager</title>") }
JavaScript