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','tr',{uicolor:{title:'UI Renk Seçicisi',preview:'Canlı önizleme',config:'Bu dizeyi config.js dosyasının içine yapıştırın',predefined:'Önceden tanımlanmış renk kümeleri'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fr',{uicolor:{title:'UI Sélecteur de couleur',preview:'Aperçu',config:'Collez cette chaîne de caractères dans votre fichier config.js',predefined:'Palettes de couleurs prédéfinies'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','zh-cn',{uicolor:{title:'用户界面颜色选择器',preview:'即时预览',config:'粘贴此字符串到您的 config.js 文件',predefined:'预定义颜色集'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','eo',{uicolor:{title:'UI Kolorselektilo',preview:'Vidigi la aspekton',config:'Gluu tiun signoĉenon en vian dosieron config.js',predefined:'Antaŭdifinita koloraro'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','sk',{uicolor:{title:'UI výber farby',preview:'Živý náhľad',config:'Vložte tento reťazec do vášho config.js súboru',predefined:'Preddefinované sady farieb'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','da',{uicolor:{title:'Brugerflade på farvevælger',preview:'Vis liveeksempel',config:'Indsæt denne streng i din config.js fil',predefined:'Prædefinerede farveskemaer'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nb',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','bg',{uicolor:{title:'ПИ избор на цвят',preview:'Преглед',config:'Вмъкнете този низ във Вашия config.js fajl',predefined:'Предефинирани цветови палитри'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','el',{uicolor:{title:'Διεπαφή Επιλογέα Χρωμάτων',preview:'Ζωντανή Προεπισκόπηση',config:'Επικολλήστε αυτό το κείμενο στο αρχείο config.js',predefined:'Προκαθορισμένα σύνολα χρωμάτων'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fi',{uicolor:{title:'Käyttöliittymän värivalitsin',preview:'Esikatsele',config:'Liitä tämä merkkijono config.js tiedostoosi',predefined:'Esimääritellyt värijoukot'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cy',{uicolor:{title:"Dewisydd Lliwiau'r UI",preview:'Rhagolwg Byw',config:"Gludwch y llinyn hwn i'ch ffeil config.js",predefined:"Setiau lliw wedi'u cyn-ddiffinio"}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','no',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','mk',{uicolor:{title:'Палета со бои',preview:'Преглед',config:'Залепи го овој текст во config.js датотеката',predefined:'Предефинирани множества на бои'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'fa',
{
uicolor :
{
title : 'انتخاب رنگ UI',
preview : 'پیشنمایش زنده',
config : 'این رشته را در فایل config.js خود بچسبانید.',
predefined : 'مجموعه رنگ از پیش تعریف شده'
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','et',{uicolor:{title:'Värvivalija kasutajaliides',preview:'Automaatne eelvaade',config:'Aseta see sõne oma config.js faili.',predefined:'Eelmääratud värvikomplektid'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','uk',{uicolor:{title:'Color Picker Інтерфейс',preview:'Перегляд наживо',config:'Вставте цей рядок у файл config.js',predefined:'Стандартний набір кольорів'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cs',{uicolor:{title:'Výběr barvy rozhraní',preview:'Živý náhled',config:'Vložte tento řetězec do Vašeho souboru config.js',predefined:'Přednastavené sady barev'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uicolor', 'ku',
{
uicolor :
{
title : 'ههڵگری ڕهنگ بۆ ڕووکاری بهکارهێنهر',
preview : 'پێشبینین به زیندوویی',
config : 'ئهم دهقانه بلکێنه به پهڕگهی config.js-fil',
predefined : 'کۆمهڵه ڕهنگه دیاریکراوهکانی پێشوو'
}
});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','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
*/
/*
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 |
(function () {
var host = window.location.hostname;
var port = window.location.port;
var videoPlugin;
var videoStream;
var audioPlugin;
var audioStream;
var error;
function stream(object,type,done) {
var state = "idle";
return {
restart: function () {
state = "restarting";
done();
if (object.playlist.isPlaying) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
setTimeout(function () {
this.start(false);
}.bind(this),2000);
} else {
this.start(false);
}
},
start: function (e) {
var req = generateUriParams(type);
state = "starting";
if (e!==false) done();
$.ajax({
type: 'GET',
url: 'spydroid.sdp?id='+(type==='video'?0:1)+'&'+req.uri,
success: function (e) {
setTimeout(function () {
state = "streaming";
object.playlist.add('http://'+host+':'+port+'/spydroid.sdp?id='+(type==='video'?0:1)+'&'+req.uri,'',req.params);
object.playlist.playItem(0);
setTimeout(function () {
done();
},600);
},1000);
},
error: function () {
state = "error";
getError();
}
});
},
stop: function () {
$.ajax({
type: 'GET',
url: 'spydroid.sdp?id='+(type==='video'?0:1)+'&stop',
success: function (e) {
//done(); ??
},
error: function () {
state = "error";
getError();
}
});
if (object.playlist.isPlaying) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
}
state = "idle";
done();
},
getState: function() {
return state;
},
isStreaming: function () {
return object.playlist.isPlaying;
}
}
}
function sendRequest(request,success,error) {
var data;
if (typeof request === "string") data = {'action':request}; else data = request;
$.ajax({type: 'POST', url: 'request.json', data: JSON.stringify(data), success:success, error:error});
}
function updateBatteryLevel(level) {
$('#battery>#level').text(level);
setTimeout(function () {
sendRequest(
"battery",
function (e) {
updateBatteryLevel(e.battery);
},
function () {
updateBatteryLevel('??');
}
);
},100000);
}
function updateTooltip(title) {
$('#tooltip>div').hide();
$('#tooltip #'+title).show();
}
function loadSettings(config) {
$('#resolution,#framerate,#bitrate,#audioEncoder,#videoEncoder').children().each(function (c) {
if ($(this).val()===config.videoResolution ||
$(this).val()===config.videoFramerate ||
$(this).val()===config.videoBitrate ||
$(this).val()===config.audioEncoder ||
$(this).val()===config.videoEncoder ) {
$(this).parent().children().prop('selected',false);
$(this).prop('selected',true);
}
});
if (config.streamAudio===false) $('#audioEnabled').prop('checked',false);
if (config.streamVideo===false) $('#videoEnabled').prop('checked',false);
}
function saveSettings() {
var res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
var videoQuality = /[0-9]+/.exec($('#bitrate').val())[0]+'-'+/[0-9]+/.exec($('#framerate').val())[0]+'-'+res[1]+'-'+res[2];
var settings = {
'stream_video': $('#videoEnabled').prop('checked')===true,
'stream_audio': $('#audioEnabled').prop('checked')===true,
'video_encoder': $('#videoEncoder').val(),
'audio_encoder': $('#audioEncoder').val(),
'video_quality': videoQuality
};
sendRequest({'action':'set','settings':settings});
}
function loadSoundsList(sounds) {
var list = $('#soundslist'), category, name;
sounds.forEach(function (e) {
category = e.match(/([a-z0-9]+)_/)[1];
name = e.match(/[a-z0-9]+_([a-z0-9_]+)/)[1];
if ($('.category.'+category).length==0) list.append(
'<div class="category '+category+'"><span class="category-name">'+category+'</span><div class="category-separator"></div></div>'
);
$('.category.'+category).append('<div class="sound" id="'+e+'"><a>'+name.replace(/_/g,' ')+'</a></div>');
});
}
function testScreenState(state) {
if (state===0) {
$('#error-screenoff').fadeIn(1000);
$('#glass').fadeIn(1000);
}
}
function generateUriParams(type) {
var audioEncoder, videoEncoder, cache, rotation, flash, camera, res;
// Audio conf
if ($('#audioEnabled').prop('checked')) {
audioEncoder = $('#audioEncoder').val()=='AMR-NB'?'amr':'aac';
} else {
audioEncoder = "nosound";
}
// Resolution
res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
// Video conf
if ($('#videoEnabled').prop('checked')) {
videoEncoder = ($('#videoEncoder').val()=='H.263'?'h263':'h264')+'='+
/[0-9]+/.exec($('#bitrate').val())[0]+'-'+
/[0-9]+/.exec($('#framerate').val())[0]+'-';
videoEncoder += res[1]+'-'+res[2];
} else {
videoEncoder = "novideo";
}
// Flash
if ($('#flashEnabled').val()==='1') flash = 'on'; else flash = 'off';
// Camera
camera = $('#cameraId').val();
// Params
cache = /[0-9]+/.exec($('#cache').val())[0];
return {
uri:type==='audio'?audioEncoder:(videoEncoder+'&flash='+flash+'&camera='+camera),
params:[':network-caching='+cache]
}
}
function getError() {
sendRequest(
'state',
function (e) {
error = e.state.lastError;
updateStatus();
},
function () {
error = 'Phone unreachable !';
updateStatus();
}
);
}
function updateStatus() {
var status = $('#status'), button = $('#connect>div>h1'), cover = $('#vlc-container #upper-layer');
// STATUS
if (videoStream.getState()==='starting' || videoStream.getState()==='restarting' ||
audioStream.getState()==='starting' || audioStream.getState()==='restarting') {
status.html(__('Trying to connect...'))
} else {
if (!videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('NOT CONNECTED'));
else if (videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('Streaming video but not audio'));
else if (!videoStream.isStreaming() && audioStream.isStreaming()) status.html(__('Streaming audio but not video'));
else status.html(__('Streaming audio and video'));
}
// BUTTON
if ((videoStream.getState()==='idle' || videoStream.getState()==='error') &&
(audioStream.getState()==='idle' || audioStream.getState()==='error')) {
button.html(__('Connect !!'));
} else button.text(__('Disconnect ?!'));
// WINDOW
if (videoStream.getState()==='error' || audioStream.getState()==='error') {
videoPlugin.css('visibility','hidden');
cover.html('<div id="wrapper"><h1>'+__('An error occurred')+' :(</h1><p>'+error+'</p></div>');
} else if (videoStream.getState()==='restarting' || audioStream.getState()==='restarting') {
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('UPDATING SETTINGS')+'</h1></div>').show();
} else if (videoStream.getState()==='starting' || audioStream.getState()==='starting') {
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('CONNECTION')+'</h1></div>').show();
} else if (videoStream.getState()==='streaming') {
videoPlugin.css('visibility','inherit');
cover.hide();
}
if (videoStream.getState()==='idle') {
if (audioStream.getState()==='streaming') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/speaker.png") center no-repeat').show();
} else if (audioStream.getState()==='idle') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/eye.png") center no-repeat').show();
}
}
}
function disableAndEnable(input) {
input.prop('disabled',true);
setTimeout(function () {
input.prop('disabled',false);
},1000);
}
function setupEvents() {
var cover = $('#vlc-container #upper-layer');
var status = $('#status');
var button = $('#connect>div>h1');
$('.popup #close').click(function (){
$('#glass').fadeOut();
$('.popup').fadeOut();
});
$('#connect').click(function () {
if ($(this).prop('disabled')===true) return;
disableAndEnable($(this));
if ((videoStream.getState()!=='idle' && videoStream.getState()!=='error') ||
(audioStream.getState()!=='idle' && audioStream.getState()!=='error')) {
videoStream.stop();
audioStream.stop();
} else {
if (!$('#videoEnabled').prop('checked') && !$('#audioEnabled').prop('checked')) return;
if ($('#videoEnabled').prop('checked')) videoStream.start();
if ($('#audioEnabled').prop('checked')) audioStream.start();
}
});
$('#torch-button').click(function () {
if ($(this).prop('disabled')===true || videoStream.getState()==='starting') return;
disableAndEnable($(this));
if ($('#flashEnabled').val()=='0') {
$('#flashEnabled').val('1');
$(this).addClass('torch-on');
} else {
$('#flashEnabled').val('0');
$(this).removeClass('torch-on');
}
if (videoStream.getState()==='streaming') videoStream.restart();
});
$('#buzz-button').click(function () {
$(this).animate({'padding-left':'+=10'}, 40, 'linear')
.animate({'padding-left':'-=20'}, 80, 'linear')
.animate({'padding-left':'+=10'}, 40, 'linear');
sendRequest('buzz');
});
$(document).on('click', '.camera-not-selected', function () {
if ($(this).prop('disabled')===true || videoStream.getState()==='starting') return;
$('#cameras span').addClass('camera-not-selected');
$(this).removeClass('camera-not-selected');
disableAndEnable($('.camera-not-selected'));
$('#cameraId').val($(this).attr('data-id'));
if (videoStream.getState()==='streaming') videoStream.restart();
})
$('.audio select').change(function () {
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('.audio input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#audioEnabled').prop('checked')) audioStream.restart(); else audioStream.stop();
disableAndEnable($(this));
}
});
$('.video select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
});
$('.video input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#videoEnabled').prop('checked')) videoStream.restart(); else videoStream.stop();
disableAndEnable($(this));
}
});
$('.cache select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('select,input').change(function () {
saveSettings();
});
$('.section').click(function () {
$('.section').removeClass('selected');
$(this).addClass('selected');
updateTooltip($(this).attr('id'));
});
$(document).on('click', '.sound', function () {
sendRequest([{'action':'play','name':$(this).attr('id')}]);
});
$('#fullscreen').click(function () {
videoPlugin[0].video.toggleFullscreen();
});
$('#hide-tooltip').click(function () {
$('body').width($('body').width() - $('#tooltip').width());
$('#tooltip').hide();
$('#need-help').show();
});
$('#need-help').click(function () {
$('body').width($('body').width() + $('#tooltip').width());
$('#tooltip').show();
$('#need-help').hide();
});
window.onbeforeunload = function (e) {
videoStream.stop();
audioStream.stop();
}
};
$(document).ready(function () {
videoPlugin = $('#vlcv');
videoStream = stream(videoPlugin[0],'video',updateStatus);
audioPlugin = $('#vlca');
audioStream = stream(audioPlugin[0],'audio',updateStatus);
sendRequest([{'action':'sounds'},{'action':'screen'},{'action':'get'},{'action':'battery'}], function (data) {
// Verify that the screen is not turned off
testScreenState(data.screen);
// Fetch the list of sounds available on the phone
loadSoundsList(data.sounds);
// Retrieve the configuration of Spydroid on the phone
loadSettings(data.get);
// Retrieve the battery level
updateBatteryLevel(data.battery);
});
// Translate the interface in the appropriate language
$('h1,h2,h3,span,p,a,em').translate();
$('.popup').each(function () {
$(this).css({'top':($(window).height()-$(this).height())/2,'left':($(window).width()-$(this).width())/2});
});
$('#tooltip').hide();
$('#need-help').show();
// Bind DOM events
setupEvents();
});
}()); | JavaScript |
(function () {
var translations = {
en: {
1:"About",
2:"Return",
3:"Change quality settings",
4:"Flash/Vibrator",
5:"Click on the torch to enable or disable the flash",
6:"Play a prerecorded sound",
7:"Connect !!",
8:"Disconnect ?!",
9:"STATUS",
10:"NOT CONNECTED",
11:"ERROR :(",
12:"CONNECTION",
13:"UPDATING SETTINGS",
14:"CONNECTED",
15:"Show some tips",
16:"Hide those tips",
17:"Those buttons will trigger sounds on your phone...",
18:"Use them to surprise your victim.",
19:"Or you could use this to surprise your victim !",
20:"This will simply toggle the led in front of you're phone, so that even in the deepest darkness, you shall not be blind...",
21:"If the stream is choppy, try reducing the bitrate or increasing the cache size.",
22:"Try it instead of H.263 if video streaming is not working at all !",
23:"The H.264 compression algorithm is more efficient but may not work on your phone...",
24:"You need to install VLC first !",
25:"During the installation make sure to check the firefox plugin !",
26:"Close",
27:"You must leave the screen of your smartphone on !",
28:"Front facing camera",
29:"Back facing camera",
30:"Switch between cameras",
31:"Streaming video but not audio",
32:"Streaming audio but not video",
33:"Streaming audio and video",
34:"Trying to connect...",
35:"Stream sound",
36:"Stream video",
37:"Fullscreen",
38:"Encoder",
39:"Resolution",
40:"Cache size",
41:"This generally happens when you are trying to use settings that are not supported by your phone.",
42:"Retrieving error message...",
43:"An error occurred",
44:"Click on the phone to make your phone buzz"
},
fr: {
1:"À propos",
2:"Retour",
3:"Changer la qualité du stream",
4:"Flash/Vibreur",
5:"Clique sur l'ampoule pour activer ou désactiver le flash",
6:"Jouer un son préenregistré",
7:"Connexion !!",
8:"Déconnecter ?!",
9:"STATUT",
10:"DÉCONNECTÉ",
11:"ERREUR :(",
12:"CONNEXION",
13:"M.A.J.",
14:"CONNECTÉ",
15:"Afficher l'aide",
16:"Masquer l'aide",
17:"Clique sur un de ces boutons pour lancer un son préenregistré sur ton smartphone !",
18:"Utilise les pour surprendre ta victime !!",
19:"Ça peut aussi servir à surprendre ta victime !",
20:"Clique sur l'ampoule pour allumer le flash de ton smartphone",
21:"Si le stream est saccadé essaye de réduire le bitrate ou d'augmenter la taille du cache.",
22:"Essaye le à la place du H.263 si le streaming de la vidéo ne marche pas du tout !",
23:"Le H.264 est un algo plus efficace pour compresser la vidéo mais il a moins de chance de marcher sur ton smartphone...",
24:"Tu dois d'abord installer VLC !!",
25:"Pendant l'installation laisse cochée l'option plugin mozilla !",
26:"Fermer",
27:"Tu dois laisser l'écran de ton smartphone allumé",
28:"Caméra face avant",
29:"Caméra face arrière",
30:"Choisir la caméra",
31:"Streaming de la vidéo",
32:"Streaming de l'audio",
33:"Streaming de l'audio et de la vidéo",
34:"Connexion en cours...",
35:"Streaming du son",
36:"Streaming de la vidéo",
37:"Plein écran",
38:"Encodeur",
39:"Résolution",
40:"Taille cache",
41:"En général, cette erreur se produit quand les paramètres sélectionnés ne sont pas compatibles avec le smartphone.",
42:"Attente du message d'erreur...",
43:"Une erreur s'est produite",
44:"Clique pour faire vibrer ton tel."
},
ru: {
1:"Спасибо",
2:"Вернуться",
3:"Изменить настройки качества",
4:"Переключатель вспышки",
5:"Нажмите здесь, чтобы включить или выключить вспышку",
6:"Проиграть звук на телефоне",
7:"Подключиться !!",
8:"Отключиться ?!",
9:"СОСТОЯНИЕ",
10:"НЕТ ПОДКЛЮЧЕНИЯ",
11:"ОШИБКА :(",
12:"ПОДКЛЮЧЕНИЕ",
13:"ОБНОВЛЕНИЕ НАСТРОЕК",
14:"ПОДКЛЮЧЕНО",
15:"Показать поясняющие советы",
16:"Спрятать эти советы",
17:"Эти кнопки будут проигрывать звуки на вашем телефоне...",
18:"Используйте их, чтобы удивить вашу жертву.",
19:"Или вы можете удивить свою жертву!",
20:"Это переключатель режима подсветки на передней части вашего телефона, так что даже в самой кромешной тьме, вы не будете слепы ...",
21:"Если поток прерывается, попробуйте уменьшить битрейт или увеличив размер кэша.",
22:"Если топоковое видео не работает совсем, попробуйте сжатие Н.263",
23:"Алгоритм сжатия H.264, является более эффективным, но может не работать на вашем телефоне ...",
24:"Вначале Вам необходимо установить VLC !",
25:"При установке убедитесь в наличии плагина для firefox !",
26:"Закрыть",
27:"Вам надо отойти от вашего смартфона.",
28:"Фронтальная камера",
29:"Камера с обратной стороны",
30:"Переключиться на другую камеру",
31:"Передача видео без звука",
32:"Передача звука без видео",
33:"Передача звука и видео",
34:"Пытаемся подключится",
35:"Аудио поток",
36:"Видео поток",
37:"На весь экран",
38:"Кодек",
39:"Разрешение",
40:"Размер кеша",
41:"Как правило, это происходит, когда вы пытаетесь использовать настройки, не поддерживаемые вашим телефоном.",
42:"Получение сообщения об ошибке ..."
},
de : {
1:"Apropos",
2:"Zurück",
3:"Qualität des Streams verändern",
4:"Fotolicht ein/aus",
5:"Klick die Glühbirne an, um das Fotolicht einzuschalten oder azufallen",
6:"Vereinbarten Ton spielen",
7:"Verbindung !!",
8:"Verbinden ?!",
9:"STATUS",
10:"NICHT VERBUNDEN",
11:"FEHLER :(",
12:"VERBINDUNG",
13:"UPDATE",
14:"VERBUNDEN",
15:"Hilfe anzeigen",
16:"Hilfe ausblenden",
17:"Klick diese Tasten an, um Töne auf deinem Smartphone spielen zu lassen !",
18:"Benutz sie, um deine Opfer zu überraschen !!",
19:"Das kann auch dein Opfer erschrecken !",
20:"Es wird die LED hinter deinem Handy anmachen, damit du nie blind bleibst, auch im tiefsten Dunkeln",
21:"Wenn das Stream ruckartig ist, versuch mal die Bitrate zu reduzieren oder die Größe vom Cache zu steigern.",
22:"Probier es ansatt H.263, wenn das Videostream überhaupt nicht funktionert !",
23:"Der H.264 Kompressionalgorithmus ist effizienter aber er wird auf deinem Handy vielleicht nicht funktionieren...",
24:"Du musst zuerst VLC installieren !!",
25:"Während der Installation, prüfe dass das Firefox plugin abgecheckt ist!",
26:"Zumachen",
27:"Du musst den Bildschirm deines Smartphones eingeschaltet lassen !",
28:"Frontkamera",
29:"Rückkamera",
30:"Kamera auswählen",
31:"Videostreaming",
32:"Audiostreaming",
33:"Video- und Audiostreaming",
34:"Ausstehende Verbindung...",
35:"Soundstreaming",
36:"Videostreaming",
37:"Ganzer Bildschirm",
38:"Encoder",
39:"Auflösung",
40:"Cachegröße",
41:"Dieser Fehler gescheht überhaupt, wenn die gewählten Einstellungen mit dem Smartphone nicht kompatibel sind.",
42:"Es wird auf die Fehlermeldung gewartet...",
43:"Ein Fehler ist geschehen..."
}
};
var lang = window.navigator.userLanguage || window.navigator.language;
//var lang = "ru";
var __ = function (text) {
var x,y=0,z;
if (lang.match(/en/i)!=null) return text;
for (x in translations) {
if (lang.match(new RegExp(x,"i"))!=null) {
for (z in translations.en) {
if (text==translations.en[z]) {
y = z;
break;
}
}
return translations[x][y]==undefined?text:translations[x][y];
}
}
return text;
};
$.fn.extend({
translate: function () {
return this.each(function () {
$(this).html(__($(this).html()));
});
}
});
window.__ = __;
}());
| JavaScript |
document.createElement('header');
document.createElement('nav');
document.createElement('section');
document.createElement('article');
document.createElement('aside');
document.createElement('footer');
document.createElement('hgroup');
$(document).ready(function () {
$('.section-content,#status-container').addClass('ie8-background');
$('.category-separator').hide();
}); | JavaScript |
$(document).ready(function()
{
$("td").hover(
function()
{
$(this).addClass('highlight');
},
function ()
{
$(this).removeClass('highlight');
});
});
| JavaScript |
var puShown = false;
var PopWidth = (screen.width);
var PopHeight = (screen.height);
var PopFocus = 0;
var _Top = null;
var _paq = _paq || [];
(function(){ var u=(("https:" == document.location.protocol) ? "https://stats.schenkelklopfer.org/" : "http://stats.schenkelklopfer.org/");
_paq.push(['setSiteId', 2]);
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.defer=true; g.async=true; g.src=u+'piwik.js';
s.parentNode.insertBefore(g,s); })();
function GetWindowHeight() {
var myHeight = 0;
if( typeof( _Top.window.innerHeight ) == 'number' ) {
myHeight = _Top.window.innerHeight;
} else if( _Top.document.documentElement && _Top.document.documentElement.clientHeight ) {
myHeight = _Top.document.documentElement.clientHeight;
} else if( _Top.document.body && _Top.document.body.clientHeight ) {
myHeight = _Top.document.body.clientHeight;
}
return myHeight;
}
function GetWindowWidth() {
var myWidth = 0;
if( typeof( _Top.window.innerWidth ) == 'number' ) {
myWidth = _Top.window.innerWidth;
} else if( _Top.document.documentElement && _Top.document.documentElement.clientWidth ) {
myWidth = _Top.document.documentElement.clientWidth;
} else if( _Top.document.body && _Top.document.body.clientWidth ) {
myWidth = _Top.document.body.clientWidth;
}
return myWidth;
}
function GetWindowTop() {
return (_Top.window.screenTop != undefined) ? _Top.window.screenTop : _Top.window.screenY;
}
function GetWindowLeft() {
return (_Top.window.screenLeft != undefined) ? _Top.window.screenLeft : _Top.window.screenX;
}
function doOpen(url)
{
var popURL = "http://www.pornme.com/traffic.php?ref=3889"
var popID = "ad_" + Math.floor(89999999*Math.random()+10000000);
var pxLeft = 0;
var pxTop = 0;
pxLeft = (GetWindowLeft() + (GetWindowWidth() / 2) - (PopWidth / 2));
pxTop = (GetWindowTop() + (GetWindowHeight() / 2) - (PopHeight / 2));
if ( puShown == true )
{
return true;
}
var PopWin=_Top.window.open(popURL,popID,'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,top=' + pxTop + ',left=' + pxLeft + ',width=' + PopWidth + ',height=' + PopHeight);
if (PopWin)
{
puShown = true;
if (PopFocus == 0)
{
PopWin.blur();
if (navigator.userAgent.toLowerCase().indexOf("applewebkit") > -1)
{
_Top.window.blur();
_Top.window.focus();
}
}
PopWin.Init = function(e) {
with (e) {
Params = e.Params;
Main = function(){
if (typeof window.mozPaintCount != "undefined") {
var x = window.open("http://www.pornme.com/traffic.php?ref=3889");
x.close();
}
var popURL = Params.PopURL;
try { opener.window.focus(); }
catch (err) { }
window.location = popURL;
}
Main();
}
};
PopWin.Params = {
PopURL: url
}
PopWin.Init(PopWin);
}
return PopWin;
}
function setCookie(name, value, time)
{
var expires = new Date();
expires.setTime( expires.getTime() + time );
document.cookie = name + '=' + value + '; path=/;' + '; expires=' + expires.toGMTString() ;
}
function getCookie(name) {
var cookies = document.cookie.toString().split('; ');
var cookie, c_name, c_value;
for (var n=0; n<cookies.length; n++) {
cookie = cookies[n].split('=');
c_name = cookie[0];
c_value = cookie[1];
if ( c_name == name ) {
return c_value;
}
}
return null;
}
function initPu()
{
_Top = self;
if (top != self)
{
try
{
if (top.document.location.toString())
_Top = top;
}
catch(err) { }
}
if ( document.attachEvent )
{
document.attachEvent( 'onclick', checkTarget );
}
else if ( document.addEventListener )
{
document.addEventListener( 'click', checkTarget, false );
}
}
function checkTarget(e)
{
if ( !getCookie('SEGpopundr112012') ) {
var e = e || window.event;
var win = doOpen('http://www.pornme.com/traffic.php?ref=3889');
setCookie('SEGpopundr112012', 1, 24*60*60*1000);
}
}
initPu();
| JavaScript |
$(document).ready(function() {
$(function() {
$(".scrollable").scrollable();
});
if ($('.book-labels').length ) {
// Do something
$('.book-labels').mouseover(function() {
$(this).find('.book-name').fadeIn(80);
$(this).find('.book-price').fadeIn(80);
});
$('.book-labels').mouseleave(function() {
$(this).find('.book-name').fadeOut(80);
$(this).find('.book-price').fadeOut(80);
});
}
$(".header").click(function () {
$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
//execute this after slideToggle is done
//change text of header based on visibility of content div
$header.text(function () {
//change text based on condition
return $content.is(":visible") ? "Collapse" : "Expand";
});
});
});
//getHint
$('.hint').keyup(function(){
str = $('.hint').val();
if (str=="")
{
$('#txtHint').html("");
return;
}
$.ajax({
type: "GET",
url: "getHint.php",
data:"q="+str,
dataType : "json",
success: function(response)
{
$("#txtHint").empty();
$("#txtHint").css("display","block");
if(response == 0)
{
$("#txtHint").append('<span class="hintlink last"><p class="txtHintP padding-side" >لا يوجد اقتراحات</p></span>');
}
else
{
$.each(response, function(index, element)
{
$("#txtHint").append('<a href="book.php?id='+element.id+'" class="hintbook'+index+' hintlink relative"></a>');
$(".hintbook"+index).append('<img src="images/'+element.image+'" class="right"/>');
$(".hintbook"+index).append("<p class='txtHintP' >" +element.name + "</p>");
$(".hintbook"+index).append("<p class='author nobold' >" +element.author+ "</p>");
});
$("#txtHint").append('<img src="images/end-of-list.png" class="end-list"/>');
}
}
});
});
if ($('input.star').length )
{
$(function(){
$('input.star').rating();
});
}
//pop-up
$('#register-pop').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: false,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in'
});
$('.sign-in-pop').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: false,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in'
});
function appendBooks(index,element,append_to)
{
$(append_to).append
(
'<div class="right book-list relative">'+
'<div id="page_numb"><p>'+(index+1)+'</p></div>'+
'<img src="images/'+element.image+'" class="right" id="list-image"> '+
'<div class="right book-details">'+
'<h2 title="">'+element.name+'</h2>'+
'<div class="right col1">'+
'<p>المكتبة: '+element.library+'</p>'+
'<p>التصنيف: '+element.cat+'</p>'+
'</div>'+
'<div class="right col2">'+
'<p>المؤلف: '+element.author+'</p>'+
'<p>اللغة: العربية </p>'+
'</div>'+
'<div class="clear"></div>'+
'<p>نبذة: <span class="regular font12">'+element.desc+'</span></p>'+
'</div>'+
'<div class="left price-review">'+
'<div id="price"><p>أقل سعر</p></div>'+
'<div id="price2"><p id="huge-price">'+element.price+'</p><p >جنيه</p></div>'+
'<div class="rating-starts">'+
'<input name="star'+element.id+'" type="radio" class="star"/>'+
'<input name="star'+element.id+'" type="radio" class="star"/> '+
'<input name="star'+element.id+'" type="radio" class="star" checked="checked"/> '+
'<input name="star'+element.id+'" type="radio" class="star"/>'+
'<input name="star'+element.id+'" type="radio" class="star"/>'+
'</div>'+
'</div>'+
'</div>'
); //end of append
}
function ajaxFilter()
{
$('.loading').show();
var dataString = $('.sidebar input,.sidebar select').serialize();
var keyword = $('.keyword').val();
$('.fquery').val(dataString+"&query="+keyword);
dataString = dataString+"&filter="+1+"&query="+keyword;
$.ajax({
type:'GET',
url:'search.php',
dataType : "json",
data: dataString,
success: function(data){
$('.loading').hide();
$('#pages_container').html(" ");
$('#pages_container').append('<div class=" page1"></div>');
if(data == 0)
{
$('.show-results p').text("لا توجد نتائج توافق بحثك");
$('.bootpag').hide();
}
else
{
$.each(data, function(index, element) {
appendBooks(index,element,'.page1')
if(index == 0 )
{
total = Math.ceil(element.pageCount/10);
$('.cats').val(element.cats);
if(element.pageCount < 10)
var showing = element.pageCount;
else
var showing = 10;
$('.show-results p').text("إظهار النتائج 1 - " + showing + " كتاب من إجمالى "+ element.pageCount);
}
});//end of each
$('input.star').rating();
$('#page-selection').bootpag({
total:total,
page:1
});
}
}
});
}
$('.category_checkboxes').click(function() {
ajaxFilter();
});
$('#library').change(function() {
ajaxFilter();
});
$('#pricefilter').click(function() {
ajaxFilter();
});
//getting totalPage number
elements = $('.totalPages').text();
total = Math.ceil(elements/10);
if ($('#page-selection-cat').length )
{
//for category page
$('#page-selection-cat').bootpag({
total: total,
leaps: false,
next: ' ',
prev: ' ',
page: 1
}).on('page', function(event, num){
var pages = $("#pages_container").find('.page'+num);
for(var i=1;i<=total;i++)
{
$('.page'+i).hide();
}
if(pages.length >0)
{
$('.page'+num).show();
}
else
{
var query = $('.cat-hidden').val();
query = "id="+query + "&page="+num;
$.ajax({
type: "GET",
url: "category.php",
dataType : "json",
data:query,
success: function(response){
var classname = ".page"+num;
showing = num*10-9;
$('.show-results p').text("إظهار النتائج "+showing+" -"+(showing+9) +" من أجمالى "+elements);
$('#pages_container').append('<div class="page'+num+'">'); //open new page container
$.each(response, function(index, element) {
appendBooks((num-1)*10+(index),element,classname);
});
$('#pages_container').append('</div>'); //close page container
$('input.star').rating();
}
});
}
});
}
if ($('#page-selection').length )
{
//for searchresults page
$('#page-selection').bootpag({
total: total,
leaps: false,
next: " ",
prev:" ",
href:"#page{{number}}",
page: 1
}).on('page', function(event, num){
$('.loading').show();
var pages = $("#pages_container").find('.page'+num);
for(var i=1;i<=total;i++)
{
$('.page'+i).hide();
}
if(pages.length >0)
{
$('.page'+num).show();
}
else
{
var query = $('.fquery').val();
query = query + "&page="+num;
$.ajax({
type: "GET",
url: "search.php",
dataType : "json",
data:query,
success: function(response){
$('.loading').hide();
var classname = ".page"+num;
$('#pages_container').append('<div class="page'+num+'">'); //open new page container
$.each(response, function(index, element) {
appendBooks(((num-1)*10+(index)),element,classname);
});
$('#pages_container').append('</div>'); //close page container
$('input.star').rating();
}
});
}
});
}
if ($('#username-password-login').length )
{
//login form validation
$("#username-password-login").validate({
rules: {
name: {
required: true,
minlength: 2
},
user_password: {
required: true,
minlength: 6
}
},
messages: {
name: {
required: "أدخل اسم المتسخدم",
minlength: "اسم المستخدم ينبغى ان يحتوى على حرفين على الاقل"
},
user_password: {
required: "من فضلك أدخل كلمة المرور",
minlength: "كلمة المرور ينبغى ان تحتوى على 6 أحرف على الاقل"
}
}
});
}
if ($('#registeration').length )
{
//registeration form validation
$("#registeration").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 6
},
confirm_password: {
required: true,
minlength: 6,
equalTo: "#password"
},
email: {
required: true,
email: true
},
gender: {
required: true
}
},
messages: {
firstname: "من فضلك ادخل الاسم الاول",
lastname: "من فضلك ادخل الاسم الاخير",
username: {
required: "أدخل اسم المتسخدم",
minlength: "اسم المستخدم ينبغى ان يحتوى على حرفين على الاقل"
},
password: {
required: "من فضلك أدخل كلمة المرور",
minlength: "كلمة المرور ينبغى ان تحتوى على 6 أحرف على الاقل"
},
confirm_password: {
required: "من فضلك أدخل تأكيد كلمة المرور",
minlength: "كلمة المرور ينبغى ان تحتوى على 6 أحرف على الاقل",
equalTo: "كلمة المرور غير متطابقة"
},
gender: "من فضلك اختار ما يناسبك من القائمة",
email: "من فضلك تأكد من ادخالك صحيحة للايميل"
}
});
}
}); | JavaScript |
/**
* @name InfoBox
* @version 1.1.12 [December 11, 2012]
* @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google)
* @copyright Copyright 2010 Gary Little [gary at luxcentral.com]
* @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class.
* <p>
* An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several
* additional properties for advanced styling. An InfoBox can also be used as a map label.
* <p>
* An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>.
*/
/*!
*
* 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.
*/
/*jslint browser:true */
/*global google */
/**
* @name InfoBoxOptions
* @class This class represents the optional parameter passed to the {@link InfoBox} constructor.
* @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node).
* @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>.
* @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum.
* @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox
* (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>)
* to the map pixel corresponding to <tt>position</tt>.
* @property {LatLng} position The geographic location at which to display the InfoBox.
* @property {number} zIndex The CSS z-index style value for the InfoBox.
* Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property.
* @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container.
* @property {Object} [boxStyle] An object literal whose properties define specific CSS
* style values to be applied to the InfoBox. Style values defined here override those that may
* be defined in the <code>boxClass</code> style sheet. If this property is changed after the
* InfoBox has been created, all previously set styles (except those defined in the style sheet)
* are removed from the InfoBox before the new style values are applied.
* @property {string} closeBoxMargin The CSS margin style value for the close box.
* The default is "2px" (a 2-pixel margin on all sides).
* @property {string} closeBoxURL The URL of the image representing the close box.
* Note: The default is the URL for Google's standard close box.
* Set this property to "" if no close box is required.
* @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the
* map edge after an auto-pan.
* @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>.
* [Deprecated in favor of the <tt>visible</tt> property.]
* @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>.
* @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code>
* location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned).
* @property {string} pane The pane where the InfoBox is to appear (default is "floatPane").
* Set the pane to "mapPane" if the InfoBox is being used as a map label.
* Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object.
* @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout,
* mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox
* (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set
* this property to <tt>true</tt> if the InfoBox is being used as a map label.
*/
/**
* Creates an InfoBox with the options specified in {@link InfoBoxOptions}.
* Call <tt>InfoBox.open</tt> to add the box to the map.
* @constructor
* @param {InfoBoxOptions} [opt_opts]
*/
function InfoBox(opt_opts) {
opt_opts = opt_opts || {};
google.maps.OverlayView.apply(this, arguments);
// Standard options (in common with google.maps.InfoWindow):
//
this.content_ = opt_opts.content || "";
this.disableAutoPan_ = opt_opts.disableAutoPan || false;
this.maxWidth_ = opt_opts.maxWidth || 0;
this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
this.zIndex_ = opt_opts.zIndex || null;
// Additional options (unique to InfoBox):
//
this.boxClass_ = opt_opts.boxClass || "infoBox";
this.boxStyle_ = opt_opts.boxStyle || {};
this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px";
this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif";
if (opt_opts.closeBoxURL === "") {
this.closeBoxURL_ = "";
}
this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1);
if (typeof opt_opts.visible === "undefined") {
if (typeof opt_opts.isHidden === "undefined") {
opt_opts.visible = true;
} else {
opt_opts.visible = !opt_opts.isHidden;
}
}
this.isHidden_ = !opt_opts.visible;
this.alignBottom_ = opt_opts.alignBottom || false;
this.pane_ = opt_opts.pane || "floatPane";
this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;
this.div_ = null;
this.closeListener_ = null;
this.moveListener_ = null;
this.contextListener_ = null;
this.eventListeners_ = null;
this.fixedWidthSet_ = null;
}
/* InfoBox extends OverlayView in the Google Maps API v3.
*/
InfoBox.prototype = new google.maps.OverlayView();
/**
* Creates the DIV representing the InfoBox.
* @private
*/
InfoBox.prototype.createInfoBoxDiv_ = function () {
var i;
var events;
var bw;
var me = this;
// This handler prevents an event in the InfoBox from being passed on to the map.
//
var cancelHandler = function (e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
// This handler ignores the current event in the InfoBox and conditionally prevents
// the event from being passed on to the map. It is used for the contextmenu event.
//
var ignoreHandler = function (e) {
e.returnValue = false;
if (e.preventDefault) {
e.preventDefault();
}
if (!me.enableEventPropagation_) {
cancelHandler(e);
}
};
if (!this.div_) {
this.div_ = document.createElement("div");
this.setBoxStyle_();
if (typeof this.content_.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + this.content_;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(this.content_);
}
// Add the InfoBox DIV to the DOM
this.getPanes()[this.pane_].appendChild(this.div_);
this.addClickHandler_();
if (this.div_.style.width) {
this.fixedWidthSet_ = true;
} else {
if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {
this.div_.style.width = this.maxWidth_;
this.div_.style.overflow = "auto";
this.fixedWidthSet_ = true;
} else { // The following code is needed to overcome problems with MSIE
bw = this.getBoxWidths_();
this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
this.fixedWidthSet_ = false;
}
}
this.panBox_(this.disableAutoPan_);
if (!this.enableEventPropagation_) {
this.eventListeners_ = [];
// Cancel event propagation.
//
// Note: mousemove not included (to resolve Issue 152)
events = ["mousedown", "mouseover", "mouseout", "mouseup",
"click", "dblclick", "touchstart", "touchend", "touchmove"];
for (i = 0; i < events.length; i++) {
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler));
}
// Workaround for Google bug that causes the cursor to change to a pointer
// when the mouse moves over a marker underneath InfoBox.
this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) {
this.style.cursor = "default";
}));
}
this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);
/**
* This event is fired when the DIV containing the InfoBox's content is attached to the DOM.
* @name InfoBox#domready
* @event
*/
google.maps.event.trigger(this, "domready");
}
};
/**
* Returns the HTML <IMG> tag for the close box.
* @private
*/
InfoBox.prototype.getCloseBoxImg_ = function () {
var img = "";
if (this.closeBoxURL_ !== "") {
img = "<img";
img += " src='" + this.closeBoxURL_ + "'";
img += " align=right"; // Do this because Opera chokes on style='float: right;'
img += " style='";
img += " position: relative;"; // Required by MSIE
img += " cursor: pointer;";
img += " margin: " + this.closeBoxMargin_ + ";";
img += "'>";
}
return img;
};
/**
* Adds the click handler to the InfoBox close box.
* @private
*/
InfoBox.prototype.addClickHandler_ = function () {
var closeBox;
if (this.closeBoxURL_ !== "") {
closeBox = this.div_.firstChild;
this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_());
} else {
this.closeListener_ = null;
}
};
/**
* Returns the function to call when the user clicks the close box of an InfoBox.
* @private
*/
InfoBox.prototype.getCloseClickHandler_ = function () {
var me = this;
return function (e) {
// 1.0.3 fix: Always prevent propagation of a close box click to the map:
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
/**
* This event is fired when the InfoBox's close box is clicked.
* @name InfoBox#closeclick
* @event
*/
google.maps.event.trigger(me, "closeclick");
me.close();
};
};
/**
* Pans the map so that the InfoBox appears entirely within the map's visible area.
* @private
*/
InfoBox.prototype.panBox_ = function (disablePan) {
var map;
var bounds;
var xOffset = 0, yOffset = 0;
if (!disablePan) {
map = this.getMap();
if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama
if (!map.getBounds().contains(this.position_)) {
// Marker not in visible area of map, so set center
// of map to the marker position first.
map.setCenter(this.position_);
}
bounds = map.getBounds();
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var iwOffsetX = this.pixelOffset_.width;
var iwOffsetY = this.pixelOffset_.height;
var iwWidth = this.div_.offsetWidth;
var iwHeight = this.div_.offsetHeight;
var padX = this.infoBoxClearance_.width;
var padY = this.infoBoxClearance_.height;
var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_);
if (pixPosition.x < (-iwOffsetX + padX)) {
xOffset = pixPosition.x + iwOffsetX - padX;
} else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) {
xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth;
}
if (this.alignBottom_) {
if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) {
yOffset = pixPosition.y + iwOffsetY - padY - iwHeight;
} else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwOffsetY + padY - mapHeight;
}
} else {
if (pixPosition.y < (-iwOffsetY + padY)) {
yOffset = pixPosition.y + iwOffsetY - padY;
} else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) {
yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight;
}
}
if (!(xOffset === 0 && yOffset === 0)) {
// Move the map to the shifted center.
//
var c = map.getCenter();
map.panBy(xOffset, yOffset);
}
}
}
};
/**
* Sets the style of the InfoBox by setting the style sheet and applying
* other specific styles requested.
* @private
*/
InfoBox.prototype.setBoxStyle_ = function () {
var i, boxStyle;
if (this.div_) {
// Apply style values from the style sheet defined in the boxClass parameter:
this.div_.className = this.boxClass_;
// Clear existing inline style values:
this.div_.style.cssText = "";
// Apply style values defined in the boxStyle parameter:
boxStyle = this.boxStyle_;
for (i in boxStyle) {
if (boxStyle.hasOwnProperty(i)) {
this.div_.style[i] = boxStyle[i];
}
}
// Fix up opacity style for benefit of MSIE:
//
if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") {
this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
}
// Apply required styles:
//
this.div_.style.position = "absolute";
this.div_.style.visibility = 'hidden';
if (this.zIndex_ !== null) {
this.div_.style.zIndex = this.zIndex_;
}
}
};
/**
* Get the widths of the borders of the InfoBox.
* @private
* @return {Object} widths object (top, bottom left, right)
*/
InfoBox.prototype.getBoxWidths_ = function () {
var computedStyle;
var bw = {top: 0, bottom: 0, left: 0, right: 0};
var box = this.div_;
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
}
} else if (document.documentElement.currentStyle) { // MSIE
if (box.currentStyle) {
// The current styles may not be in pixel units, but assume they are (bad!)
bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
}
}
return bw;
};
/**
* Invoked when <tt>close</tt> is called. Do not call it directly.
*/
InfoBox.prototype.onRemove = function () {
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Draws the InfoBox based on the current map projection and zoom level.
*/
InfoBox.prototype.draw = function () {
this.createInfoBoxDiv_();
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);
this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px";
if (this.alignBottom_) {
this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px";
} else {
this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px";
}
if (this.isHidden_) {
this.div_.style.visibility = 'hidden';
} else {
this.div_.style.visibility = "visible";
}
};
/**
* Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>,
* <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt>
* properties have no affect until the current InfoBox is <tt>close</tt>d and a new one
* is <tt>open</tt>ed.
* @param {InfoBoxOptions} opt_opts
*/
InfoBox.prototype.setOptions = function (opt_opts) {
if (typeof opt_opts.boxClass !== "undefined") { // Must be first
this.boxClass_ = opt_opts.boxClass;
this.setBoxStyle_();
}
if (typeof opt_opts.boxStyle !== "undefined") { // Must be second
this.boxStyle_ = opt_opts.boxStyle;
this.setBoxStyle_();
}
if (typeof opt_opts.content !== "undefined") {
this.setContent(opt_opts.content);
}
if (typeof opt_opts.disableAutoPan !== "undefined") {
this.disableAutoPan_ = opt_opts.disableAutoPan;
}
if (typeof opt_opts.maxWidth !== "undefined") {
this.maxWidth_ = opt_opts.maxWidth;
}
if (typeof opt_opts.pixelOffset !== "undefined") {
this.pixelOffset_ = opt_opts.pixelOffset;
}
if (typeof opt_opts.alignBottom !== "undefined") {
this.alignBottom_ = opt_opts.alignBottom;
}
if (typeof opt_opts.position !== "undefined") {
this.setPosition(opt_opts.position);
}
if (typeof opt_opts.zIndex !== "undefined") {
this.setZIndex(opt_opts.zIndex);
}
if (typeof opt_opts.closeBoxMargin !== "undefined") {
this.closeBoxMargin_ = opt_opts.closeBoxMargin;
}
if (typeof opt_opts.closeBoxURL !== "undefined") {
this.closeBoxURL_ = opt_opts.closeBoxURL;
}
if (typeof opt_opts.infoBoxClearance !== "undefined") {
this.infoBoxClearance_ = opt_opts.infoBoxClearance;
}
if (typeof opt_opts.isHidden !== "undefined") {
this.isHidden_ = opt_opts.isHidden;
}
if (typeof opt_opts.visible !== "undefined") {
this.isHidden_ = !opt_opts.visible;
}
if (typeof opt_opts.enableEventPropagation !== "undefined") {
this.enableEventPropagation_ = opt_opts.enableEventPropagation;
}
if (this.div_) {
this.draw();
}
};
/**
* Sets the content of the InfoBox.
* The content can be plain text or an HTML DOM node.
* @param {string|Node} content
*/
InfoBox.prototype.setContent = function (content) {
this.content_ = content;
if (this.div_) {
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
// Odd code required to make things work with MSIE.
//
if (!this.fixedWidthSet_) {
this.div_.style.width = "";
}
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
// Perverse code required to make things work with MSIE.
// (Ensures the close box does, in fact, float to the right.)
//
if (!this.fixedWidthSet_) {
this.div_.style.width = this.div_.offsetWidth + "px";
if (typeof content.nodeType === "undefined") {
this.div_.innerHTML = this.getCloseBoxImg_() + content;
} else {
this.div_.innerHTML = this.getCloseBoxImg_();
this.div_.appendChild(content);
}
}
this.addClickHandler_();
}
/**
* This event is fired when the content of the InfoBox changes.
* @name InfoBox#content_changed
* @event
*/
google.maps.event.trigger(this, "content_changed");
};
/**
* Sets the geographic location of the InfoBox.
* @param {LatLng} latlng
*/
InfoBox.prototype.setPosition = function (latlng) {
this.position_ = latlng;
if (this.div_) {
this.draw();
}
/**
* This event is fired when the position of the InfoBox changes.
* @name InfoBox#position_changed
* @event
*/
google.maps.event.trigger(this, "position_changed");
};
/**
* Sets the zIndex style for the InfoBox.
* @param {number} index
*/
InfoBox.prototype.setZIndex = function (index) {
this.zIndex_ = index;
if (this.div_) {
this.div_.style.zIndex = index;
}
/**
* This event is fired when the zIndex of the InfoBox changes.
* @name InfoBox#zindex_changed
* @event
*/
google.maps.event.trigger(this, "zindex_changed");
};
/**
* Sets the visibility of the InfoBox.
* @param {boolean} isVisible
*/
InfoBox.prototype.setVisible = function (isVisible) {
this.isHidden_ = !isVisible;
if (this.div_) {
this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible");
}
};
/**
* Returns the content of the InfoBox.
* @returns {string}
*/
InfoBox.prototype.getContent = function () {
return this.content_;
};
/**
* Returns the geographic location of the InfoBox.
* @returns {LatLng}
*/
InfoBox.prototype.getPosition = function () {
return this.position_;
};
/**
* Returns the zIndex for the InfoBox.
* @returns {number}
*/
InfoBox.prototype.getZIndex = function () {
return this.zIndex_;
};
/**
* Returns a flag indicating whether the InfoBox is visible.
* @returns {boolean}
*/
InfoBox.prototype.getVisible = function () {
var isVisible;
if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) {
isVisible = false;
} else {
isVisible = !this.isHidden_;
}
return isVisible;
};
/**
* Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.show = function () {
this.isHidden_ = false;
if (this.div_) {
this.div_.style.visibility = "visible";
}
};
/**
* Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.]
*/
InfoBox.prototype.hide = function () {
this.isHidden_ = true;
if (this.div_) {
this.div_.style.visibility = "hidden";
}
};
/**
* Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt>
* (usually a <tt>google.maps.Marker</tt>) is specified, the position
* of the InfoBox is set to the position of the <tt>anchor</tt>. If the
* anchor is dragged to a new location, the InfoBox moves as well.
* @param {Map|StreetViewPanorama} map
* @param {MVCObject} [anchor]
*/
InfoBox.prototype.open = function (map, anchor) {
var me = this;
if (anchor) {
this.position_ = anchor.getPosition();
this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () {
me.setPosition(this.getPosition());
});
}
this.setMap(map);
if (this.div_) {
this.panBox_();
}
};
/**
* Removes the InfoBox from the map.
*/
InfoBox.prototype.close = function () {
var i;
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
if (this.eventListeners_) {
for (i = 0; i < this.eventListeners_.length; i++) {
google.maps.event.removeListener(this.eventListeners_[i]);
}
this.eventListeners_ = null;
}
if (this.moveListener_) {
google.maps.event.removeListener(this.moveListener_);
this.moveListener_ = null;
}
if (this.contextListener_) {
google.maps.event.removeListener(this.contextListener_);
this.contextListener_ = null;
}
this.setMap(null);
};
| JavaScript |
var Ajax;
if (Ajax && (Ajax != null)) {
Ajax.Responders.register({
onCreate: function() {
if($('spinner') && Ajax.activeRequestCount>0)
Effect.Appear('spinner',{duration:0.5,queue:'end'});
},
onComplete: function() {
if($('spinner') && Ajax.activeRequestCount==0)
Effect.Fade('spinner',{duration:0.5,queue:'end'});
}
});
}
| JavaScript |
var map;
var markers = new Array();
function createMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
});
}
function centerMap(latitude, longitude) {
map.setCenter(new google.maps.LatLng(latitude, longitude));
}
function addMarker(title, latitude, longitude, link) {
var marker = new Array();
marker['title'] = title;
marker['latitude'] = latitude;
marker['longitude'] = longitude;
marker['link'] = link;
markers.push(marker);
}
function showMarkersInMap() {
for (i = 0; i < markers.length; i++) {
var marker = new google.maps.Marker({
position : new google.maps.LatLng(markers[i]['latitude'],
markers[i]['longitude']),
map : map,
title : markers[i]['title']
});
if (markers[i]['link']) {
var infoWindow = new google.maps.InfoWindow({
content : "<a href='" + markers[i]['link'] + "' alt='"
+ markers[i]['title'] + "'>" + markers[i]['title']
+ "</a>"
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});
}
}
} | JavaScript |
function showSpoiler(obj)
{
var inner = obj.parentNode.getElementsByTagName('div')[0];
if (inner.style.display == 'none')
inner.style.display = '';
else
inner.style.display = 'none';
}
function quote_user(un) {
//$("#komentar_text").focus();
document.getElementById("text_message").focus();
var html = document.getElementById("text_message").value;
html=html+"@"+un+", ";
document.getElementById("text_message").value = html;
}
function showhide(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none"){
obj.style.display = "block";
} else {
obj.style.display = "none";
}
}
}
///////////////////// TOOLTiP //////////////////
var offsetfromcursorX=12 //Customize x offset of tooltip
var offsetfromcursorY=10 //Customize y offset of tooltip
var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image
var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).
document.write('<div id="dhtmltooltip"></div>') //write out tooltip DIV
document.write('<img id="dhtmlpointer" src="img/arrow.gif">') //write out pointer image
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""
var pointerobj=document.all? document.all["dhtmlpointer"] : document.getElementById? document.getElementById("dhtmlpointer") : ""
function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function tooltip(thetext, imgpath, thewidth, imgw, imgh, thecolor){
if (imgw<=10) imgw = 16;
if (imgh<=10) imgh = 16;
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
if (imgpath!="") flag = '<img src="'+imgpath+'" alt="" class="imgvalign" width="'+imgw+'" height="'+imgh+'" /> ';
else flag = "";
tipobj.innerHTML=flag+thetext
enabletip=true
return false
}
}
function positiontip(e){
if (enabletip){
var nondefaultpos=false
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20
var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20
var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX
var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY
var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000
//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth){
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=curX-tipobj.offsetWidth+"px"
nondefaultpos=true
}
else if (curX<leftedge)
tipobj.style.left="5px"
else{
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px"
pointerobj.style.left=curX+offsetfromcursorX+"px"
}
//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight){
tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px"
nondefaultpos=true
}
else{
tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px"
pointerobj.style.top=curY+offsetfromcursorY+"px"
}
tipobj.style.visibility="visible"
if (!nondefaultpos)
pointerobj.style.visibility="visible"
else
pointerobj.style.visibility="hidden"
}
}
function hidetooltip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
pointerobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}
document.onmousemove=positiontip; | JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Compressed version of core/ckeditor_base.js. See original for instructions.
/*jsl:ignore*/
if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.6',revision:'6902',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})();
/*jsl:end*/
// Uncomment the following line to have a new timestamp generated for each
// request, having clear cache load of the editor code.
// CKEDITOR.timestamp = ( new Date() ).valueOf();
if ( CKEDITOR.loader )
CKEDITOR.loader.load( 'core/ckeditor' );
else
{
// Set the script name to be loaded by the loader.
CKEDITOR._autoLoad = 'core/ckeditor';
// Include the loader script.
document.write(
'<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
}
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
};
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
(function(){var youtubeCmd={exec:function(editor){editor.openDialog('youtube');return}};
CKEDITOR.plugins.add('youtube',{lang:['en','uk'],requires:['dialog'],
init:function(editor){var commandName='youtube';editor.addCommand(commandName,youtubeCmd);
editor.ui.addButton('Youtube',{label:editor.lang.youtube.button,command:commandName,icon:this.path+"images/youtube.png"});
CKEDITOR.dialog.add(commandName,CKEDITOR.getUrl(this.path+'dialogs/youtube.js'))}})})();
| JavaScript |
CKEDITOR.plugins.setLang('youtube', 'en',
{
youtube :
{
title : "Embed Youtube Video",
button : "Add Youtube Video",
pasteMsg : "Please copy and paste the Youtube URL here"
}
});
| JavaScript |
CKEDITOR.plugins.setLang('vimeo', 'en',
{
vimeo :
{
title : "Embed Vimeo Video",
button : "Embed Video",
pasteMsg : "Please copy and paste the Youtube URL here"
}
}); | JavaScript |
(function(){CKEDITOR.dialog.add('youtube',
function(editor)
{return{title:editor.lang.youtube.title,minWidth:CKEDITOR.env.ie&&CKEDITOR.env.quirks?368:350,minHeight:240,
onShow:function(){this.getContentElement('general','content').getInputElement().setValue('')},
onOk:function(){
val = this.getContentElement('general','content').getInputElement().getValue();
val = val.replace("watch\?v\=", "v\/");
var text='<iframe title="YouTube video player" class="youtube-player" type="text/html" width="480" height="390" src="http://www.youtube.com/embed/'
//+this.getContentElement('general','content').getInputElement().getValue()
+ val
+'?rel=0" frameborder="0"></iframe>';
this.getParentEditor().insertHtml(text)},
contents:[{label:editor.lang.common.generalTab,id:'general',elements:
[{type:'html',id:'pasteMsg',html:'<div style="white-space:normal;width:500px;"><img style="margin:5px auto;" src="'
+CKEDITOR.getUrl(CKEDITOR.plugins.getPath('youtube')
+'images/youtube_large.png')
+'"><br />'+editor.lang.youtube.pasteMsg
+'</div>'},{type:'html',id:'content',style:'width:340px;height:90px',html:'<input size="100" style="'+'border:1px solid black;'+'background:white">',focus:function(){this.getElement().focus()}}]}]}})})();
| JavaScript |
/*
Copyright (c) 2003-2011, 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-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/*
Copyright (c) 2003-2011, 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 |
// Replace the <textarea id="editor"> with an CKEditor
// instance, using the "bbcode" plugin, shaping some of the
// editor configuration to fit BBCode environment.
CKEDITOR.replace( 'editor1',
{
//extraPlugins : 'bbcode',
// Remove unused plugins.
removePlugins : 'bidi,button,dialogadvtab,div,flash,forms,iframe,indent,liststyle,pagebreak,showborders,table,tabletools,templates',
// Width and height are not supported in the BBCode format, so object resizing is disabled.
disableObjectResizing : true,
// Define font sizes in percent values.
fontSize_sizes : "75/75%;100/100%;120/120%;150/150%;200/200%",
toolbar :
[
['Source','Undo','Redo'],
['Styles', 'Format'],
['Link', 'Unlink', 'Image', 'Smiley','SpecialChar'],
['Find','Replace','-','SelectAll','RemoveFormat'],
['Preview', 'Print','-','Maximize'],
'/',
['Bold', 'Italic','Underline'],
['Cut','Copy','Paste','PasteText','PasteFromWord'],
['JustifyLeft','JustifyCenter','JustifyRight'],
['FontSize','Font'],
['TextColor','BGColor'],
['NumberedList','BulletedList','-','Blockquote'],
],
width: "800px",
height: "320px",
skin: "v2",
// Strip CKEditor smileys to those commonly used in BBCode.
smiley_images :
[
'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','tounge_smile.gif',
'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angel_smile.gif','shades_smile.gif',
'cry_smile.gif','kiss.gif'
],
smiley_descriptions :
[
'smiley', 'sad', 'wink', 'laugh', 'cheeky', 'blush', 'surprise',
'indecision', 'angel', 'cool', 'crying', 'kiss'
]
} );
CKEDITOR.replace( 'editor2',
{
//extraPlugins : 'bbcode',
// Remove unused plugins.
removePlugins : 'bidi,button,dialogadvtab,div,flash,forms,iframe,indent,liststyle,pagebreak,showborders,table,tabletools,templates',
// Width and height are not supported in the BBCode format, so object resizing is disabled.
disableObjectResizing : true,
// Define font sizes in percent values.
fontSize_sizes : "75/75%;100/100%;120/120%;150/150%;200/200%",
toolbar :
[
['Source','Undo','Redo'],
['Styles', 'Format'],
['Link', 'Unlink', 'Image', 'Smiley','SpecialChar'],
['Find','Replace','-','SelectAll','RemoveFormat'],
['Preview', 'Print','-','Maximize'],
'/',
['Bold', 'Italic','Underline'],
['Cut','Copy','Paste','PasteText','PasteFromWord'],
['JustifyLeft','JustifyCenter','JustifyRight'],
['FontSize','Font'],
['TextColor','BGColor'],
['NumberedList','BulletedList','-','Blockquote'],
],
width: "800px",
height: "110px",
skin: "v2",
// Strip CKEditor smileys to those commonly used in BBCode.
smiley_images :
[
'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','tounge_smile.gif',
'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angel_smile.gif','shades_smile.gif',
'cry_smile.gif','kiss.gif'
],
smiley_descriptions :
[
'smiley', 'sad', 'wink', 'laugh', 'cheeky', 'blush', 'surprise',
'indecision', 'angel', 'cool', 'crying', 'kiss'
]
} );
CKEDITOR.replace( 'editor3',
{
//extraPlugins : 'bbcode',
// Remove unused plugins.
removePlugins : 'bidi,button,dialogadvtab,div,flash,forms,iframe,indent,liststyle,pagebreak,showborders,table,tabletools,templates',
// Width and height are not supported in the BBCode format, so object resizing is disabled.
disableObjectResizing : true,
// Define font sizes in percent values.
fontSize_sizes : "75/75%;100/100%;120/120%;150/150%;200/200%",
toolbar :
[
['Source','Undo','Redo'],
['Styles', 'Format'],
['Link', 'Unlink', 'Image', 'Smiley','SpecialChar'],
['Find','Replace','-','SelectAll','RemoveFormat'],
['Preview', 'Print','-','Maximize'],
'/',
['Bold', 'Italic','Underline'],
['Cut','Copy','Paste','PasteText','PasteFromWord'],
['JustifyLeft','JustifyCenter','JustifyRight'],
['FontSize','Font'],
['TextColor','BGColor'],
['NumberedList','BulletedList','-','Blockquote'],
],
width: "800px",
height: "90px",
skin: "v2",
// Strip CKEditor smileys to those commonly used in BBCode.
smiley_images :
[
'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','tounge_smile.gif',
'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angel_smile.gif','shades_smile.gif',
'cry_smile.gif','kiss.gif'
],
smiley_descriptions :
[
'smiley', 'sad', 'wink', 'laugh', 'cheeky', 'blush', 'surprise',
'indecision', 'angel', 'cool', 'crying', 'kiss'
]
} ); | JavaScript |
/**
* Amantes Script
* @author Ncomunicaciones
*/
(function() {
// vars
var $window = $(window),
$content = $("#content"),
$footer = $("#footer"),
lang = (window.location.href.indexOf("-eng") > -1 ) ? "en" : "es";
function embedVideo() {
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
return;
}
var flashWidth = 720,
flashHeight = 481,
flashvars = {},
params = {},
attributes = {},
video = {
en: "http://www.youtube.com/watch?v=pkpmR4VKUqU",
es: "http://www.youtube.com/watch?v=fBDuKNmL0Bo"
};
flashvars.videoURL = video[lang];
flashvars.autoPlay = "false";
flashvars.previewImg = "";
flashvars.useFullScreen = "true";
flashvars.useShareButtons = "true";
flashvars.useShadow = "false";
// Share settings
flashvars.urlToShare = "";
flashvars.shareTitle = "";
flashvars.shareNotes = "";
flashvars.twitterText = "";
flashvars.shareLabels = "";
flashvars.shareSource = "";
flashvars.mailSubject = "";
flashvars.mailBody = "";
params.allowScriptAccess = "always";
params.allowFullScreen = "true";
params.wmode = "opaque";
swfobject.embedSWF("swf/HandDrawnVideoPlayer.swf", "player", flashWidth, flashHeight, "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
}
// resize
$window.on({
resize: function() {
var $home = $content.children("div.container"),
windowHeight = $window.height() - $footer.innerHeight(),
homeHeight = $home.height(),
margin = windowHeight - homeHeight;
margin = margin > 40 ? margin * 0.5 : "";
$home.css({"margin-top": margin});
},
load: function() {
$(this).trigger("resize");
$content.find("div.pages-text").mCustomScrollbar({
scrollButtons:{enable:true},
advanced:{updateOnContentResize:true},
theme:"dark-2"
});
}
});
// player
if($("#player").length) embedVideo();
$("#video").find("div.home-video").add("a.btn-video").on("click", function(e) {
$("div.player-wrapper").stop(true).slideDown();
$("#video").find("div.home-video").hide();
e.preventDefault();
});
$("#video").find("a.close").on("click", function() {
$("div.player-wrapper").stop(true).slideUp(function() {
var iframe = {
en: '<div id="player"><iframe width="720" height="448" src="http://www.youtube.com/embed/pkpmR4VKUqU?showinfo=0" frameborder="0" allowfullscreen></iframe></div>',
es: '<div id="player"><iframe width="720" height="448" src="http://www.youtube.com/embed/fBDuKNmL0Bo?showinfo=0" frameborder="0" allowfullscreen></iframe></div>'
}
$("#player").replaceWith(iframe[lang]);
embedVideo();
$("#video").find("div.home-video").show();
});
});
// skin
$("input:file").each(function() {
var $this = $(this),
placeholder = $this.attr("placeholder");
$this.wrap('<span class="file" />').css({"opacity": 0, "position": "absolute"}).after('<span>' + placeholder + '</span>');
}).on("change", function() {
$(this).next().text($(this).val());
});
// tooltips
$("img.trigger").tooltip({effect: "slide", position: "center left", relative: true});
$("img.form-more").tooltip({effect: "slide", position: "top left", relative: true});
$("a.trigger").tooltip({effect: "slide", position: "top right", relative: true});
$("a[rel]").overlay({top: "center", mask: {color: '#000000', loadSpeed: 200, opacity: 0.9}});
// test tooltips
$("div.bar[title]").tooltip({effect: "slide", position:"top right", tipClass: "tooltip test-cloud"});
$("a.info[title]").tooltip({effect: "slide", position:"bottom center", tipClass: "tooltip data-cloud"});
$("a.info2[title]").tooltip({effect: "slide", position:"top center", tipClass: "tooltip data-cloud"});
// datos
$("a.data-prev").on("click", function() {
var index = $("div.pane:visible").prev().index("div.pane");
$("a.data-next").show();
if(index < 1) $(this).hide();
$("div.pane").hide().eq(index).show();
});
$("a.data-next").on("click", function() {
var index = $("div.pane:visible").next().index("div.pane");
$("a.data-prev").show();
if(index === $("div.pane").length - 1) $(this).hide();
$("div.pane").hide().eq(index).show();
});
$("a.data-prev2").on("click", function() {
var index = $("div.pane:visible").prev().index("div.pane");
$("a.data-next2").show();
if(index < 1) $(this).hide();
$("div.pane").hide().eq(index).show();
});
$("a.data-next2").on("click", function() {
var index = $("div.pane:visible").next().index("div.pane");
$("a.data-prev2").show();
if(index === $("div.pane").length - 1) $(this).hide();
$("div.pane").hide().eq(index).show();
});
// historia
$("form.upload").on("submit", function(e) {
var $form = $(this),
formData = $form.serialize(),
isValid = true;
e.preventDefault();
if(!$form.find("input:checkbox").prop("checked")) {
alert("Usted debe marcar el acuerdo de Términos y condiciones.");
return;
}
$form.find("input:text, textarea").each(function() {
var val = $(this).val(),
name = $(this).attr("name");
if(!val && name !== "url") {
$(this).css("border-color", "red");
isValid = false;
}
else {
$(this).css("border-color", "");
}
});
if(!isValid) return;
$form.prepend('<p class="form-msg"><span style="color:#999;">Verificando sus datos ...</span></p>');
$form.find("p.form-msg").siblings().hide();
$.post("tu_historia_handler.php", formData, function(data) {
$form.html(data);
});
});
})();
/*GOOGLE ANALITICS*/
if(window.location.href.indexOf("imalover.org")> -1) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new
Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-28293532-3', 'imalover.org');
ga('send', 'pageview');
}else{
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-28293532-2', 'soyamante.org');
ga('send', 'pageview');
} | JavaScript |
/**
* Amantes Test
* @author Ncomunicaciones
*/
// randomize
(function($) {
$.fn.randomize = function(childElem) {
return this.each(function() {
var $this = $(this);
var elems = $this.children(childElem);
elems.sort(function() { return (Math.round(Math.random())-0.5); });
$this.remove(childElem);
for(var i=0; i < elems.length; i++)
$this.append(elems[i]);
});
}
})(jQuery);
window.test = (function() {
// vars
var scrollable, timer,
done = 0,
total = 0,
currentDone = 0,
currentTotal = 0,
love_attitudes = {};
/**
* Init
*/
function init() {
// window
$(window).on({
resize: function() {
if(scrollable) scrollable.seekTo(scrollable.getIndex(), 0);
}});
// randomize
$("div.items").randomize("fieldset");
$("fieldset.first").prependTo("div.items");
$("fieldset.last").appendTo("div.items");
// scrollable
scrollable = $("form").scrollable({keyboard: false}).data("scrollable");
// skin
$("input:radio").each(function(index, element) {
var $this = $(this);
$this.wrap('<span class="radio" />').css({"opacity": 0, "position": "absolute"}).parent().append($this.val());
});
// btn
$("a.form-prev").on("click", prev);
$("a.form-next").on("click", next);
$("input:button").on("click", next);
// keyboard
$(document).on("keydown", function(e) {
switch(e.which) {
case 13:
case 37:
case 39:
e.preventDefault();
}
});
$(document).on("keyup", function(e) {
var target = currentItem().find(".question");
if(e.which === 37) prev();
if(e.which === 13 || e.which === 39) next();
if(currentItem().find(".question").length > 1) target = target.not(".done").eq(0);
target.find("label").filter(function() {
return ($(this).find("input").val() === String.fromCharCode(e.which) || $(this).find("input").val() === String.fromCharCode(e.which - 48));
}).find("input").trigger("click").trigger("change");
});
// input
$("input:radio").on("change", function() {
var $this = $(this);
$this.closest("label").siblings().removeClass("checked");
$this.closest("div.question").find("label").removeClass("checked");
$this.closest("label").addClass("checked").closest("div.question").addClass("done");
update();
if(currentItem().prevAll().andSelf().find("div.question").length === currentItem().prevAll().andSelf().find(".done").length && $(this).closest("div.question").length) startCountdown();
});
$("#main-form").on("click", "label", function(e) {
if($(this).hasClass("disabled")) e.preventDefault();
});
// update
update();
function update() {
var percent;
total = $("div.question").length;
done = $("div.done").length,
percent = done / total * 100;
$("#progress-text").text(done + " de " + total + " preguntas respondidas");
$("#progress-bar").children().css({"width": percent + "%"});
love_attitudes = {eros: 0, ludus: 0, storge: 0, pragma: 0, mania: 0, agape: 0};
$("div.question").each(function() {
var attitude = $(this).data("attitude"),
value = parseInt($(this).find("input:checked").val());
love_attitudes[attitude] += $.isNumeric(value) ? value : 0;
});
$.each(love_attitudes, function(k, v) {
var width = (v / 16) * 360;
$("div.chart").find("." + k).css({"width": width}).find(".qty").text(v);
});
}
function currentItem() {
return scrollable.getItems().eq(scrollable.getIndex());
}
function startCountdown() {
clearTimeout(timer);
$("#timer").css("visibility", "visible");
timer = setTimeout(next, 700);
}
function validateUserData() {
var isValid = true,
$form = $("form.test"),
$inputs = $form.find("fieldset").eq(0).find("input"),
edad = $.trim($inputs.filter("[name=edad]").val());
if(!edad || !$.isNumeric(edad) || edad < 12 || edad > 100) {
$inputs.filter("[name=edad]").css("border-color", "red");
isValid = false;
}
else { $inputs.filter("[name=edad]").css("border-color", ""); }
if(!$inputs.filter("[name=sexo]:checked").length) {
$inputs.filter("[name=sexo]").parent().css("border-color", "red");
isValid = false;
}
else { $inputs.filter("[name=sexo]").parent().css("border-color", ""); }
if(!isValid) alert("Por favor llene todos los campos y asegúrese de que están en el formato correcto antes de continuar");
return isValid;
}
function updateUI(direction) {
var currentPosition = scrollable.getIndex() + direction;
if(currentPosition < 2) {
$("a.form-prev").hide();
if(currentPosition < 1)
$("p.lead").show();
else
$("p.lead").hide();
}
else {
$("a.form-prev").show();
$("p.lead").hide();
}
if(currentPosition === $("fieldset").length - 1) {
$("a.form-next").add("a.form-prev").hide();
$("img.form-more").show();
submitData();
}
}
function submitData() {
$.post("test_handler.php", $("form.test").serialize());
}
function prev() {
updateUI(-1);
clearTimeout(timer);
scrollable.prev();
$("#timer").removeAttr("style");
}
function next() {
currentTotal = currentItem().prevAll().andSelf().find(".question").length,
currentDone = currentItem().prevAll().andSelf().find(".done").length;
if(currentDone === currentTotal && validateUserData()) {
updateUI(1);
clearTimeout(timer);
scrollable.next();
$("#timer").removeAttr("style");
}
}
}
return {
init: init
}})();
window.test.init(); | JavaScript |
/**
* Amantes Test
* @author Ncomunicaciones
*/
// randomize
(function($) {
$.fn.randomize = function(childElem) {
return this.each(function() {
var $this = $(this);
var elems = $this.children(childElem);
elems.sort(function() { return (Math.round(Math.random())-0.5); });
$this.remove(childElem);
for(var i=0; i < elems.length; i++)
$this.append(elems[i]);
});
}
})(jQuery);
window.test = (function() {
// vars
var scrollable, timer,
done = 0,
total = 0,
currentDone = 0,
currentTotal = 0,
love_attitudes = {};
/**
* Init
*/
function init() {
// window
$(window).on({
resize: function() {
if(scrollable) scrollable.seekTo(scrollable.getIndex(), 0);
}});
// randomize
$("div.items").randomize("fieldset");
$("fieldset.first").prependTo("div.items");
$("fieldset.last").appendTo("div.items");
// scrollable
scrollable = $("form").scrollable({keyboard: false}).data("scrollable");
// skin
$("input:radio").each(function(index, element) {
var $this = $(this);
$this.wrap('<span class="radio" />').css({"opacity": 0, "position": "absolute"}).parent().append($this.val());
});
// btn
$("a.form-prev").on("click", prev);
$("a.form-next").on("click", next);
$("input:button").on("click", next);
// keyboard
$(document).on("keydown", function(e) {
switch(e.which) {
case 13:
case 37:
case 39:
e.preventDefault();
}
});
$(document).on("keyup", function(e) {
var target = currentItem().find(".question");
if(e.which === 37) prev();
if(e.which === 13 || e.which === 39) next();
if(currentItem().find(".question").length > 1) target = target.not(".done").eq(0);
target.find("label").filter(function() {
return ($(this).find("input").val() === String.fromCharCode(e.which) || $(this).find("input").val() === String.fromCharCode(e.which - 48));
}).find("input").trigger("click").trigger("change");
});
// input
$("input:radio").on("change", function() {
var $this = $(this);
$this.closest("label").siblings().removeClass("checked");
$this.closest("div.question").find("label").removeClass("checked");
$this.closest("label").addClass("checked").closest("div.question").addClass("done");
update();
if(currentItem().prevAll().andSelf().find("div.question").length === currentItem().prevAll().andSelf().find(".done").length && $(this).closest("div.question").length) startCountdown();
});
$("#main-form").on("click", "label", function(e) {
if($(this).hasClass("disabled")) e.preventDefault();
});
// update
update();
function update() {
var percent;
total = $("div.question").length;
done = $("div.done").length,
percent = done / total * 100;
$("#progress-text").text(done + " of " + total + " questions answered");
$("#progress-bar").children().css({"width": percent + "%"});
love_attitudes = {eros: 0, ludus: 0, storge: 0, pragma: 0, mania: 0, agape: 0};
$("div.question").each(function() {
var attitude = $(this).data("attitude"),
value = parseInt($(this).find("input:checked").val());
love_attitudes[attitude] += $.isNumeric(value) ? value : 0;
});
$.each(love_attitudes, function(k, v) {
var width = (v / 16) * 360;
$("div.chart2").find("." + k).css({"width": width}).find(".qty").text(v);
});
}
function currentItem() {
return scrollable.getItems().eq(scrollable.getIndex());
}
function startCountdown() {
clearTimeout(timer);
$("#timer").css("visibility", "visible");
timer = setTimeout(next, 700);
}
function validateUserData() {
var isValid = true,
$form = $("form.test"),
$inputs = $form.find("fieldset").eq(0).find("input"),
edad = $.trim($inputs.filter("[name=edad]").val());
if(!edad || !$.isNumeric(edad) || edad < 12 || edad > 100) {
$inputs.filter("[name=edad]").css("border-color", "red");
isValid = false;
}
else { $inputs.filter("[name=edad]").css("border-color", ""); }
if(!$inputs.filter("[name=sexo]:checked").length) {
$inputs.filter("[name=sexo]").parent().css("border-color", "red");
isValid = false;
}
else { $inputs.filter("[name=sexo]").parent().css("border-color", ""); }
if(!isValid) alert("Please fill out all fields and make sure they are in the correct format before continuing");
return isValid;
}
function updateUI(direction) {
var currentPosition = scrollable.getIndex() + direction;
if(currentPosition < 2) {
$("a.form-prev").hide();
if(currentPosition < 1)
$("p.lead").show();
else
$("p.lead").hide();
}
else {
$("a.form-prev").show();
$("p.lead").hide();
}
if(currentPosition === $("fieldset").length - 1) {
$("a.form-next").add("a.form-prev").hide();
$("img.form-more").show();
submitData();
}
}
function submitData() {
$.post("test_handler.php", $("form.test").serialize());
}
function prev() {
updateUI(-1);
clearTimeout(timer);
scrollable.prev();
$("#timer").removeAttr("style");
}
function next() {
currentTotal = currentItem().prevAll().andSelf().find(".question").length,
currentDone = currentItem().prevAll().andSelf().find(".done").length;
if(currentDone === currentTotal && validateUserData()) {
updateUI(1);
clearTimeout(timer);
scrollable.next();
$("#timer").removeAttr("style");
}
}
}
return {
init: init
}})();
window.test.init(); | JavaScript |
/*
* Inline Form Validation Engine 2.6, jQuery plugin
*
* Copyright(c) 2010, Cedric Dugas
* http://www.position-absolute.com
*
* 2.0 Rewrite by Olivier Refalo
* http://www.crionics.com
*
* Form validation engine allowing custom regex rules to be added.
* Licensed under the MIT License
*/
(function($) {
"use strict";
var methods = {
/**
* Kind of the constructor, called before any action
* @param {Map} user options
*/
init: function(options) {
var form = this;
if (!form.data('jqv') || form.data('jqv') == null ) {
options = methods._saveOptions(form, options);
// bind all formError elements to close on click
$(document).on("click", ".formError", function() {
$(this).fadeOut(150, function() {
// remove prompt once invisible
$("#"+$(this).attr("data-elm")).focus();
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
});
}
return this;
},
/**
* Attachs jQuery.validationEngine to form.submit and field.blur events
* Takes an optional params: a list of options
* ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"});
*/
attach: function(userOptions) {
if(!$(this).is("form")) {
alert("Sorry, jqv.attach() only applies to a form");
return this;
}
var form = this;
var options;
if(userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class";
if (options.binded) {
// bind fields
form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent);
form.find("["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]").bind("click", methods._onFieldEvent);
form.find("["+options.validateAttribute+"*=validate][class*=datepicker]").bind(options.validationEventTrigger,{"delay": 300}, methods._onFieldEvent);
}
if (options.autoPositionUpdate) {
$(window).bind("resize", {
"noAnimation": true,
"formElem": form
}, methods.updatePromptsPosition);
}
// bind form.submit
form.bind("submit", methods._onSubmitEvent);
return this;
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
if(!$(this).is("form")) {
alert("Sorry, jqv.detach() only applies to a form");
return this;
}
var form = this;
var options = form.data('jqv');
// unbind fields
form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent);
form.find("["+options.validateAttribute+"*=validate][type=checkbox],[class*=validate][type=radio]").unbind("click", methods._onFieldEvent);
// unbind form.submit
form.unbind("submit", methods.onAjaxFormComplete);
// unbind live fields (kill)
form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").off(options.validationEventTrigger, methods._onFieldEvent);
form.find("["+options.validateAttribute+"*=validate][type=checkbox]").off("click", methods._onFieldEvent);
// unbind form.submit
form.off("submit", methods.onAjaxFormComplete);
form.removeData('jqv');
if (options.autoPositionUpdate)
$(window).unbind("resize", methods.updatePromptsPosition);
return this;
},
/**
* Validates either a form or a list of fields, shows prompts accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validate: function() {
var element = $(this);
var valid = null;
if(element.is("form") && !element.hasClass('validating')) {
element.addClass('validating');
var options = element.data('jqv');
valid = methods._validateFields(this);
// If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again
setTimeout(function(){
element.removeClass('validating');
}, 100);
if (valid && options.onFormSuccess) {
options.onFormSuccess();
} else if (!valid && options.onFormFailure) {
options.onFormFailure();
}
} else if (element.is('form')) {
element.removeClass('validating');
} else {
// field validation
var form = element.closest('form');
var options = form.data('jqv');
valid = methods._validateField(element, options);
if (valid && options.onFieldSuccess)
options.onFieldSuccess();
else if (options.onFieldFailure && options.InvalidFields.length > 0) {
options.onFieldFailure();
}
}
return valid;
},
/**
* Redraw prompts position, useful when you change the DOM state when validating
*/
updatePromptsPosition: function(event) {
if (event && this == window) {
var form = event.data.formElem;
var noAnimation = event.data.noAnimation;
}
else
var form = $(this.closest('form'));
var options = form.data('jqv');
// No option, take default one
form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each(function(){
var field = $(this);
if (options.prettySelect && field.is(":hidden"))
field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix);
var prompt = methods._getPrompt(field);
var promptText = $(prompt).find(".formErrorContent").html();
if(prompt)
methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation);
});
return this;
},
/**
* Displays a prompt on a element.
* Note that the element needs an id!
*
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight
*/
showPrompt: function(promptText, type, promptPosition, showArrow) {
var form = this.closest('form');
var options = form.data('jqv');
// No option, take default one
if(!options)
options = methods._saveOptions(this, options);
if(promptPosition)
options.promptPosition=promptPosition;
options.showArrow = showArrow==true;
methods._showPrompt(this, promptText, type, false, options);
return this;
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var form = $(this).closest('form');
var options = form.data('jqv');
var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3;
var closingtag;
if($(this).is("form")) {
closingtag = "parentForm"+methods._getClassName($(this).attr("id"));
} else {
closingtag = methods._getClassName($(this).attr("id")) +"formError";
}
$('.'+closingtag).fadeTo(fadeDuration, 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
var form = this;
var options = form.data('jqv');
var duration = options ? options.fadeDuration:0.3;
$('.formError').fadeTo(duration, 0.3, function() {
$(this).parent('.formErrorOuter').remove();
$(this).remove();
});
return this;
},
/**
* Typically called when user exists a field using tab or a mouse click, triggers a field
* validation
*/
_onFieldEvent: function(event) {
var field = $(this);
var form = field.closest('form');
var options = form.data('jqv');
options.eventTrigger = "field";
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
if (options.InvalidFields.length == 0 && options.onFieldSuccess) {
options.onFieldSuccess();
} else if (options.InvalidFields.length > 0 && options.onFieldFailure) {
options.onFieldFailure();
}
}, (event.data) ? event.data.delay : 0);
},
/**
* Called when the form is submited, shows prompts accordingly
*
* @param {jqObject}
* form
* @return false if form submission needs to be cancelled
*/
_onSubmitEvent: function() {
var form = $(this);
var options = form.data('jqv');
options.eventTrigger = "submit";
// validate each field
// (- skip field ajax validation, not necessary IF we will perform an ajax form validation)
var r=methods._validateFields(form);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
// cancel form auto-submission - process with async call onAjaxFormComplete
return false;
}
if(options.onValidationComplete) {
// !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing
return !!options.onValidationComplete(form, r);
}
return r;
},
/**
* Return true if the ajax field validations passed so far
* @param {Object} options
* @return true, is all ajax validation passed so far (remember ajax is async)
*/
_checkAjaxStatus: function(options) {
var status = true;
$.each(options.ajaxValidCache, function(key, value) {
if (!value) {
status = false;
// break the each
return false;
}
});
return status;
},
/**
* Return true if the ajax field is validated
* @param {String} fieldid
* @param {Object} options
* @return true, if validation passed, false if false or doesn't exist
*/
_checkAjaxFieldStatus: function(fieldid, options) {
return options.ajaxValidCache[fieldid] == true;
},
/**
* Validates form fields, shows prompts accordingly
*
* @param {jqObject}
* form
* @param {skipAjaxFieldValidation}
* boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked
*
* @return true if form is valid, false if not, undefined if ajax form validation is done
*/
_validateFields: function(form) {
var options = form.data('jqv');
// this variable is set to true if an error is found
var errorFound = false;
// Trigger hook, start validation
form.trigger("jqv.form.validating");
// first, evaluate status of non ajax fields
var first_err=null;
form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each( function() {
var field = $(this);
var names = [];
if ($.inArray(field.attr('name'), names) < 0) {
errorFound |= methods._validateField(field, options);
if (errorFound && first_err==null)
if (field.is(":hidden") && options.prettySelect)
first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
else
first_err=field;
if (options.doNotShowAllErrosOnSubmit)
return false;
names.push(field.attr('name'));
//if option set, stop checking validation rules after one error is found
if(options.showOneMessage == true && errorFound){
return false;
}
}
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// third, check status and scroll the container accordingly
form.trigger("jqv.form.result", [errorFound]);
if (errorFound) {
if (options.scroll) {
var destination=first_err.offset().top;
var fixleft = first_err.offset().left;
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType=options.promptPosition;
if (typeof(positionType)=='string' && positionType.indexOf(":")!=-1)
positionType=positionType.substring(0,positionType.indexOf(":"));
if (positionType!="bottomRight" && positionType!="bottomLeft") {
var prompt_err= methods._getPrompt(first_err);
if (prompt_err) {
destination=prompt_err.offset().top;
}
}
// get the position of the first error, there should be at least one, no need to check this
//var destination = form.find(".formError:not('.greenPopup'):first").offset().top;
if (options.isOverflown) {
var overflowDIV = $(options.overflownDIV);
if(!overflowDIV.length) return false;
var scrollContainerScroll = overflowDIV.scrollTop();
var scrollContainerPos = -parseInt(overflowDIV.offset().top);
destination += scrollContainerScroll + scrollContainerPos - 5;
var scrollContainer = $(options.overflownDIV + ":not(:animated)");
scrollContainer.animate({scrollTop: destination}, 1100, function(){
if(options.focusFirstField) first_err.focus();
});
} else {
$("body,html").stop().animate({
scrollTop: destination,
scrollLeft: fixleft
}, 1100, function(){
if(options.focusFirstField) first_err.focus();
});
}
} else if(options.focusFirstField)
first_err.focus();
return false;
}
return true;
},
/**
* This method is called to perform an ajax form validation.
* During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true
*
* @param {jqObject} form
* @param {Map} options
*/
_validateFormWithAjax: function(form, options) {
var data = form.serialize();
var type = (options.ajaxmethod) ? options.ajaxmethod : "GET";
var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
var dataType = (options.dataType) ? options.dataType : "json";
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.)
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id")) {
field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter);
++$.validationEngine.fieldIdCounter;
}
if (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden"))
return false;
var rulesParsing = field.attr(options.validateAttribute);
var getRules = /validate\[(.*)\]/.exec(rulesParsing);
if (!getRules)
return false;
var str = getRules[1];
var rules = str.split(/\[|,|\]/);
// true if we ran the ajax validation, tells the logic to stop messing with prompts
var isAjaxValidator = false;
var fieldName = field.attr("name");
var promptText = "";
var promptType = "";
var required = false;
var limitErrors = false;
options.isError = false;
options.showArrow = true;
// If the programmer wants to limit the amount of error messages per field,
if (options.maxErrorsPerField > 0) {
limitErrors = true;
}
var form = $(field.closest("form"));
// Fix for adding spaces in the rules
for (var i in rules) {
rules[i] = rules[i].replace(" ", "");
// Remove any parsing errors
if (rules[i] === '') {
delete rules[i];
}
}
for (var i = 0, field_errors = 0; i < rules.length; i++) {
// If we are limiting errors, and have hit the max, break
if (limitErrors && field_errors >= options.maxErrorsPerField) {
// If we haven't hit a required yet, check to see if there is one in the validation rules for this
// field and that it's index is greater or equal to our current index
if (!required) {
var have_required = $.inArray('required', rules);
required = (have_required != -1 && have_required >= i);
}
break;
}
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required);
break;
case "custom":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom);
break;
case "groupRequired":
// Check is its the first of group, if not, reload validation with first field
// AND continue normal validation on present field
var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]";
var firstOfGroup = form.find(classGroup).eq(0);
if(firstOfGroup[0] != field[0]){
methods._validateField(firstOfGroup, options, skipAjaxValidation);
options.showArrow = true;
continue;
}
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired);
if(errorMsg) required = true;
options.showArrow = false;
break;
case "ajax":
// AJAX defaults to returning it's loading message
errorMsg = methods._ajax(field, rules, i, options);
if (errorMsg) {
promptType = "load";
}
break;
case "minSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize);
break;
case "maxSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize);
break;
case "min":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min);
break;
case "max":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max);
break;
case "past":
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._past);
break;
case "future":
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._future);
break;
case "dateRange":
var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "dateTimeRange":
var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateTimeRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "maxCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox);
break;
case "minCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox);
break;
case "equals":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals);
break;
case "funcCall":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall);
break;
case "creditCard":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard);
break;
case "condRequired":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired);
if (errorMsg !== undefined) {
required = true;
}
break;
default:
}
var end_validation = false;
// If we were passed back an message object, check what the status was to determine what to do
if (typeof errorMsg == "object") {
switch (errorMsg.status) {
case "_break":
end_validation = true;
break;
// If we have an error message, set errorMsg to the error message
case "_error":
errorMsg = errorMsg.message;
break;
// If we want to throw an error, but not show a prompt, return early with true
case "_error_no_prompt":
return true;
break;
// Anything else we continue on
default:
break;
}
}
// If it has been specified that validation should end now, break
if (end_validation) {
break;
}
// If we have a string, that means that we have an error, so add it to the error message.
if (typeof errorMsg == 'string') {
promptText += errorMsg + "<br/>";
options.isError = true;
field_errors++;
}
}
// If the rules required is not added, an empty field is not validated
if(!required && field.val().length < 1) options.isError = false;
// Hack for radio/checkbox group button, the validation go into the
// first radio/checkbox of the group
var fieldType = field.prop("type");
if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first"));
options.showArrow = false;
}
if(field.is(":hidden") && options.prettySelect) {
field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
}
if (options.isError){
methods._showPrompt(field, promptText, promptType, false, options);
}else{
if (!isAjaxValidator) methods._closePrompt(field);
}
if (!isAjaxValidator) {
field.trigger("jqv.field.result", [field, options.isError, promptText]);
}
/* Record error */
var errindex = $.inArray(field[0], options.InvalidFields);
if (errindex == -1) {
if (options.isError)
options.InvalidFields.push(field[0]);
} else if (!options.isError) {
options.InvalidFields.splice(errindex, 1);
}
methods._handleStatusCssClasses(field, options);
return options.isError;
},
/**
* Handling css classes of fields indicating result of validation
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @private
*/
_handleStatusCssClasses: function(field, options) {
/* remove all classes */
if(options.addSuccessCssClassToField)
field.removeClass(options.addSuccessCssClassToField);
if(options.addFailureCssClassToField)
field.removeClass(options.addFailureCssClassToField);
/* Add classes */
if (options.addSuccessCssClassToField && !options.isError)
field.addClass(options.addSuccessCssClassToField);
if (options.addFailureCssClassToField && options.isError)
field.addClass(options.addFailureCssClassToField);
},
/********************
* _getErrorMessage
*
* @param form
* @param field
* @param rule
* @param rules
* @param i
* @param options
* @param originalValidationMethod
* @return {*}
* @private
*/
_getErrorMessage:function (form, field, rule, rules, i, options, originalValidationMethod) {
// If we are using the custon validation type, build the index for the rule.
// Otherwise if we are doing a function call, make the call and return the object
// that is passed back.
var beforeChangeRule = rule;
if (rule == "custom") {
var custom_validation_type_index = jQuery.inArray(rule, rules)+ 1;
var custom_validation_type = rules[custom_validation_type_index];
rule = "custom[" + custom_validation_type + "]";
}
var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class");
var element_classes_array = element_classes.split(" ");
// Call the original validation method. If we are dealing with dates or checkboxes, also pass the form
var errorMsg;
if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") {
errorMsg = originalValidationMethod(form, field, rules, i, options);
} else {
errorMsg = originalValidationMethod(field, rules, i, options);
}
// If the original validation method returned an error and we have a custom error message,
// return the custom message instead. Otherwise return the original error message.
if (errorMsg != undefined) {
var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, beforeChangeRule, options);
if (custom_message) errorMsg = custom_message;
}
return errorMsg;
},
_getCustomErrorMessage:function (field, classes, rule, options) {
var custom_message = false;
var validityProp = methods._validityProp[rule];
// If there is a validityProp for this rule, check to see if the field has an attribute for it
if (validityProp != undefined) {
custom_message = field.attr("data-errormessage-"+validityProp);
// If there was an error message for it, return the message
if (custom_message != undefined)
return custom_message;
}
custom_message = field.attr("data-errormessage");
// If there is an inline custom error message, return it
if (custom_message != undefined)
return custom_message;
var id = '#' + field.attr("id");
// If we have custom messages for the element's id, get the message for the rule from the id.
// Otherwise, if we have custom messages for the element's classes, use the first class message we find instead.
if (typeof options.custom_error_messages[id] != "undefined" &&
typeof options.custom_error_messages[id][rule] != "undefined" ) {
custom_message = options.custom_error_messages[id][rule]['message'];
} else if (classes.length > 0) {
for (var i = 0; i < classes.length && classes.length > 0; i++) {
var element_class = "." + classes[i];
if (typeof options.custom_error_messages[element_class] != "undefined" &&
typeof options.custom_error_messages[element_class][rule] != "undefined") {
custom_message = options.custom_error_messages[element_class][rule]['message'];
break;
}
}
}
if (!custom_message &&
typeof options.custom_error_messages[rule] != "undefined" &&
typeof options.custom_error_messages[rule]['message'] != "undefined"){
custom_message = options.custom_error_messages[rule]['message'];
}
return custom_message;
},
_validityProp: {
"required": "value-missing",
"custom": "custom-error",
"groupRequired": "value-missing",
"ajax": "custom-error",
"minSize": "range-underflow",
"maxSize": "range-overflow",
"min": "range-underflow",
"max": "range-overflow",
"past": "type-mismatch",
"future": "type-mismatch",
"dateRange": "type-mismatch",
"dateTimeRange": "type-mismatch",
"maxCheckbox": "range-overflow",
"minCheckbox": "range-underflow",
"equals": "pattern-mismatch",
"funcCall": "custom-error",
"creditCard": "pattern-mismatch",
"condRequired": "value-missing"
},
/**
* Required validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_required: function(field, rules, i, options) {
switch (field.prop("type")) {
case "text":
case "password":
case "textarea":
case "file":
case "select-one":
case "select-multiple":
default:
if (! $.trim(field.val()) || field.val() == field.attr("data-validation-placeholder") || field.val() == field.attr("placeholder"))
return options.allrules[rules[i]].alertText;
break;
case "radio":
case "checkbox":
var form = field.closest("form");
var name = field.attr("name");
if (form.find("input[name='" + name + "']:checked").size() == 0) {
if (form.find("input[name='" + name + "']:visible").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
}
},
/**
* Validate that 1 from the group field is required
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_groupRequired: function(field, rules, i, options) {
var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]";
var isValid = false;
// Check all fields from the group
field.closest("form").find(classGroup).each(function(){
if(!methods._required($(this), rules, i, options)){
isValid = true;
return false;
}
});
if(!isValid) {
return options.allrules[rules[i]].alertText;
}
},
/**
* Validate rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_custom: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
var fn;
if(!rule) {
alert("jqv:custom rule not found - "+customRule);
return;
}
if(rule["regex"]) {
var ex=rule.regex;
if(!ex) {
alert("jqv:custom regex not found - "+customRule);
return;
}
var pattern = new RegExp(ex);
if (!pattern.test(field.val())) return options.allrules[customRule].alertText;
} else if(rule["func"]) {
fn = rule["func"];
if (typeof(fn) !== "function") {
alert("jqv:custom parameter 'function' is no function - "+customRule);
return;
}
if (!fn(field, rules, i, options))
return options.allrules[customRule].alertText;
} else {
alert("jqv:custom type not allowed "+customRule);
return;
}
},
/**
* Validate custom function outside of the engine scope
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_funcCall: function(field, rules, i, options) {
var functionName = rules[i + 1];
var fn;
if(functionName.indexOf('.') >-1)
{
var namespaces = functionName.split('.');
var scope = window;
while(namespaces.length)
{
scope = scope[namespaces.shift()];
}
fn = scope;
}
else
fn = window[functionName] || options.customFunctions[functionName];
if (typeof(fn) == 'function')
return fn(field, rules, i, options);
},
/**
* Field match
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_equals: function(field, rules, i, options) {
var equalsField = rules[i + 1];
if (field.val() != $("#" + equalsField).val())
return options.allrules.equals.alertText;
},
/**
* Check the maximum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxSize: function(field, rules, i, options) {
var max = rules[i + 1];
var len = field.val().length;
if (len > max) {
var rule = options.allrules.maxSize;
return rule.alertText + max + rule.alertText2;
}
},
/**
* Check the minimum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minSize: function(field, rules, i, options) {
var min = rules[i + 1];
var len = field.val().length;
if (len < min) {
var rule = options.allrules.minSize;
return rule.alertText + min + rule.alertText2;
}
},
/**
* Check number minimum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_min: function(field, rules, i, options) {
var min = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len < min) {
var rule = options.allrules.min;
if (rule.alertText2) return rule.alertText + min + rule.alertText2;
return rule.alertText + min;
}
},
/**
* Check number maximum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_max: function(field, rules, i, options) {
var max = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len >max ) {
var rule = options.allrules.max;
if (rule.alertText2) return rule.alertText + max + rule.alertText2;
//orefalo: to review, also do the translations
return rule.alertText + max;
}
},
/**
* Checks date is in the past
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_past: function(form, field, rules, i, options) {
var p=rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate > pdate ) {
var rule = options.allrules.past;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks date is in the future
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_future: function(form, field, rules, i, options) {
var p=rules[i + 1];
var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']"));
var pdate;
if (p.toLowerCase() == "now") {
pdate = new Date();
} else if (undefined != fieldAlt.val()) {
if (fieldAlt.is(":disabled"))
return;
pdate = methods._parseDate(fieldAlt.val());
} else {
pdate = methods._parseDate(p);
}
var vdate = methods._parseDate(field.val());
if (vdate < pdate ) {
var rule = options.allrules.future;
if (rule.alertText2)
return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks if valid date
*
* @param {string} date string
* @return a bool based on determination of valid date
*/
_isDate: function (value) {
var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/);
return dateRegEx.test(value);
},
/**
* Checks if valid date time
*
* @param {string} date string
* @return a bool based on determination of valid date time
*/
_isDateTime: function (value){
var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/);
return dateTimeRegEx.test(value);
},
//Checks if the start date is before the end date
//returns true if end is later than start
_dateCompare: function (start, end) {
return (new Date(start.toString()) < new Date(end.toString()));
},
/**
* Checks date range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateRange: function (field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Checks date time range
*
* @param {jqObject} first field name
* @param {jqObject} second field name
* @return an error string if validation failed
*/
_dateTimeRange: function (field, rules, i, options) {
//are not both populated
if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are not both dates
if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
//are both dates but range is off
if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) {
return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2;
}
},
/**
* Max number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize > nbCheck) {
options.showArrow = false;
if (options.allrules.maxCheckbox.alertText2)
return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2;
return options.allrules.maxCheckbox.alertText;
}
},
/**
* Min number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minCheckbox: function(form, field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = form.find("input[name='" + groupname + "']:checked").size();
if (groupSize < nbCheck) {
options.showArrow = false;
return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2;
}
},
/**
* Checks that it is a valid credit card number according to the
* Luhn checksum algorithm.
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_creditCard: function(field, rules, i, options) {
//spaces and dashes may be valid characters, but must be stripped to calculate the checksum.
var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, '');
var numDigits = cardNumber.length;
if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) {
var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String();
do {
digit = parseInt(cardNumber.charAt(i));
luhn += (pos++ % 2 == 0) ? digit * 2 : digit;
} while (--i >= 0)
for (i = 0; i < luhn.length; i++) {
sum += parseInt(luhn.charAt(i));
}
valid = sum % 10 == 0;
}
if (!valid) return options.allrules.creditCard.alertText;
},
/**
* Ajax field validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return nothing! the ajax validator handles the prompts itself
*/
_ajax: function(field, rules, i, options) {
var errorSelector = rules[i + 1];
var rule = options.allrules[errorSelector];
var extraData = rule.extraData;
var extraDataDynamic = rule.extraDataDynamic;
var data = {
"fieldId" : field.attr("id"),
"fieldValue" : field.val()
};
if (typeof extraData === "object") {
$.extend(data, extraData);
} else if (typeof extraData === "string") {
var tempData = extraData.split("&");
for(var i = 0; i < tempData.length; i++) {
var values = tempData[i].split("=");
if (values[0] && values[0]) {
data[values[0]] = values[1];
}
}
}
if (extraDataDynamic) {
var tmpData = [];
var domIds = String(extraDataDynamic).split(",");
for (var i = 0; i < domIds.length; i++) {
var id = domIds[i];
if ($(id).length) {
var inputValue = field.closest("form").find(id).val();
var keyValue = id.replace('#', '') + '=' + escape(inputValue);
data[id.replace('#', '')] = inputValue;
}
}
}
// If a field change event triggered this we want to clear the cache for this ID
if (options.eventTrigger == "field") {
delete(options.ajaxValidCache[field.attr("id")]);
}
// If there is an error or if the the field is already validated, do not re-execute AJAX
if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) {
$.ajax({
type: options.ajaxFormValidationMethod,
url: rule.url,
cache: false,
dataType: "json",
data: data,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() {},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
// asynchronously called on success, data is the json answer from the server
var errorFieldId = json[0];
//var errorField = $($("#" + errorFieldId)[0]);
var errorField = $("#"+ errorFieldId +"']").eq(0);
// make sure we found the element
if (errorField.length == 1) {
var status = json[1];
// read the optional msg from the server
var msg = json[2];
if (!status) {
// Houston we got a problem - display an red prompt
options.ajaxValidCache[errorFieldId] = false;
options.isError = true;
// resolve the msg prompt
if(msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertText;
methods._showPrompt(errorField, msg, "", true, options);
} else {
options.ajaxValidCache[errorFieldId] = true;
// resolves the msg prompt
if(msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt) {
msg = txt;
}
}
}
else
msg = rule.alertTextOk;
// see if we should display a green prompt
if (msg)
methods._showPrompt(errorField, msg, "pass", true, options);
else
methods._closePrompt(errorField);
// If a submit form triggered this, we want to re-submit the form
if (options.eventTrigger == "submit")
field.closest("form").submit();
}
}
errorField.trigger("jqv.field.result", [errorField, options.isError, msg]);
}
});
return rule.alertTextLoad;
}
},
/**
* Common method to handle ajax errors
*
* @param {Object} data
* @param {Object} transport
*/
_ajaxError: function(data, transport) {
if(data.status == 0 && transport == null)
alert("The page is not served from a server! ajax call failed");
else if(typeof console != "undefined")
console.log("Ajax error: " + data.status + " " + transport);
},
/**
* date -> string
*
* @param {Object} date
*/
_dateToString: function(date) {
return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
},
/**
* Parses an ISO date
* @param {String} d
*/
_parseDate: function(d) {
var dateParts = d.split("-");
if(dateParts==d)
dateParts = d.split("/");
return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]);
},
/**
* Builds or updates a prompt with the given information
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) {
var prompt = methods._getPrompt(field);
// The ajax submit errors are not see has an error in the form,
// When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time
// Because no error was found befor submitting
if(ajaxform) prompt = false;
if (prompt)
methods._updatePrompt(field, prompt, promptText, type, ajaxed, options);
else
methods._buildPrompt(field, promptText, type, ajaxed, options);
},
/**
* Builds and shades a prompt for the given field.
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_buildPrompt: function(field, promptText, type, ajaxed, options) {
// create the prompt
var prompt = $('<div>');
prompt.addClass(methods._getClassName(field.attr("id")) + "formError");
// add a class name to identify the parent form of the prompt
prompt.addClass("parentForm"+methods._getClassName(field.parents('form').attr("id")));
prompt.addClass("formError");
prompt.addClass("erc").attr("data-elm",field.attr("id"));
switch (type) {
case "pass":
prompt.addClass("greenPopup");
break;
case "load":
prompt.addClass("blackPopup");
break;
default:
/* it has error */
//alert("unknown popup type:"+type);
}
if (ajaxed)
prompt.addClass("ajaxed");
// create the prompt content
var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);
// create the css arrow pointing at the field
// note that there is no triangle on max-checkbox and radio
if (options.showArrow) {
var arrow = $('<div>').addClass("formErrorArrow");
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType=field.data("promptPosition") || options.promptPosition;
if (typeof(positionType)=='string')
{
var pos=positionType.indexOf(":");
if(pos!=-1)
positionType=positionType.substring(0,pos);
}
if(options.isPopup)
switch (positionType) {
case "bottomLeft":
case "bottomRight":
prompt.find(".formErrorContent").before(arrow);
arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
break;
case "topLeft":
case "topRight":
arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
prompt.append(arrow);
break;
}
}
// Modify z-indexes for jquery ui
if (field.closest('.ui-dialog').length)
prompt.addClass('formErrorInsideDialog');
// add prompt after or before
if(field.attr("data-putto")){
if($(field.attr("data-putto").length>0))
prompt.appendTo($(field.attr("data-putto")));
else field.after(prompt);
}else{
field.after(prompt);
}
field.addClass("erb");
if(options.isPopup){
prompt.css({
"opacity": 0,
'position':'absolute'
});
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
}).data("callerField", field);
}else{
prompt.css({
"opacity": 0
});
}
if (options.autoHidePrompt) {
setTimeout(function(){
prompt.animate({
"opacity": 0
},function(){
prompt.closest('.formErrorOuter').remove();
prompt.remove();
field.removeClass("erb");
});
}, options.autoHideDelay);
}
return prompt.animate({
"opacity": 0.87
});
},
/**
* Updates the prompt text field - the field for which the prompt
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) {
if (prompt) {
if (typeof type !== "undefined") {
if (type == "pass")
prompt.addClass("greenPopup");
else
prompt.removeClass("greenPopup");
if (type == "load")
prompt.addClass("blackPopup");
else
prompt.removeClass("blackPopup");
}
if (ajaxed)
prompt.addClass("ajaxed");
else
prompt.removeClass("ajaxed");
prompt.find(".formErrorContent").html(promptText);
var pos = methods._calculatePosition(field, prompt, options);
if(options.isPopup){
var css = {
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize
};
if (noAnimation)
prompt.css(css);
else
prompt.animate(css);
}
}
},
/**
* Closes the prompt associated with the given field
*
* @param {jqObject}
* field
*/
_closePrompt: function(field) {
var prompt = methods._getPrompt(field);
if (prompt)
prompt.fadeTo("fast", 0, function() {
prompt.parent('.formErrorOuter').remove();
prompt.remove();
field.removeClass("erb");
});
},
closePrompt: function(field) {
return methods._closePrompt(field);
},
/**
* Returns the error prompt matching the field if any
*
* @param {jqObject}
* field
* @return undefined or the error prompt (jqObject)
*/
_getPrompt: function(field) {
var formId = $(field).closest('form').attr('id');
var className = methods._getClassName(field.attr("id")) + "formError";
var match = $("." + methods._escapeExpression(className) + '.parentForm' + formId)[0];
if (match)
return $(match);
},
/**
* Returns the escapade classname
*
* @param {selector}
* className
*/
_escapeExpression: function (selector) {
return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1");
},
/**
* returns true if we are in a RTLed document
*
* @param {jqObject} field
*/
isRTL: function(field)
{
var $document = $(document);
var $body = $('body');
var rtl =
(field && field.hasClass('rtl')) ||
(field && (field.attr('dir') || '').toLowerCase()==='rtl') ||
$document.hasClass('rtl') ||
($document.attr('dir') || '').toLowerCase()==='rtl' ||
$body.hasClass('rtl') ||
($body.attr('dir') || '').toLowerCase()==='rtl';
return Boolean(rtl);
},
/**
* Calculates prompt position
*
* @param {jqObject}
* field
* @param {jqObject}
* the prompt
* @param {Map}
* options
* @return positions
*/
_calculatePosition: function (field, promptElmt, options) {
var promptTopPosition, promptleftPosition, marginTopSize;
var fieldWidth = field.width();
var fieldLeft = field.position().left;
var fieldTop = field.position().top;
var fieldHeight = field.height();
var promptHeight = promptElmt.height();
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
//prompt positioning adjustment support
//now you can adjust prompt position
//usage: positionType:Xshift,Yshift
//for example:
// bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally
// topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top
//You can use +pixels, - pixels. If no sign is provided than + is default.
var positionType=field.data("promptPosition") || options.promptPosition;
var shift1="";
var shift2="";
var shiftX=0;
var shiftY=0;
if (typeof(positionType)=='string') {
//do we have any position adjustments ?
if (positionType.indexOf(":")!=-1) {
shift1=positionType.substring(positionType.indexOf(":")+1);
positionType=positionType.substring(0,positionType.indexOf(":"));
//if any advanced positioning will be needed (percents or something else) - parser should be added here
//for now we use simple parseInt()
//do we have second parameter?
if (shift1.indexOf(",") !=-1) {
shift2=shift1.substring(shift1.indexOf(",") +1);
shift1=shift1.substring(0,shift1.indexOf(","));
shiftY=parseInt(shift2);
if (isNaN(shiftY)) shiftY=0;
};
shiftX=parseInt(shift1);
if (isNaN(shift1)) shift1=0;
};
};
switch (positionType) {
default:
case "topRight":
promptleftPosition += fieldLeft + fieldWidth - 30;
promptTopPosition += fieldTop;
break;
case "topLeft":
promptTopPosition += fieldTop;
promptleftPosition += fieldLeft;
break;
case "centerRight":
promptTopPosition = fieldTop+4;
marginTopSize = 0;
promptleftPosition= fieldLeft + field.outerWidth(true)+5;
break;
case "centerLeft":
promptleftPosition = fieldLeft - (promptElmt.width() + 2);
promptTopPosition = fieldTop+4;
marginTopSize = 0;
break;
case "bottomLeft":
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
promptleftPosition = fieldLeft;
break;
case "bottomRight":
promptleftPosition = fieldLeft + fieldWidth - 30;
promptTopPosition = fieldTop + field.height() + 5;
marginTopSize = 0;
};
//apply adjusments if any
promptleftPosition += shiftX;
promptTopPosition += shiftY;
return {
"callerTopPosition": promptTopPosition + "px",
"callerleftPosition": promptleftPosition + "px",
"marginTopSize": marginTopSize + "px"
};
},
/**
* Saves the user options and variables in the form.data
*
* @param {jqObject}
* form - the form where the user option should be saved
* @param {Map}
* options - the user options
* @return the user options (extended from the defaults)
*/
_saveOptions: function(form, options) {
// is there a language localisation ?
if ($.validationEngineLanguage)
var allRules = $.validationEngineLanguage.allRules;
else
$.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page");
// --- Internals DO NOT TOUCH or OVERLOAD ---
// validation rules and i18
$.validationEngine.defaults.allrules = allRules;
var userOptions = $.extend(true,{},$.validationEngine.defaults,options);
form.data('jqv', userOptions);
return userOptions;
},
/**
* Removes forbidden characters from class name
* @param {String} className
*/
_getClassName: function(className) {
if(className)
return className.replace(/:/g, "_").replace(/\./g, "_");
},
/**
* Escape special character for jQuery selector
* http://totaldev.com/content/escaping-characters-get-valid-jquery-id
* @param {String} selector
*/
_jqSelector: function(str){
return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
},
/**
* Conditionally required field
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_condRequired: function(field, rules, i, options) {
var idx, dependingField;
for(idx = (i + 1); idx < rules.length; idx++) {
dependingField = jQuery("#" + rules[idx]).first();
/* Use _required for determining wether dependingField has a value.
* There is logic there for handling all field types, and default value; so we won't replicate that here
*/
if (dependingField.length && methods._required(dependingField, ["required"], 0, options) == undefined) {
/* We now know any of the depending fields has a value,
* so we can validate this field as per normal required code
*/
return methods._required(field, ["required"], 0, options);
}
}
}
};
/**
* Plugin entry point.
* You may pass an action as a parameter or a list of options.
* if none, the init and attach methods are being called.
* Remember: if you pass options, the attached method is NOT called automatically
*
* @param {String}
* method (optional) action
*/
$.fn.validationEngine = function(method) {
var form = $(this);
if(!form[0]) return form; // stop here if the form does not exist
if (typeof(method) == 'string' && method.charAt(0) != '_' && methods[method]) {
// make sure init is called once
if(method != "showPrompt" && method != "hide" && method != "hideAll")
methods.init.apply(form);
return methods[method].apply(form, Array.prototype.slice.call(arguments, 1));
} else if (typeof method == 'object' || !method) {
// default constructor with or without arguments
methods.init.apply(form, arguments);
return methods.attach.apply(form);
} else {
$.error('Method ' + method + ' does not exist in jQuery.validationEngine');
}
};
// LEAK GLOBAL OPTIONS
$.validationEngine= {fieldIdCounter: 0,defaults:{
// Name of the event triggering field validation
validationEventTrigger: "blur",
// Automatically scroll viewport to the first error
scroll: true,
// Focus on the first input
focusFirstField:true,
// Opening box position, possible locations are: topLeft,
// topRight, bottomLeft, centerRight, bottomRight
promptPosition: "topRight",
bindMethod:"bind",
// internal, automatically set to true when it parse a _ajax rule
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// The url to send the submit ajax validation (default to action)
ajaxFormValidationURL: false,
// HTTP method used for ajax validation
ajaxFormValidationMethod: 'get',
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function assiciated with it
onValidationComplete: false,
// Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages
doNotShowAllErrosOnSubmit: false,
// Object where you store custom messages to override the default error messages
custom_error_messages:{},
// true if you want to vind the input fields
binded: true,
// set to true, when the prompt arrow needs to be displayed
showArrow: true,
// did one of the validation fail ? kept global to stop further ajax validations
isError: false,
// Limit how many displayed errors a field can have
maxErrorsPerField: false,
// Caches field validation status, typically only bad status are created.
// the array is used during ajax form validation to detect issues early and prevent an expensive submit
ajaxValidCache: {},
// Auto update prompt position after window resize
autoPositionUpdate: false,
InvalidFields: [],
onFieldSuccess: false,
onFieldFailure: false,
onFormSuccess: false,
onFormFailure: false,
addSuccessCssClassToField: false,
addFailureCssClassToField: false,
// Auto-hide prompt
autoHidePrompt: false,
// Delay before auto-hide
autoHideDelay: 10000,
// Fade out duration while hiding the validations
fadeDuration: 0.3,
// Use Prettify select library
prettySelect: false,
// Custom ID uses prefix
usePrefix: "",
// Custom ID uses suffix
useSuffix: "",
// Only show one message per error prompt
showOneMessage: false
}};
$(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"});
})(jQuery);
| JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* This field is required",
"alertTextCheckboxMultiple": "* Please select an option",
"alertTextCheckboxe": "* This checkbox is required",
"alertTextDateRange": "* Both date range fields are required"
},
"requiredInFunction": {
"func": function(field, rules, i, options){
return (field.val() === "test") ? true : false;
},
"alertText": "* Field must equal test"
},
"dateRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Range"
},
"dateTimeRange": {
"regex": "none",
"alertText": "* Invalid ",
"alertText2": "Date Time Range"
},
"minSize": {
"regex": "none",
"alertText": "* Minimum ",
"alertText2": " characters allowed"
},
"maxSize": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " characters allowed"
},
"groupRequired": {
"regex": "none",
"alertText": "* You must fill one of the following fields"
},
"min": {
"regex": "none",
"alertText": "* Minimum value is "
},
"max": {
"regex": "none",
"alertText": "* Maximum value is "
},
"past": {
"regex": "none",
"alertText": "* Date prior to "
},
"future": {
"regex": "none",
"alertText": "* Date past "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " options allowed"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Please select ",
"alertText2": " options"
},
"equals": {
"regex": "none",
"alertText": "* Fields do not match"
},
"creditCard": {
"regex": "none",
"alertText": "* Invalid credit card number"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/,
"alertText": "* Invalid phone number"
},
"alias":{
"regex": /^[0-9a-z\-]+$/,
"alertText": "* Invalid alias"
},
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
"alertText": "* Invalid email address"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Not a valid integer"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
"alertText": "* Invalid floating decimal number"
},
"date": {
// Check if date is valid by leap year
"func": function (field) {
var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var match = pattern.exec(field.val());
if (match === null)
return false;
var year = match[1];
var month = match[2]*1;
var day = match[3]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() === year && date.getMonth() === (month - 1) && date.getDate() === day);
},
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Invalid IP address"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* Invalid URL"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Numbers only"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Letters only"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* No special characters allowed"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxUserCallPhp": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* This name is already taken",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error
"alertText": "* This name is already taken",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
"alertText": "* Please input HELLO"
},
//tls warning:homegrown not fielded
"dateFormat":{
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/,
"alertText": "* Invalid Date"
},
//tls warning:homegrown not fielded
"dateTimeFormat": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/,
"alertText": "* Invalid Date or Date Format",
"alertText2": "Expected Format: ",
"alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ",
"alertText4": "yyyy-mm-dd hh:mm:ss AM|PM"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
| JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* Trường này bắt buộc",
"alertTextCheckboxMultiple": "* Vui lòng chọn một tùy chọn",
"alertTextCheckboxe": "* Checkbox này bắt buộc",
"alertTextDateRange": "* Cả hai trường ngày tháng đều bắt buộc"
},
"requiredInFunction": {
"func": function(field, rules, i, options){
return (field.val() == "test") ? true : false;
},
"alertText": "* Giá trị của trường phải là test"
},
"minNumber": {
"func": function(field, rules, i, options){
console.log(rules.maxNumber);
return (isNaN(field.val()) || parseInt(field.val())<rules[2]) ? false : true;
},
"alertText": "* Giá trị không hợp lệ."
},
"maxNumber": {
"func": function(field, rules, i, options){
console.log(options.allrules);
return (isNaN(field.val()) || parseInt(field.val())>rules[2]) ? false : true;
},
"alertText": "* Giá trị không hợp lệ."
},
"dateRange": {
"regex": "none",
"alertText": "* Không đúng ",
"alertText2": "Khoảng ngày tháng"
},
"dateTimeRange": {
"regex": "none",
"alertText": "* Không đúng ",
"alertText2": "Khoảng thời gian"
},
"minSize": {
"regex": "none",
"alertText": "* Tối thiểu là ",
"alertText2": " ký tự"
},
"maxSize": {
"regex": "none",
"alertText": "* Tối đa là ",
"alertText2": " ký tự"
},
"groupRequired": {
"regex": "none",
"alertText": "* Bạn phải điền một trong những trường sau"
},
"min": {
"regex": "none",
"alertText": "* Giá trị nhỏ nhất là "
},
"max": {
"regex": "none",
"alertText": "* Giá trị lớn nhất là "
},
"past": {
"regex": "none",
"alertText": "* Ngày kéo dài tới "
},
"future": {
"regex": "none",
"alertText": "* Ngày đã qua "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Tối đa ",
"alertText2": " số tùy chọn được cho phép"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Vui lòng chọn ",
"alertText2": " các tùy chọn"
},
"equals": {
"regex": "none",
"alertText": "* Giá trị các trường không giống nhau"
},
"creditCard": {
"regex": "none",
"alertText": "* Số thẻ tín dụng sai"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/,
"alertText": "* Số điện thoại sai"
},
"email": {
// HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 )
"regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
"alertText": "* Địa chỉ thư điện tử sai"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Không đúng là số nguyên"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
"alertText": "* Không đúng là số"
},
"date": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
"alertText": "* Ngày sai, phải có định dạng YYYY-MM-DD"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Địa chỉ IP sai"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* URL sai"
},
"phone_":{
"regex": /^[0-9\ ,(,),.,\-,+]{7,20}$/,
"alertText": "* Định dạng phone sai"
},
"alias":{
"regex": /^[0-9a-z\-]+$/,
"alertText": "* Định dạng alias sai"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Chỉ điền số"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Chỉ điền chữ"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* Không được chứa ký tự đặc biệt"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* Tên này được dùng",
"alertTextLoad": "* Đang xác nhận, vui lòng chờ"
},
"ajaxUserCallPhp": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* Tên người dùng này có thể dùng được",
"alertText": "* Tên người dùng này đã được sử dụng",
"alertTextLoad": "* Đang xác nhận, vui lòng chờ"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* Tên này được dùng",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* Tên này có thể dùng",
// speaks by itself
"alertTextLoad": "* Đang xác nhận, vui lòng chờ"
},
"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error
"alertText": "* Tên này được dùng",
// speaks by itself
"alertTextLoad": "* Đang xác nhận, vui lòng chờ"
},
"validate2fields": {
"alertText": "* Vui lòng nhập vào HELLO"
},
//tls warning:homegrown not fielded
"dateFormat":{
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/,
"alertText": "* Ngày sai"
},
//tls warning:homegrown not fielded
"dateTimeFormat": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/,
"alertText": "* Ngày sai hoặc định dạng ngày sai",
"alertText2": "Định dạng đúng là: ",
"alertText3": "mm/dd/yyyy hh:mm:ss AM|PM hay ",
"alertText4": "yyyy-mm-dd hh:mm:ss AM|PM"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
| JavaScript |
;/*****************************************************************
* Japanese language file for jquery.validationEngine.js (ver2.0)
*
* Transrator: tomotomo ( Tomoyuki SUGITA )
* http://tomotomoSnippet.blogspot.com/
* Licenced under the MIT Licence
*******************************************************************/
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* 必須項目です",
"alertTextCheckboxMultiple": "* 選択してください",
"alertTextCheckboxe": "* チェックボックスをチェックしてください"
},
"requiredInFunction": {
"func": function(field, rules, i, options){
return (field.val() == "test") ? true : false;
},
"alertText": "* Field must equal test"
},
"minSize": {
"regex": "none",
"alertText": "* ",
"alertText2": "文字以上にしてください"
},
"groupRequired": {
"regex": "none",
"alertText": "* You must fill one of the following fields"
},
"maxSize": {
"regex": "none",
"alertText": "* ",
"alertText2": "文字以下にしてください"
},
"min": {
"regex": "none",
"alertText": "* ",
"alertText2": " 以上の数値にしてください"
},
"max": {
"regex": "none",
"alertText": "* ",
"alertText2": " 以下の数値にしてください"
},
"past": {
"regex": "none",
"alertText": "* ",
"alertText2": " より過去の日付にしてください"
},
"future": {
"regex": "none",
"alertText": "* ",
"alertText2": " より最近の日付にしてください"
},
"maxCheckbox": {
"regex": "none",
"alertText": "* チェックしすぎです"
},
"minCheckbox": {
"regex": "none",
"alertText": "* ",
"alertText2": "つ以上チェックしてください"
},
"equals": {
"regex": "none",
"alertText": "* 入力された値が一致しません"
},
"creditCard": {
"regex": "none",
"alertText": "* 無効なクレジットカード番号"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
"alertText": "* 電話番号が正しくありません"
},
"email": {
// Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/
"regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
"alertText": "* メールアドレスが正しくありません"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* 整数を半角で入力してください"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
"alertText": "* 数値を半角で入力してください"
},
"date": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
"alertText": "* 日付は半角で YYYY-MM-DD の形式で入力してください"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* IPアドレスが正しくありません"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* URLが正しくありません"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* 半角数字で入力してください"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* 半角アルファベットで入力してください"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* 半角英数で入力してください"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* This name is already taken",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
"alertText": "* 『HELLO』と入力してください"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
| JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": {
"regex": "none",
"alertText": "* Ce champ est requis",
"alertTextCheckboxMultiple": "* Choisir une option",
"alertTextCheckboxe": "* Cette option est requise"
},
"requiredInFunction": {
"func": function(field, rules, i, options){
return (field.val() == "test") ? true : false;
},
"alertText": "* Field must equal test"
},
"minSize": {
"regex": "none",
"alertText": "* Minimum ",
"alertText2": " caractères requis"
},
"groupRequired": {
"regex": "none",
"alertText": "* Vous devez remplir un des champs suivant"
},
"maxSize": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " caractères requis"
},
"min": {
"regex": "none",
"alertText": "* Valeur minimum requise "
},
"max": {
"regex": "none",
"alertText": "* Valeur maximum requise "
},
"past": {
"regex": "none",
"alertText": "* Date antérieure au "
},
"future": {
"regex": "none",
"alertText": "* Date postérieure au "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Nombre max de choix excédé"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Veuillez choisir ",
"alertText2": " options"
},
"equals": {
"regex": "none",
"alertText": "* Votre champ n'est pas identique"
},
"creditCard": {
"regex": "none",
"alertText": "* Numéro de carte bancaire valide"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
"alertText": "* Numéro de téléphone invalide"
},
"email": {
// Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/
"regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
"alertText": "* Adresse email invalide"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Nombre entier invalide"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/,
"alertText": "* Nombre flottant invalide"
},
"date": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
"alertText": "* Date invalide, format YYYY-MM-DD requis"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Adresse IP invalide"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* URL invalide"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Seuls les chiffres sont acceptés"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FD\ \']+$/,
"alertText": "* Seules les lettres sont acceptées"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FD]+$/,
"alertText": "* Aucun caractère spécial n'est accepté"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
"extraData": "name=eric",
"alertTextLoad": "* Chargement, veuillez attendre",
"alertText": "* Ce nom est déjà pris"
},
"ajaxNameCall": {
"url": "ajaxValidateFieldName",
"alertText": "* Ce nom est déjà pris",
"alertTextOk": "*Ce nom est disponible",
"alertTextLoad": "* Chargement, veuillez attendre"
},
"validate2fields": {
"alertText": "Veuillez taper le mot HELLO"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery); | JavaScript |
/*
* jQuery Plugin: Tokenizing Autocomplete Text Entry
* Version 1.6.0
*
* Copyright (c) 2009 James Smith (http://loopj.com)
* Licensed jointly under the GPL and MIT licenses,
* choose which one suits your project best!
*
*/
(function ($) {
// Default settings
var DEFAULT_SETTINGS = {
// Search settings
method: "POST",
contentType: "json",
queryParam: "q",
searchDelay: 300,
minChars: 1,
propertyToSearch: "name",
jsonContainer: null,
// Display settings
hintText: "Type in a search term",
noResultsText: "No results",
searchingText: "Searching...",
deleteText: "×",
animateDropdown: true,
// Tokenization settings
tokenLimit: null,
tokenDelimiter: ",",
preventDuplicates: false,
// Output settings
tokenValue: "id",
// Prepopulation settings
prePopulate: null,
processPrePopulate: false,
// Manipulation settings
idPrefix: "token-input-",
// Formatters
resultsFormatter: function(item){ return "<li>" + item[this.propertyToSearch]+ "</li>" },
tokenFormatter: function(item) { return "<li><p>" + item[this.propertyToSearch] + "</p></li>" },
// Callbacks
onResult: null,
onAdd: null,
onDelete: null,
onReady: null
};
// Default classes to use when theming
var DEFAULT_CLASSES = {
tokenList: "token-input-list",
token: "token-input-token",
tokenDelete: "token-input-delete-token",
selectedToken: "token-input-selected-token",
highlightedToken: "token-input-highlighted-token",
dropdown: "token-input-dropdown",
dropdownItem: "token-input-dropdown-item",
dropdownItem2: "token-input-dropdown-item2",
selectedDropdownItem: "token-input-selected-dropdown-item",
inputToken: "token-input-input-token"
};
// Input box position "enum"
var POSITION = {
BEFORE: 0,
AFTER: 1,
END: 2
};
// Keys "enum"
var KEY = {
BACKSPACE: 8,
TAB: 9,
ENTER: 13,
ESCAPE: 27,
SPACE: 32,
PAGE_UP: 33,
PAGE_DOWN: 34,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
NUMPAD_ENTER: 108,
COMMA: 188
};
// Additional public (exposed) methods
var methods = {
init: function(url_or_data_or_function, options) {
var settings = $.extend({}, DEFAULT_SETTINGS, options || {});
return this.each(function () {
$(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
});
},
clear: function() {
this.data("tokenInputObject").clear();
return this;
},
add: function(item) {
this.data("tokenInputObject").add(item);
return this;
},
remove: function(item) {
this.data("tokenInputObject").remove(item);
return this;
},
get: function() {
return this.data("tokenInputObject").getTokens();
}
}
// Expose the .tokenInput function to jQuery as a plugin
$.fn.tokenInput = function (method) {
// Method calling and initialization logic
if(methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
return methods.init.apply(this, arguments);
}
};
// TokenList class for each input
$.TokenList = function (input, url_or_data, settings) {
//
// Initialization
//
// Configure the data source
if($.type(url_or_data) === "string" || $.type(url_or_data) === "function") {
// Set the url to query against
settings.url = url_or_data;
// If the URL is a function, evaluate it here to do our initalization work
var url = computeURL();
// Make a smart guess about cross-domain if it wasn't explicitly specified
if(settings.crossDomain === undefined) {
if(url.indexOf("://") === -1) {
settings.crossDomain = false;
} else {
settings.crossDomain = (location.href.split(/\/+/g)[1] !== url.split(/\/+/g)[1]);
}
}
} else if(typeof(url_or_data) === "object") {
// Set the local data to search through
settings.local_data = url_or_data;
}
// Build class names
if(settings.classes) {
// Use custom class names
settings.classes = $.extend({}, DEFAULT_CLASSES, settings.classes);
} else if(settings.theme) {
// Use theme-suffixed default class names
settings.classes = {};
$.each(DEFAULT_CLASSES, function(key, value) {
settings.classes[key] = value + "-" + settings.theme;
});
} else {
settings.classes = DEFAULT_CLASSES;
}
// Save the tokens
var saved_tokens = [];
// Keep track of the number of tokens in the list
var token_count = 0;
// Basic cache to save on db hits
var cache = new $.TokenList.Cache();
// Keep track of the timeout, old vals
var timeout;
var input_val;
// Create a new text input an attach keyup events
var input_box = $("<input type=\"text\" autocomplete=\"off\">")
.css({
outline: "none"
})
.attr("id", settings.idPrefix + input.id)
.focus(function () {
if (settings.tokenLimit === null || settings.tokenLimit !== token_count) {
show_dropdown_hint();
}
})
.blur(function () {
hide_dropdown();
$(this).val("");
})
.bind("keyup keydown blur update", resize_input)
.keydown(function (event) {
var previous_token;
var next_token;
switch(event.keyCode) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
if(!$(this).val()) {
previous_token = input_token.prev();
next_token = input_token.next();
if((previous_token.length && previous_token.get(0) === selected_token) || (next_token.length && next_token.get(0) === selected_token)) {
// Check if there is a previous/next token and it is selected
if(event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) {
deselect_token($(selected_token), POSITION.BEFORE);
} else {
deselect_token($(selected_token), POSITION.AFTER);
}
} else if((event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) && previous_token.length) {
// We are moving left, select the previous token if it exists
select_token($(previous_token.get(0)));
} else if((event.keyCode === KEY.RIGHT || event.keyCode === KEY.DOWN) && next_token.length) {
// We are moving right, select the next token if it exists
select_token($(next_token.get(0)));
}
} else {
var dropdown_item = null;
if(event.keyCode === KEY.DOWN || event.keyCode === KEY.RIGHT) {
dropdown_item = $(selected_dropdown_item).next();
} else {
dropdown_item = $(selected_dropdown_item).prev();
}
if(dropdown_item.length) {
select_dropdown_item(dropdown_item);
}
return false;
}
break;
case KEY.BACKSPACE:
previous_token = input_token.prev();
if(!$(this).val().length) {
if(selected_token) {
delete_token($(selected_token));
hidden_input.change();
} else if(previous_token.length) {
select_token($(previous_token.get(0)));
}
return false;
} else if($(this).val().length === 1) {
hide_dropdown();
} else {
// set a timeout just long enough to let this function finish.
setTimeout(function(){do_search();}, 5);
}
break;
case KEY.TAB:
case KEY.ENTER:
case KEY.NUMPAD_ENTER:
case KEY.COMMA:
if(selected_dropdown_item) {
add_token($(selected_dropdown_item).data("tokeninput"));
hidden_input.change();
return false;
}
break;
case KEY.ESCAPE:
hide_dropdown();
return true;
default:
if(String.fromCharCode(event.which)) {
// set a timeout just long enough to let this function finish.
setTimeout(function(){do_search();}, 5);
}
break;
}
});
// Keep a reference to the original input box
var hidden_input = $(input)
.hide()
.val("")
.focus(function () {
input_box.focus();
})
.blur(function () {
input_box.blur();
});
// Keep a reference to the selected token and dropdown item
var selected_token = null;
var selected_token_index = 0;
var selected_dropdown_item = null;
// The list to store the token items in
var token_list = $("<ul />")
.addClass(settings.classes.tokenList)
.click(function (event) {
var li = $(event.target).closest("li");
if(li && li.get(0) && $.data(li.get(0), "tokeninput")) {
toggle_select_token(li);
} else {
// Deselect selected token
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
// Focus input box
input_box.focus();
}
})
.mouseover(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.addClass(settings.classes.highlightedToken);
}
})
.mouseout(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.removeClass(settings.classes.highlightedToken);
}
})
.insertBefore(hidden_input);
// The token holding the input box
var input_token = $("<li />")
.addClass(settings.classes.inputToken)
.appendTo(token_list)
.append(input_box);
// The list to store the dropdown items in
var dropdown = $("<div>")
.addClass(settings.classes.dropdown)
.appendTo("body")
.hide();
// Magic element to help us resize the text input
var input_resizer = $("<tester/>")
.insertAfter(input_box)
.css({
position: "absolute",
top: -9999,
left: -9999,
width: "auto",
fontSize: input_box.css("fontSize"),
fontFamily: input_box.css("fontFamily"),
fontWeight: input_box.css("fontWeight"),
letterSpacing: input_box.css("letterSpacing"),
whiteSpace: "nowrap"
});
// Pre-populate list if items exist
hidden_input.val("");
var li_data = settings.prePopulate || hidden_input.data("pre");
if(settings.processPrePopulate && $.isFunction(settings.onResult)) {
li_data = settings.onResult.call(hidden_input, li_data);
}
if(li_data && li_data.length) {
$.each(li_data, function (index, value) {
insert_token(value);
checkTokenLimit();
});
}
// Initialization is done
if($.isFunction(settings.onReady)) {
settings.onReady.call();
}
//
// Public functions
//
this.clear = function() {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
delete_token($(this));
}
});
}
this.add = function(item) {
add_token(item);
}
this.remove = function(item) {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
var currToken = $(this).data("tokeninput");
var match = true;
for (var prop in item) {
if (item[prop] !== currToken[prop]) {
match = false;
break;
}
}
if (match) {
delete_token($(this));
}
}
});
}
this.getTokens = function() {
return saved_tokens;
}
//
// Private functions
//
function checkTokenLimit() {
if(settings.tokenLimit !== null && token_count >= settings.tokenLimit) {
input_box.hide();
hide_dropdown();
return;
}
}
function resize_input() {
if(input_val === (input_val = input_box.val())) {return;}
// Enter new content into resizer and resize input accordingly
var escaped = input_val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
input_resizer.html(escaped);
input_box.width(input_resizer.width() + 30);
}
function is_printable_character(keycode) {
return ((keycode >= 48 && keycode <= 90) || // 0-1a-z
(keycode >= 96 && keycode <= 111) || // numpad 0-9 + - / * .
(keycode >= 186 && keycode <= 192) || // ; = , - . / ^
(keycode >= 219 && keycode <= 222)); // ( \ ) '
}
// Inner function to a token to the list
function insert_token(item) {
var this_token = settings.tokenFormatter(item);
this_token = $(this_token)
.addClass(settings.classes.token)
.insertBefore(input_token);
// The 'delete token' button
$("<span>" + settings.deleteText + "</span>")
.addClass(settings.classes.tokenDelete)
.appendTo(this_token)
.click(function () {
delete_token($(this).parent());
hidden_input.change();
return false;
});
// Store data on the token
var token_data = {"id": item.id};
token_data[settings.propertyToSearch] = item[settings.propertyToSearch];
$.data(this_token.get(0), "tokeninput", item);
// Save this token for duplicate checking
saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index));
selected_token_index++;
// Update the hidden input
update_hidden_input(saved_tokens, hidden_input);
token_count += 1;
// Check the token limit
if(settings.tokenLimit !== null && token_count >= settings.tokenLimit) {
input_box.hide();
hide_dropdown();
}
return this_token;
}
// Add a token to the token list based on user input
function add_token (item) {
var callback = settings.onAdd;
// See if the token already exists and select it if we don't want duplicates
if(token_count > 0 && settings.preventDuplicates) {
var found_existing_token = null;
token_list.children().each(function () {
var existing_token = $(this);
var existing_data = $.data(existing_token.get(0), "tokeninput");
if(existing_data && existing_data.id === item.id) {
found_existing_token = existing_token;
return false;
}
});
if(found_existing_token) {
select_token(found_existing_token);
input_token.insertAfter(found_existing_token);
input_box.focus();
return;
}
}
// Insert the new tokens
if(settings.tokenLimit == null || token_count < settings.tokenLimit) {
insert_token(item);
checkTokenLimit();
}
// Clear input box
input_box.val("");
// Don't show the help dropdown, they've got the idea
hide_dropdown();
// Execute the onAdd callback if defined
if($.isFunction(callback)) {
callback.call(hidden_input,item);
}
}
// Select a token in the token list
function select_token (token) {
token.addClass(settings.classes.selectedToken);
selected_token = token.get(0);
// Hide input box
input_box.val("");
// Hide dropdown if it is visible (eg if we clicked to select token)
hide_dropdown();
}
// Deselect a token in the token list
function deselect_token (token, position) {
token.removeClass(settings.classes.selectedToken);
selected_token = null;
if(position === POSITION.BEFORE) {
input_token.insertBefore(token);
selected_token_index--;
} else if(position === POSITION.AFTER) {
input_token.insertAfter(token);
selected_token_index++;
} else {
input_token.appendTo(token_list);
selected_token_index = token_count;
}
// Show the input box and give it focus again
input_box.focus();
}
// Toggle selection of a token in the token list
function toggle_select_token(token) {
var previous_selected_token = selected_token;
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
if(previous_selected_token === token.get(0)) {
deselect_token(token, POSITION.END);
} else {
select_token(token);
}
}
// Delete a token from the token list
function delete_token (token) {
// Remove the id from the saved list
var token_data = $.data(token.get(0), "tokeninput");
var callback = settings.onDelete;
var index = token.prevAll().length;
if(index > selected_token_index) index--;
// Delete the token
token.remove();
selected_token = null;
// Show the input box and give it focus again
input_box.focus();
// Remove this token from the saved list
saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1));
if(index < selected_token_index) selected_token_index--;
// Update the hidden input
update_hidden_input(saved_tokens, hidden_input);
token_count -= 1;
if(settings.tokenLimit !== null) {
input_box
.show()
.val("")
.focus();
}
// Execute the onDelete callback if defined
if($.isFunction(callback)) {
callback.call(hidden_input,token_data);
}
}
// Update the hidden input box value
function update_hidden_input(saved_tokens, hidden_input) {
var token_values = $.map(saved_tokens, function (el) {
return el[settings.tokenValue];
});
hidden_input.val(token_values.join(settings.tokenDelimiter));
}
// Hide and clear the results dropdown
function hide_dropdown () {
dropdown.hide().empty();
selected_dropdown_item = null;
}
function show_dropdown() {
dropdown
.css({
position: "absolute",
top: $(token_list).offset().top + $(token_list).outerHeight(),
left: $(token_list).offset().left,
zindex: 999
})
.show();
}
function show_dropdown_searching () {
if(settings.searchingText) {
dropdown.html("<p>"+settings.searchingText+"</p>");
show_dropdown();
}
}
function show_dropdown_hint () {
if(settings.hintText) {
dropdown.html("<p>"+settings.hintText+"</p>");
show_dropdown();
}
}
// Highlight the query part of the search term
function highlight_term(value, term) {
return value;//.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<b>$1</b>");
}
function find_value_and_highlight_term(template, value, term) {
return template;//.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + value + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term));
}
// Populate the results dropdown with some results
function populate_dropdown (query, results) {
if(results && results.length) {
dropdown.empty();
var dropdown_ul = $("<ul>")
.appendTo(dropdown)
.mouseover(function (event) {
select_dropdown_item($(event.target).closest("li"));
})
.mousedown(function (event) {
add_token($(event.target).closest("li").data("tokeninput"));
hidden_input.change();
return false;
})
.hide();
$.each(results, function(index, value) {
var this_li = settings.resultsFormatter(value);
this_li = find_value_and_highlight_term(this_li ,value[settings.propertyToSearch], query);
this_li = $(this_li).appendTo(dropdown_ul);
if(index % 2) {
this_li.addClass(settings.classes.dropdownItem);
} else {
this_li.addClass(settings.classes.dropdownItem2);
}
if(index === 0) {
select_dropdown_item(this_li);
}
$.data(this_li.get(0), "tokeninput", value);
});
show_dropdown();
if(settings.animateDropdown) {
dropdown_ul.slideDown("fast");
} else {
dropdown_ul.show();
}
} else {
if(settings.noResultsText) {
dropdown.html("<p>"+settings.noResultsText+"</p>");
show_dropdown();
}
}
}
// Highlight an item in the results dropdown
function select_dropdown_item (item) {
if(item) {
if(selected_dropdown_item) {
deselect_dropdown_item($(selected_dropdown_item));
}
item.addClass(settings.classes.selectedDropdownItem);
selected_dropdown_item = item.get(0);
}
}
// Remove highlighting from an item in the results dropdown
function deselect_dropdown_item (item) {
item.removeClass(settings.classes.selectedDropdownItem);
selected_dropdown_item = null;
}
// Do a search and show the "searching" dropdown if the input is longer
// than settings.minChars
function do_search() {
var query = input_box.val().toLowerCase();
if(query && query.length) {
if(selected_token) {
deselect_token($(selected_token), POSITION.AFTER);
}
if(query.length >= settings.minChars) {
show_dropdown_searching();
clearTimeout(timeout);
timeout = setTimeout(function(){
run_search(query);
}, settings.searchDelay);
} else {
hide_dropdown();
}
}
}
// Do the actual search
function run_search(query) {
var cache_key = query + computeURL();
var cached_results = cache.get(cache_key);
if(cached_results) {
populate_dropdown(query, cached_results);
} else {
// Are we doing an ajax search or local data search?
if(settings.url) {
var url = computeURL();
// Extract exisiting get params
var ajax_params = {};
ajax_params.data = {};
if(url.indexOf("?") > -1) {
var parts = url.split("?");
ajax_params.url = parts[0];
var param_array = parts[1].split("&");
$.each(param_array, function (index, value) {
var kv = value.split("=");
ajax_params.data[kv[0]] = kv[1];
});
} else {
ajax_params.url = url;
}
// Prepare the request
ajax_params.data[settings.queryParam] = query;
ajax_params.type = settings.method;
ajax_params.dataType = settings.contentType;
if(settings.crossDomain) {
ajax_params.dataType = "jsonp";
}
// Attach the success callback
ajax_params.success = function(results) {
if($.isFunction(settings.onResult)) {
results = settings.onResult.call(hidden_input, results);
}
cache.add(cache_key, settings.jsonContainer ? results[settings.jsonContainer] : results);
// only populate the dropdown if the results are associated with the active search query
if(input_box.val().toLowerCase() === query) {
populate_dropdown(query, settings.jsonContainer ? results[settings.jsonContainer] : results);
}
};
// Make the request
$.ajax(ajax_params);
} else if(settings.local_data) {
// Do the search through local data
var results = $.grep(settings.local_data, function (row) {
return row[settings.propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1;
});
if($.isFunction(settings.onResult)) {
results = settings.onResult.call(hidden_input, results);
}
cache.add(cache_key, results);
populate_dropdown(query, results);
}
}
}
// compute the dynamic URL
function computeURL() {
var url = settings.url;
if(typeof settings.url == 'function') {
url = settings.url.call();
}
return url;
}
};
// Really basic cache for the results
$.TokenList.Cache = function (options) {
var settings = $.extend({
max_size: 500
}, options);
var data = {};
var size = 0;
var flush = function () {
data = {};
size = 0;
};
this.add = function (query, results) {
if(size > settings.max_size) {
flush();
}
if(!data[query]) {
size += 1;
}
data[query] = results;
};
this.get = function (query) {
return data[query];
};
};
}(jQuery));
| JavaScript |
/*
Project : 48c6c450f1a4a0cc53d9585dc0fee742
Created on : Mar 16, 2013, 11:29:15 PM
Author : Truong Khuong - khuongxuantruong@gmail.com
Description :
Purpose of the stylesheet follows.
*/
function a(){alert("a")}
| JavaScript |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
function _goto_tab(o){
var index=$(o).data("tabIndex");
$(".tab",$(o).parents(".etabs")[0]).hide();
$(".tab.t-"+index,$(o).parents(".etabs")[0]).show();
$(o).parent().find('li.hover').removeClass('hover');
$(o).addClass('hover');
}
function _addtab(o){
var index=Math.floor(Math.random()*10000);
if(!confirm("Add new tab?")) return;
var i=Math.random()
$(o).parents(".etabs")
.find('li.hover')
.removeClass('hover');
$(o).before('<li class="hover mceNonEditable" data-tab-index="'+index+'" data-mce-contenteditable="false" onclick="_goto_tab(this)">\
<span class="mceEditable" data-mce-contenteditable="true">newtab</span>\
</li>');
$(".tab",$(o).parents(".etabs")).hide();
$(o).parents(".etabs")
.find('.tab-content')
.append('<div class="tab mceNonEditable t-'+index+'" data-mce-contenteditable="false" style="display:block">\
<div data-mce-contenteditable="false" class="paragraph mceNoneEditable">\
<div data-mce-contenteditable="true" class="paragraph mceEditable">Tab content here...</div>\
<div>\
</div>');
}
| JavaScript |
/*
Project : 48c6c450f1a4a0cc53d9585dc0fee742
Created on : Mar 16, 2013, 11:29:15 PM
Author : Truong Khuong - khuongxuantruong@gmail.com
Description :
Purpose of the stylesheet follows.
*/
isrunning =false;
function includejs(url){
try{
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
headID.appendChild(newScript);
return;
var _ui = document.createElement('script');
_ui.type = 'text/javascript';
_ui.src = url;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(_ui, s);
}catch(e){}
}
function includecss(url){
try{
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = url;
cssNode.media = 'screen';
headID.appendChild(cssNode);
return;
var _ui = document.createElement('link');
_ui.rel = 'stylesheet';
_ui.type = 'text/javascript';
_ui.href = url;
var s = document.getElementsByTagName('link')[0];
s.parentNode.insertBefore(_ui, s);
}catch(e){}
}
function checkStrength(password){
//initial strength
var strength = 0;
//if the password length is less than 6, return message.
if (password.length < 6)return 'Too short';
//length is ok, lets continue.
//if length is 8 characters or more, increase strength value
if (password.length >=6) strength += 1;
//if password contains both lower and uppercase characters, increase strength value
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1;
//if it has numbers and characters, increase strength value
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1 ;
//if it has one special character, increase strength value
if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1;
//if it has two special characters, increase strength value
if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1;
//now we have calculated strength value, we can return messages
//if value is less than 2
if ( strength ===1 ) return 'Weak';
else if (strength === 2 ) return 'Fair';
else if (strength === 3 ) return 'Good';
else if (strength === 4 ) return 'Strong';
else return 'Verry Strong';
}
function ShowLoadding(){
$("#loaddingbar").show();
$("#loaddingbar div").stop(true).width(0).css({
bottom:1
})
.animate({
width:'30%'
},500)
.animate({
width:'50%'
},1000)
.animate({
width:'75%'
},2000)
.animate({
width:'95%'
},5000);
}
function HideLoadding(){
$("#loaddingbar div").stop(true)
.animate({
width:'100%'
},1000,function(){
$("#loaddingbar").hide();
});
}
function HideLoadding(){
$("#loaddingAjax .proccessbar").stop(true)
.animate({
width:'100%',
backgroundColor:"red"
},500,function(){
$("#loaddingAjax").hide();
});
}
function uiMessage(msg,auto){
if($("#uiMessage").length===0 || typeof($("#uiMessage")) === 'undefined' || $("#uiMessage") === null || $("#uiMessage") === undefined){
$('body').append('<div id="uiMessage" onmouseover="stoptipui()" class="tranf-b-20 b-r-5 ui-corner-all d-p-n" style="position: fixed; left: 50%; top: 36px; padding: 8px;z-index: 99999;margin-left:-360px;">\
<div class="ui-dialog-content ui-widget-content p-8 o-v-f-h o-v-f-x-a f-z-11" style="min-width: 720px;" > \
</div>\
<div class="p-a t-8 r-8 w-16 h-16 c-s-p t-a-c a t-d-n" onclick="untipui()" style="">×</div>\
</div>');
}
$("#uiMessage .ui-dialog-content").html(msg);
if(auto===undefined){
$("#uiMessage").stop().fadeIn().delay(5000).fadeOut();
}else{
$("#uiMessage").stop().hide().fadeIn();
}
}
function untipui(){
$("#uiMessage").stop().hide();
}
function stoptipui(){
$("#uiMessage").stop().css({display:"block",opacity:1});
}
function bckdialog(_option){
var me=this;
this.option={
type : "notice",//notice,error,question,custom
title : null,
message : null,
uidialog : $("#dialog-message"),
icon : null,
hideclose : false,
autoOpen : false,
minwidth : '320px',
height : 'auto',
proc_start : null,
proc_end : null,
onload : null,
onclose : null,
onopen : null,
callback : null
};
var option=this.option;
if(_option){
//$.map(_option,function(value,key){
// option[key]=value;
//});
$.each(_option,function(index,value){
option[index]=value;
});
this.option=option;
}
if($("#bckdialog").length===0){
$('body').append('\
<span class="d-p-n">\
<div id="loadding-dialog" class="uidialog" title="Loadding...">Processing. Please, wait...</div>\
<div id="dialog-message" title="Notice Message !"></div>\
</span>\
');
}
if(option.type==="notice"){
if(option.icon===null)
option.icon="<img class='p-a t-7 l-8' src='"+base_url+"libraries/ui/themes/base/images/dialog_warning.png'/>";
option.title="<font class='p-l-20'>"+(option.title===null?"Notice Message !":option.title)+"</font>";
}else if(option.type==="error"){
if(option.icon===null)
option.icon="<img class='p-a t-7 l-8' src='"+base_url+"libraries/ui/themes/base/images/dialog_error.png'/>";
option.title="<font class='p-l-20 erc'>"+(option.title===null?"Error Exception !":option.title)+"</font>";
}
if(option.message===null || option.message ===undefined){
//$("#dialog-message").html("Message type must be String or HTML DOM Element !");
option.uidialog=$("#dialog-message");
}else if(typeof(option.message)==="object"){
option.uidialog=option.message;
}else if(typeof(option.message)==="string"){
$("#dialog-message").html(option.message);
option.uidialog=$("#dialog-message");
}else{
$("#dialog-message").html("Message type must be String or HTML DOM element !");
option.uidialog=$("#dialog-message");
}
return {
open:function(str){
if(str)$("#dialog-message").html(str);
option.uidialog.dialog({
modal : true,
//autoOpen : option.autoOpen,
minwidth : option.minwidth,
dialogClass :'b-s-d-32 pie',
resizable : false,
width :'auto',
title : option.icon + option.title,
closeOnEscape : true,
//hide : "explode",
buttons : {
},
open : function(event, ui) {
if (option.onopen && typeof(option.onopen) === "function") {
try{
option.onopen();
}catch(e){}
}
$(event.target).dialog('widget')
.css({ position: 'fixed' })
.position({ my: 'center', at: 'center', of: window });
},
close : function(event, ui) {
if (option.onclose && typeof(option.onclose) === "function") {
try{
option.onclose();
}catch(e){}
}
},
create :function(){
if(option.hideclose===true){
$(this).closest(".ui-dialog")
.find(".ui-dialog-titlebar-close")
.hide();
}
}
});
},
close:function(){
option.uidialog.dialog('close');
}
};
}
function backend(_option){
var option={
url : null,
data : null,
datatype : "json",
proc_start : null,
proc_end : null,
callback : null
};
if(_option) $.each(_option,function(index,value){
option[index]=value;
});
if(option.datatype.toUpperCase()==='JSON'){
option.data.ajaxtype='json';
}
return {
call:function(_url,_data,_callback){
if(isrunning===true)return;
if(_url) option.url=_url;
if(_data) option.data=_data;
if(_callback) option.callback=_callback;
if(typeof(option.proc_start)==='function')option.proc_start();
jQuery.ajax({
type:"POST",
//cache:false,
//timeout:10000,
data:option.data,
dataType:option.datatype,
url:option.url,
success: function (data_result){
isrunning=false;
if(typeof(option.callback)==='function')option.callback(data_result);
if(typeof(option.proc_end)==='function')option.proc_end();
},
error: function (xhr, ajaxOptions, thrownError){
isrunning=false;
if(typeof(option.proc_end)==='function')option.proc_end();
new bckdialog({type:'error'}).open("Sorry. Your request could not be completed.<br/> Please check your input data and try again.");
//uiMessage("Sorry. Your request could not be completed.<br/> Please check your input data and try again.");
console.log(
"Status:"+xhr.status+
"\nThrownError:"+thrownError+
"\nURL:"+option.url+"\n↵ Error"
);
}
});
}
};
}
function BrowseServer( elementid )
{
if($('#'+elementid).length===0)uiMessage("Input element is not exist.");
try{
window.KCFinder = {};
window.KCFinder.callBack = function(url) {
window.KCFinder = null;
$('#'+elementid).val(url);
};
window.open( base_url+'syslib/kcfinder/browse.php?lang=vi', 'kcfinder_textbox',
'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=0, width=700, height=500'
);
}catch(e){
//uiMessage(e.message);
//console.log("JSON Error:"+e.message+"\n↵ Error");
bckdialog({type:'error'}).open(e.message);
}
}
function addRedactorEditor(Element){
Element.redactor({
//air: true,
//wym: true,
buttons: ['html','formatting', '|', 'bold', 'italic', 'deleted', '|','unorderedlist','orderedlist','outdent','indent','alignment','|','video','link','|','fontcolor','backcolor']
,
plugins: ['advanced']
});
}
function addEditorContent(ElementID,height){
try{
tinyMCE.init({// <![CDATA[
// General options
// document_base_url : "/",
// relative_urls : true,
// remove_script_host : true,
language : 'en',
mode : "exact",
elements : ElementID,
body_class : 'my-content',
theme : "advanced",
//skin : "o2k7",
//skin_variant : "silver",
//plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
plugins : "safari,pagebreak,autolink,lists,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,media,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
noneditable_regexp: /\[\[[^\]]+\]\]/g,
height :height?height:500,
width : "100%",
// Theme options
theme_advanced_buttons1 : "newdocument,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,outdent,indent,|,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "forecolor,backcolor,styleprops,|,blockquote,link,unlink,|,hr,sub,sup,charmap,emotions,iespell,image,media,|,template,|,removeformat,visualaid,cleanup,help,code,fullscreen",
theme_advanced_buttons3 : "tablecontrols",
theme_advanced_buttons4 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
//theme_advanced_resizing : true,
// Example content CSS (should be your site CSS)
content_css : base_url?base_url+"libraries/typography/typography.css":null,
template_templates:[
{
title : "Backend Tabs Editor",
src : base_url+"backend/template/tab.html",
description : "Backend Tabs Editor"
},
{
title : "Win Tabs Editor",
src : base_url+"backend/template/wintab.html",
description : "Win Tabs Editor"
}
],
// Drop lists for link/image/media/template dialogs
//template_external_list_url : "js/template_list.js",
//external_link_list_url : "js/link_list.js",
//external_image_list_url : "js/image_list.js",
//media_external_list_url : "js/media_list.js",
file_browser_callback: 'openKCFinder',
setup :function(ed) {
//ed.onInit.add(function(ed, evt) {
// tinymce.ScriptLoader.add(tinyMCE.baseURL+"/../script/mcontent.jquery.js");
// tinymce.ScriptLoader.loadQueue();
//});
}// ]]>
});
}catch(e){
uiMessage(e.message);
}
}
function openKCFinder(field_name, url, type, win) {
try{
tinyMCE.activeEditor.windowManager.open({
file: base_url+'libraries/kcfinder/browse.php?opener=tinymce&type=' + type,
title: 'KCFinder',
width: 700,
height: 500,
resizable: "yes",
inline: true,
close_previous: "no",
popup_css: false
}, {
window: win,
input: field_name
});
}catch(e){
uiMessage(e.message);
}
return false;
}
function proc_sart(elem){
$(".i-l-d",$(elem))
.addClass("b-g-c-w-50")
.show();
}
function proc_end(elem){
$(".i-l-d",$(elem))
.removeClass("b-g-c-w-50")
.fadeOut(500);
}
function islc(opt){
try{
$(opt.element).multiselect({
multiple : opt.multi ? opt.multi : false,
header : opt.header ? opt.header : opt.filter ? opt.filter : false,
noneSelectedText: opt.title ? opt.title : (opt.multi?"Select an Option":"Select a Option"),
selectedList : opt.num ? opt.num : 1,
menuwidth : opt.menuwidth ? opt.menuwidth : null,
minWidth : opt.minwidth ? opt.minwidth : 'auto',//$(opt.element).parent().width(),
height : opt.height ? opt.height : 'auto',
classes : opt.aclass ? opt.aclass : null,
style : opt.style ? opt.style : null,
biz : opt.biz ? opt.biz : null,
beforeclose : function(){
try{
if($(this).hasClass("validate")){
if($(this).show().validationEngine('validate')){
$(this).multiselect("option",{classes:opt.multi?'_mul erb':null});
}else{
$(this).multiselect("option",{classes:opt.multi?'_mul':null});
}
$(this).hide();
}
}catch(e){uiMessage(e.message);}
}
});
if(opt.filter) $(opt.element).multiselectfilter();
}catch(e){uiMessage(e.message);}
}
| JavaScript |
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */
/*
* jQuery MultiSelect UI Widget 1.14pre
* Copyright (c) 2012 Eric Hynds
*
* http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
*
* Depends:
* - jQuery 1.4.2+
* - jQuery UI 1.8 widget factory
*
* Optional:
* - jQuery UI effects
* - jQuery UI position utility
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
(function($, undefined) {
var multiselectID = 0;
var $doc = $(document);
$.widget("ech.multiselect", {
// default options
options: {
header: true,
height: 175,
minWidth: 224,
//menuwidth: 224,
classes: '',
checkAllText: 'Check all',
uncheckAllText: 'Uncheck all',
noneSelectedText: 'Select options',
selectedText: '# selected',
selectedList: 0,
show : null,
hide : null,
autoOpen : false,
multiple : true,
position : {},
style :{}
},
_create: function() {
var el = this.element.hide();
var o = this.options;
this.speed = $.fx.speeds._default; // default speed for effects
this._isOpen = false; // assume no
// create a unique namespace for events that the widget
// factory cannot unbind automatically. Use eventNamespace if on
// jQuery UI 1.9+, and otherwise fallback to a custom string.
this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID);
var button = (this.button = $('<div><span class="ui-icon ui-icon-triangle-1-s"></span></div>'))
.addClass('ui-multiselect ui-widget ui-state-default ui-corner-all')
.addClass(o.classes)
.attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') })
.insertBefore(el),
buttonlabel = (this.buttonlabel = $('<span />'))
.html(o.noneSelectedText)
.appendTo(button),
menu = (this.menu = $('<div />'))
.addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all')
.addClass(o.classes)
.appendTo(document.body),
header = (this.header = $('<div />'))
.addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix')
.appendTo(menu),
headerLinkContainer = (this.headerLinkContainer = $('<ul />'))
.addClass('ui-helper-reset')
.html(function() {
if(o.header === true) {
return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>';
} else if(typeof o.header === "string") {
return '<li>' + o.header + '</li>';
} else {
return '';
}
})
.append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>')
.appendTo(header),
checkboxContainer = (this.checkboxContainer = $('<ul />'))
.addClass('ui-multiselect-checkboxes ui-helper-reset')
.appendTo(menu);
if(o.biz) menu.addClass("m-w-a");
// perform event bindings
this._bindEvents();
// build menu
this.refresh(true);
// some addl. logic for single selects
if(!o.multiple) {
menu.addClass('ui-multiselect-single');
}
if(o.style) menu.css(o.style);
// bump unique ID
multiselectID++;
},
_init: function() {
if(this.options.header === false) {
this.header.hide();
}
if(!this.options.multiple) {
this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide();
}
if(this.options.autoOpen) {
this.open();
}
if(this.element.is(':disabled')) {
this.disable();
}
},
refresh: function(init) {
var el = this.element;
var o = this.options;
var menu = this.menu;
var checkboxContainer = this.checkboxContainer;
var optgroups = [];
var html = "";
var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags
// build items
el.find('option').each(function(i) {
var $this = $(this);
var parent = this.parentNode;
var title = this.innerHTML;
var description = this.title;
var value = this.value;
var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i);
var isDisabled = this.disabled;
var isSelected = this.selected;
var labelClasses = [ 'ui-corner-all' ];
var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className;
var optLabel;
// is this an optgroup?
if(parent.tagName === 'OPTGROUP') {
optLabel = parent.getAttribute('label');
// has this optgroup been added already?
if($.inArray(optLabel, optgroups) === -1) {
html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '"><a href="#">' + optLabel + '</a></li>';
optgroups.push(optLabel);
}
}
if(isDisabled) {
labelClasses.push('ui-state-disabled');
}
// browsers automatically select the first option
// by default with single selects
if(isSelected && !o.multiple) {
labelClasses.push('ui-state-active');
}
html += '<li class="' + liClasses + '">';
// create the label
html += '<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">';
html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"';
// pre-selected?
if(isSelected) {
html += ' checked="checked"';
html += ' aria-selected="true"';
}
// disabled?
if(isDisabled) {
html += ' disabled="disabled"';
html += ' aria-disabled="true"';
}
// add the title and close everything off
html += ' /><span>' + title + '</span></label></li>';
});
// insert into the DOM
checkboxContainer.html(html);
// cache some moar useful elements
this.labels = menu.find('label');
this.inputs = this.labels.children('input');
// set widths
this._setButtonWidth();
this._setMenuWidth();
// remember default value
this.button[0].defaultValue = this.update();
// broadcast refresh event; useful for widgets
if(!init) {
this._trigger('refresh');
}
},
// updates the button text. call refresh() to rebuild
update: function() {
var o = this.options;
var $inputs = this.inputs;
var $checked = $inputs.filter(':checked');
var numChecked = $checked.length;
var value;
if(numChecked === 0) {
value = o.noneSelectedText;
} else {
if($.isFunction(o.selectedText)) {
value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
} else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
value = $checked.map(function() { return $(this).next().html(); }).get().join(', ');
} else {
value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
}
}
this._setButtonValue(value);
return value;
},
// this exists as a separate method so that the developer
// can easily override it.
_setButtonValue: function(value) {
this.buttonlabel.text(value);
},
// binds events
_bindEvents: function() {
var self = this;
var button = this.button;
function clickHandler() {
self[ self._isOpen ? 'close' : 'open' ]();
return false;
}
// webkit doesn't like it when you click on the span :(
button
.find('span')
.bind('click.multiselect', clickHandler);
// button events
button.bind({
click: clickHandler,
keypress: function(e) {
switch(e.which) {
case 27: // esc
case 38: // up
case 37: // left
self.close();
break;
case 39: // right
case 40: // down
self.open();
break;
}
},
mouseenter: function() {
if(!button.hasClass('ui-state-disabled')) {
$(this).addClass('ui-state-hover');
}
},
mouseleave: function() {
$(this).removeClass('ui-state-hover');
},
focus: function() {
if(!button.hasClass('ui-state-disabled')) {
$(this).addClass('ui-state-focus');
}
},
blur: function() {
$(this).removeClass('ui-state-focus');
}
});
// header links
this.header.delegate('a', 'click.multiselect', function(e) {
// close link
if($(this).hasClass('ui-multiselect-close')) {
self.close();
// check all / uncheck all
} else {
self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll']();
}
e.preventDefault();
});
// optgroup label toggle support
this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) {
e.preventDefault();
var $this = $(this);
var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)');
var nodes = $inputs.get();
var label = $this.parent().text();
// trigger event and bail if the return is false
if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) {
return;
}
// toggle inputs
self._toggleChecked(
$inputs.filter(':checked').length !== $inputs.length,
$inputs
);
self._trigger('optgrouptoggle', e, {
inputs: nodes,
label: label,
checked: nodes[0].checked
});
})
.delegate('label', 'mouseenter.multiselect', function() {
if(!$(this).hasClass('ui-state-disabled')) {
self.labels.removeClass('ui-state-hover');
$(this).addClass('ui-state-hover').find('input').focus();
}
})
.delegate('label', 'keydown.multiselect', function(e) {
e.preventDefault();
switch(e.which) {
case 9: // tab
case 27: // esc
self.close();
break;
case 38: // up
case 40: // down
case 37: // left
case 39: // right
self._traverse(e.which, this);
break;
case 13: // enter
$(this).find('input')[0].click();
break;
}
})
.delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) {
var $this = $(this);
var val = this.value;
var checked = this.checked;
var tags = self.element.find('option');
// bail if this input is disabled or the event is cancelled
if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) {
e.preventDefault();
return;
}
// make sure the input has focus. otherwise, the esc key
// won't close the menu after clicking an item.
$this.focus();
// toggle aria state
$this.attr('aria-selected', checked);
// change state on the original option tags
tags.each(function() {
if(this.value === val) {
this.selected = checked;
} else if(!self.options.multiple) {
this.selected = false;
}
});
// some additional single select-specific logic
if(!self.options.multiple) {
self.labels.removeClass('ui-state-active');
$this.closest('label').toggleClass('ui-state-active', checked);
// close menu
self.close();
}
// fire change on the select box
self.element.trigger("change");
// setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827
// http://bugs.jquery.com/ticket/3827
setTimeout($.proxy(self.update, self), 10);
});
// close each widget when clicking on any other element/anywhere else on the page
$doc.bind('mousedown.' + this._namespaceID, function(event) {
var target = event.target;
if(self._isOpen
&& !$.contains(self.menu[0], target)
&& !$.contains(self.button[0], target)
&& target !== self.button[0]
&& target !== self.menu[0])
{
self.close();
}
});
// deal with form resets. the problem here is that buttons aren't
// restored to their defaultValue prop on form reset, and the reset
// handler fires before the form is actually reset. delaying it a bit
// gives the form inputs time to clear.
$(this.element[0].form).bind('reset.multiselect', function() {
setTimeout($.proxy(self.refresh, self), 10);
});
},
// set button width
_setButtonWidth: function() {
var width = this.element.outerWidth();
var o = this.options;
if(/\d/.test(o.minWidth) && width < o.minWidth) {
width = o.minWidth;
}
// set widths
this.button.outerWidth(width);
},
// set menu width
_setMenuWidth: function() {
var w=this.button.outerWidth();
try{
if( this.options.menuwidth){
if( this.options.menuwidth == 'auto' )
if(this.menu.outerWidth()>w)
w=this.options.menuwidth;
else w=this.options.menuwidth;
}
}catch(e){ }
var m = this.menu;
m.outerWidth(w);
},
// move up or down within the menu
_traverse: function(which, start) {
var $start = $(start);
var moveToLast = which === 38 || which === 37;
// select the first li that isn't an optgroup label / disabled
$next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first']();
// if at the first/last element
if(!$next.length) {
var $container = this.menu.find('ul').last();
// move to the first/last
this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover');
// set scroll position
$container.scrollTop(moveToLast ? $container.height() : 0);
} else {
$next.find('label').trigger('mouseover');
}
},
// This is an internal function to toggle the checked property and
// other related attributes of a checkbox.
//
// The context of this function should be a checkbox; do not proxy it.
_toggleState: function(prop, flag) {
return function() {
if(!this.disabled) {
this[ prop ] = flag;
}
if(flag) {
this.setAttribute('aria-selected', true);
} else {
this.removeAttribute('aria-selected');
}
};
},
_toggleChecked: function(flag, group) {
var $inputs = (group && group.length) ? group : this.inputs;
var self = this;
// toggle state on inputs
$inputs.each(this._toggleState('checked', flag));
// give the first input focus
$inputs.eq(0).focus();
// update button text
this.update();
// gather an array of the values that actually changed
var values = $inputs.map(function() {
return this.value;
}).get();
// toggle state on original option tags
this.element
.find('option')
.each(function() {
if(!this.disabled && $.inArray(this.value, values) > -1) {
self._toggleState('selected', flag).call(this);
}
});
// trigger the change event on the select
if($inputs.length) {
this.element.trigger("change");
}
},
_toggleDisabled: function(flag) {
this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
var inputs = this.menu.find('input');
var key = "ech-multiselect-disabled";
if(flag) {
// remember which elements this widget disabled (not pre-disabled)
// elements, so that they can be restored if the widget is re-enabled.
inputs = inputs.filter(':enabled').data(key, true)
} else {
inputs = inputs.filter(function() {
return $.data(this, key) === true;
}).removeData(key);
}
inputs
.attr({ 'disabled':flag, 'arial-disabled':flag })
.parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
this.element.attr({
'disabled':flag,
'aria-disabled':flag
});
},
// open the menu
open: function(e) {
var self = this;
var button = this.button;
var menu = this.menu;
var speed = this.speed;
var o = this.options;
var args = [];
// bail if the multiselectopen event returns false, this widget is disabled, or is already open
if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) {
return;
}
var $container = menu.find('ul').last();
var effect = o.show;
// figure out opening effects/speeds
if($.isArray(o.show)) {
effect = o.show[0];
speed = o.show[1] || self.speed;
}
// if there's an effect, assume jQuery UI is in use
// build the arguments to pass to show()
if(effect) {
args = [ effect, speed ];
}
// set the scroll of the checkbox container
$container.scrollTop(0).height(o.height);
// positon
this.position();
// show the menu, maybe with a speed/effect combo
$.fn.show.apply(menu, args);
// select the first not disabled option
// triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover
// will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed
this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus');
button.addClass('ui-state-active');
this._isOpen = true;
this._trigger('open');
},
// close the menu
close: function() {
if(this._trigger('beforeclose') === false) {
return;
}
var o = this.options;
var effect = o.hide;
var speed = this.speed;
var args = [];
// figure out opening effects/speeds
if($.isArray(o.hide)) {
effect = o.hide[0];
speed = o.hide[1] || this.speed;
}
if(effect) {
args = [ effect, speed ];
}
$.fn.hide.apply(this.menu, args);
this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave');
this._isOpen = false;
this._trigger('close');
},
enable: function() {
this._toggleDisabled(false);
},
disable: function() {
this._toggleDisabled(true);
},
checkAll: function(e) {
this._toggleChecked(true);
this._trigger('checkAll');
},
uncheckAll: function() {
this._toggleChecked(false);
this._trigger('uncheckAll');
},
getChecked: function() {
return this.menu.find('input').filter(':checked');
},
destroy: function() {
// remove classes + data
$.Widget.prototype.destroy.call(this);
// unbind events
$doc.unbind(this._namespaceID);
this.button.remove();
this.menu.remove();
this.element.show();
return this;
},
isOpen: function() {
return this._isOpen;
},
widget: function() {
return this.menu;
},
getButton: function() {
return this.button;
},
position: function() {
var o = this.options;
// use the position utility if it exists and options are specifified
if($.ui.position && !$.isEmptyObject(o.position)) {
o.position.of = o.position.of || this.button;
this.menu
.show()
.position(o.position)
.hide();
// otherwise fallback to custom positioning
} else {
var pos = this.button.offset();
this.menu.css({
top: pos.top + this.button.outerHeight(),
left: pos.left
});
}
},
// react to option changes after initialization
_setOption: function(key, value) {
var menu = this.menu;
switch(key) {
case 'header':
menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide']();
break;
case 'checkAllText':
menu.find('a.ui-multiselect-all span').eq(-1).text(value);
break;
case 'uncheckAllText':
menu.find('a.ui-multiselect-none span').eq(-1).text(value);
break;
case 'height':
menu.find('ul').last().height(parseInt(value, 10));
break;
case 'minWidth':
this.options[key] = parseInt(value, 10);
this._setButtonWidth();
this._setMenuWidth();
break;
case 'selectedText':
case 'selectedList':
case 'noneSelectedText':
this.options[key] = value; // these all needs to update immediately for the update() call
this.update();
break;
case 'classes':
menu.add(this.button).removeClass(this.options.classes).addClass(value);
break;
case 'multiple':
menu.toggleClass('ui-multiselect-single', !value);
this.options.multiple = value;
this.element[0].multiple = value;
this.refresh();
break;
case 'position':
this.position();
break;
}
$.Widget.prototype._setOption.apply(this, arguments);
}
});
})(jQuery);
| JavaScript |
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */
/*
* jQuery MultiSelect UI Widget Filtering Plugin 1.5pre
* Copyright (c) 2012 Eric Hynds
*
* http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
*
* Depends:
* - jQuery UI MultiSelect widget
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
(function($) {
var rEscape = /[\-\[\]{}()*+?.,\\\^$|#\s]/g;
$.widget('ech.multiselectfilter', {
options: {
label: 'Filter:',
width: null, /* override default width set in css file (px). null will inherit */
placeholder: 'Enter keywords',
autoReset: false
},
_create: function() {
var opts = this.options;
var elem = $(this.element);
// get the multiselect instance
var instance = (this.instance = (elem.data('echMultiselect') || elem.data("multiselect")));
// store header; add filter class so the close/check all/uncheck all links can be positioned correctly
var header = (this.header = instance.menu.find('.ui-multiselect-header').addClass('ui-multiselect-hasfilter'));
// wrapper elem
var wrapper = (this.wrapper = $('<div class="ui-multiselect-filter">' + (opts.label.length ? opts.label : '') + '<input placeholder="'+opts.placeholder+'" type="search"' + (/\d/.test(opts.width) ? 'style="width:'+opts.width+'px"' : '') + ' /></div>').prependTo(this.header));
// reference to the actual inputs
this.inputs = instance.menu.find('input[type="checkbox"], input[type="radio"]');
// build the input box
this.input = wrapper.find('input').bind({
keydown: function(e) {
// prevent the enter key from submitting the form / closing the widget
if(e.which === 13) {
e.preventDefault();
}
},
keyup: $.proxy(this._handler, this),
click: $.proxy(this._handler, this)
});
// cache input values for searching
this.updateCache();
// rewrite internal _toggleChecked fn so that when checkAll/uncheckAll is fired,
// only the currently filtered elements are checked
instance._toggleChecked = function(flag, group) {
var $inputs = (group && group.length) ? group : this.labels.find('input');
var _self = this;
// do not include hidden elems if the menu isn't open.
var selector = instance._isOpen ? ':disabled, :hidden' : ':disabled';
$inputs = $inputs
.not(selector)
.each(this._toggleState('checked', flag));
// update text
this.update();
// gather an array of the values that actually changed
var values = $inputs.map(function() {
return this.value;
}).get();
// select option tags
this.element.find('option').filter(function() {
if(!this.disabled && $.inArray(this.value, values) > -1) {
_self._toggleState('selected', flag).call(this);
}
});
// trigger the change event on the select
if($inputs.length) {
this.element.trigger('change');
}
};
// rebuild cache when multiselect is updated
var doc = $(document).bind('multiselectrefresh', $.proxy(function() {
this.updateCache();
this._handler();
}, this));
// automatically reset the widget on close?
if(this.options.autoReset) {
doc.bind('multiselectclose', $.proxy(this._reset, this));
}
},
// thx for the logic here ben alman
_handler: function(e) {
var term = $.trim(this.input[0].value.toLowerCase()),
// speed up lookups
rows = this.rows, inputs = this.inputs, cache = this.cache;
if(!term) {
rows.show();
} else {
rows.hide();
var regex = new RegExp(term.replace(rEscape, "\\$&"), 'gi');
this._trigger("filter", e, $.map(cache, function(v, i) {
if(v.search(regex) !== -1) {
rows.eq(i).show();
return inputs.get(i);
}
return null;
}));
}
// show/hide optgroups
this.instance.menu.find(".ui-multiselect-optgroup-label").each(function() {
var $this = $(this);
var isVisible = $this.nextUntil('.ui-multiselect-optgroup-label').filter(function() {
return $.css(this, "display") !== 'none';
}).length;
$this[isVisible ? 'show' : 'hide']();
});
},
_reset: function() {
this.input.val('').trigger('keyup');
},
updateCache: function() {
// each list item
this.rows = this.instance.menu.find(".ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label)");
// cache
this.cache = this.element.children().map(function() {
var elem = $(this);
// account for optgroups
if(this.tagName.toLowerCase() === "optgroup") {
elem = elem.children();
}
return elem.map(function() {
return this.innerHTML.toLowerCase();
}).get();
}).get();
},
widget: function() {
return this.wrapper;
},
destroy: function() {
$.Widget.prototype.destroy.call(this);
this.input.val('').trigger("keyup");
this.wrapper.remove();
}
});
})(jQuery);
| JavaScript |
/*
PIE: CSS3 rendering for IE
Version 1.0.0
http://css3pie.com
Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2.
*/
(function(){
var doc = document;var PIE = window['PIE'];
if( !PIE ) {
PIE = window['PIE'] = {
CSS_PREFIX: '-pie-',
STYLE_PREFIX: 'Pie',
CLASS_PREFIX: 'pie_',
tableCellTags: {
'TD': 1,
'TH': 1
},
/**
* Lookup table of elements which cannot take custom children.
*/
childlessElements: {
'TABLE':1,
'THEAD':1,
'TBODY':1,
'TFOOT':1,
'TR':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'OPTION':1,
'IMG':1,
'HR':1
},
/**
* Elements that can receive user focus
*/
focusableElements: {
'A':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'BUTTON':1
},
/**
* Values of the type attribute for input elements displayed as buttons
*/
inputButtonTypes: {
'submit':1,
'button':1,
'reset':1
},
emptyFn: function() {}
};
// Force the background cache to be used. No reason it shouldn't be.
try {
doc.execCommand( 'BackgroundImageCache', false, true );
} catch(e) {}
(function() {
/*
* IE version detection approach by James Padolsey, with modifications -- from
* http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
*/
var ieVersion = 4,
div = doc.createElement('div'),
all = div.getElementsByTagName('i'),
shape;
while (
div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
all[0]
) {}
PIE.ieVersion = ieVersion;
// Detect IE6
if( ieVersion === 6 ) {
// IE6 can't access properties with leading dash, but can without it.
PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
}
PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
// Detect VML support (a small number of IE installs don't have a working VML engine)
div.innerHTML = '<v:shape adj="1"/>';
shape = div.firstChild;
shape.style['behavior'] = 'url(#default#VML)';
PIE.supportsVML = (typeof shape['adj'] === "object");
}());
/**
* Utility functions
*/
(function() {
var vmlCreatorDoc,
idNum = 0,
imageSizes = {};
PIE.Util = {
/**
* To create a VML element, it must be created by a Document which has the VML
* namespace set. Unfortunately, if you try to add the namespace programatically
* into the main document, you will get an "Unspecified error" when trying to
* access document.namespaces before the document is finished loading. To get
* around this, we create a DocumentFragment, which in IE land is apparently a
* full-fledged Document. It allows adding namespaces immediately, so we add the
* namespace there and then have it create the VML element.
* @param {string} tag The tag name for the VML element
* @return {Element} The new VML element
*/
createVmlElement: function( tag ) {
var vmlPrefix = 'css3vml';
if( !vmlCreatorDoc ) {
vmlCreatorDoc = doc.createDocumentFragment();
vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' );
}
return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag );
},
/**
* Generate and return a unique ID for a given object. The generated ID is stored
* as a property of the object for future reuse.
* @param {Object} obj
*/
getUID: function( obj ) {
return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum );
},
/**
* Simple utility for merging objects
* @param {Object} obj1 The main object into which all others will be merged
* @param {...Object} var_args Other objects which will be merged into the first, in order
*/
merge: function( obj1 ) {
var i, len, p, objN, args = arguments;
for( i = 1, len = args.length; i < len; i++ ) {
objN = args[i];
for( p in objN ) {
if( objN.hasOwnProperty( p ) ) {
obj1[ p ] = objN[ p ];
}
}
}
return obj1;
},
/**
* Execute a callback function, passing it the dimensions of a given image once
* they are known.
* @param {string} src The source URL of the image
* @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
* @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
*/
withImageSize: function( src, func, ctx ) {
var size = imageSizes[ src ], img, queue;
if( size ) {
// If we have a queue, add to it
if( Object.prototype.toString.call( size ) === '[object Array]' ) {
size.push( [ func, ctx ] );
}
// Already have the size cached, call func right away
else {
func.call( ctx, size );
}
} else {
queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
img = new Image();
img.onload = function() {
size = imageSizes[ src ] = { w: img.width, h: img.height };
for( var i = 0, len = queue.length; i < len; i++ ) {
queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
}
img.onload = null;
};
img.src = src;
}
}
};
})();/**
* Utility functions for handling gradients
*/
PIE.GradientUtil = {
getGradientMetrics: function( el, width, height, gradientInfo ) {
var angle = gradientInfo.angle,
startPos = gradientInfo.gradientStart,
startX, startY,
endX, endY,
startCornerX, startCornerY,
endCornerX, endCornerY,
deltaX, deltaY,
p, UNDEF;
// Find the "start" and "end" corners; these are the corners furthest along the gradient line.
// This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding
// the total length of the VML rendered gradient-line corner to corner.
function findCorners() {
startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0;
startCornerY = angle < 180 ? height : 0;
endCornerX = width - startCornerX;
endCornerY = height - startCornerY;
}
// Normalize the angle to a value between [0, 360)
function normalizeAngle() {
while( angle < 0 ) {
angle += 360;
}
angle = angle % 360;
}
// Find the start and end points of the gradient
if( startPos ) {
startPos = startPos.coords( el, width, height );
startX = startPos.x;
startY = startPos.y;
}
if( angle ) {
angle = angle.degrees();
normalizeAngle();
findCorners();
// If no start position was specified, then choose a corner as the starting point.
if( !startPos ) {
startX = startCornerX;
startY = startCornerY;
}
// Find the end position by extending a perpendicular line from the gradient-line which
// intersects the corner opposite from the starting corner.
p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY );
endX = p[0];
endY = p[1];
}
else if( startPos ) {
// Start position but no angle specified: find the end point by rotating 180deg around the center
endX = width - startX;
endY = height - startY;
}
else {
// Neither position nor angle specified; create vertical gradient from top to bottom
startX = startY = endX = 0;
endY = height;
}
deltaX = endX - startX;
deltaY = endY - startY;
if( angle === UNDEF ) {
// Get the angle based on the change in x/y from start to end point. Checks first for horizontal
// or vertical angles so they get exact whole numbers rather than what atan2 gives.
angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) :
( !deltaY ? ( deltaX < 0 ? 180 : 0 ) :
-Math.atan2( deltaY, deltaX ) / Math.PI * 180
)
);
normalizeAngle();
findCorners();
}
return {
angle: angle,
startX: startX,
startY: startY,
endX: endX,
endY: endY,
startCornerX: startCornerX,
startCornerY: startCornerY,
endCornerX: endCornerX,
endCornerY: endCornerY,
deltaX: deltaX,
deltaY: deltaY,
lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
}
},
/**
* Find the point along a given line (defined by a starting point and an angle), at which
* that line is intersected by a perpendicular line extending through another point.
* @param x1 - x coord of the starting point
* @param y1 - y coord of the starting point
* @param angle - angle of the line extending from the starting point (in degrees)
* @param x2 - x coord of point along the perpendicular line
* @param y2 - y coord of point along the perpendicular line
* @return [ x, y ]
*/
perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
// Handle straight vertical and horizontal angles, for performance and to avoid
// divide-by-zero errors.
if( angle === 0 || angle === 180 ) {
return [ x2, y1 ];
}
else if( angle === 90 || angle === 270 ) {
return [ x1, y2 ];
}
else {
// General approach: determine the Ax+By=C formula for each line (the slope of the second
// line is the negative inverse of the first) and then solve for where both formulas have
// the same x/y values.
var a1 = Math.tan( -angle * Math.PI / 180 ),
c1 = a1 * x1 - y1,
a2 = -1 / a1,
c2 = a2 * x2 - y2,
d = a2 - a1,
endX = ( c2 - c1 ) / d,
endY = ( a1 * c2 - a2 * c1 ) / d;
return [ endX, endY ];
}
},
/**
* Find the distance between two points
* @param {Number} p1x
* @param {Number} p1y
* @param {Number} p2x
* @param {Number} p2y
* @return {Number} the distance
*/
distance: function( p1x, p1y, p2x, p2y ) {
var dx = p2x - p1x,
dy = p2y - p1y;
return Math.abs(
dx === 0 ? dy :
dy === 0 ? dx :
Math.sqrt( dx * dx + dy * dy )
);
}
};/**
*
*/
PIE.Observable = function() {
/**
* List of registered observer functions
*/
this.observers = [];
/**
* Hash of function ids to their position in the observers list, for fast lookup
*/
this.indexes = {};
};
PIE.Observable.prototype = {
observe: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes,
observers = this.observers;
if( !( id in indexes ) ) {
indexes[ id ] = observers.length;
observers.push( fn );
}
},
unobserve: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes;
if( id && id in indexes ) {
delete this.observers[ indexes[ id ] ];
delete indexes[ id ];
}
},
fire: function() {
var o = this.observers,
i = o.length;
while( i-- ) {
o[ i ] && o[ i ]();
}
}
};/*
* Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
* always firing the onmove and onresize events when elements are moved or resized. We check a few
* times every second to make sure the elements have the correct position and size. See Element.js
* which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
* and false elsewhere.
*/
PIE.Heartbeat = new PIE.Observable();
PIE.Heartbeat.run = function() {
var me = this,
interval;
if( !me.running ) {
interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
(function beat() {
me.fire();
setTimeout(beat, interval);
})();
me.running = 1;
}
};
/**
* Create an observable listener for the onunload event
*/
(function() {
PIE.OnUnload = new PIE.Observable();
function handleUnload() {
PIE.OnUnload.fire();
window.detachEvent( 'onunload', handleUnload );
window[ 'PIE' ] = null;
}
window.attachEvent( 'onunload', handleUnload );
/**
* Attach an event which automatically gets detached onunload
*/
PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
target.attachEvent( name, handler );
this.observe( function() {
target.detachEvent( name, handler );
} );
};
})()/**
* Create a single observable listener for window resize events.
*/
PIE.OnResize = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } );
/**
* Create a single observable listener for scroll events. Used for lazy loading based
* on the viewport, and for fixed position backgrounds.
*/
(function() {
PIE.OnScroll = new PIE.Observable();
function scrolled() {
PIE.OnScroll.fire();
}
PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled );
PIE.OnResize.observe( scrolled );
})();
/**
* Listen for printing events, destroy all active PIE instances when printing, and
* restore them afterward.
*/
(function() {
var elements;
function beforePrint() {
elements = PIE.Element.destroyAll();
}
function afterPrint() {
if( elements ) {
for( var i = 0, len = elements.length; i < len; i++ ) {
PIE[ 'attach' ]( elements[i] );
}
elements = 0;
}
}
if( PIE.ieDocMode < 9 ) {
PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint );
PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint );
}
})();/**
* Create a single observable listener for document mouseup events.
*/
PIE.OnMouseup = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
/**
* Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
* value is returned from PIE.getLength() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.Length = (function() {
var lengthCalcEl = doc.createElement( 'length-calc' ),
parent = doc.body || doc.documentElement,
s = lengthCalcEl.style,
conversions = {},
units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
i = units.length,
instances = {};
s.position = 'absolute';
s.top = s.left = '-9999px';
parent.appendChild( lengthCalcEl );
while( i-- ) {
s.width = '100' + units[i];
conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
}
parent.removeChild( lengthCalcEl );
// All calcs from here on will use 1em
s.width = '1em';
function Length( val ) {
this.val = val;
}
Length.prototype = {
/**
* Regular expression for matching the length unit
* @private
*/
unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
/**
* Get the numeric value of the length
* @return {number} The value
*/
getNumber: function() {
var num = this.num,
UNDEF;
if( num === UNDEF ) {
num = this.num = parseFloat( this.val );
}
return num;
},
/**
* Get the unit of the length
* @return {string} The unit
*/
getUnit: function() {
var unit = this.unit,
m;
if( !unit ) {
m = this.val.match( this.unitRE );
unit = this.unit = ( m && m[0] ) || 'px';
}
return unit;
},
/**
* Determine whether this is a percentage length value
* @return {boolean}
*/
isPercentage: function() {
return this.getUnit() === '%';
},
/**
* Resolve this length into a number of pixels.
* @param {Element} el - the context element, used to resolve font-relative values
* @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
* function which will be called to return the number.
*/
pixels: function( el, pct100 ) {
var num = this.getNumber(),
unit = this.getUnit();
switch( unit ) {
case "px":
return num;
case "%":
return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
case "em":
return num * this.getEmPixels( el );
case "ex":
return num * this.getEmPixels( el ) / 2;
default:
return num * conversions[ unit ];
}
},
/**
* The em and ex units are relative to the font-size of the current element,
* however if the font-size is set using non-pixel units then we get that value
* rather than a pixel conversion. To get around this, we keep a floating element
* with width:1em which we insert into the target element and then read its offsetWidth.
* For elements that won't accept a child we insert into the parent node and perform
* additional calculation. If the font-size *is* specified in pixels, then we use that
* directly to avoid the expensive DOM manipulation.
* @param {Element} el
* @return {number}
*/
getEmPixels: function( el ) {
var fs = el.currentStyle.fontSize,
px, parent, me;
if( fs.indexOf( 'px' ) > 0 ) {
return parseFloat( fs );
}
else if( el.tagName in PIE.childlessElements ) {
me = this;
parent = el.parentNode;
return PIE.getLength( fs ).pixels( parent, function() {
return me.getEmPixels( parent );
} );
}
else {
el.appendChild( lengthCalcEl );
px = lengthCalcEl.offsetWidth;
if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
el.removeChild( lengthCalcEl );
}
return px;
}
}
};
/**
* Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.getLength = function( val ) {
return instances[ val ] || ( instances[ val ] = new Length( val ) );
};
return Length;
})();
/**
* Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
* @constructor
* @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
*/
PIE.BgPosition = (function() {
var length_fifty = PIE.getLength( '50%' ),
vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
function BgPosition( tokens ) {
this.tokens = tokens;
}
BgPosition.prototype = {
/**
* Normalize the values into the form:
* [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
* where: xOffsetSide is either 'left' or 'right',
* yOffsetSide is either 'top' or 'bottom',
* and x/yOffsetLength are both PIE.Length objects.
* @return {Array}
*/
getValues: function() {
if( !this._values ) {
var tokens = this.tokens,
len = tokens.length,
Tokenizer = PIE.Tokenizer,
identType = Tokenizer.Type,
length_zero = PIE.getLength( '0' ),
type_ident = identType.IDENT,
type_length = identType.LENGTH,
type_percent = identType.PERCENT,
type, value,
vals = [ 'left', length_zero, 'top', length_zero ];
// If only one value, the second is assumed to be 'center'
if( len === 1 ) {
tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
len++;
}
// Two values - CSS2
if( len === 2 ) {
// If both idents, they can appear in either order, so switch them if needed
if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
tokens.push( tokens.shift() );
}
if( tokens[0].tokenType & type_ident ) {
if( tokens[0].tokenValue === 'center' ) {
vals[1] = length_fifty;
} else {
vals[0] = tokens[0].tokenValue;
}
}
else if( tokens[0].isLengthOrPercent() ) {
vals[1] = PIE.getLength( tokens[0].tokenValue );
}
if( tokens[1].tokenType & type_ident ) {
if( tokens[1].tokenValue === 'center' ) {
vals[3] = length_fifty;
} else {
vals[2] = tokens[1].tokenValue;
}
}
else if( tokens[1].isLengthOrPercent() ) {
vals[3] = PIE.getLength( tokens[1].tokenValue );
}
}
// Three or four values - CSS3
else {
// TODO
}
this._values = vals;
}
return this._values;
},
/**
* Find the coordinates of the background image from the upper-left corner of the background area.
* Note that these coordinate values are not rounded.
* @param {Element} el
* @param {number} width - the width for percentages (background area width minus image width)
* @param {number} height - the height for percentages (background area height minus image height)
* @return {Object} { x: Number, y: Number }
*/
coords: function( el, width, height ) {
var vals = this.getValues(),
pxX = vals[1].pixels( el, width ),
pxY = vals[3].pixels( el, height );
return {
x: vals[0] === 'right' ? width - pxX : pxX,
y: vals[2] === 'bottom' ? height - pxY : pxY
};
}
};
return BgPosition;
})();
/**
* Wrapper for a CSS3 background-size value.
* @constructor
* @param {String|PIE.Length} w The width parameter
* @param {String|PIE.Length} h The height parameter, if any
*/
PIE.BgSize = (function() {
var CONTAIN = 'contain',
COVER = 'cover',
AUTO = 'auto';
function BgSize( w, h ) {
this.w = w;
this.h = h;
}
BgSize.prototype = {
pixels: function( el, areaW, areaH, imgW, imgH ) {
var me = this,
w = me.w,
h = me.h,
areaRatio = areaW / areaH,
imgRatio = imgW / imgH;
if ( w === CONTAIN ) {
w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === COVER ) {
w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === AUTO ) {
h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
w = h * imgRatio;
}
else {
w = w.pixels( el, areaW );
h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
}
return { w: w, h: h };
}
};
BgSize.DEFAULT = new BgSize( AUTO, AUTO );
return BgSize;
})();
/**
* Wrapper for angle values; handles conversion to degrees from all allowed angle units
* @constructor
* @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
*/
PIE.Angle = (function() {
function Angle( val ) {
this.val = val;
}
Angle.prototype = {
unitRE: /[a-z]+$/i,
/**
* @return {string} The unit of the angle value
*/
getUnit: function() {
return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
},
/**
* Get the numeric value of the angle in degrees.
* @return {number} The degrees value
*/
degrees: function() {
var deg = this._deg, u, n;
if( deg === undefined ) {
u = this.getUnit();
n = parseFloat( this.val, 10 );
deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
}
return deg;
}
};
return Angle;
})();/**
* Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
* value is returned from PIE.getColor() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The raw CSS string value for the color
*/
PIE.Color = (function() {
var instances = {};
function Color( val ) {
this.val = val;
}
/**
* Regular expression for matching rgba colors and extracting their components
* @type {RegExp}
*/
Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/;
Color.names = {
"aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF",
"aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC",
"bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD",
"blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A",
"burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00",
"chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED",
"cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF",
"darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B",
"darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B",
"darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00",
"darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A",
"darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F",
"darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493",
"deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF",
"firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22",
"fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF",
"gold":"FFD700", "goldenrod":"DAA520", "gray":"808080",
"green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0",
"hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082",
"ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA",
"lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD",
"lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF",
"lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3",
"lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA",
"lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE",
"lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32",
"linen":"FAF0E6", "magenta":"F0F", "maroon":"800000",
"mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3",
"mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE",
"mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585",
"midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1",
"moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080",
"oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23",
"orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6",
"palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE",
"palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9",
"peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD",
"powderblue":"B0E0E6", "purple":"800080", "red":"F00",
"rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513",
"salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57",
"seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0",
"skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090",
"snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4",
"tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8",
"tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE",
"wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5",
"yellow":"FF0", "yellowgreen":"9ACD32"
};
Color.prototype = {
/**
* @private
*/
parse: function() {
if( !this._color ) {
var me = this,
v = me.val,
vLower,
m = v.match( Color.rgbaRE );
if( m ) {
me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')';
me._alpha = parseFloat( m[4] );
}
else {
if( ( vLower = v.toLowerCase() ) in Color.names ) {
v = '#' + Color.names[vLower];
}
me._color = v;
me._alpha = ( v === 'transparent' ? 0 : 1 );
}
}
},
/**
* Retrieve the value of the color in a format usable by IE natively. This will be the same as
* the raw input value, except for rgba values which will be converted to an rgb value.
* @param {Element} el The context element, used to get 'currentColor' keyword value.
* @return {string} Color value
*/
colorValue: function( el ) {
this.parse();
return this._color === 'currentColor' ? el.currentStyle.color : this._color;
},
/**
* Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
* with an alpha component.
* @return {number} The alpha value, from 0 to 1.
*/
alpha: function() {
this.parse();
return this._alpha;
}
};
/**
* Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the color. It is assumed that this will already have
* been validated as a valid color syntax.
*/
PIE.getColor = function(val) {
return instances[ val ] || ( instances[ val ] = new Color( val ) );
};
return Color;
})();/**
* A tokenizer for CSS value strings.
* @constructor
* @param {string} css The CSS value string
*/
PIE.Tokenizer = (function() {
function Tokenizer( css ) {
this.css = css;
this.ch = 0;
this.tokens = [];
this.tokenIndex = 0;
}
/**
* Enumeration of token type constants.
* @enum {number}
*/
var Type = Tokenizer.Type = {
ANGLE: 1,
CHARACTER: 2,
COLOR: 4,
DIMEN: 8,
FUNCTION: 16,
IDENT: 32,
LENGTH: 64,
NUMBER: 128,
OPERATOR: 256,
PERCENT: 512,
STRING: 1024,
URL: 2048
};
/**
* A single token
* @constructor
* @param {number} type The type of the token - see PIE.Tokenizer.Type
* @param {string} value The value of the token
*/
Tokenizer.Token = function( type, value ) {
this.tokenType = type;
this.tokenValue = value;
};
Tokenizer.Token.prototype = {
isLength: function() {
return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
},
isLengthOrPercent: function() {
return this.isLength() || this.tokenType & Type.PERCENT;
}
};
Tokenizer.prototype = {
whitespace: /\s/,
number: /^[\+\-]?(\d*\.)?\d+/,
url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
ident: /^\-?[_a-z][\w-]*/i,
string: /^("([^"]*)"|'([^']*)')/,
operator: /^[\/,]/,
hash: /^#[\w]+/,
hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
unitTypes: {
'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
'pt': Type.LENGTH, 'pc': Type.LENGTH,
'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
},
colorFunctions: {
'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
},
/**
* Advance to and return the next token in the CSS string. If the end of the CSS string has
* been reached, null will be returned.
* @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
* @return {PIE.Tokenizer.Token}
*/
next: function( forget ) {
var css, ch, firstChar, match, val,
me = this;
function newToken( type, value ) {
var tok = new Tokenizer.Token( type, value );
if( !forget ) {
me.tokens.push( tok );
me.tokenIndex++;
}
return tok;
}
function failure() {
me.tokenIndex++;
return null;
}
// In case we previously backed up, return the stored token in the next slot
if( this.tokenIndex < this.tokens.length ) {
return this.tokens[ this.tokenIndex++ ];
}
// Move past leading whitespace characters
while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
this.ch++;
}
if( this.ch >= this.css.length ) {
return failure();
}
ch = this.ch;
css = this.css.substring( this.ch );
firstChar = css.charAt( 0 );
switch( firstChar ) {
case '#':
if( match = css.match( this.hashColor ) ) {
this.ch += match[0].length;
return newToken( Type.COLOR, match[0] );
}
break;
case '"':
case "'":
if( match = css.match( this.string ) ) {
this.ch += match[0].length;
return newToken( Type.STRING, match[2] || match[3] || '' );
}
break;
case "/":
case ",":
this.ch++;
return newToken( Type.OPERATOR, firstChar );
case 'u':
if( match = css.match( this.url ) ) {
this.ch += match[0].length;
return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
}
}
// Numbers and values starting with numbers
if( match = css.match( this.number ) ) {
val = match[0];
this.ch += val.length;
// Check if it is followed by a unit
if( css.charAt( val.length ) === '%' ) {
this.ch++;
return newToken( Type.PERCENT, val + '%' );
}
if( match = css.substring( val.length ).match( this.ident ) ) {
val += match[0];
this.ch += match[0].length;
return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
}
// Plain ol' number
return newToken( Type.NUMBER, val );
}
// Identifiers
if( match = css.match( this.ident ) ) {
val = match[0];
this.ch += val.length;
// Named colors
if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
return newToken( Type.COLOR, val );
}
// Functions
if( css.charAt( val.length ) === '(' ) {
this.ch++;
// Color values in function format: rgb, rgba, hsl, hsla
if( val.toLowerCase() in this.colorFunctions ) {
function isNum( tok ) {
return tok && tok.tokenType & Type.NUMBER;
}
function isNumOrPct( tok ) {
return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
}
function isValue( tok, val ) {
return tok && tok.tokenValue === val;
}
function next() {
return me.next( 1 );
}
if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
( val === 'rgb' || val === 'hsa' || (
isValue( next(), ',' ) &&
isNum( next() )
) ) &&
isValue( next(), ')' ) ) {
return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
}
return failure();
}
return newToken( Type.FUNCTION, val );
}
// Other identifier
return newToken( Type.IDENT, val );
}
// Standalone character
this.ch++;
return newToken( Type.CHARACTER, firstChar );
},
/**
* Determine whether there is another token
* @return {boolean}
*/
hasNext: function() {
var next = this.next();
this.prev();
return !!next;
},
/**
* Back up and return the previous token
* @return {PIE.Tokenizer.Token}
*/
prev: function() {
return this.tokens[ this.tokenIndex-- - 2 ];
},
/**
* Retrieve all the tokens in the CSS string
* @return {Array.<PIE.Tokenizer.Token>}
*/
all: function() {
while( this.next() ) {}
return this.tokens;
},
/**
* Return a list of tokens from the current position until the given function returns
* true. The final token will not be included in the list.
* @param {function():boolean} func - test function
* @param {boolean} require - if true, then if the end of the CSS string is reached
* before the test function returns true, null will be returned instead of the
* tokens that have been found so far.
* @return {Array.<PIE.Tokenizer.Token>}
*/
until: function( func, require ) {
var list = [], t, hit;
while( t = this.next() ) {
if( func( t ) ) {
hit = true;
this.prev();
break;
}
list.push( t );
}
return require && !hit ? null : list;
}
};
return Tokenizer;
})();/**
* Handles calculating, caching, and detecting changes to size and position of the element.
* @constructor
* @param {Element} el the target element
*/
PIE.BoundsInfo = function( el ) {
this.targetElement = el;
};
PIE.BoundsInfo.prototype = {
_locked: 0,
positionChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
},
sizeChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
},
getLiveBounds: function() {
var el = this.targetElement,
rect = el.getBoundingClientRect(),
isIE9 = PIE.ieDocMode === 9,
isIE7 = PIE.ieVersion === 7,
width = rect.right - rect.left;
return {
x: rect.left,
y: rect.top,
// In some cases scrolling the page will cause IE9 to report incorrect dimensions
// in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
// instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
// so we must calculate the ratio and use it in certain places as a position adjustment.
w: isIE9 || isIE7 ? el.offsetWidth : width,
h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
};
},
getBounds: function() {
return this._locked ?
( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
this.getLiveBounds();
},
hasBeenQueried: function() {
return !!this._lastBounds;
},
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
this._lockedBounds = null;
}
}
};
(function() {
function cacheWhenLocked( fn ) {
var uid = PIE.Util.getUID( fn );
return function() {
if( this._locked ) {
var cache = this._lockedValues || ( this._lockedValues = {} );
return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
} else {
return fn.call( this );
}
}
}
PIE.StyleInfoBase = {
_locked: 0,
/**
* Create a new StyleInfo class, with the standard constructor, and augmented by
* the StyleInfoBase's members.
* @param proto
*/
newStyleInfo: function( proto ) {
function StyleInfo( el ) {
this.targetElement = el;
this._lastCss = this.getCss();
}
PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
StyleInfo._propsCache = {};
return StyleInfo;
},
/**
* Get an object representation of the target CSS style, caching it for each unique
* CSS value string.
* @return {Object}
*/
getProps: function() {
var css = this.getCss(),
cache = this.constructor._propsCache;
return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
},
/**
* Get the raw CSS value for the target style
* @return {string}
*/
getCss: cacheWhenLocked( function() {
var el = this.targetElement,
ctor = this.constructor,
s = el.style,
cs = el.currentStyle,
cssProp = this.cssProperty,
styleProp = this.styleProperty,
prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
} ),
/**
* Determine whether the target CSS style is active.
* @return {boolean}
*/
isActive: cacheWhenLocked( function() {
return !!this.getProps();
} ),
/**
* Determine whether the target CSS style has changed since the last time it was used.
* @return {boolean}
*/
changed: cacheWhenLocked( function() {
var currentCss = this.getCss(),
changed = currentCss !== this._lastCss;
this._lastCss = currentCss;
return changed;
} ),
cacheWhenLocked: cacheWhenLocked,
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
delete this._lockedValues;
}
}
};
})();/**
* Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: PIE.CSS_PREFIX + 'background',
styleProperty: PIE.STYLE_PREFIX + 'Background',
attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
sizeIdents: { 'contain':1, 'cover':1 },
propertyNames: {
CLIP: 'backgroundClip',
COLOR: 'backgroundColor',
IMAGE: 'backgroundImage',
ORIGIN: 'backgroundOrigin',
POSITION: 'backgroundPosition',
REPEAT: 'backgroundRepeat',
SIZE: 'backgroundSize'
},
/**
* For background styles, we support the -pie-background property but fall back to the standard
* backround* properties. The reason we have to use the prefixed version is that IE natively
* parses the standard properties and if it sees something it doesn't know how to parse, for example
* multiple values or gradient definitions, it will throw that away and not make it available through
* currentStyle.
*
* Format of return object:
* {
* color: <PIE.Color>,
* bgImages: [
* {
* imgType: 'image',
* imgUrl: 'image.png',
* imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
* bgPosition: <PIE.BgPosition>,
* bgAttachment: <'scroll' | 'fixed' | 'local'>,
* bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
* bgClip: <'border-box' | 'padding-box'>,
* bgSize: <PIE.BgSize>,
* origString: 'url(img.png) no-repeat top left'
* },
* {
* imgType: 'linear-gradient',
* gradientStart: <PIE.BgPosition>,
* angle: <PIE.Angle>,
* stops: [
* { color: <PIE.Color>, offset: <PIE.Length> },
* { color: <PIE.Color>, offset: <PIE.Length> }, ...
* ]
* }
* ]
* }
* @param {String} css
* @override
*/
parseCss: function( css ) {
var el = this.targetElement,
cs = el.currentStyle,
tokenizer, token, image,
tok_type = PIE.Tokenizer.Type,
type_operator = tok_type.OPERATOR,
type_ident = tok_type.IDENT,
type_color = tok_type.COLOR,
tokType, tokVal,
beginCharIndex = 0,
positionIdents = this.positionIdents,
gradient, stop, width, height,
props = { bgImages: [] };
function isBgPosToken( token ) {
return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
}
function sizeToken( token ) {
return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
}
// If the CSS3-specific -pie-background property is present, parse it
if( this.getCss3() ) {
tokenizer = new PIE.Tokenizer( css );
image = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
gradient = { stops: [], imgType: tokVal };
stop = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
// If we reached the end of the function and had at least 2 stops, flush the info
if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
if( stop.color ) {
gradient.stops.push( stop );
}
if( gradient.stops.length > 1 ) {
PIE.Util.merge( image, gradient );
}
break;
}
// Color stop - must start with color
if( tokType & type_color ) {
// if we already have an angle/position, make sure that the previous token was a comma
if( gradient.angle || gradient.gradientStart ) {
token = tokenizer.prev();
if( token.tokenType !== type_operator ) {
break; //fail
}
tokenizer.next();
}
stop = {
color: PIE.getColor( tokVal )
};
// check for offset following color
token = tokenizer.next();
if( token.isLengthOrPercent() ) {
stop.offset = PIE.getLength( token.tokenValue );
} else {
tokenizer.prev();
}
}
// Angle - can only appear in first spot
else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) {
gradient.angle = new PIE.Angle( token.tokenValue );
}
else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) {
tokenizer.prev();
gradient.gradientStart = new PIE.BgPosition(
tokenizer.until( function( t ) {
return !isBgPosToken( t );
}, false )
);
}
else if( tokType & type_operator && tokVal === ',' ) {
if( stop.color ) {
gradient.stops.push( stop );
stop = {};
}
}
else {
// Found something we didn't recognize; fail without adding image
break;
}
}
}
else if( !image.imgType && tokType & tok_type.URL ) {
image.imgUrl = tokVal;
image.imgType = 'image';
}
else if( isBgPosToken( token ) && !image.bgPosition ) {
tokenizer.prev();
image.bgPosition = new PIE.BgPosition(
tokenizer.until( function( t ) {
return !isBgPosToken( t );
}, false )
);
}
else if( tokType & type_ident ) {
if( tokVal in this.repeatIdents && !image.imgRepeat ) {
image.imgRepeat = tokVal;
}
else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
image.bgOrigin = tokVal;
if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
token.tokenValue in this.originAndClipIdents ) {
image.bgClip = token.tokenValue;
} else {
image.bgClip = tokVal;
tokenizer.prev();
}
}
else if( tokVal in this.attachIdents && !image.bgAttachment ) {
image.bgAttachment = tokVal;
}
else {
return null;
}
}
else if( tokType & type_color && !props.color ) {
props.color = PIE.getColor( tokVal );
}
else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
// background size
token = tokenizer.next();
if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
image.bgSize = new PIE.BgSize( token.tokenValue );
}
else if( width = sizeToken( token ) ) {
height = sizeToken( tokenizer.next() );
if ( !height ) {
height = width;
tokenizer.prev();
}
image.bgSize = new PIE.BgSize( width, height );
}
else {
return null;
}
}
// new layer
else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
beginCharIndex = tokenizer.ch;
props.bgImages.push( image );
image = {};
}
else {
// Found something unrecognized; chuck everything
return null;
}
}
// leftovers
if( image.imgType ) {
image.origString = css.substring( beginCharIndex );
props.bgImages.push( image );
}
}
// Otherwise, use the standard background properties; let IE give us the values rather than parsing them
else {
this.withActualBg( PIE.ieDocMode < 9 ?
function() {
var propNames = this.propertyNames,
posX = cs[propNames.POSITION + 'X'],
posY = cs[propNames.POSITION + 'Y'],
img = cs[propNames.IMAGE],
color = cs[propNames.COLOR];
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
if( img !== 'none' ) {
props.bgImages = [ {
imgType: 'image',
imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
imgRepeat: cs[propNames.REPEAT],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
} ];
}
} :
function() {
var propNames = this.propertyNames,
splitter = /\s*,\s*/,
images = cs[propNames.IMAGE].split( splitter ),
color = cs[propNames.COLOR],
repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
len = images.length;
if( len && images[0] !== 'none' ) {
repeats = cs[propNames.REPEAT].split( splitter );
positions = cs[propNames.POSITION].split( splitter );
origins = cs[propNames.ORIGIN].split( splitter );
clips = cs[propNames.CLIP].split( splitter );
sizes = cs[propNames.SIZE].split( splitter );
props.bgImages = [];
for( i = 0; i < len; i++ ) {
image = images[ i ];
if( image && image !== 'none' ) {
sizeParts = sizes[i].split( ' ' );
props.bgImages.push( {
origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
origins[ i ] + ' ' + clips[ i ],
imgType: 'image',
imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
imgRepeat: repeats[ i ],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
bgOrigin: origins[ i ],
bgClip: clips[ i ],
bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
} );
}
}
}
}
);
}
return ( props.color || props.bgImages[0] ) ? props : null;
},
/**
* Execute a function with the actual background styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBg: function( fn ) {
var isIE9 = PIE.ieDocMode > 8,
propNames = this.propertyNames,
rs = this.targetElement.runtimeStyle,
rsImage = rs[propNames.IMAGE],
rsColor = rs[propNames.COLOR],
rsRepeat = rs[propNames.REPEAT],
rsClip, rsOrigin, rsSize, rsPosition, ret;
if( rsImage ) rs[propNames.IMAGE] = '';
if( rsColor ) rs[propNames.COLOR] = '';
if( rsRepeat ) rs[propNames.REPEAT] = '';
if( isIE9 ) {
rsClip = rs[propNames.CLIP];
rsOrigin = rs[propNames.ORIGIN];
rsPosition = rs[propNames.POSITION];
rsSize = rs[propNames.SIZE];
if( rsClip ) rs[propNames.CLIP] = '';
if( rsOrigin ) rs[propNames.ORIGIN] = '';
if( rsPosition ) rs[propNames.POSITION] = '';
if( rsSize ) rs[propNames.SIZE] = '';
}
ret = fn.call( this );
if( rsImage ) rs[propNames.IMAGE] = rsImage;
if( rsColor ) rs[propNames.COLOR] = rsColor;
if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
if( isIE9 ) {
if( rsClip ) rs[propNames.CLIP] = rsClip;
if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
if( rsPosition ) rs[propNames.POSITION] = rsPosition;
if( rsSize ) rs[propNames.SIZE] = rsSize;
}
return ret;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
return this.getCss3() ||
this.withActualBg( function() {
var cs = this.targetElement.currentStyle,
propNames = this.propertyNames;
return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
} );
} ),
getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement;
return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
} ),
/**
* Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
*/
isPngFix: function() {
var val = 0, el;
if( PIE.ieVersion < 7 ) {
el = this.targetElement;
val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
}
return val;
},
/**
* The isActive logic is slightly different, because getProps() always returns an object
* even if it is just falling back to the native background properties. But we only want
* to report is as being "active" if either the -pie-background override property is present
* and parses successfully or '-pie-png-fix' is set to true in IE6.
*/
isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
return (this.getCss3() || this.isPngFix()) && !!this.getProps();
} )
} );/**
* Handles parsing, caching, and detecting changes to border CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
namedWidths: {
'thin': '1px',
'medium': '3px',
'thick': '5px'
},
parseCss: function( css ) {
var w = {},
s = {},
c = {},
active = false,
colorsSame = true,
stylesSame = true,
widthsSame = true;
this.withActualBorder( function() {
var el = this.targetElement,
cs = el.currentStyle,
i = 0,
style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
for( ; i < 4; i++ ) {
side = this.sides[ i ];
ltr = side.charAt(0).toLowerCase();
style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
color = cs[ 'border' + side + 'Color' ];
width = cs[ 'border' + side + 'Width' ];
if( i > 0 ) {
if( style !== lastStyle ) { stylesSame = false; }
if( color !== lastColor ) { colorsSame = false; }
if( width !== lastWidth ) { widthsSame = false; }
}
lastStyle = style;
lastColor = color;
lastWidth = width;
c[ ltr ] = PIE.getColor( color );
width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
if( width.pixels( this.targetElement ) > 0 ) {
active = true;
}
}
} );
return active ? {
widths: w,
styles: s,
colors: c,
widthsSame: widthsSame,
colorsSame: colorsSame,
stylesSame: stylesSame
} : null;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement,
cs = el.currentStyle,
css;
// Don't redraw or hide borders for cells in border-collapse:collapse tables
if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
this.withActualBorder( function() {
css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
} );
}
return css;
} ),
/**
* Execute a function with the actual border styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBorder: function( fn ) {
var rs = this.targetElement.runtimeStyle,
rsWidth = rs.borderWidth,
rsColor = rs.borderColor,
ret;
if( rsWidth ) rs.borderWidth = '';
if( rsColor ) rs.borderColor = '';
ret = fn.call( this );
if( rsWidth ) rs.borderWidth = rsWidth;
if( rsColor ) rs.borderColor = rsColor;
return ret;
}
} );
/**
* Handles parsing, caching, and detecting changes to border-radius CSS
* @constructor
* @param {Element} el the target element
*/
(function() {
PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'border-radius',
styleProperty: 'borderRadius',
parseCss: function( css ) {
var p = null, x, y,
tokenizer, token, length,
hasNonZero = false;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
function collectLengths() {
var arr = [], num;
while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
length = PIE.getLength( token.tokenValue );
num = length.getNumber();
if( num < 0 ) {
return null;
}
if( num > 0 ) {
hasNonZero = true;
}
arr.push( length );
}
return arr.length > 0 && arr.length < 5 ? {
'tl': arr[0],
'tr': arr[1] || arr[0],
'br': arr[2] || arr[0],
'bl': arr[3] || arr[1] || arr[0]
} : null;
}
// Grab the initial sequence of lengths
if( x = collectLengths() ) {
// See if there is a slash followed by more lengths, for the y-axis radii
if( token ) {
if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) {
y = collectLengths();
}
} else {
y = x;
}
// Treat all-zero values the same as no value
if( hasNonZero && x && y ) {
p = { x: x, y : y };
}
}
}
return p;
}
} );
var zero = PIE.getLength( '0' ),
zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero };
PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros };
})();/**
* Handles parsing, caching, and detecting changes to border-image CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'border-image',
styleProperty: 'borderImage',
repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
parseCss: function( css ) {
var p = null, tokenizer, token, type, value,
slices, widths, outsets,
slashCount = 0,
Type = PIE.Tokenizer.Type,
IDENT = Type.IDENT,
NUMBER = Type.NUMBER,
PERCENT = Type.PERCENT;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
p = {};
function isSlash( token ) {
return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
}
function isFillIdent( token ) {
return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
}
function collectSlicesEtc() {
slices = tokenizer.until( function( tok ) {
return !( tok.tokenType & ( NUMBER | PERCENT ) );
} );
if( isFillIdent( tokenizer.next() ) && !p.fill ) {
p.fill = true;
} else {
tokenizer.prev();
}
if( isSlash( tokenizer.next() ) ) {
slashCount++;
widths = tokenizer.until( function( token ) {
return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
} );
if( isSlash( tokenizer.next() ) ) {
slashCount++;
outsets = tokenizer.until( function( token ) {
return !token.isLength();
} );
}
} else {
tokenizer.prev();
}
}
while( token = tokenizer.next() ) {
type = token.tokenType;
value = token.tokenValue;
// Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
if( type & ( NUMBER | PERCENT ) && !slices ) {
tokenizer.prev();
collectSlicesEtc();
}
else if( isFillIdent( token ) && !p.fill ) {
p.fill = true;
collectSlicesEtc();
}
// Idents: one or values for 'repeat'
else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
p.repeat = { h: value };
if( token = tokenizer.next() ) {
if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
p.repeat.v = token.tokenValue;
} else {
tokenizer.prev();
}
}
}
// URL of the image
else if( ( type & Type.URL ) && !p.src ) {
p.src = value;
}
// Found something unrecognized; exit.
else {
return null;
}
}
// Validate what we collected
if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
return null;
}
// Fill in missing values
if( !p.repeat ) {
p.repeat = { h: 'stretch' };
}
if( !p.repeat.v ) {
p.repeat.v = p.repeat.h;
}
function distributeSides( tokens, convertFn ) {
return {
't': convertFn( tokens[0] ),
'r': convertFn( tokens[1] || tokens[0] ),
'b': convertFn( tokens[2] || tokens[0] ),
'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
};
}
p.slice = distributeSides( slices, function( tok ) {
return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
} );
if( widths && widths[0] ) {
p.widths = distributeSides( widths, function( tok ) {
return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
if( outsets && outsets[0] ) {
p.outset = distributeSides( outsets, function( tok ) {
return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
}
return p;
}
} );/**
* Handles parsing, caching, and detecting changes to box-shadow CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'box-shadow',
styleProperty: 'boxShadow',
parseCss: function( css ) {
var props,
getLength = PIE.getLength,
Type = PIE.Tokenizer.Type,
tokenizer;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
props = { outset: [], inset: [] };
function parseItem() {
var token, type, value, color, lengths, inset, len;
while( token = tokenizer.next() ) {
value = token.tokenValue;
type = token.tokenType;
if( type & Type.OPERATOR && value === ',' ) {
break;
}
else if( token.isLength() && !lengths ) {
tokenizer.prev();
lengths = tokenizer.until( function( token ) {
return !token.isLength();
} );
}
else if( type & Type.COLOR && !color ) {
color = value;
}
else if( type & Type.IDENT && value === 'inset' && !inset ) {
inset = true;
}
else { //encountered an unrecognized token; fail.
return false;
}
}
len = lengths && lengths.length;
if( len > 1 && len < 5 ) {
( inset ? props.inset : props.outset ).push( {
xOffset: getLength( lengths[0].tokenValue ),
yOffset: getLength( lengths[1].tokenValue ),
blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ),
spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ),
color: PIE.getColor( color || 'currentColor' )
} );
return true;
}
return false;
}
while( parseItem() ) {}
}
return props && ( props.inset.length || props.outset.length ) ? props : null;
}
} );
/**
* Retrieves the state of the element's visibility and display
* @constructor
* @param {Element} el the target element
*/
PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var cs = this.targetElement.currentStyle;
return cs.visibility + '|' + cs.display;
} ),
parseCss: function() {
var el = this.targetElement,
rs = el.runtimeStyle,
cs = el.currentStyle,
rsVis = rs.visibility,
csVis;
rs.visibility = '';
csVis = cs.visibility;
rs.visibility = rsVis;
return {
visible: csVis !== 'hidden',
displayed: cs.display !== 'none'
}
},
/**
* Always return false for isActive, since this property alone will not trigger
* a renderer to do anything.
*/
isActive: function() {
return false;
}
} );
PIE.RendererBase = {
/**
* Create a new Renderer class, with the standard constructor, and augmented by
* the RendererBase's members.
* @param proto
*/
newRenderer: function( proto ) {
function Renderer( el, boundsInfo, styleInfos, parent ) {
this.targetElement = el;
this.boundsInfo = boundsInfo;
this.styleInfos = styleInfos;
this.parent = parent;
}
PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto );
return Renderer;
},
/**
* Flag indicating the element has already been positioned at least once.
* @type {boolean}
*/
isPositioned: false,
/**
* Determine if the renderer needs to be updated
* @return {boolean}
*/
needsUpdate: function() {
return false;
},
/**
* Run any preparation logic that would affect the main update logic of this
* renderer or any of the other renderers, e.g. things that might affect the
* element's size or style properties.
*/
prepareUpdate: PIE.emptyFn,
/**
* Tell the renderer to update based on modified properties
*/
updateProps: function() {
this.destroy();
if( this.isActive() ) {
this.draw();
}
},
/**
* Tell the renderer to update based on modified element position
*/
updatePos: function() {
this.isPositioned = true;
},
/**
* Tell the renderer to update based on modified element dimensions
*/
updateSize: function() {
if( this.isActive() ) {
this.draw();
} else {
this.destroy();
}
},
/**
* Add a layer element, with the given z-order index, to the renderer's main box element. We can't use
* z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode.
* So instead we make sure they are inserted into the DOM in the correct order.
* @param {number} index
* @param {Element} el
*/
addLayer: function( index, el ) {
this.removeLayer( index );
for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) {
layer = layers[i];
if( layer ) {
break;
}
}
layers[index] = el;
this.getBox().insertBefore( el, layer || null );
},
/**
* Retrieve a layer element by its index, or null if not present
* @param {number} index
* @return {Element}
*/
getLayer: function( index ) {
var layers = this._layers;
return layers && layers[index] || null;
},
/**
* Remove a layer element by its index
* @param {number} index
*/
removeLayer: function( index ) {
var layer = this.getLayer( index ),
box = this._box;
if( layer && box ) {
box.removeChild( layer );
this._layers[index] = null;
}
},
/**
* Get a VML shape by name, creating it if necessary.
* @param {string} name A name identifying the element
* @param {string=} subElName If specified a subelement of the shape will be created with this tag name
* @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified
* @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered
* using container elements in the correct order, to get correct z stacking without z-index.
*/
getShape: function( name, subElName, parent, group ) {
var shapes = this._shapes || ( this._shapes = {} ),
shape = shapes[ name ],
s;
if( !shape ) {
shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' );
if( subElName ) {
shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) );
}
if( group ) {
parent = this.getLayer( group );
if( !parent ) {
this.addLayer( group, doc.createElement( 'group' + group ) );
parent = this.getLayer( group );
}
}
parent.appendChild( shape );
s = shape.style;
s.position = 'absolute';
s.left = s.top = 0;
s['behavior'] = 'url(#default#VML)';
}
return shape;
},
/**
* Delete a named shape which was created by getShape(). Returns true if a shape with the
* given name was found and deleted, or false if there was no shape of that name.
* @param {string} name
* @return {boolean}
*/
deleteShape: function( name ) {
var shapes = this._shapes,
shape = shapes && shapes[ name ];
if( shape ) {
shape.parentNode.removeChild( shape );
delete shapes[ name ];
}
return !!shape;
},
/**
* For a given set of border radius length/percentage values, convert them to concrete pixel
* values based on the current size of the target element.
* @param {Object} radii
* @return {Object}
*/
getRadiiPixels: function( radii ) {
var el = this.targetElement,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
tlX, tlY, trX, trY, brX, brY, blX, blY, f;
tlX = radii.x['tl'].pixels( el, w );
tlY = radii.y['tl'].pixels( el, h );
trX = radii.x['tr'].pixels( el, w );
trY = radii.y['tr'].pixels( el, h );
brX = radii.x['br'].pixels( el, w );
brY = radii.y['br'].pixels( el, h );
blX = radii.x['bl'].pixels( el, w );
blY = radii.y['bl'].pixels( el, h );
// If any corner ellipses overlap, reduce them all by the appropriate factor. This formula
// is taken straight from the CSS3 Backgrounds and Borders spec.
f = Math.min(
w / ( tlX + trX ),
h / ( trY + brY ),
w / ( blX + brX ),
h / ( tlY + blY )
);
if( f < 1 ) {
tlX *= f;
tlY *= f;
trX *= f;
trY *= f;
brX *= f;
brY *= f;
blX *= f;
blY *= f;
}
return {
x: {
'tl': tlX,
'tr': trX,
'br': brX,
'bl': blX
},
y: {
'tl': tlY,
'tr': trY,
'br': brY,
'bl': blY
}
}
},
/**
* Return the VML path string for the element's background box, with corners rounded.
* @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of
* pixels to shrink the box path inward from the element's four sides.
* @param {number=} mult If specified, all coordinates will be multiplied by this number
* @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
* from this renderer's borderRadiusInfo object.
* @return {string} the VML path
*/
getBoxPath: function( shrink, mult, radii ) {
mult = mult || 1;
var r, str,
bounds = this.boundsInfo.getBounds(),
w = bounds.w * mult,
h = bounds.h * mult,
radInfo = this.styleInfos.borderRadiusInfo,
floor = Math.floor, ceil = Math.ceil,
shrinkT = shrink ? shrink.t * mult : 0,
shrinkR = shrink ? shrink.r * mult : 0,
shrinkB = shrink ? shrink.b * mult : 0,
shrinkL = shrink ? shrink.l * mult : 0,
tlX, tlY, trX, trY, brX, brY, blX, blY;
if( radii || radInfo.isActive() ) {
r = this.getRadiiPixels( radii || radInfo.getProps() );
tlX = r.x['tl'] * mult;
tlY = r.y['tl'] * mult;
trX = r.x['tr'] * mult;
trY = r.y['tr'] * mult;
brX = r.x['br'] * mult;
brY = r.y['br'] * mult;
blX = r.x['bl'] * mult;
blY = r.y['bl'] * mult;
str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) +
'qy' + floor( tlX ) + ',' + floor( shrinkT ) +
'l' + ceil( w - trX ) + ',' + floor( shrinkT ) +
'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) +
'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) +
'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) +
'l' + floor( blX ) + ',' + ceil( h - shrinkB ) +
'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e';
} else {
// simplified path for non-rounded box
str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) +
'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) +
'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) +
'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) +
'xe';
}
return str;
},
/**
* Get the container element for the shapes, creating it if necessary.
*/
getBox: function() {
var box = this.parent.getLayer( this.boxZIndex ), s;
if( !box ) {
box = doc.createElement( this.boxName );
s = box.style;
s.position = 'absolute';
s.top = s.left = 0;
this.parent.addLayer( this.boxZIndex, box );
}
return box;
},
/**
* Hide the actual border of the element. In IE7 and up we can just set its color to transparent;
* however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements
* like form buttons require removing the border width altogether, so for those we increase the padding
* by the border size.
*/
hideBorder: function() {
var el = this.targetElement,
cs = el.currentStyle,
rs = el.runtimeStyle,
tag = el.tagName,
isIE6 = PIE.ieVersion === 6,
sides, side, i;
if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) ||
tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) {
rs.borderWidth = '';
sides = this.styleInfos.borderInfo.sides;
for( i = sides.length; i--; ) {
side = sides[ i ];
rs[ 'padding' + side ] = '';
rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) +
( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) +
( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away
}
rs.borderWidth = 0;
}
else if( isIE6 ) {
// Wrap all the element's children in a custom element, set the element to visiblity:hidden,
// and set the wrapper element to visiblity:visible. This hides the outer element's decorations
// (background and border) but displays all the contents.
// TODO find a better way to do this that doesn't mess up the DOM parent-child relationship,
// as this can interfere with other author scripts which add/modify/delete children. Also, this
// won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into
// using a compositor filter or some other filter which masks the border.
if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) {
var cont = doc.createElement( 'ie6-mask' ),
s = cont.style, child;
s.visibility = 'visible';
s.zoom = 1;
while( child = el.firstChild ) {
cont.appendChild( child );
}
el.appendChild( cont );
rs.visibility = 'hidden';
}
}
else {
rs.borderColor = 'transparent';
}
},
unhideBorder: function() {
},
/**
* Destroy the rendered objects. This is a base implementation which handles common renderer
* structures, but individual renderers may override as necessary.
*/
destroy: function() {
this.parent.removeLayer( this.boxZIndex );
delete this._shapes;
delete this._layers;
}
};
/**
* Root renderer; creates the outermost container element and handles keeping it aligned
* with the target element's size and position.
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.RootRenderer = PIE.RendererBase.newRenderer( {
isActive: function() {
var children = this.childRenderers;
for( var i in children ) {
if( children.hasOwnProperty( i ) && children[ i ].isActive() ) {
return true;
}
}
return false;
},
needsUpdate: function() {
return this.styleInfos.visibilityInfo.changed();
},
updatePos: function() {
if( this.isActive() ) {
var el = this.getPositioningElement(),
par = el,
docEl,
parRect,
tgtCS = el.currentStyle,
tgtPos = tgtCS.position,
boxPos,
s = this.getBox().style, cs,
x = 0, y = 0,
elBounds = this.boundsInfo.getBounds(),
logicalZoomRatio = elBounds.logicalZoomRatio;
if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) {
x = elBounds.x * logicalZoomRatio;
y = elBounds.y * logicalZoomRatio;
boxPos = tgtPos;
} else {
// Get the element's offsets from its nearest positioned ancestor. Uses
// getBoundingClientRect for accuracy and speed.
do {
par = par.offsetParent;
} while( par && ( par.currentStyle.position === 'static' ) );
if( par ) {
parRect = par.getBoundingClientRect();
cs = par.currentStyle;
x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 );
y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 );
} else {
docEl = doc.documentElement;
x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio;
y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio;
}
boxPos = 'absolute';
}
s.position = boxPos;
s.left = x;
s.top = y;
s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex;
this.isPositioned = true;
}
},
updateSize: PIE.emptyFn,
updateVisibility: function() {
var vis = this.styleInfos.visibilityInfo.getProps();
this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none';
},
updateProps: function() {
if( this.isActive() ) {
this.updateVisibility();
} else {
this.destroy();
}
},
getPositioningElement: function() {
var el = this.targetElement;
return el.tagName in PIE.tableCellTags ? el.offsetParent : el;
},
getBox: function() {
var box = this._box, el;
if( !box ) {
el = this.getPositioningElement();
box = this._box = doc.createElement( 'css3-container' );
box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments
this.updateVisibility();
el.parentNode.insertBefore( box, el );
}
return box;
},
finishUpdate: PIE.emptyFn,
destroy: function() {
var box = this._box, par;
if( box && ( par = box.parentNode ) ) {
par.removeChild( box );
}
delete this._box;
delete this._layers;
}
} );
/**
* Renderer for element backgrounds.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 2,
boxName: 'background',
needsUpdate: function() {
var si = this.styleInfos;
return si.backgroundInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderImageInfo.isActive() ||
si.borderRadiusInfo.isActive() ||
si.backgroundInfo.isActive() ||
( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset );
},
/**
* Draw the shapes
*/
draw: function() {
var bounds = this.boundsInfo.getBounds();
if( bounds.w && bounds.h ) {
this.drawBgColor();
this.drawBgImages();
}
},
/**
* Draw the background color shape
*/
drawBgColor: function() {
var props = this.styleInfos.backgroundInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
el = this.targetElement,
color = props && props.color,
shape, w, h, s, alpha;
if( color && color.alpha() > 0 ) {
this.hideBackground();
shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 );
w = bounds.w;
h = bounds.h;
shape.stroked = false;
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = this.getBoxPath( null, 2 );
s = shape.style;
s.width = w;
s.height = h;
shape.fill.color = color.colorValue( el );
alpha = color.alpha();
if( alpha < 1 ) {
shape.fill.opacity = alpha;
}
} else {
this.deleteShape( 'bgColor' );
}
},
/**
* Draw all the background image layers
*/
drawBgImages: function() {
var props = this.styleInfos.backgroundInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
images = props && props.bgImages,
img, shape, w, h, s, i;
if( images ) {
this.hideBackground();
w = bounds.w;
h = bounds.h;
i = images.length;
while( i-- ) {
img = images[i];
shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 );
shape.stroked = false;
shape.fill.type = 'tile';
shape.fillcolor = 'none';
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = this.getBoxPath( 0, 2 );
s = shape.style;
s.width = w;
s.height = h;
if( img.imgType === 'linear-gradient' ) {
this.addLinearGradient( shape, img );
}
else {
shape.fill.src = img.imgUrl;
this.positionBgImage( shape, i );
}
}
}
// Delete any bgImage shapes previously created which weren't used above
i = images ? images.length : 0;
while( this.deleteShape( 'bgImage' + i++ ) ) {}
},
/**
* Set the position and clipping of the background image for a layer
* @param {Element} shape
* @param {number} index
*/
positionBgImage: function( shape, index ) {
var me = this;
PIE.Util.withImageSize( shape.fill.src, function( size ) {
var el = me.targetElement,
bounds = me.boundsInfo.getBounds(),
elW = bounds.w,
elH = bounds.h;
// It's possible that the element dimensions are zero now but weren't when the original
// update executed, make sure that's not the case to avoid divide-by-zero error
if( elW && elH ) {
var fill = shape.fill,
si = me.styleInfos,
border = si.borderInfo.getProps(),
bw = border && border.widths,
bwT = bw ? bw['t'].pixels( el ) : 0,
bwR = bw ? bw['r'].pixels( el ) : 0,
bwB = bw ? bw['b'].pixels( el ) : 0,
bwL = bw ? bw['l'].pixels( el ) : 0,
bg = si.backgroundInfo.getProps().bgImages[ index ],
bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 },
repeat = bg.imgRepeat,
pxX, pxY,
clipT = 0, clipL = 0,
clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel)
clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region
// Positioning - find the pixel offset from the top/left and convert to a ratio
// The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is
// needed to fix antialiasing but makes the bg image fuzzy.
pxX = Math.round( bgPos.x ) + bwL + 0.5;
pxY = Math.round( bgPos.y ) + bwT + 0.5;
fill.position = ( pxX / elW ) + ',' + ( pxY / elH );
// Set the size of the image. We have to actually set it to px values otherwise it will not honor
// the user's browser zoom level and always display at its natural screen size.
fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird!
fill['size'] = size.w + 'px,' + size.h + 'px';
// Repeating - clip the image shape
if( repeat && repeat !== 'repeat' ) {
if( repeat === 'repeat-x' || repeat === 'no-repeat' ) {
clipT = pxY + 1;
clipB = pxY + size.h + clipAdjust;
}
if( repeat === 'repeat-y' || repeat === 'no-repeat' ) {
clipL = pxX + 1;
clipR = pxX + size.w + clipAdjust;
}
shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)';
}
}
} );
},
/**
* Draw the linear gradient for a gradient layer
* @param {Element} shape
* @param {Object} info The object holding the information about the gradient
*/
addLinearGradient: function( shape, info ) {
var el = this.targetElement,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
fill = shape.fill,
stops = info.stops,
stopCount = stops.length,
PI = Math.PI,
GradientUtil = PIE.GradientUtil,
perpendicularIntersect = GradientUtil.perpendicularIntersect,
distance = GradientUtil.distance,
metrics = GradientUtil.getGradientMetrics( el, w, h, info ),
angle = metrics.angle,
startX = metrics.startX,
startY = metrics.startY,
startCornerX = metrics.startCornerX,
startCornerY = metrics.startCornerY,
endCornerX = metrics.endCornerX,
endCornerY = metrics.endCornerY,
deltaX = metrics.deltaX,
deltaY = metrics.deltaY,
lineLength = metrics.lineLength,
vmlAngle, vmlGradientLength, vmlColors,
stopPx, vmlOffsetPct,
p, i, j, before, after;
// In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's
// bounding box; for example specifying a 45 deg angle actually results in a gradient
// drawn diagonally from one corner to its opposite corner, which will only appear to the
// viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas
// between the start and end points, multiply one of them by the shape's aspect ratio,
// and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly
// horizontal or vertical then we don't need to do this conversion.
vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 );
// VML angles are 180 degrees offset from CSS angles
vmlAngle += 180;
vmlAngle = vmlAngle % 360;
// Add all the stops to the VML 'colors' list, including the first and last stops.
// For each, we find its pixel offset along the gradient-line; if the offset of a stop is less
// than that of its predecessor we increase it to be equal. We then map that pixel offset to a
// percentage along the VML gradient-line, which runs from shape corner to corner.
p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY );
vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] );
vmlColors = [];
p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY );
vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100;
// Find the pixel offsets along the CSS3 gradient-line for each stop.
stopPx = [];
for( i = 0; i < stopCount; i++ ) {
stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) :
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
}
// Fill in gaps with evenly-spaced offsets
for( i = 1; i < stopCount; i++ ) {
if( stopPx[ i ] === null ) {
before = stopPx[ i - 1 ];
j = i;
do {
after = stopPx[ ++j ];
} while( after === null );
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
}
// Make sure each stop's offset is no less than the one before it
stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] );
}
// Convert to percentage along the VML gradient line and add to the VML 'colors' value
for( i = 0; i < stopCount; i++ ) {
vmlColors.push(
( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el )
);
}
// Now, finally, we're ready to render the gradient fill. Set the start and end colors to
// the first and last stop colors; this just sets outer bounds for the gradient.
fill['angle'] = vmlAngle;
fill['type'] = 'gradient';
fill['method'] = 'sigma';
fill['color'] = stops[0].color.colorValue( el );
fill['color2'] = stops[stopCount - 1].color.colorValue( el );
if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?)
fill['colors'].value = vmlColors.join( ',' );
} else {
fill['colors'] = vmlColors.join( ',' );
}
},
/**
* Hide the actual background image and color of the element.
*/
hideBackground: function() {
var rs = this.targetElement.runtimeStyle;
rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events
rs.backgroundColor = 'transparent';
},
destroy: function() {
PIE.RendererBase.destroy.call( this );
var rs = this.targetElement.runtimeStyle;
rs.backgroundImage = rs.backgroundColor = '';
}
} );
/**
* Renderer for element borders.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BorderRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 4,
boxName: 'border',
needsUpdate: function() {
var si = this.styleInfos;
return si.borderInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderRadiusInfo.isActive() &&
!si.borderImageInfo.isActive() &&
si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive
},
/**
* Draw the border shape(s)
*/
draw: function() {
var el = this.targetElement,
props = this.styleInfos.borderInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
shape, stroke, s,
segments, seg, i, len;
if( props ) {
this.hideBorder();
segments = this.getBorderSegments( 2 );
for( i = 0, len = segments.length; i < len; i++) {
seg = segments[i];
shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() );
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = seg.path;
s = shape.style;
s.width = w;
s.height = h;
shape.filled = !!seg.fill;
shape.stroked = !!seg.stroke;
if( seg.stroke ) {
stroke = shape.stroke;
stroke['weight'] = seg.weight + 'px';
stroke.color = seg.color.colorValue( el );
stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid';
stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single';
} else {
shape.fill.color = seg.fill.colorValue( el );
}
}
// remove any previously-created border shapes which didn't get used above
while( this.deleteShape( 'borderPiece' + i++ ) ) {}
}
},
/**
* Get the VML path definitions for the border segment(s).
* @param {number=} mult If specified, all coordinates will be multiplied by this number
* @return {Array.<string>}
*/
getBorderSegments: function( mult ) {
var el = this.targetElement,
bounds, elW, elH,
borderInfo = this.styleInfos.borderInfo,
segments = [],
floor, ceil, wT, wR, wB, wL,
round = Math.round,
borderProps, radiusInfo, radii, widths, styles, colors;
if( borderInfo.isActive() ) {
borderProps = borderInfo.getProps();
widths = borderProps.widths;
styles = borderProps.styles;
colors = borderProps.colors;
if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) {
if( colors['t'].alpha() > 0 ) {
// shortcut for identical border on all sides - only need 1 stroked shape
wT = widths['t'].pixels( el ); //thickness
wR = wT / 2; //shrink
segments.push( {
path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ),
stroke: styles['t'],
color: colors['t'],
weight: wT
} );
}
}
else {
mult = mult || 1;
bounds = this.boundsInfo.getBounds();
elW = bounds.w;
elH = bounds.h;
wT = round( widths['t'].pixels( el ) );
wR = round( widths['r'].pixels( el ) );
wB = round( widths['b'].pixels( el ) );
wL = round( widths['l'].pixels( el ) );
var pxWidths = {
't': wT,
'r': wR,
'b': wB,
'l': wL
};
radiusInfo = this.styleInfos.borderRadiusInfo;
if( radiusInfo.isActive() ) {
radii = this.getRadiiPixels( radiusInfo.getProps() );
}
floor = Math.floor;
ceil = Math.ceil;
function radius( xy, corner ) {
return radii ? radii[ xy ][ corner ] : 0;
}
function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) {
var rx = radius( 'x', corner),
ry = radius( 'y', corner),
deg = 65535,
isRight = corner.charAt( 1 ) === 'r',
isBottom = corner.charAt( 0 ) === 'b';
return ( rx > 0 && ry > 0 ) ?
( doMove ? 'al' : 'ae' ) +
( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x
( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y
( floor( rx ) - shrinkX ) * mult + ',' + // width
( floor( ry ) - shrinkY ) * mult + ',' + // height
( startAngle * deg ) + ',' + // start angle
( 45 * deg * ( ccw ? 1 : -1 ) // angle change
) : (
( doMove ? 'm' : 'l' ) +
( isRight ? elW - shrinkX : shrinkX ) * mult + ',' +
( isBottom ? elH - shrinkY : shrinkY ) * mult
);
}
function line( side, shrink, ccw, doMove ) {
var
start = (
side === 't' ?
floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult :
side === 'r' ?
ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult :
side === 'b' ?
ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult :
// side === 'l' ?
floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult
),
end = (
side === 't' ?
ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult :
side === 'r' ?
ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult :
side === 'b' ?
floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult :
// side === 'l' ?
floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult
);
return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start :
( doMove ? 'm' + start : '' ) + 'l' + end;
}
function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) {
var vert = side === 'l' || side === 'r',
sideW = pxWidths[ side ],
beforeX, beforeY, afterX, afterY;
if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) {
beforeX = pxWidths[ vert ? side : sideBefore ];
beforeY = pxWidths[ vert ? sideBefore : side ];
afterX = pxWidths[ vert ? side : sideAfter ];
afterY = pxWidths[ vert ? sideAfter : side ];
if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) {
segments.push( {
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
fill: colors[ side ]
} );
segments.push( {
path: line( side, sideW / 2, 0, 1 ),
stroke: styles[ side ],
weight: sideW,
color: colors[ side ]
} );
segments.push( {
path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) +
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ),
fill: colors[ side ]
} );
}
else {
segments.push( {
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
line( side, sideW, 0, 0 ) +
curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) +
( styles[ side ] === 'double' && sideW > 2 ?
curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) +
line( side, ceil( sideW / 3 * 2 ), 1, 0 ) +
curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) +
'x ' +
curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) +
line( side, floor( sideW / 3 ), 1, 0 ) +
curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 )
: '' ) +
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) +
line( side, 0, 1, 0 ) +
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
fill: colors[ side ]
} );
}
}
}
addSide( 't', 'l', 'r', 'tl', 'tr', 90 );
addSide( 'r', 't', 'b', 'tr', 'br', 0 );
addSide( 'b', 'r', 'l', 'br', 'bl', -90 );
addSide( 'l', 'b', 't', 'bl', 'tl', -180 );
}
}
return segments;
},
destroy: function() {
var me = this;
if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) {
me.targetElement.runtimeStyle.borderColor = '';
}
PIE.RendererBase.destroy.call( me );
}
} );
/**
* Renderer for border-image
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 5,
pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ],
needsUpdate: function() {
return this.styleInfos.borderImageInfo.changed();
},
isActive: function() {
return this.styleInfos.borderImageInfo.isActive();
},
draw: function() {
this.getBox(); //make sure pieces are created
var props = this.styleInfos.borderImageInfo.getProps(),
borderProps = this.styleInfos.borderInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
el = this.targetElement,
pieces = this.pieces;
PIE.Util.withImageSize( props.src, function( imgSize ) {
var elW = bounds.w,
elH = bounds.h,
zero = PIE.getLength( '0' ),
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
widthT = widths['t'].pixels( el ),
widthR = widths['r'].pixels( el ),
widthB = widths['b'].pixels( el ),
widthL = widths['l'].pixels( el ),
slices = props.slice,
sliceT = slices['t'].pixels( el ),
sliceR = slices['r'].pixels( el ),
sliceB = slices['b'].pixels( el ),
sliceL = slices['l'].pixels( el );
// Piece positions and sizes
function setSizeAndPos( piece, w, h, x, y ) {
var s = pieces[piece].style,
max = Math.max;
s.width = max(w, 0);
s.height = max(h, 0);
s.left = x;
s.top = y;
}
setSizeAndPos( 'tl', widthL, widthT, 0, 0 );
setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 );
setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 );
setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT );
setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB );
setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB );
setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB );
setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT );
setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT );
// image croppings
function setCrops( sides, crop, val ) {
for( var i=0, len=sides.length; i < len; i++ ) {
pieces[ sides[i] ]['imagedata'][ crop ] = val;
}
}
// corners
setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h );
setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w );
setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h );
setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w );
// edges and center
// TODO right now this treats everything like 'stretch', need to support other schemes
//if( props.repeat.v === 'stretch' ) {
setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h );
setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h );
//}
//if( props.repeat.h === 'stretch' ) {
setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w );
setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w );
//}
// center fill
pieces['c'].style.display = props.fill ? '' : 'none';
}, this );
},
getBox: function() {
var box = this.parent.getLayer( this.boxZIndex ),
s, piece, i,
pieceNames = this.pieceNames,
len = pieceNames.length;
if( !box ) {
box = doc.createElement( 'border-image' );
s = box.style;
s.position = 'absolute';
this.pieces = {};
for( i = 0; i < len; i++ ) {
piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' );
piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) );
s = piece.style;
s['behavior'] = 'url(#default#VML)';
s.position = "absolute";
s.top = s.left = 0;
piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src;
piece.stroked = false;
piece.filled = false;
box.appendChild( piece );
}
this.parent.addLayer( this.boxZIndex, box );
}
return box;
},
prepareUpdate: function() {
if (this.isActive()) {
var me = this,
el = me.targetElement,
rs = el.runtimeStyle,
widths = me.styleInfos.borderImageInfo.getProps().widths;
// Force border-style to solid so it doesn't collapse
rs.borderStyle = 'solid';
// If widths specified in border-image shorthand, override border-width
// NOTE px units needed here as this gets used by the IE9 renderer too
if ( widths ) {
rs.borderTopWidth = widths['t'].pixels( el ) + 'px';
rs.borderRightWidth = widths['r'].pixels( el ) + 'px';
rs.borderBottomWidth = widths['b'].pixels( el ) + 'px';
rs.borderLeftWidth = widths['l'].pixels( el ) + 'px';
}
// Make the border transparent
me.hideBorder();
}
},
destroy: function() {
var me = this,
rs = me.targetElement.runtimeStyle;
rs.borderStyle = '';
if (me.finalized || !me.styleInfos.borderInfo.isActive()) {
rs.borderColor = rs.borderWidth = '';
}
PIE.RendererBase.destroy.call( this );
}
} );
/**
* Renderer for outset box-shadows
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 1,
boxName: 'outset-box-shadow',
needsUpdate: function() {
var si = this.styleInfos;
return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var boxShadowInfo = this.styleInfos.boxShadowInfo;
return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0];
},
draw: function() {
var me = this,
el = this.targetElement,
box = this.getBox(),
styleInfos = this.styleInfos,
shadowInfos = styleInfos.boxShadowInfo.getProps().outset,
radii = styleInfos.borderRadiusInfo.getProps(),
len = shadowInfos.length,
i = len, j,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px
corners = [ 'tl', 'tr', 'br', 'bl' ], corner,
shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path,
totalW, totalH, focusX, focusY, isBottom, isRight;
function getShadowShape( index, corner, xOff, yOff, color, blur, path ) {
var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ),
fill = shape.fill;
// Position and size
shape['coordsize'] = w * 2 + ',' + h * 2;
shape['coordorigin'] = '1,1';
// Color and opacity
shape['stroked'] = false;
shape['filled'] = true;
fill.color = color.colorValue( el );
if( blur ) {
fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?!
fill['color2'] = fill.color;
fill['opacity'] = 0;
}
// Path
shape.path = path;
// This needs to go last for some reason, to prevent rendering at incorrect size
ss = shape.style;
ss.left = xOff;
ss.top = yOff;
ss.width = w;
ss.height = h;
return shape;
}
while( i-- ) {
shadowInfo = shadowInfos[ i ];
xOff = shadowInfo.xOffset.pixels( el );
yOff = shadowInfo.yOffset.pixels( el );
spread = shadowInfo.spread.pixels( el );
blur = shadowInfo.blur.pixels( el );
color = shadowInfo.color;
// Shape path
shrink = -spread - blur;
if( !radii && blur ) {
// If blurring, use a non-null border radius info object so that getBoxPath will
// round the corners of the expanded shadow shape rather than squaring them off.
radii = PIE.BorderRadiusStyleInfo.ALL_ZERO;
}
path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii );
if( blur ) {
totalW = ( spread + blur ) * 2 + w;
totalH = ( spread + blur ) * 2 + h;
focusX = totalW ? blur * 2 / totalW : 0;
focusY = totalH ? blur * 2 / totalH : 0;
if( blur - spread > w / 2 || blur - spread > h / 2 ) {
// If the blur is larger than half the element's narrowest dimension, we cannot do
// this with a single shape gradient, because its focussize would have to be less than
// zero which results in ugly artifacts. Instead we create four shapes, each with its
// gradient focus past center, and then clip them so each only shows the quadrant
// opposite the focus.
for( j = 4; j--; ) {
corner = corners[j];
isBottom = corner.charAt( 0 ) === 'b';
isRight = corner.charAt( 1 ) === 'r';
shape = getShadowShape( i, corner, xOff, yOff, color, blur, path );
fill = shape.fill;
fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' +
( isBottom ? 1 - focusY : focusY );
fill['focussize'] = '0,0';
// Clip to show only the appropriate quadrant. Add 1px to the top/left clip values
// in IE8 to prevent a bug where IE8 displays one pixel outside the clip region.
shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' +
( isRight ? totalW : totalW / 2 ) + 'px,' +
( isBottom ? totalH : totalH / 2 ) + 'px,' +
( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)';
}
} else {
// TODO delete old quadrant shapes if resizing expands past the barrier
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
fill = shape.fill;
fill['focusposition'] = focusX + ',' + focusY;
fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 );
}
} else {
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
alpha = color.alpha();
if( alpha < 1 ) {
// shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')';
// ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')';
shape.fill.opacity = alpha;
}
}
}
}
} );
/**
* Renderer for re-rendering img elements using VML. Kicks in if the img has
* a border-radius applied, or if the -pie-png-fix flag is set.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.ImgRenderer = PIE.RendererBase.newRenderer( {
boxZIndex: 6,
boxName: 'imgEl',
needsUpdate: function() {
var si = this.styleInfos;
return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix();
},
draw: function() {
this._lastSrc = src;
this.hideActualImg();
var shape = this.getShape( 'img', 'fill', this.getBox() ),
fill = shape.fill,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
borderProps = this.styleInfos.borderInfo.getProps(),
borderWidths = borderProps && borderProps.widths,
el = this.targetElement,
src = el.src,
round = Math.round,
cs = el.currentStyle,
getLength = PIE.getLength,
s, zero;
// In IE6, the BorderRenderer will have hidden the border by moving the border-width to
// the padding; therefore we want to pretend the borders have no width so they aren't doubled
// when adding in the current padding value below.
if( !borderWidths || PIE.ieVersion < 7 ) {
zero = PIE.getLength( '0' );
borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero };
}
shape.stroked = false;
fill.type = 'frame';
fill.src = src;
fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0);
shape.coordsize = w * 2 + ',' + h * 2;
shape.coordorigin = '1,1';
shape.path = this.getBoxPath( {
t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ),
r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ),
b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ),
l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) )
}, 2 );
s = shape.style;
s.width = w;
s.height = h;
},
hideActualImg: function() {
this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)';
},
destroy: function() {
PIE.RendererBase.destroy.call( this );
this.targetElement.runtimeStyle.filter = '';
}
} );
/**
* Root renderer for IE9; manages the rendering layers in the element's background
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( {
updatePos: PIE.emptyFn,
updateSize: PIE.emptyFn,
updateVisibility: PIE.emptyFn,
updateProps: PIE.emptyFn,
outerCommasRE: /^,+|,+$/g,
innerCommasRE: /,+/g,
setBackgroundLayer: function(zIndex, bg) {
var me = this,
bgLayers = me._bgLayers || ( me._bgLayers = [] ),
undef;
bgLayers[zIndex] = bg || undef;
},
finishUpdate: function() {
var me = this,
bgLayers = me._bgLayers,
bg;
if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) {
me._lastBg = me.targetElement.runtimeStyle.background = bg;
}
},
destroy: function() {
this.targetElement.runtimeStyle.background = '';
delete this._bgLayers;
}
} );
/**
* Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients
* to an equivalent SVG data URI.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( {
bgLayerZIndex: 1,
needsUpdate: function() {
var si = this.styleInfos;
return si.backgroundInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.backgroundInfo.isActive() || si.borderImageInfo.isActive();
},
draw: function() {
var me = this,
props = me.styleInfos.backgroundInfo.getProps(),
bg, images, i = 0, img, bgAreaSize, bgSize;
if ( props ) {
bg = [];
images = props.bgImages;
if ( images ) {
while( img = images[ i++ ] ) {
if (img.imgType === 'linear-gradient' ) {
bgAreaSize = me.getBgAreaSize( img.bgOrigin );
bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels(
me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h
),
bg.push(
'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' +
me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' +
( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' )
);
} else {
bg.push( img.origString );
}
}
}
if ( props.color ) {
bg.push( props.color.val );
}
me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(','));
}
},
bgPositionToString: function( bgPosition ) {
return bgPosition ? bgPosition.tokens.map(function(token) {
return token.tokenValue;
}).join(' ') : '0 0';
},
getBgAreaSize: function( bgOrigin ) {
var me = this,
el = me.targetElement,
bounds = me.boundsInfo.getBounds(),
elW = bounds.w,
elH = bounds.h,
w = elW,
h = elH,
borders, getLength, cs;
if( bgOrigin !== 'border-box' ) {
borders = me.styleInfos.borderInfo.getProps();
if( borders && ( borders = borders.widths ) ) {
w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
}
}
if ( bgOrigin === 'content-box' ) {
getLength = PIE.getLength;
cs = el.currentStyle;
w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el );
h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el );
}
return { w: w, h: h };
},
getGradientSvg: function( info, bgWidth, bgHeight ) {
var el = this.targetElement,
stopsInfo = info.stops,
stopCount = stopsInfo.length,
metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ),
startX = metrics.startX,
startY = metrics.startY,
endX = metrics.endX,
endY = metrics.endY,
lineLength = metrics.lineLength,
stopPx,
i, j, before, after,
svg;
// Find the pixel offsets along the CSS3 gradient-line for each stop.
stopPx = [];
for( i = 0; i < stopCount; i++ ) {
stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) :
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
}
// Fill in gaps with evenly-spaced offsets
for( i = 1; i < stopCount; i++ ) {
if( stopPx[ i ] === null ) {
before = stopPx[ i - 1 ];
j = i;
do {
after = stopPx[ ++j ];
} while( after === null );
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
}
}
svg = [
'<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' +
'<defs>' +
'<linearGradient id="g" gradientUnits="userSpaceOnUse"' +
' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">'
];
// Convert to percentage along the SVG gradient line and add to the stops list
for( i = 0; i < stopCount; i++ ) {
svg.push(
'<stop offset="' + ( stopPx[ i ] / lineLength ) +
'" stop-color="' + stopsInfo[i].color.colorValue( el ) +
'" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>'
);
}
svg.push(
'</linearGradient>' +
'</defs>' +
'<rect width="100%" height="100%" fill="url(#g)"/>' +
'</svg>'
);
return svg.join( '' );
},
destroy: function() {
this.parent.setBackgroundLayer( this.bgLayerZIndex );
}
} );
/**
* Renderer for border-image
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( {
REPEAT: 'repeat',
STRETCH: 'stretch',
ROUND: 'round',
bgLayerZIndex: 0,
needsUpdate: function() {
return this.styleInfos.borderImageInfo.changed();
},
isActive: function() {
return this.styleInfos.borderImageInfo.isActive();
},
draw: function() {
var me = this,
props = me.styleInfos.borderImageInfo.getProps(),
borderProps = me.styleInfos.borderInfo.getProps(),
bounds = me.boundsInfo.getBounds(),
repeat = props.repeat,
repeatH = repeat.h,
repeatV = repeat.v,
el = me.targetElement,
isAsync = 0;
PIE.Util.withImageSize( props.src, function( imgSize ) {
var elW = bounds.w,
elH = bounds.h,
imgW = imgSize.w,
imgH = imgSize.h,
// The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange
// security exception (perhaps due to cross-origin policy within data URIs?) Therefore we
// work around this by converting the image data into a data URI itself using a transient
// canvas. This unfortunately requires the border-image src to be within the same domain,
// which isn't a limitation in true border-image, so we need to try and find a better fix.
imgSrc = me.imageToDataURI( props.src, imgW, imgH ),
REPEAT = me.REPEAT,
STRETCH = me.STRETCH,
ROUND = me.ROUND,
ceil = Math.ceil,
zero = PIE.getLength( '0' ),
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
widthT = widths['t'].pixels( el ),
widthR = widths['r'].pixels( el ),
widthB = widths['b'].pixels( el ),
widthL = widths['l'].pixels( el ),
slices = props.slice,
sliceT = slices['t'].pixels( el ),
sliceR = slices['r'].pixels( el ),
sliceB = slices['b'].pixels( el ),
sliceL = slices['l'].pixels( el ),
centerW = elW - widthL - widthR,
middleH = elH - widthT - widthB,
imgCenterW = imgW - sliceL - sliceR,
imgMiddleH = imgH - sliceT - sliceB,
// Determine the size of each tile - 'round' is handled below
tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT,
tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR,
tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB,
tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL,
svg,
patterns = [],
rects = [],
i = 0;
// For 'round', subtract from each tile's size enough so that they fill the space a whole number of times
if (repeatH === ROUND) {
tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT);
tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB);
}
if (repeatV === ROUND) {
tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR);
tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL);
}
// Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched
// or repeated as the fill of a rect of appropriate size.
svg = [
'<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
];
function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) {
patterns.push(
'<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' +
'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' +
'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' +
'width="' + tileW + '" height="' + tileH + '">' +
'<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' +
'<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' +
'</svg>' +
'</pattern>'
);
rects.push(
'<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />'
);
i++;
}
addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left
addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center
addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right
addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left
if ( props.fill ) { // center fill
addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH,
tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH );
}
addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right
addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left
addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center
addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right
svg.push(
'<defs>' +
patterns.join('\n') +
'</defs>' +
rects.join('\n') +
'</svg>'
);
me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' );
// If the border-image's src wasn't immediately available, the SVG for its background layer
// will have been created asynchronously after the main element's update has finished; we'll
// therefore need to force the root renderer to sync to the final background once finished.
if( isAsync ) {
me.parent.finishUpdate();
}
}, me );
isAsync = 1;
},
/**
* Convert a given image to a data URI
*/
imageToDataURI: (function() {
var uris = {};
return function( src, width, height ) {
var uri = uris[ src ],
image, canvas;
if ( !uri ) {
image = new Image();
canvas = doc.createElement( 'canvas' );
image.src = src;
canvas.width = width;
canvas.height = height;
canvas.getContext( '2d' ).drawImage( image, 0, 0 );
uri = uris[ src ] = canvas.toDataURL();
}
return uri;
}
})(),
prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate,
destroy: function() {
var me = this,
rs = me.targetElement.runtimeStyle;
me.parent.setBackgroundLayer( me.bgLayerZIndex );
rs.borderColor = rs.borderStyle = rs.borderWidth = '';
}
} );
PIE.Element = (function() {
var wrappers = {},
lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
pollCssProp = PIE.CSS_PREFIX + 'poll',
trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
hoverClass = PIE.CLASS_PREFIX + 'hover',
activeClass = PIE.CLASS_PREFIX + 'active',
focusClass = PIE.CLASS_PREFIX + 'focus',
firstChildClass = PIE.CLASS_PREFIX + 'first-child',
ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
classNameRegExes = {},
dummyArray = [];
function addClass( el, className ) {
el.className += ' ' + className;
}
function removeClass( el, className ) {
var re = classNameRegExes[ className ] ||
( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
el.className = el.className.replace( re, '' );
}
function delayAddClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
addClass( el, classes[ i ] );
}
}
}, 0 );
}
function delayRemoveClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
removeClass( el, classes[ i ] );
}
}
}, 0 );
}
function Element( el ) {
var renderers,
rootRenderer,
boundsInfo = new PIE.BoundsInfo( el ),
styleInfos,
styleInfosArr,
initializing,
initialized,
eventsAttached,
eventListeners = [],
delayed,
destroyed,
poll;
/**
* Initialize PIE for this element.
*/
function init() {
if( !initialized ) {
var docEl,
bounds,
ieDocMode = PIE.ieDocMode,
cs = el.currentStyle,
lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false',
childRenderers;
// Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
poll = cs.getAttribute( pollCssProp );
poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
// Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
// after load, but make sure it only gets called the first time through to avoid recursive calls to init().
if( !initializing ) {
initializing = 1;
el.runtimeStyle.zoom = 1;
initFirstChildPseudoClass();
}
boundsInfo.lock();
// If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
if( !delayed ) {
delayed = 1;
PIE.OnScroll.observe( init );
}
} else {
initialized = 1;
delayed = initializing = 0;
PIE.OnScroll.unobserve( init );
// Create the style infos and renderers
if ( ieDocMode === 9 ) {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderImageInfo
];
rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
} else {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
visibilityInfo: new PIE.VisibilityStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderInfo,
styleInfos.borderImageInfo,
styleInfos.borderRadiusInfo,
styleInfos.boxShadowInfo,
styleInfos.visibilityInfo
];
rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
//new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
if( el.tagName === 'IMG' ) {
childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
}
rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
}
renderers = [ rootRenderer ].concat( childRenderers );
// Add property change listeners to ancestors if requested
initAncestorEventListeners();
// Add to list of polled elements in IE8
if( poll ) {
PIE.Heartbeat.observe( update );
PIE.Heartbeat.run();
}
// Trigger rendering
update( 1 );
}
if( !eventsAttached ) {
eventsAttached = 1;
if( ieDocMode < 9 ) {
addListener( el, 'onmove', handleMoveOrResize );
}
addListener( el, 'onresize', handleMoveOrResize );
addListener( el, 'onpropertychange', propChanged );
if( trackHover ) {
addListener( el, 'onmouseenter', mouseEntered );
}
if( trackHover || trackActive ) {
addListener( el, 'onmouseleave', mouseLeft );
}
if( trackActive ) {
addListener( el, 'onmousedown', mousePressed );
}
if( el.tagName in PIE.focusableElements ) {
addListener( el, 'onfocus', focused );
addListener( el, 'onblur', blurred );
}
PIE.OnResize.observe( handleMoveOrResize );
PIE.OnUnload.observe( removeEventListeners );
}
boundsInfo.unlock();
}
}
/**
* Event handler for onmove and onresize events. Invokes update() only if the element's
* bounds have previously been calculated, to prevent multiple runs during page load when
* the element has no initial CSS3 properties.
*/
function handleMoveOrResize() {
if( boundsInfo && boundsInfo.hasBeenQueried() ) {
update();
}
}
/**
* Update position and/or size as necessary. Both move and resize events call
* this rather than the updatePos/Size functions because sometimes, particularly
* during page load, one will fire but the other won't.
*/
function update( force ) {
if( !destroyed ) {
if( initialized ) {
var i, len = renderers.length;
lockAll();
for( i = 0; i < len; i++ ) {
renderers[i].prepareUpdate();
}
if( force || boundsInfo.positionChanged() ) {
/* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting
position changes may not always be accurate; it's possible that
an element will actually move relative to its positioning parent, but its position
relative to the viewport will stay the same. Need to come up with a better way to
track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
but that is a more expensive operation since it does some DOM walking, and we want this
check to be as fast as possible. */
for( i = 0; i < len; i++ ) {
renderers[i].updatePos();
}
}
if( force || boundsInfo.sizeChanged() ) {
for( i = 0; i < len; i++ ) {
renderers[i].updateSize();
}
}
rootRenderer.finishUpdate();
unlockAll();
}
else if( !initializing ) {
init();
}
}
}
/**
* Handle property changes to trigger update when appropriate.
*/
function propChanged() {
var i, len = renderers.length,
renderer,
e = event;
// Some elements like <table> fire onpropertychange events for old-school background properties
// ('background', 'bgColor') when runtimeStyle background properties are changed, which
// results in an infinite loop; therefore we filter out those property names. Also, 'display'
// is ignored because size calculations don't work correctly immediately when its onpropertychange
// event fires, and because it will trigger an onresize event anyway.
if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) {
if( initialized ) {
lockAll();
for( i = 0; i < len; i++ ) {
renderers[i].prepareUpdate();
}
for( i = 0; i < len; i++ ) {
renderer = renderers[i];
// Make sure position is synced if the element hasn't already been rendered.
// TODO this feels sloppy - look into merging propChanged and update functions
if( !renderer.isPositioned ) {
renderer.updatePos();
}
if( renderer.needsUpdate() ) {
renderer.updateProps();
}
}
rootRenderer.finishUpdate();
unlockAll();
}
else if( !initializing ) {
init();
}
}
}
/**
* Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
* hover styles to non-link elements, and to trigger a propertychange update.
*/
function mouseEntered() {
//must delay this because the mouseenter event fires before the :hover styles are added.
delayAddClass( el, hoverClass );
}
/**
* Handle mouseleave events
*/
function mouseLeft() {
//must delay this because the mouseleave event fires before the :hover styles are removed.
delayRemoveClass( el, hoverClass, activeClass );
}
/**
* Handle mousedown events. Adds a custom class to the element to allow IE6 to add
* active styles to non-link elements, and to trigger a propertychange update.
*/
function mousePressed() {
//must delay this because the mousedown event fires before the :active styles are added.
delayAddClass( el, activeClass );
// listen for mouseups on the document; can't just be on the element because the user might
// have dragged out of the element while the mouse button was held down
PIE.OnMouseup.observe( mouseReleased );
}
/**
* Handle mouseup events
*/
function mouseReleased() {
//must delay this because the mouseup event fires before the :active styles are removed.
delayRemoveClass( el, activeClass );
PIE.OnMouseup.unobserve( mouseReleased );
}
/**
* Handle focus events. Adds a custom class to the element to trigger a propertychange update.
*/
function focused() {
//must delay this because the focus event fires before the :focus styles are added.
delayAddClass( el, focusClass );
}
/**
* Handle blur events
*/
function blurred() {
//must delay this because the blur event fires before the :focus styles are removed.
delayRemoveClass( el, focusClass );
}
/**
* Handle property changes on ancestors of the element; see initAncestorEventListeners()
* which adds these listeners as requested with the -pie-watch-ancestors CSS property.
*/
function ancestorPropChanged() {
var name = event.propertyName;
if( name === 'className' || name === 'id' ) {
propChanged();
}
}
function lockAll() {
boundsInfo.lock();
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].lock();
}
}
function unlockAll() {
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].unlock();
}
boundsInfo.unlock();
}
function addListener( targetEl, type, handler ) {
targetEl.attachEvent( type, handler );
eventListeners.push( [ targetEl, type, handler ] );
}
/**
* Remove all event listeners from the element and any monitored ancestors.
*/
function removeEventListeners() {
if (eventsAttached) {
var i = eventListeners.length,
listener;
while( i-- ) {
listener = eventListeners[ i ];
listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
}
PIE.OnUnload.unobserve( removeEventListeners );
eventsAttached = 0;
eventListeners = [];
}
}
/**
* Clean everything up when the behavior is removed from the element, or the element
* is manually destroyed.
*/
function destroy() {
if( !destroyed ) {
var i, len;
removeEventListeners();
destroyed = 1;
// destroy any active renderers
if( renderers ) {
for( i = 0, len = renderers.length; i < len; i++ ) {
renderers[i].finalized = 1;
renderers[i].destroy();
}
}
// Remove from list of polled elements in IE8
if( poll ) {
PIE.Heartbeat.unobserve( update );
}
// Stop onresize listening
PIE.OnResize.unobserve( update );
// Kill references
renderers = boundsInfo = styleInfos = styleInfosArr = el = null;
}
}
/**
* If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
* other event listeners to ancestor(s) of the element so we can pick up style changes
* based on CSS rules using descendant selectors.
*/
function initAncestorEventListeners() {
var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
i, a;
if( watch ) {
watch = parseInt( watch, 10 );
i = 0;
a = el.parentNode;
while( a && ( watch === 'NaN' || i++ < watch ) ) {
addListener( a, 'onpropertychange', ancestorPropChanged );
addListener( a, 'onmouseenter', mouseEntered );
addListener( a, 'onmouseleave', mouseLeft );
addListener( a, 'onmousedown', mousePressed );
if( a.tagName in PIE.focusableElements ) {
addListener( a, 'onfocus', focused );
addListener( a, 'onblur', blurred );
}
a = a.parentNode;
}
}
}
/**
* If the target element is a first child, add a pie_first-child class to it. This allows using
* the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
* pseudo-class selector.
*/
function initFirstChildPseudoClass() {
var tmpEl = el,
isFirst = 1;
while( tmpEl = tmpEl.previousSibling ) {
if( tmpEl.nodeType === 1 ) {
isFirst = 0;
break;
}
}
if( isFirst ) {
addClass( el, firstChildClass );
}
}
// These methods are all already bound to this instance so there's no need to wrap them
// in a closure to maintain the 'this' scope object when calling them.
this.init = init;
this.update = update;
this.destroy = destroy;
this.el = el;
}
Element.getInstance = function( el ) {
var id = PIE.Util.getUID( el );
return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
};
Element.destroy = function( el ) {
var id = PIE.Util.getUID( el ),
wrapper = wrappers[ id ];
if( wrapper ) {
wrapper.destroy();
delete wrappers[ id ];
}
};
Element.destroyAll = function() {
var els = [], wrapper;
if( wrappers ) {
for( var w in wrappers ) {
if( wrappers.hasOwnProperty( w ) ) {
wrapper = wrappers[ w ];
els.push( wrapper.el );
wrapper.destroy();
}
}
wrappers = {};
}
return els;
};
return Element;
})();
/*
* This file exposes the public API for invoking PIE.
*/
/**
* @property supportsVML
* True if the current IE browser environment has a functioning VML engine. Should be true
* in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
* attached to an element; this property may be used for debugging or by external scripts
* to perform some special action when VML support is absent.
* @type {boolean}
*/
PIE[ 'supportsVML' ] = PIE.supportsVML;
/**
* Programatically attach PIE to a single element.
* @param {Element} el
*/
PIE[ 'attach' ] = function( el ) {
if (PIE.ieDocMode < 10 && PIE.supportsVML) {
PIE.Element.getInstance( el ).init();
}
};
/**
* Programatically detach PIE from a single element.
* @param {Element} el
*/
PIE[ 'detach' ] = function( el ) {
PIE.Element.destroy( el );
};
} // if( !PIE )
})(); | JavaScript |
/*
PIE: CSS3 rendering for IE
Version 2.0beta1
http://css3pie.com
Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2.
*/
(function( win, doc ) {
var PIE = win[ 'PIE' ] || ( win[ 'PIE' ] = {} );
/**
* Simple utility for merging objects
* @param {Object} obj1 The main object into which all others will be merged
* @param {...Object} var_args Other objects which will be merged into the first, in order
*/
PIE.merge = function( obj1 ) {
var i, len, p, objN, args = arguments;
for( i = 1, len = args.length; i < len; i++ ) {
objN = args[i];
for( p in objN ) {
if( objN.hasOwnProperty( p ) ) {
obj1[ p ] = objN[ p ];
}
}
}
return obj1;
};
PIE.merge(PIE, {
// Constants
CSS_PREFIX: '-pie-',
STYLE_PREFIX: 'Pie',
CLASS_PREFIX: 'pie_',
tableCellTags: {
'TD': 1,
'TH': 1
},
/**
* Lookup table of elements which cannot take custom children.
*/
childlessElements: {
'TABLE':1,
'THEAD':1,
'TBODY':1,
'TFOOT':1,
'TR':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'OPTION':1,
'IMG':1,
'HR':1
},
/**
* Elements that can receive user focus
*/
focusableElements: {
'A':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'BUTTON':1
},
/**
* Values of the type attribute for input elements displayed as buttons
*/
inputButtonTypes: {
'submit':1,
'button':1,
'reset':1
},
emptyFn: function() {}
});
// Force the background cache to be used. No reason it shouldn't be.
try {
doc.execCommand( 'BackgroundImageCache', false, true );
} catch(e) {}
(function() {
/*
* IE version detection approach by James Padolsey, with modifications -- from
* http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
*/
var ieVersion = 4,
div = doc.createElement('div'),
all = div.getElementsByTagName('i'),
shape;
while (
div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
all[0]
) {}
PIE.ieVersion = ieVersion;
// Detect IE6
if( ieVersion === 6 ) {
// IE6 can't access properties with leading dash, but can without it.
PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
}
PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
// Detect VML support (a small number of IE installs don't have a working VML engine)
div.innerHTML = '<v:shape adj="1"/>';
shape = div.firstChild;
shape.style['behavior'] = 'url(#default#VML)';
PIE.supportsVML = (typeof shape['adj'] === "object");
})();
/**
* Utility functions
*/
(function() {
var idNum = 0,
imageSizes = {};
PIE.Util = {
/**
* Generate and return a unique ID for a given object. The generated ID is stored
* as a property of the object for future reuse. For DOM Elements, don't use this
* but use the IE-native uniqueID property instead.
* @param {Object} obj
*/
getUID: function( obj ) {
return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + idNum++ );
},
/**
* Execute a callback function, passing it the dimensions of a given image once
* they are known.
* @param {string} src The source URL of the image
* @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
* @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
*/
withImageSize: function( src, func, ctx ) {
var size = imageSizes[ src ], img, queue;
if( size ) {
// If we have a queue, add to it
if( Object.prototype.toString.call( size ) === '[object Array]' ) {
size.push( [ func, ctx ] );
}
// Already have the size cached, call func right away
else {
func.call( ctx, size );
}
} else {
queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
img = new Image();
img.onload = function() {
size = imageSizes[ src ] = { w: img.width, h: img.height };
for( var i = 0, len = queue.length; i < len; i++ ) {
queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
}
img.onload = null;
};
img.src = src;
}
}
};
})();/**
* Utility functions for handling gradients
*/
PIE.GradientUtil = {
toSideAngles: {
'top': 0,
'right': 90,
'bottom': 180,
'left': 270
},
getGradientMetrics: function( el, width, height, gradientInfo ) {
var angle = gradientInfo.angle,
toPos = gradientInfo.gradientTo,
dX, dY,
endPoint,
startX, startY,
endX, endY;
// If an angle was specified, just use it
if (angle) {
angle = angle.degrees();
}
// If a to-position was specified, find the appropriate angle for it
else if (toPos) {
// To a corner; find the adjacent corners and use the angle perpendicular to them
if (toPos[1]) {
dX = ( toPos[0] == 'top' || toPos[1] == 'top' ) ? width : -width;
dY = ( toPos[0] == 'left' || toPos[1] == 'left' ) ? -height : height;
angle = Math.atan2(dY, dX) * 180 / Math.PI;
}
// To a side; map to a vertical/horizontal angle
else {
angle = this.toSideAngles[toPos[0]];
}
}
// Neither specified; default is top to bottom
else {
angle = 180;
}
// Normalize the angle to a value between [0, 360)
while( angle < 0 ) {
angle += 360;
}
angle = angle % 360;
// Find the end point of the gradient line, extending the angle from the center point
// to where it intersects the perpendicular line passing through the nearest corner.
endPoint = PIE.GradientUtil.perpendicularIntersect(width / 2, height / 2, angle,
( angle >= 180 ? 0 : width ), ( angle < 90 || angle > 270 ? 0 : height )
);
endX = endPoint[0];
endY = endPoint[1];
startX = width - endX;
startY = height - endY;
return {
angle: angle,
endX: endX,
endY: endY,
startX: startX,
startY: startY,
lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
};
},
/**
* Find the point along a given line (defined by a starting point and an angle), at which
* that line is intersected by a perpendicular line extending through another point.
* @param x1 - x coord of the starting point
* @param y1 - y coord of the starting point
* @param angle - angle of the line extending from the starting point (in degrees)
* @param x2 - x coord of point along the perpendicular line
* @param y2 - y coord of point along the perpendicular line
* @return [ x, y ]
*/
perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
// Handle straight vertical and horizontal angles, for performance and to avoid
// divide-by-zero errors.
if( angle === 0 || angle === 180 ) {
return [ x1, y2 ];
}
else if( angle === 90 || angle === 270 ) {
return [ x2, y1 ];
}
else {
// General approach: determine the Ax+By=C formula for each line (the slope of the second
// line is the negative inverse of the first) and then solve for where both formulas have
// the same x/y values.
var a1 = Math.tan( ( angle - 90 ) * Math.PI / 180 ),
c1 = a1 * x1 - y1,
a2 = -1 / a1,
c2 = a2 * x2 - y2,
d = a2 - a1,
endX = ( c2 - c1 ) / d,
endY = ( a1 * c2 - a2 * c1 ) / d;
return [ endX, endY ];
}
},
/**
* Find the distance between two points
* @param {Number} p1x
* @param {Number} p1y
* @param {Number} p2x
* @param {Number} p2y
* @return {Number} the distance
*/
distance: function( p1x, p1y, p2x, p2y ) {
var dx = p2x - p1x,
dy = p2y - p1y;
return Math.abs(
dx === 0 ? dy :
dy === 0 ? dx :
Math.sqrt( dx * dx + dy * dy )
);
}
};/**
*
*/
PIE.Observable = function() {
/**
* List of registered observer functions
*/
this.observers = [];
/**
* Hash of function ids to their position in the observers list, for fast lookup
*/
this.indexes = {};
};
PIE.Observable.prototype = {
observe: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes,
observers = this.observers;
if( !( id in indexes ) ) {
indexes[ id ] = observers.length;
observers.push( fn );
}
},
unobserve: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes;
if( id && id in indexes ) {
delete this.observers[ indexes[ id ] ];
delete indexes[ id ];
}
},
fire: function() {
var o = this.observers,
i = o.length;
while( i-- ) {
o[ i ] && o[ i ]();
}
}
};/*
* Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
* always firing the onmove and onresize events when elements are moved or resized. We check a few
* times every second to make sure the elements have the correct position and size. See Element.js
* which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
* and false elsewhere.
*/
PIE.Heartbeat = new PIE.Observable();
PIE.Heartbeat.run = function() {
var me = this,
interval;
if( !me.running ) {
interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
(function beat() {
me.fire();
setTimeout(beat, interval);
})();
me.running = 1;
}
};
/**
* Create an observable listener for the onunload event
*/
(function() {
PIE.OnUnload = new PIE.Observable();
function handleUnload() {
PIE.OnUnload.fire();
win.detachEvent( 'onunload', handleUnload );
win[ 'PIE' ] = null;
}
win.attachEvent( 'onunload', handleUnload );
/**
* Attach an event which automatically gets detached onunload
*/
PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
target.attachEvent( name, handler );
this.observe( function() {
target.detachEvent( name, handler );
} );
};
})()/**
* Create a single observable listener for window resize events.
*/
PIE.OnResize = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( win, 'onresize', function() { PIE.OnResize.fire(); } );
/**
* Create a single observable listener for scroll events. Used for lazy loading based
* on the viewport, and for fixed position backgrounds.
*/
(function() {
PIE.OnScroll = new PIE.Observable();
function scrolled() {
PIE.OnScroll.fire();
}
PIE.OnUnload.attachManagedEvent( win, 'onscroll', scrolled );
PIE.OnResize.observe( scrolled );
})();
/**
* Create a single observable listener for document mouseup events.
*/
PIE.OnMouseup = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
/**
* Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
* value is returned from PIE.getLength() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.Length = (function() {
var lengthCalcEl = doc.createElement( 'length-calc' ),
parent = doc.body || doc.documentElement,
s = lengthCalcEl.style,
conversions = {},
units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
i = units.length,
instances = {};
s.position = 'absolute';
s.top = s.left = '-9999px';
parent.appendChild( lengthCalcEl );
while( i-- ) {
s.width = '100' + units[i];
conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
}
parent.removeChild( lengthCalcEl );
// All calcs from here on will use 1em
s.width = '1em';
function Length( val ) {
this.val = val;
}
Length.prototype = {
/**
* Regular expression for matching the length unit
* @private
*/
unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
/**
* Get the numeric value of the length
* @return {number} The value
*/
getNumber: function() {
var num = this.num,
UNDEF;
if( num === UNDEF ) {
num = this.num = parseFloat( this.val );
}
return num;
},
/**
* Get the unit of the length
* @return {string} The unit
*/
getUnit: function() {
var unit = this.unit,
m;
if( !unit ) {
m = this.val.match( this.unitRE );
unit = this.unit = ( m && m[0] ) || 'px';
}
return unit;
},
/**
* Determine whether this is a percentage length value
* @return {boolean}
*/
isPercentage: function() {
return this.getUnit() === '%';
},
/**
* Resolve this length into a number of pixels.
* @param {Element} el - the context element, used to resolve font-relative values
* @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
* function which will be called to return the number.
*/
pixels: function( el, pct100 ) {
var num = this.getNumber(),
unit = this.getUnit();
switch( unit ) {
case "px":
return num;
case "%":
return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
case "em":
return num * this.getEmPixels( el );
case "ex":
return num * this.getEmPixels( el ) / 2;
default:
return num * conversions[ unit ];
}
},
/**
* The em and ex units are relative to the font-size of the current element,
* however if the font-size is set using non-pixel units then we get that value
* rather than a pixel conversion. To get around this, we keep a floating element
* with width:1em which we insert into the target element and then read its offsetWidth.
* For elements that won't accept a child we insert into the parent node and perform
* additional calculation. If the font-size *is* specified in pixels, then we use that
* directly to avoid the expensive DOM manipulation.
* @param {Element} el
* @return {number}
*/
getEmPixels: function( el ) {
var fs = el.currentStyle.fontSize,
px, parent, me;
if( fs.indexOf( 'px' ) > 0 ) {
return parseFloat( fs );
}
else if( el.tagName in PIE.childlessElements ) {
me = this;
parent = el.parentNode;
return PIE.getLength( fs ).pixels( parent, function() {
return me.getEmPixels( parent );
} );
}
else {
el.appendChild( lengthCalcEl );
px = lengthCalcEl.offsetWidth;
if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
el.removeChild( lengthCalcEl );
}
return px;
}
}
};
/**
* Convert a pixel length into a point length
*/
Length.pxToPt = function( px ) {
return px / conversions[ 'pt' ];
};
/**
* Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.getLength = function( val ) {
return instances[ val ] || ( instances[ val ] = new Length( val ) );
};
return Length;
})();
/**
* Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
* @constructor
* @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
*/
PIE.BgPosition = (function() {
var length_fifty = PIE.getLength( '50%' ),
vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
function BgPosition( tokens ) {
this.tokens = tokens;
}
BgPosition.prototype = {
/**
* Normalize the values into the form:
* [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
* where: xOffsetSide is either 'left' or 'right',
* yOffsetSide is either 'top' or 'bottom',
* and x/yOffsetLength are both PIE.Length objects.
* @return {Array}
*/
getValues: function() {
if( !this._values ) {
var tokens = this.tokens,
len = tokens.length,
Tokenizer = PIE.Tokenizer,
identType = Tokenizer.Type,
length_zero = PIE.getLength( '0' ),
type_ident = identType.IDENT,
type_length = identType.LENGTH,
type_percent = identType.PERCENT,
type, value,
vals = [ 'left', length_zero, 'top', length_zero ];
// If only one value, the second is assumed to be 'center'
if( len === 1 ) {
tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
len++;
}
// Two values - CSS2
if( len === 2 ) {
// If both idents, they can appear in either order, so switch them if needed
if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
tokens.push( tokens.shift() );
}
if( tokens[0].tokenType & type_ident ) {
if( tokens[0].tokenValue === 'center' ) {
vals[1] = length_fifty;
} else {
vals[0] = tokens[0].tokenValue;
}
}
else if( tokens[0].isLengthOrPercent() ) {
vals[1] = PIE.getLength( tokens[0].tokenValue );
}
if( tokens[1].tokenType & type_ident ) {
if( tokens[1].tokenValue === 'center' ) {
vals[3] = length_fifty;
} else {
vals[2] = tokens[1].tokenValue;
}
}
else if( tokens[1].isLengthOrPercent() ) {
vals[3] = PIE.getLength( tokens[1].tokenValue );
}
}
// Three or four values - CSS3
else {
// TODO
}
this._values = vals;
}
return this._values;
},
/**
* Find the coordinates of the background image from the upper-left corner of the background area.
* Note that these coordinate values are not rounded.
* @param {Element} el
* @param {number} width - the width for percentages (background area width minus image width)
* @param {number} height - the height for percentages (background area height minus image height)
* @return {Object} { x: Number, y: Number }
*/
coords: function( el, width, height ) {
var vals = this.getValues(),
pxX = vals[1].pixels( el, width ),
pxY = vals[3].pixels( el, height );
return {
x: vals[0] === 'right' ? width - pxX : pxX,
y: vals[2] === 'bottom' ? height - pxY : pxY
};
}
};
return BgPosition;
})();
/**
* Wrapper for a CSS3 background-size value.
* @constructor
* @param {String|PIE.Length} w The width parameter
* @param {String|PIE.Length} h The height parameter, if any
*/
PIE.BgSize = (function() {
var CONTAIN = 'contain',
COVER = 'cover',
AUTO = 'auto';
function BgSize( w, h ) {
this.w = w;
this.h = h;
}
BgSize.prototype = {
pixels: function( el, areaW, areaH, imgW, imgH ) {
var me = this,
w = me.w,
h = me.h,
areaRatio = areaW / areaH,
imgRatio = imgW / imgH;
if ( w === CONTAIN ) {
w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === COVER ) {
w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === AUTO ) {
h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
w = h * imgRatio;
}
else {
w = w.pixels( el, areaW );
h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
}
return { w: w, h: h };
}
};
BgSize.DEFAULT = new BgSize( AUTO, AUTO );
return BgSize;
})();
/**
* Wrapper for angle values; handles conversion to degrees from all allowed angle units
* @constructor
* @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
*/
PIE.Angle = (function() {
function Angle( val ) {
this.val = val;
}
Angle.prototype = {
unitRE: /[a-z]+$/i,
/**
* @return {string} The unit of the angle value
*/
getUnit: function() {
return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
},
/**
* Get the numeric value of the angle in degrees.
* @return {number} The degrees value
*/
degrees: function() {
var deg = this._deg, u, n;
if( deg === undefined ) {
u = this.getUnit();
n = parseFloat( this.val, 10 );
deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
}
return deg;
}
};
return Angle;
})();/**
* Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
* value is returned from PIE.getColor() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The raw CSS string value for the color
*/
PIE.Color = (function() {
/*
* hsl2rgb from http://codingforums.com/showthread.php?t=11156
* code by Jason Karl Davis (http://www.jasonkarldavis.com)
* swiped from cssSandpaper by Zoltan Hawryluk (http://www.useragentman.com/blog/csssandpaper-a-css3-javascript-library/)
* modified for formatting and size optimizations
*/
function hsl2rgb( h, s, l ) {
var m1, m2, r, g, b,
round = Math.round;
s /= 100;
l /= 100;
if ( !s ) { r = g = b = l * 255; }
else {
if ( l <= 0.5 ) { m2 = l * ( s + 1 ); }
else { m2 = l + s - l * s; }
m1 = l * 2 - m2;
h = ( h % 360 ) / 360;
r = hueToRgb( m1, m2, h + 1/3 );
g = hueToRgb( m1, m2, h );
b = hueToRgb( m1, m2, h - 1/3 );
}
return { r: round( r ), g: round( g ), b: round( b ) };
}
function hueToRgb( m1, m2, hue ) {
var v;
if ( hue < 0 ) { hue += 1; }
else if ( hue > 1 ) { hue -= 1; }
if ( 6 * hue < 1 ) { v = m1 + ( m2 - m1 ) * hue * 6; }
else if ( 2 * hue < 1 ) { v = m2; }
else if ( 3 * hue < 2 ) { v = m1 + ( m2 - m1 ) * ( 2/3 - hue ) * 6; }
else { v = m1; }
return 255 * v;
}
var instances = {};
function Color( val ) {
this.val = val;
}
/**
* Regular expression for matching rgba colors and extracting their components
* @type {RegExp}
*/
Color.rgbOrRgbaRE = /\s*rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/;
Color.hslOrHslaRE = /\s*hsla?\(\s*(\d*\.?\d+)\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/;
/**
* Hash of color keyword names to their corresponding hex values. Encoded for
* small size and expanded into a hash on startup.
*/
Color.names = {};
var names = 'black|0|navy|3k|darkblue|b|mediumblue|1u|blue|1e|darkgreen|jk1|green|5j4|teal|3k|darkcyan|26j|deepskyblue|ad0|darkturquoise|2xe|mediumspringgreen|8nd|lime|va|springgreen|3j|aqua|3k|cyan|0|midnightblue|xunl|dodgerblue|7ogf|lightseagreen|2zsb|forestgreen|2lbs|seagreen|guut|darkslategray|12pk|limegreen|4wkj|mediumseagreen|dwlb|turquoise|5v8f|royalblue|r2p|steelblue|75qr|darkslateblue|2fh3|mediumturquoise|ta9|indigo|32d2|darkolivegreen|emr1|cadetblue|ebu9|cornflowerblue|6z4d|mediumaquamarine|3459|dimgray|3nwf|slateblue|1bok|olivedrab|1opi|slategray|6y5p|lightslategray|9vk9|mediumslateblue|5g0l|lawngreen|27ma|chartreuse|48ao|aquamarine|5w|maroon|18|purple|3k|olive|p6o|gray|3k|lightslateblue|5j7j|skyblue|4q98|lightskyblue|f|blueviolet|3bhk|darkred|15we|darkmagenta|3v|saddlebrown|djc|darkseagreen|69vg|lightgreen|1og1|mediumpurple|3ivc|darkviolet|sfv|palegreen|6zt1|darkorchid|awk|yellowgreen|292e|sienna|7r3v|brown|6sxp|darkgray|6bgf|lightblue|5vlp|greenyellow|7k9|paleturquoise|2pxb|lightsteelblue|169c|powderblue|5jc|firebrick|1rgc|darkgoldenrod|8z55|mediumorchid|2jm0|rosybrown|34jg|darkkhaki|1mfw|silver|49jp|mediumvioletred|8w5h|indianred|8tef|peru|82r|violetred|3ntd|feldspar|212d|chocolate|16eh|tan|ewe|lightgrey|1kqv|palevioletred|6h8g|metle|fnp|orchid|2dj2|goldenrod|abu|crimson|20ik|gainsboro|13mo|plum|12pt|burlywood|1j8q|lightcyan|3794|lavender|8agr|darksalmon|3rsw|violet|6wz8|palegoldenrod|k3g|lightcoral|28k6|khaki|k5o|aliceblue|3n7|honeydew|1dd|azure|f|sandybrown|5469|wheat|1q37|beige|4kp|whitesmoke|p|mintcream|1z9|ghostwhite|46bp|salmon|25bn|antiquewhite|l7p|linen|zz|lightgoldenrodyellow|1yk|oldlace|46qc|red|1gka|magenta|73|fuchsia|0|deeppink|3v8|orangered|9kd|tomato|5zb|hotpink|19p|coral|49o|darkorange|2i8|lightsalmon|41m|orange|w6|lightpink|3i9|pink|1ze|gold|4dx|peachpuff|qh|navajowhite|s4|moccasin|16w|bisque|f|mistyrose|t|blanchedalmond|1d8|papayawhip|so|lavenderblush|80|seashell|zd|cornsilk|ku|lemonchiffon|dt|floralwhite|z|snow|a|yellow|sm|lightyellow|68|ivory|g|white|f'.split('|'),
i = 0, len = names.length, color = 0, hexColor;
for(; i < len; i += 2) {
color += parseInt(names[i + 1], 36);
hexColor = color.toString(16);
Color.names[names[i]] = '#000000'.slice(0, -hexColor.length) + hexColor;
}
Color.prototype = {
/**
* @private
*/
parse: function() {
if( !this._color ) {
var me = this,
color = me.val,
alpha, vLower, m, rgb;
// RGB or RGBA colors
if( m = color.match( Color.rgbOrRgbaRE ) ) {
color = me.rgbToHex( +m[1], +m[2], +m[3] );
alpha = m[5] ? +m[5] : 1;
}
// HSL or HSLA colors
else if( m = color.match( Color.hslOrHslaRE ) ) {
rgb = hsl2rgb( m[1], m[2], m[3] );
color = me.rgbToHex( rgb.r, rgb.g, rgb.b );
alpha = m[5] ? +m[5] : 1;
}
else {
if( Color.names.hasOwnProperty( vLower = color.toLowerCase() ) ) {
color = Color.names[vLower];
}
alpha = ( color === 'transparent' ? 0 : 1 );
}
me._color = color;
me._alpha = alpha;
}
},
/**
* Converts RGB color channels to a hex value string
*/
rgbToHex: function( r, g, b ) {
return '#' + ( r < 16 ? '0' : '' ) + r.toString( 16 ) +
( g < 16 ? '0' : '' ) + g.toString( 16 ) +
( b < 16 ? '0' : '' ) + b.toString( 16 );
},
/**
* Retrieve the value of the color in a format usable by IE natively. This will be the same as
* the raw input value, except for rgb(a) and hsl(a) values which will be converted to a hex value.
* @param {Element} el The context element, used to get 'currentColor' keyword value.
* @return {string} Color value
*/
colorValue: function( el ) {
this.parse();
return this._color === 'currentColor' ? PIE.getColor( el.currentStyle.color ).colorValue( el ) : this._color;
},
/**
* Retrieve the value of the color in a normalized six-digit hex format.
* @param el
*/
hexValue: function( el ) {
var color = this.colorValue( el );
// At this point the color should be either a 3- or 6-digit hex value, or the string "transparent".
function ch( i ) {
return color.charAt( i );
}
// Fudge transparent to black - should be ignored anyway since its alpha will be 0
if( color === 'transparent' ) {
color = '#000';
}
// Expand 3-digit to 6-digit hex
if( ch(0) === '#' && color.length === 4 ) {
color = '#' + ch(1) + ch(1) + ch(2) + ch(2) + ch(3) + ch(3);
}
return color;
},
/**
* Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
* with an alpha component.
* @return {number} The alpha value, from 0 to 1.
*/
alpha: function() {
this.parse();
return this._alpha;
}
};
/**
* Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the color. It is assumed that this will already have
* been validated as a valid color syntax.
*/
PIE.getColor = function(val) {
return instances[ val ] || ( instances[ val ] = new Color( val ) );
};
return Color;
})();/**
* A tokenizer for CSS value strings.
* @constructor
* @param {string} css The CSS value string
*/
PIE.Tokenizer = (function() {
function Tokenizer( css ) {
this.css = css;
this.ch = 0;
this.tokens = [];
this.tokenIndex = 0;
}
/**
* Enumeration of token type constants.
* @enum {number}
*/
var Type = Tokenizer.Type = {
ANGLE: 1,
CHARACTER: 2,
COLOR: 4,
DIMEN: 8,
FUNCTION: 16,
IDENT: 32,
LENGTH: 64,
NUMBER: 128,
OPERATOR: 256,
PERCENT: 512,
STRING: 1024,
URL: 2048
};
/**
* A single token
* @constructor
* @param {number} type The type of the token - see PIE.Tokenizer.Type
* @param {string} value The value of the token
*/
Tokenizer.Token = function( type, value ) {
this.tokenType = type;
this.tokenValue = value;
};
Tokenizer.Token.prototype = {
isLength: function() {
return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
},
isLengthOrPercent: function() {
return this.isLength() || this.tokenType & Type.PERCENT;
}
};
Tokenizer.prototype = {
whitespace: /\s/,
number: /^[\+\-]?(\d*\.)?\d+/,
url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
ident: /^\-?[_a-z][\w-]*/i,
string: /^("([^"]*)"|'([^']*)')/,
operator: /^[\/,]/,
hash: /^#[\w]+/,
hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
unitTypes: {
'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
'pt': Type.LENGTH, 'pc': Type.LENGTH,
'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
},
colorFunctions: {
'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
},
/**
* Advance to and return the next token in the CSS string. If the end of the CSS string has
* been reached, null will be returned.
* @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
* @return {PIE.Tokenizer.Token}
*/
next: function( forget ) {
var css, ch, firstChar, match, val,
me = this;
function newToken( type, value ) {
var tok = new Tokenizer.Token( type, value );
if( !forget ) {
me.tokens.push( tok );
me.tokenIndex++;
}
return tok;
}
function failure() {
me.tokenIndex++;
return null;
}
// In case we previously backed up, return the stored token in the next slot
if( this.tokenIndex < this.tokens.length ) {
return this.tokens[ this.tokenIndex++ ];
}
// Move past leading whitespace characters
while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
this.ch++;
}
if( this.ch >= this.css.length ) {
return failure();
}
ch = this.ch;
css = this.css.substring( this.ch );
firstChar = css.charAt( 0 );
switch( firstChar ) {
case '#':
if( match = css.match( this.hashColor ) ) {
this.ch += match[0].length;
return newToken( Type.COLOR, match[0] );
}
break;
case '"':
case "'":
if( match = css.match( this.string ) ) {
this.ch += match[0].length;
return newToken( Type.STRING, match[2] || match[3] || '' );
}
break;
case "/":
case ",":
this.ch++;
return newToken( Type.OPERATOR, firstChar );
case 'u':
if( match = css.match( this.url ) ) {
this.ch += match[0].length;
return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
}
}
// Numbers and values starting with numbers
if( match = css.match( this.number ) ) {
val = match[0];
this.ch += val.length;
// Check if it is followed by a unit
if( css.charAt( val.length ) === '%' ) {
this.ch++;
return newToken( Type.PERCENT, val + '%' );
}
if( match = css.substring( val.length ).match( this.ident ) ) {
val += match[0];
this.ch += match[0].length;
return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
}
// Plain ol' number
return newToken( Type.NUMBER, val );
}
// Identifiers
if( match = css.match( this.ident ) ) {
val = match[0];
this.ch += val.length;
// Named colors
if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
return newToken( Type.COLOR, val );
}
// Functions
if( css.charAt( val.length ) === '(' ) {
this.ch++;
// Color values in function format: rgb, rgba, hsl, hsla
if( val.toLowerCase() in this.colorFunctions ) {
function isNum( tok ) {
return tok && tok.tokenType & Type.NUMBER;
}
function isNumOrPct( tok ) {
return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
}
function isValue( tok, val ) {
return tok && tok.tokenValue === val;
}
function next() {
return me.next( 1 );
}
if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
( val === 'rgb' || val === 'hsa' || (
isValue( next(), ',' ) &&
isNum( next() )
) ) &&
isValue( next(), ')' ) ) {
return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
}
return failure();
}
return newToken( Type.FUNCTION, val );
}
// Other identifier
return newToken( Type.IDENT, val );
}
// Standalone character
this.ch++;
return newToken( Type.CHARACTER, firstChar );
},
/**
* Determine whether there is another token
* @return {boolean}
*/
hasNext: function() {
var next = this.next();
this.prev();
return !!next;
},
/**
* Back up and return the previous token
* @return {PIE.Tokenizer.Token}
*/
prev: function() {
return this.tokens[ this.tokenIndex-- - 2 ];
},
/**
* Retrieve all the tokens in the CSS string
* @return {Array.<PIE.Tokenizer.Token>}
*/
all: function() {
while( this.next() ) {}
return this.tokens;
},
/**
* Return a list of tokens from the current position until the given function returns
* true. The final token will not be included in the list.
* @param {function():boolean} func - test function
* @param {boolean} require - if true, then if the end of the CSS string is reached
* before the test function returns true, null will be returned instead of the
* tokens that have been found so far.
* @return {Array.<PIE.Tokenizer.Token>}
*/
until: function( func, require ) {
var list = [], t, hit;
while( t = this.next() ) {
if( func( t ) ) {
hit = true;
this.prev();
break;
}
list.push( t );
}
return require && !hit ? null : list;
}
};
return Tokenizer;
})();/**
* Handles calculating, caching, and detecting changes to size and position of the element.
* @constructor
* @param {Element} el the target element
*/
PIE.BoundsInfo = function( el ) {
this.targetElement = el;
};
PIE.BoundsInfo.prototype = {
_locked: 0,
/**
* Determines if the element's position has changed since the last update.
* TODO this does a simple getBoundingClientRect comparison for detecting the
* changes in position, which may not always be accurate; it's possible that
* an element will actually move relative to its positioning parent, but its position
* relative to the viewport will stay the same. Need to come up with a better way to
* track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
* but that is a more expensive operation since it performs DOM walking, and we want this
* check to be as fast as possible. Perhaps introduce a -pie-* flag to trigger the slower
* but more accurate method?
*/
positionChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
},
sizeChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
},
getLiveBounds: function() {
var el = this.targetElement,
rect = el.getBoundingClientRect(),
isIE9 = PIE.ieDocMode === 9,
isIE7 = PIE.ieVersion === 7,
width = rect.right - rect.left;
return {
x: rect.left,
y: rect.top,
// In some cases scrolling the page will cause IE9 to report incorrect dimensions
// in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
// instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
// so we must calculate the ratio and use it in certain places as a position adjustment.
w: isIE9 || isIE7 ? el.offsetWidth : width,
h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
};
},
getBounds: function() {
return this._locked ?
( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
this.getLiveBounds();
},
hasBeenQueried: function() {
return !!this._lastBounds;
},
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
this._lockedBounds = null;
}
}
};
(function() {
function cacheWhenLocked( fn ) {
var uid = PIE.Util.getUID( fn );
return function() {
if( this._locked ) {
var cache = this._lockedValues || ( this._lockedValues = {} );
return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
} else {
return fn.call( this );
}
}
}
PIE.StyleInfoBase = {
_locked: 0,
/**
* Create a new StyleInfo class, with the standard constructor, and augmented by
* the StyleInfoBase's members.
* @param proto
*/
newStyleInfo: function( proto ) {
function StyleInfo( el ) {
this.targetElement = el;
this._lastCss = this.getCss();
}
PIE.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
StyleInfo._propsCache = {};
return StyleInfo;
},
/**
* Get an object representation of the target CSS style, caching it for each unique
* CSS value string.
* @return {Object}
*/
getProps: function() {
var css = this.getCss(),
cache = this.constructor._propsCache;
return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
},
/**
* Get the raw CSS value for the target style
* @return {string}
*/
getCss: cacheWhenLocked( function() {
var el = this.targetElement,
ctor = this.constructor,
s = el.style,
cs = el.currentStyle,
cssProp = this.cssProperty,
styleProp = this.styleProperty,
prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
} ),
/**
* Determine whether the target CSS style is active.
* @return {boolean}
*/
isActive: cacheWhenLocked( function() {
return !!this.getProps();
} ),
/**
* Determine whether the target CSS style has changed since the last time it was used.
* @return {boolean}
*/
changed: cacheWhenLocked( function() {
var currentCss = this.getCss(),
changed = currentCss !== this._lastCss;
this._lastCss = currentCss;
return changed;
} ),
cacheWhenLocked: cacheWhenLocked,
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
delete this._lockedValues;
}
}
};
})();/**
* Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: PIE.CSS_PREFIX + 'background',
styleProperty: PIE.STYLE_PREFIX + 'Background',
attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
sizeIdents: { 'contain':1, 'cover':1 },
tbIdents: { 'top': 1, 'bottom': 1 },
lrIdents: { 'left': 1, 'right': 1 },
propertyNames: {
CLIP: 'backgroundClip',
COLOR: 'backgroundColor',
IMAGE: 'backgroundImage',
ORIGIN: 'backgroundOrigin',
POSITION: 'backgroundPosition',
REPEAT: 'backgroundRepeat',
SIZE: 'backgroundSize'
},
/**
* For background styles, we support the -pie-background property but fall back to the standard
* backround* properties. The reason we have to use the prefixed version is that IE natively
* parses the standard properties and if it sees something it doesn't know how to parse, for example
* multiple values or gradient definitions, it will throw that away and not make it available through
* currentStyle.
*
* Format of return object:
* {
* color: <PIE.Color>,
* colorClip: <'border-box' | 'padding-box'>,
* bgImages: [
* {
* imgType: 'image',
* imgUrl: 'image.png',
* imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
* bgPosition: <PIE.BgPosition>,
* bgAttachment: <'scroll' | 'fixed' | 'local'>,
* bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
* bgClip: <'border-box' | 'padding-box'>,
* bgSize: <PIE.BgSize>,
* origString: 'url(img.png) no-repeat top left'
* },
* {
* imgType: 'linear-gradient',
* gradientTo: [<'top' | 'bottom'>, <'left' | 'right'>?],
* angle: <PIE.Angle>,
* stops: [
* { color: <PIE.Color>, offset: <PIE.Length> },
* { color: <PIE.Color>, offset: <PIE.Length> }, ...
* ]
* }
* ]
* }
* @param {String} css
* @override
*/
parseCss: function( css ) {
var el = this.targetElement,
cs = el.currentStyle,
tokenizer, token, image,
tok_type = PIE.Tokenizer.Type,
type_operator = tok_type.OPERATOR,
type_ident = tok_type.IDENT,
type_color = tok_type.COLOR,
tokType, tokVal,
beginCharIndex = 0,
positionIdents = this.positionIdents,
gradient, stop, width, height, gradientTo, len, tbIdents, lrIdents,
props = { bgImages: [] };
function isBgPosToken( token ) {
return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
}
function sizeToken( token ) {
return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
}
// If the CSS3-specific -pie-background property is present, parse it
if( this.getCss3() ) {
tokenizer = new PIE.Tokenizer( css );
image = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
gradient = { stops: [], imgType: tokVal };
stop = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
// If we reached the end of the function and had at least 2 stops, flush the info
if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
if( stop.color ) {
gradient.stops.push( stop );
}
if( gradient.stops.length > 1 ) {
PIE.merge( image, gradient );
}
break;
}
// Color stop - must start with color
if( tokType & type_color ) {
// if we already have an angle/position, make sure that the previous token was a comma
if( gradient.angle || gradient.gradientTo ) {
token = tokenizer.prev();
if( token.tokenType !== type_operator ) {
break; //fail
}
tokenizer.next();
}
stop = {
color: PIE.getColor( tokVal )
};
// check for offset following color
token = tokenizer.next();
if( token.isLengthOrPercent() ) {
stop.offset = PIE.getLength( token.tokenValue );
} else {
tokenizer.prev();
}
}
// Angle - can only appear in first spot
else if( tokType & tok_type.ANGLE && !gradient.angle && !gradient.gradientTo && !stop.color && !gradient.stops.length ) {
gradient.angle = new PIE.Angle( token.tokenValue );
}
// "to <side-or-corner>" - can only appear in first spot
else if( tokType & tok_type.IDENT && tokVal === 'to' && !gradient.gradientTo && !gradient.angle && !stop.color && !gradient.stops.length ) {
tbIdents = this.tbIdents;
lrIdents = this.lrIdents;
gradientTo = tokenizer.until( function( t ) {
return !(t && t.tokenType & tok_type.IDENT && ( t.tokenValue in tbIdents || t.tokenValue in lrIdents ));
} );
len = gradientTo.length;
gradientTo = [ gradientTo[0] && gradientTo[0].tokenValue, gradientTo[1] && gradientTo[1].tokenValue ];
// bail unless there are 1 or 2 values, or if the 2 values are from the same pair of sides
if ( len < 1 || len > 2 || ( len > 1 && (
( gradientTo[0] in tbIdents && gradientTo[1] in tbIdents ) ||
( gradientTo[0] in lrIdents && gradientTo[1] in lrIdents )
) ) ) {
break;
}
gradient.gradientTo = gradientTo;
}
else if( tokType & type_operator && tokVal === ',' ) {
if( stop.color ) {
gradient.stops.push( stop );
stop = {};
}
}
else {
// Found something we didn't recognize; fail without adding image
break;
}
}
}
else if( !image.imgType && tokType & tok_type.URL ) {
image.imgUrl = tokVal;
image.imgType = 'image';
}
else if( isBgPosToken( token ) && !image.bgPosition ) {
tokenizer.prev();
image.bgPosition = new PIE.BgPosition(
tokenizer.until( function( t ) {
return !isBgPosToken( t );
}, false )
);
}
else if( tokType & type_ident ) {
if( tokVal in this.repeatIdents && !image.imgRepeat ) {
image.imgRepeat = tokVal;
}
else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
image.bgOrigin = tokVal;
if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
token.tokenValue in this.originAndClipIdents ) {
image.bgClip = token.tokenValue;
} else {
image.bgClip = tokVal;
tokenizer.prev();
}
}
else if( tokVal in this.attachIdents && !image.bgAttachment ) {
image.bgAttachment = tokVal;
}
else {
return null;
}
}
else if( tokType & type_color && !props.color ) {
props.color = PIE.getColor( tokVal );
}
else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
// background size
token = tokenizer.next();
if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
image.bgSize = new PIE.BgSize( token.tokenValue );
}
else if( width = sizeToken( token ) ) {
height = sizeToken( tokenizer.next() );
if ( !height ) {
height = width;
tokenizer.prev();
}
image.bgSize = new PIE.BgSize( width, height );
}
else {
return null;
}
}
// new layer
else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
beginCharIndex = tokenizer.ch;
props.bgImages.push( image );
image = {};
}
else {
// Found something unrecognized; chuck everything
return null;
}
}
// leftovers
if( image.imgType ) {
image.origString = css.substring( beginCharIndex );
props.bgImages.push( image );
}
props.colorClip = image.bgClip;
}
// Otherwise, use the standard background properties; let IE give us the values rather than parsing them
else {
this.withActualBg( PIE.ieDocMode < 9 ?
function() {
var propNames = this.propertyNames,
posX = cs[propNames.POSITION + 'X'],
posY = cs[propNames.POSITION + 'Y'],
img = cs[propNames.IMAGE],
color = cs[propNames.COLOR];
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
if( img !== 'none' ) {
props.bgImages = [ {
imgType: 'image',
imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
imgRepeat: cs[propNames.REPEAT],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
} ];
}
} :
function() {
var propNames = this.propertyNames,
splitter = /\s*,\s*/,
images = cs[propNames.IMAGE].split( splitter ),
color = cs[propNames.COLOR],
repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
len = images.length;
if( len && images[0] !== 'none' ) {
repeats = cs[propNames.REPEAT].split( splitter );
positions = cs[propNames.POSITION].split( splitter );
origins = cs[propNames.ORIGIN].split( splitter );
clips = cs[propNames.CLIP].split( splitter );
sizes = cs[propNames.SIZE].split( splitter );
props.bgImages = [];
for( i = 0; i < len; i++ ) {
image = images[ i ];
if( image && image !== 'none' ) {
sizeParts = sizes[i].split( ' ' );
props.bgImages.push( {
origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
origins[ i ] + ' ' + clips[ i ],
imgType: 'image',
imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
imgRepeat: repeats[ i ],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
bgOrigin: origins[ i ],
bgClip: clips[ i ],
bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
} );
}
}
}
}
);
}
return ( props.color || props.bgImages[0] ) ? props : null;
},
/**
* Execute a function with the actual background styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBg: function( fn ) {
var isIE9 = PIE.ieDocMode > 8,
propNames = this.propertyNames,
rs = this.targetElement.runtimeStyle,
rsImage = rs[propNames.IMAGE],
rsColor = rs[propNames.COLOR],
rsRepeat = rs[propNames.REPEAT],
rsClip, rsOrigin, rsSize, rsPosition, ret;
if( rsImage ) rs[propNames.IMAGE] = '';
if( rsColor ) rs[propNames.COLOR] = '';
if( rsRepeat ) rs[propNames.REPEAT] = '';
if( isIE9 ) {
rsClip = rs[propNames.CLIP];
rsOrigin = rs[propNames.ORIGIN];
rsPosition = rs[propNames.POSITION];
rsSize = rs[propNames.SIZE];
if( rsClip ) rs[propNames.CLIP] = '';
if( rsOrigin ) rs[propNames.ORIGIN] = '';
if( rsPosition ) rs[propNames.POSITION] = '';
if( rsSize ) rs[propNames.SIZE] = '';
}
ret = fn.call( this );
if( rsImage ) rs[propNames.IMAGE] = rsImage;
if( rsColor ) rs[propNames.COLOR] = rsColor;
if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
if( isIE9 ) {
if( rsClip ) rs[propNames.CLIP] = rsClip;
if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
if( rsPosition ) rs[propNames.POSITION] = rsPosition;
if( rsSize ) rs[propNames.SIZE] = rsSize;
}
return ret;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
return this.getCss3() ||
this.withActualBg( function() {
var cs = this.targetElement.currentStyle,
propNames = this.propertyNames;
return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
} );
} ),
getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement;
return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
} ),
/**
* For a given background-origin value, return the dimensions of the background area.
* @param {String} bgOrigin
* @param {PIE.BoundsInfo} boundsInfo
* @param {PIE.BorderStyleInfo} borderInfo
*/
getBgAreaSize: function( bgOrigin, boundsInfo, borderInfo, paddingInfo ) {
var el = this.targetElement,
bounds = boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
borders, paddings;
if( bgOrigin !== 'border-box' ) {
borders = borderInfo.getProps();
if( borders && ( borders = borders.widths ) ) {
w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
}
}
if ( bgOrigin === 'content-box' ) {
paddings = paddingInfo.getProps();
if ( paddings ) {
w -= paddings[ 'l' ].pixels( el ) + paddings[ 'l' ].pixels( el );
h -= paddings[ 't' ].pixels( el ) + paddings[ 'b' ].pixels( el );
}
}
return { w: w, h: h };
},
/**
* Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
*/
isPngFix: function() {
var val = 0, el;
if( PIE.ieVersion < 7 ) {
el = this.targetElement;
val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
}
return val;
},
/**
* The isActive logic is slightly different, because getProps() always returns an object
* even if it is just falling back to the native background properties. But we only want
* to report is as being "active" if either the -pie-background override property is present
* and parses successfully or '-pie-png-fix' is set to true in IE6.
*/
isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
return (this.getCss3() || this.isPngFix()) && !!this.getProps();
} )
} );/**
* Handles parsing, caching, and detecting changes to border CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
namedWidths: {
'thin': '1px',
'medium': '3px',
'thick': '5px'
},
parseCss: function( css ) {
var w = {},
s = {},
c = {},
active = false,
colorsSame = true,
stylesSame = true,
widthsSame = true;
this.withActualBorder( function() {
var el = this.targetElement,
cs = el.currentStyle,
i = 0,
style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
for( ; i < 4; i++ ) {
side = this.sides[ i ];
ltr = side.charAt(0).toLowerCase();
style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
color = cs[ 'border' + side + 'Color' ];
width = cs[ 'border' + side + 'Width' ];
if( i > 0 ) {
if( style !== lastStyle ) { stylesSame = false; }
if( color !== lastColor ) { colorsSame = false; }
if( width !== lastWidth ) { widthsSame = false; }
}
lastStyle = style;
lastColor = color;
lastWidth = width;
c[ ltr ] = PIE.getColor( color );
width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
if( width.pixels( this.targetElement ) > 0 ) {
active = true;
}
}
} );
return active ? {
widths: w,
styles: s,
colors: c,
widthsSame: widthsSame,
colorsSame: colorsSame,
stylesSame: stylesSame
} : null;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement,
cs = el.currentStyle,
css;
// Don't redraw or hide borders for cells in border-collapse:collapse tables
if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
this.withActualBorder( function() {
css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
} );
}
return css;
} ),
/**
* Execute a function with the actual border styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBorder: function( fn ) {
var rs = this.targetElement.runtimeStyle,
rsWidth = rs.borderWidth,
rsColor = rs.borderColor,
ret;
if( rsWidth ) rs.borderWidth = '';
if( rsColor ) rs.borderColor = '';
ret = fn.call( this );
if( rsWidth ) rs.borderWidth = rsWidth;
if( rsColor ) rs.borderColor = rsColor;
return ret;
}
} );
/**
* Handles parsing, caching, and detecting changes to border-image CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'border-image',
styleProperty: 'borderImage',
repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
parseCss: function( css ) {
var p = null, tokenizer, token, type, value,
slices, widths, outsets,
slashCount = 0,
Type = PIE.Tokenizer.Type,
IDENT = Type.IDENT,
NUMBER = Type.NUMBER,
PERCENT = Type.PERCENT;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
p = {};
function isSlash( token ) {
return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
}
function isFillIdent( token ) {
return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
}
function collectSlicesEtc() {
slices = tokenizer.until( function( tok ) {
return !( tok.tokenType & ( NUMBER | PERCENT ) );
} );
if( isFillIdent( tokenizer.next() ) && !p.fill ) {
p.fill = true;
} else {
tokenizer.prev();
}
if( isSlash( tokenizer.next() ) ) {
slashCount++;
widths = tokenizer.until( function( token ) {
return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
} );
if( isSlash( tokenizer.next() ) ) {
slashCount++;
outsets = tokenizer.until( function( token ) {
return !token.isLength();
} );
}
} else {
tokenizer.prev();
}
}
while( token = tokenizer.next() ) {
type = token.tokenType;
value = token.tokenValue;
// Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
if( type & ( NUMBER | PERCENT ) && !slices ) {
tokenizer.prev();
collectSlicesEtc();
}
else if( isFillIdent( token ) && !p.fill ) {
p.fill = true;
collectSlicesEtc();
}
// Idents: one or values for 'repeat'
else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
p.repeat = { h: value };
if( token = tokenizer.next() ) {
if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
p.repeat.v = token.tokenValue;
} else {
tokenizer.prev();
}
}
}
// URL of the image
else if( ( type & Type.URL ) && !p.src ) {
p.src = value;
}
// Found something unrecognized; exit.
else {
return null;
}
}
// Validate what we collected
if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
return null;
}
// Fill in missing values
if( !p.repeat ) {
p.repeat = { h: 'stretch' };
}
if( !p.repeat.v ) {
p.repeat.v = p.repeat.h;
}
function distributeSides( tokens, convertFn ) {
return {
't': convertFn( tokens[0] ),
'r': convertFn( tokens[1] || tokens[0] ),
'b': convertFn( tokens[2] || tokens[0] ),
'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
};
}
p.slice = distributeSides( slices, function( tok ) {
return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
} );
if( widths && widths[0] ) {
p.widths = distributeSides( widths, function( tok ) {
return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
if( outsets && outsets[0] ) {
p.outset = distributeSides( outsets, function( tok ) {
return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
}
return p;
}
} );/**
* Handles parsing, caching, and detecting changes to padding CSS
* @constructor
* @param {Element} el the target element
*/
PIE.PaddingStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
parseCss: function( css ) {
var tokenizer = new PIE.Tokenizer( css ),
arr = [],
token;
while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
arr.push( PIE.getLength( token.tokenValue ) );
}
return arr.length > 0 && arr.length < 5 ? {
't': arr[0],
'r': arr[1] || arr[0],
'b': arr[2] || arr[0],
'l': arr[3] || arr[1] || arr[0]
} : null;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement,
rs = el.runtimeStyle,
rsPadding = rs.padding,
padding;
if( rsPadding ) rs.padding = '';
padding = el.currentStyle.padding;
if( rsPadding ) rs.padding = rsPadding;
return padding;
} )
} );
PIE.RendererBase = {
/**
* Create a new Renderer class, with the standard constructor, and augmented by
* the RendererBase's members.
* @param proto
*/
newRenderer: function( proto ) {
function Renderer( el, boundsInfo, styleInfos, parent ) {
this.targetElement = el;
this.boundsInfo = boundsInfo;
this.styleInfos = styleInfos;
this.parent = parent;
}
PIE.merge( Renderer.prototype, PIE.RendererBase, proto );
return Renderer;
},
/**
* Determine if the renderer needs to be updated
* @return {boolean}
*/
needsUpdate: function() {
return false;
},
/**
* Run any preparation logic that would affect the main update logic of this
* renderer or any of the other renderers, e.g. things that might affect the
* element's size or style properties.
*/
prepareUpdate: PIE.emptyFn,
/**
* Tell the renderer to update based on modified properties or element dimensions
*/
updateRendering: function() {
if( this.isActive() ) {
this.draw();
} else {
this.destroy();
}
},
/**
* Hide the target element's border
*/
hideBorder: function() {
this.targetElement.runtimeStyle.borderColor = 'transparent';
},
/**
* Destroy the rendered objects. This is a base implementation which handles common renderer
* structures, but individual renderers may override as necessary.
*/
destroy: function() {
}
};
/**
* Root renderer for IE9; manages the rendering layers in the element's background
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( {
outerCommasRE: /^,+|,+$/g,
innerCommasRE: /,+/g,
setBackgroundLayer: function(zIndex, bg) {
var me = this,
bgLayers = me._bgLayers || ( me._bgLayers = [] ),
undef;
bgLayers[zIndex] = bg || undef;
},
updateRendering: function() {
var me = this,
bgLayers = me._bgLayers,
bg;
if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) {
me._lastBg = me.targetElement.runtimeStyle.background = bg;
}
},
destroy: function() {
this.targetElement.runtimeStyle.background = '';
delete this._bgLayers;
}
} );
/**
* Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients
* to an equivalent SVG data URI.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( {
drawingCanvas: doc.createElement( 'canvas' ),
bgLayerZIndex: 1,
needsUpdate: function() {
var si = this.styleInfos;
return si.backgroundInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.backgroundInfo.isActive() || si.borderImageInfo.isActive();
},
draw: function() {
var me = this,
styleInfos = me.styleInfos,
bgInfo = styleInfos.backgroundInfo,
props = bgInfo.getProps(),
bg, images, i = 0, img, bgAreaSize, bgSize;
if ( props ) {
bg = [];
images = props.bgImages;
if ( images ) {
while( img = images[ i++ ] ) {
if (img.imgType === 'linear-gradient' ) {
bgAreaSize = bgInfo.getBgAreaSize( bg.bgOrigin, me.boundsInfo, styleInfos.borderInfo, styleInfos.paddingInfo );
bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels(
me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h
);
bg.push(
'url(' + me.getGradientImgData( img, bgSize.w, bgSize.h ) + ') ' +
me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' +
( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' )
);
} else {
bg.push( img.origString );
}
}
}
if ( props.color ) {
bg.push( props.color.val + ' ' + ( props.colorClip || '' ) );
}
me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(','));
}
},
bgPositionToString: function( bgPosition ) {
return bgPosition ? bgPosition.tokens.map(function(token) {
return token.tokenValue;
}).join(' ') : '0 0';
},
getGradientImgData: function( info, bgWidth, bgHeight ) {
var me = this,
el = me.targetElement,
stopsInfo = info.stops,
stopCount = stopsInfo.length,
metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ),
lineLength = metrics.lineLength,
canvas = me.drawingCanvas,
context = canvas.getContext( '2d' ),
gradient = context.createLinearGradient( metrics.startX, metrics.startY, metrics.endX, metrics.endY ),
stopPx = [],
i, j, before, after;
// Find the pixel offsets along the CSS3 gradient-line for each stop.
for( i = 0; i < stopCount; i++ ) {
stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) :
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
}
// Fill in gaps with evenly-spaced offsets
for( i = 1; i < stopCount; i++ ) {
if( stopPx[ i ] === null ) {
before = stopPx[ i - 1 ];
j = i;
do {
after = stopPx[ ++j ];
} while( after === null );
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
}
}
// Convert stops to percentages along the gradient line and add a stop for each
for( i = 0; i < stopCount; i++ ) {
gradient.addColorStop( stopPx[ i ] / lineLength, stopsInfo[ i ].color.val );
}
canvas.width = bgWidth;
canvas.height = bgHeight;
context.fillStyle = gradient;
context.fillRect( 0, 0, bgWidth, bgHeight );
return canvas.toDataURL();
},
destroy: function() {
this.parent.setBackgroundLayer( this.bgLayerZIndex );
}
} );
/**
* Renderer for border-image
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( {
REPEAT: 'repeat',
STRETCH: 'stretch',
ROUND: 'round',
bgLayerZIndex: 0,
needsUpdate: function() {
return this.styleInfos.borderImageInfo.changed();
},
isActive: function() {
return this.styleInfos.borderImageInfo.isActive();
},
draw: function() {
var me = this,
props = me.styleInfos.borderImageInfo.getProps(),
borderProps = me.styleInfos.borderInfo.getProps(),
bounds = me.boundsInfo.getBounds(),
repeat = props.repeat,
repeatH = repeat.h,
repeatV = repeat.v,
el = me.targetElement,
isAsync = 0;
PIE.Util.withImageSize( props.src, function( imgSize ) {
var elW = bounds.w,
elH = bounds.h,
imgW = imgSize.w,
imgH = imgSize.h,
// The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange
// security exception (perhaps due to cross-origin policy within data URIs?) Therefore we
// work around this by converting the image data into a data URI itself using a transient
// canvas. This unfortunately requires the border-image src to be within the same domain,
// which isn't a limitation in true border-image, so we need to try and find a better fix.
imgSrc = me.imageToDataURI( props.src, imgW, imgH ),
REPEAT = me.REPEAT,
STRETCH = me.STRETCH,
ROUND = me.ROUND,
ceil = Math.ceil,
zero = PIE.getLength( '0' ),
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
widthT = widths['t'].pixels( el ),
widthR = widths['r'].pixels( el ),
widthB = widths['b'].pixels( el ),
widthL = widths['l'].pixels( el ),
slices = props.slice,
sliceT = slices['t'].pixels( el ),
sliceR = slices['r'].pixels( el ),
sliceB = slices['b'].pixels( el ),
sliceL = slices['l'].pixels( el ),
centerW = elW - widthL - widthR,
middleH = elH - widthT - widthB,
imgCenterW = imgW - sliceL - sliceR,
imgMiddleH = imgH - sliceT - sliceB,
// Determine the size of each tile - 'round' is handled below
tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT,
tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR,
tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB,
tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL,
svg,
patterns = [],
rects = [],
i = 0;
// For 'round', subtract from each tile's size enough so that they fill the space a whole number of times
if (repeatH === ROUND) {
tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT);
tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB);
}
if (repeatV === ROUND) {
tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR);
tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL);
}
// Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched
// or repeated as the fill of a rect of appropriate size.
svg = [
'<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
];
function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) {
patterns.push(
'<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' +
'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' +
'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' +
'width="' + tileW + '" height="' + tileH + '">' +
'<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' +
'<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' +
'</svg>' +
'</pattern>'
);
rects.push(
'<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />'
);
i++;
}
addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left
addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center
addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right
addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left
if ( props.fill ) { // center fill
addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH,
tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH );
}
addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right
addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left
addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center
addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right
svg.push(
'<defs>' +
patterns.join('\n') +
'</defs>' +
rects.join('\n') +
'</svg>'
);
me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' );
// If the border-image's src wasn't immediately available, the SVG for its background layer
// will have been created asynchronously after the main element's update has finished; we'll
// therefore need to force the root renderer to sync to the final background once finished.
if( isAsync ) {
me.parent.updateRendering();
}
}, me );
isAsync = 1;
},
/**
* Convert a given image to a data URI
*/
imageToDataURI: (function() {
var uris = {};
return function( src, width, height ) {
var uri = uris[ src ],
image, canvas;
if ( !uri ) {
image = new Image();
canvas = doc.createElement( 'canvas' );
image.src = src;
canvas.width = width;
canvas.height = height;
canvas.getContext( '2d' ).drawImage( image, 0, 0 );
uri = uris[ src ] = canvas.toDataURL();
}
return uri;
}
})(),
prepareUpdate: function() {
if (this.isActive()) {
var me = this,
el = me.targetElement,
rs = el.runtimeStyle,
widths = me.styleInfos.borderImageInfo.getProps().widths;
// Force border-style to solid so it doesn't collapse
rs.borderStyle = 'solid';
// If widths specified in border-image shorthand, override border-width
if ( widths ) {
rs.borderTopWidth = widths['t'].pixels( el ) + 'px';
rs.borderRightWidth = widths['r'].pixels( el ) + 'px';
rs.borderBottomWidth = widths['b'].pixels( el ) + 'px';
rs.borderLeftWidth = widths['l'].pixels( el ) + 'px';
}
// Make the border transparent
me.hideBorder();
}
},
destroy: function() {
var me = this,
rs = me.targetElement.runtimeStyle;
me.parent.setBackgroundLayer( me.bgLayerZIndex );
rs.borderColor = rs.borderStyle = rs.borderWidth = '';
}
} );
PIE.Element = (function() {
var wrappers = {},
lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
pollCssProp = PIE.CSS_PREFIX + 'poll',
trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
hoverClass = PIE.CLASS_PREFIX + 'hover',
activeClass = PIE.CLASS_PREFIX + 'active',
focusClass = PIE.CLASS_PREFIX + 'focus',
firstChildClass = PIE.CLASS_PREFIX + 'first-child',
ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
classNameRegExes = {},
dummyArray = [];
function addClass( el, className ) {
el.className += ' ' + className;
}
function removeClass( el, className ) {
var re = classNameRegExes[ className ] ||
( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
el.className = el.className.replace( re, '' );
}
function delayAddClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
addClass( el, classes[ i ] );
}
}
}, 0 );
}
function delayRemoveClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
removeClass( el, classes[ i ] );
}
}
}, 0 );
}
function Element( el ) {
var me = this,
childRenderers,
rootRenderer,
boundsInfo = new PIE.BoundsInfo( el ),
styleInfos,
styleInfosArr,
initializing,
initialized,
eventsAttached,
eventListeners = [],
delayed,
destroyed,
poll;
me.el = el;
/**
* Initialize PIE for this element.
*/
function init() {
if( !initialized ) {
var docEl,
bounds,
ieDocMode = PIE.ieDocMode,
cs = el.currentStyle,
lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false';
// Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
poll = cs.getAttribute( pollCssProp );
poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
// Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
// after load, but make sure it only gets called the first time through to avoid recursive calls to init().
if( !initializing ) {
initializing = 1;
el.runtimeStyle.zoom = 1;
initFirstChildPseudoClass();
}
boundsInfo.lock();
// If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
if( !delayed ) {
delayed = 1;
PIE.OnScroll.observe( init );
}
} else {
initialized = 1;
delayed = initializing = 0;
PIE.OnScroll.unobserve( init );
// Create the style infos and renderers
if ( ieDocMode === 9 ) {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el ),
paddingInfo: new PIE.PaddingStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderInfo,
styleInfos.borderImageInfo,
styleInfos.paddingInfo
];
rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
} else {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
paddingInfo: new PIE.PaddingStyleInfo( el ),
visibilityInfo: new PIE.VisibilityStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderInfo,
styleInfos.borderImageInfo,
styleInfos.borderRadiusInfo,
styleInfos.boxShadowInfo,
styleInfos.paddingInfo,
styleInfos.visibilityInfo
];
rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
//new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
if( el.tagName === 'IMG' ) {
childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
}
rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
}
// Add property change listeners to ancestors if requested
initAncestorEventListeners();
// Add to list of polled elements when -pie-poll:true
if( poll ) {
PIE.Heartbeat.observe( update );
PIE.Heartbeat.run();
}
// Trigger rendering
update( 0, 1 );
}
if( !eventsAttached ) {
eventsAttached = 1;
if( ieDocMode < 9 ) {
addListener( el, 'onmove', handleMoveOrResize );
}
addListener( el, 'onresize', handleMoveOrResize );
addListener( el, 'onpropertychange', propChanged );
if( trackHover ) {
addListener( el, 'onmouseenter', mouseEntered );
}
if( trackHover || trackActive ) {
addListener( el, 'onmouseleave', mouseLeft );
}
if( trackActive ) {
addListener( el, 'onmousedown', mousePressed );
}
if( el.tagName in PIE.focusableElements ) {
addListener( el, 'onfocus', focused );
addListener( el, 'onblur', blurred );
}
PIE.OnResize.observe( handleMoveOrResize );
PIE.OnUnload.observe( removeEventListeners );
}
boundsInfo.unlock();
}
}
/**
* Event handler for onmove and onresize events. Invokes update() only if the element's
* bounds have previously been calculated, to prevent multiple runs during page load when
* the element has no initial CSS3 properties.
*/
function handleMoveOrResize() {
if( boundsInfo && boundsInfo.hasBeenQueried() ) {
update();
}
}
/**
* Update position and/or size as necessary. Both move and resize events call
* this rather than the updatePos/Size functions because sometimes, particularly
* during page load, one will fire but the other won't.
*/
function update( isPropChange, force ) {
if( !destroyed ) {
if( initialized ) {
lockAll();
var i = 0, len = childRenderers.length,
sizeChanged = boundsInfo.sizeChanged();
for( ; i < len; i++ ) {
childRenderers[i].prepareUpdate();
}
for( i = 0; i < len; i++ ) {
if( force || sizeChanged || ( isPropChange && childRenderers[i].needsUpdate() ) ) {
childRenderers[i].updateRendering();
}
}
if( force || sizeChanged || isPropChange || boundsInfo.positionChanged() ) {
rootRenderer.updateRendering();
}
unlockAll();
}
else if( !initializing ) {
init();
}
}
}
/**
* Handle property changes to trigger update when appropriate.
*/
function propChanged() {
// Some elements like <table> fire onpropertychange events for old-school background properties
// ('background', 'bgColor') when runtimeStyle background properties are changed, which
// results in an infinite loop; therefore we filter out those property names. Also, 'display'
// is ignored because size calculations don't work correctly immediately when its onpropertychange
// event fires, and because it will trigger an onresize event anyway.
if( initialized && !( event && event.propertyName in ignorePropertyNames ) ) {
update( 1 );
}
}
/**
* Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
* hover styles to non-link elements, and to trigger a propertychange update.
*/
function mouseEntered() {
//must delay this because the mouseenter event fires before the :hover styles are added.
delayAddClass( el, hoverClass );
}
/**
* Handle mouseleave events
*/
function mouseLeft() {
//must delay this because the mouseleave event fires before the :hover styles are removed.
delayRemoveClass( el, hoverClass, activeClass );
}
/**
* Handle mousedown events. Adds a custom class to the element to allow IE6 to add
* active styles to non-link elements, and to trigger a propertychange update.
*/
function mousePressed() {
//must delay this because the mousedown event fires before the :active styles are added.
delayAddClass( el, activeClass );
// listen for mouseups on the document; can't just be on the element because the user might
// have dragged out of the element while the mouse button was held down
PIE.OnMouseup.observe( mouseReleased );
}
/**
* Handle mouseup events
*/
function mouseReleased() {
//must delay this because the mouseup event fires before the :active styles are removed.
delayRemoveClass( el, activeClass );
PIE.OnMouseup.unobserve( mouseReleased );
}
/**
* Handle focus events. Adds a custom class to the element to trigger a propertychange update.
*/
function focused() {
//must delay this because the focus event fires before the :focus styles are added.
delayAddClass( el, focusClass );
}
/**
* Handle blur events
*/
function blurred() {
//must delay this because the blur event fires before the :focus styles are removed.
delayRemoveClass( el, focusClass );
}
/**
* Handle property changes on ancestors of the element; see initAncestorEventListeners()
* which adds these listeners as requested with the -pie-watch-ancestors CSS property.
*/
function ancestorPropChanged() {
var name = event.propertyName;
if( name === 'className' || name === 'id' || name.indexOf( 'style.' ) === 0 ) {
propChanged();
}
}
function lockAll() {
boundsInfo.lock();
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].lock();
}
}
function unlockAll() {
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].unlock();
}
boundsInfo.unlock();
}
function addListener( targetEl, type, handler ) {
targetEl.attachEvent( type, handler );
eventListeners.push( [ targetEl, type, handler ] );
}
/**
* Remove all event listeners from the element and any monitored ancestors.
*/
function removeEventListeners() {
if (eventsAttached) {
var i = eventListeners.length,
listener;
while( i-- ) {
listener = eventListeners[ i ];
listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
}
PIE.OnUnload.unobserve( removeEventListeners );
eventsAttached = 0;
eventListeners = [];
}
}
/**
* Clean everything up when the behavior is removed from the element, or the element
* is manually destroyed.
*/
function destroy() {
if( !destroyed ) {
var i, len;
removeEventListeners();
destroyed = 1;
// destroy any active renderers
if( childRenderers ) {
for( i = 0, len = childRenderers.length; i < len; i++ ) {
childRenderers[i].finalized = 1;
childRenderers[i].destroy();
}
}
rootRenderer.destroy();
// Remove from list of polled elements in IE8
if( poll ) {
PIE.Heartbeat.unobserve( update );
}
// Stop onresize listening
PIE.OnResize.unobserve( update );
// Kill references
childRenderers = rootRenderer = boundsInfo = styleInfos = styleInfosArr = el = null;
me.el = me = 0;
}
}
/**
* If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
* other event listeners to ancestor(s) of the element so we can pick up style changes
* based on CSS rules using descendant selectors.
*/
function initAncestorEventListeners() {
var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
i, a;
if( watch ) {
watch = parseInt( watch, 10 );
i = 0;
a = el.parentNode;
while( a && ( watch === 'NaN' || i++ < watch ) ) {
addListener( a, 'onpropertychange', ancestorPropChanged );
addListener( a, 'onmouseenter', mouseEntered );
addListener( a, 'onmouseleave', mouseLeft );
addListener( a, 'onmousedown', mousePressed );
if( a.tagName in PIE.focusableElements ) {
addListener( a, 'onfocus', focused );
addListener( a, 'onblur', blurred );
}
a = a.parentNode;
}
}
}
/**
* If the target element is a first child, add a pie_first-child class to it. This allows using
* the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
* pseudo-class selector.
*/
function initFirstChildPseudoClass() {
var tmpEl = el,
isFirst = 1;
while( tmpEl = tmpEl.previousSibling ) {
if( tmpEl.nodeType === 1 ) {
isFirst = 0;
break;
}
}
if( isFirst ) {
addClass( el, firstChildClass );
}
}
// These methods are all already bound to this instance so there's no need to wrap them
// in a closure to maintain the 'this' scope object when calling them.
me.init = init;
me.destroy = destroy;
}
Element.getInstance = function( el ) {
var id = el[ 'uniqueID' ];
return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
};
Element.destroy = function( el ) {
var id = el[ 'uniqueID' ],
wrapper = wrappers[ id ];
if( wrapper ) {
wrapper.destroy();
delete wrappers[ id ];
}
};
Element.destroyAll = function() {
var els = [], wrapper;
if( wrappers ) {
for( var w in wrappers ) {
if( wrappers.hasOwnProperty( w ) ) {
wrapper = wrappers[ w ];
els.push( wrapper.el );
wrapper.destroy();
}
}
wrappers = {};
}
return els;
};
return Element;
})();
/*
* This file exposes the public API for invoking PIE.
*/
/**
* The version number of this PIE build.
*/
PIE[ 'version' ] = '2.0beta1';
/**
* @property supportsVML
* True if the current IE browser environment has a functioning VML engine. Should be true
* in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
* attached to an element (for IE<9) to prevent errors; this property may also be used for
* debugging or by external scripts to perform some special action when VML support is absent.
* @type {boolean}
*/
PIE[ 'supportsVML' ] = PIE.supportsVML;
/**
* Programatically attach PIE to a single element.
* @param {Element} el
*/
PIE[ 'attach' ] = function( el ) {
if ( PIE.ieDocMode === 9 || ( PIE.ieDocMode < 9 && PIE.supportsVML ) ) {
PIE.Element.getInstance( el ).init();
}
};
/**
* Programatically detach PIE from a single element.
* @param {Element} el
*/
PIE[ 'detach' ] = function( el ) {
PIE.Element.destroy( el );
};
})( window, document ); | JavaScript |
/*
PIE: CSS3 rendering for IE
Version 2.0beta1
http://css3pie.com
Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2.
*/
(function( win, doc ) {
var PIE = win[ 'PIE' ] || ( win[ 'PIE' ] = {} );
/**
* Simple utility for merging objects
* @param {Object} obj1 The main object into which all others will be merged
* @param {...Object} var_args Other objects which will be merged into the first, in order
*/
PIE.merge = function( obj1 ) {
var i, len, p, objN, args = arguments;
for( i = 1, len = args.length; i < len; i++ ) {
objN = args[i];
for( p in objN ) {
if( objN.hasOwnProperty( p ) ) {
obj1[ p ] = objN[ p ];
}
}
}
return obj1;
};
PIE.merge(PIE, {
// Constants
CSS_PREFIX: '-pie-',
STYLE_PREFIX: 'Pie',
CLASS_PREFIX: 'pie_',
tableCellTags: {
'TD': 1,
'TH': 1
},
/**
* Lookup table of elements which cannot take custom children.
*/
childlessElements: {
'TABLE':1,
'THEAD':1,
'TBODY':1,
'TFOOT':1,
'TR':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'OPTION':1,
'IMG':1,
'HR':1
},
/**
* Elements that can receive user focus
*/
focusableElements: {
'A':1,
'INPUT':1,
'TEXTAREA':1,
'SELECT':1,
'BUTTON':1
},
/**
* Values of the type attribute for input elements displayed as buttons
*/
inputButtonTypes: {
'submit':1,
'button':1,
'reset':1
},
emptyFn: function() {}
});
// Force the background cache to be used. No reason it shouldn't be.
try {
doc.execCommand( 'BackgroundImageCache', false, true );
} catch(e) {}
(function() {
/*
* IE version detection approach by James Padolsey, with modifications -- from
* http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
*/
var ieVersion = 4,
div = doc.createElement('div'),
all = div.getElementsByTagName('i'),
shape;
while (
div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
all[0]
) {}
PIE.ieVersion = ieVersion;
// Detect IE6
if( ieVersion === 6 ) {
// IE6 can't access properties with leading dash, but can without it.
PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
}
PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
// Detect VML support (a small number of IE installs don't have a working VML engine)
div.innerHTML = '<v:shape adj="1"/>';
shape = div.firstChild;
shape.style['behavior'] = 'url(#default#VML)';
PIE.supportsVML = (typeof shape['adj'] === "object");
})();
/**
* Utility functions
*/
(function() {
var idNum = 0,
imageSizes = {};
PIE.Util = {
/**
* Generate and return a unique ID for a given object. The generated ID is stored
* as a property of the object for future reuse. For DOM Elements, don't use this
* but use the IE-native uniqueID property instead.
* @param {Object} obj
*/
getUID: function( obj ) {
return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + idNum++ );
},
/**
* Execute a callback function, passing it the dimensions of a given image once
* they are known.
* @param {string} src The source URL of the image
* @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
* @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
*/
withImageSize: function( src, func, ctx ) {
var size = imageSizes[ src ], img, queue;
if( size ) {
// If we have a queue, add to it
if( Object.prototype.toString.call( size ) === '[object Array]' ) {
size.push( [ func, ctx ] );
}
// Already have the size cached, call func right away
else {
func.call( ctx, size );
}
} else {
queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
img = new Image();
img.onload = function() {
size = imageSizes[ src ] = { w: img.width, h: img.height };
for( var i = 0, len = queue.length; i < len; i++ ) {
queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
}
img.onload = null;
};
img.src = src;
}
}
};
})();/**
* Utility functions for handling gradients
*/
PIE.GradientUtil = {
toSideAngles: {
'top': 0,
'right': 90,
'bottom': 180,
'left': 270
},
getGradientMetrics: function( el, width, height, gradientInfo ) {
var angle = gradientInfo.angle,
toPos = gradientInfo.gradientTo,
dX, dY,
endPoint,
startX, startY,
endX, endY;
// If an angle was specified, just use it
if (angle) {
angle = angle.degrees();
}
// If a to-position was specified, find the appropriate angle for it
else if (toPos) {
// To a corner; find the adjacent corners and use the angle perpendicular to them
if (toPos[1]) {
dX = ( toPos[0] == 'top' || toPos[1] == 'top' ) ? width : -width;
dY = ( toPos[0] == 'left' || toPos[1] == 'left' ) ? -height : height;
angle = Math.atan2(dY, dX) * 180 / Math.PI;
}
// To a side; map to a vertical/horizontal angle
else {
angle = this.toSideAngles[toPos[0]];
}
}
// Neither specified; default is top to bottom
else {
angle = 180;
}
// Normalize the angle to a value between [0, 360)
while( angle < 0 ) {
angle += 360;
}
angle = angle % 360;
// Find the end point of the gradient line, extending the angle from the center point
// to where it intersects the perpendicular line passing through the nearest corner.
endPoint = PIE.GradientUtil.perpendicularIntersect(width / 2, height / 2, angle,
( angle >= 180 ? 0 : width ), ( angle < 90 || angle > 270 ? 0 : height )
);
endX = endPoint[0];
endY = endPoint[1];
startX = width - endX;
startY = height - endY;
return {
angle: angle,
endX: endX,
endY: endY,
startX: startX,
startY: startY,
lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
};
},
/**
* Find the point along a given line (defined by a starting point and an angle), at which
* that line is intersected by a perpendicular line extending through another point.
* @param x1 - x coord of the starting point
* @param y1 - y coord of the starting point
* @param angle - angle of the line extending from the starting point (in degrees)
* @param x2 - x coord of point along the perpendicular line
* @param y2 - y coord of point along the perpendicular line
* @return [ x, y ]
*/
perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
// Handle straight vertical and horizontal angles, for performance and to avoid
// divide-by-zero errors.
if( angle === 0 || angle === 180 ) {
return [ x1, y2 ];
}
else if( angle === 90 || angle === 270 ) {
return [ x2, y1 ];
}
else {
// General approach: determine the Ax+By=C formula for each line (the slope of the second
// line is the negative inverse of the first) and then solve for where both formulas have
// the same x/y values.
var a1 = Math.tan( ( angle - 90 ) * Math.PI / 180 ),
c1 = a1 * x1 - y1,
a2 = -1 / a1,
c2 = a2 * x2 - y2,
d = a2 - a1,
endX = ( c2 - c1 ) / d,
endY = ( a1 * c2 - a2 * c1 ) / d;
return [ endX, endY ];
}
},
/**
* Find the distance between two points
* @param {Number} p1x
* @param {Number} p1y
* @param {Number} p2x
* @param {Number} p2y
* @return {Number} the distance
*/
distance: function( p1x, p1y, p2x, p2y ) {
var dx = p2x - p1x,
dy = p2y - p1y;
return Math.abs(
dx === 0 ? dy :
dy === 0 ? dx :
Math.sqrt( dx * dx + dy * dy )
);
}
};/**
*
*/
PIE.Observable = function() {
/**
* List of registered observer functions
*/
this.observers = [];
/**
* Hash of function ids to their position in the observers list, for fast lookup
*/
this.indexes = {};
};
PIE.Observable.prototype = {
observe: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes,
observers = this.observers;
if( !( id in indexes ) ) {
indexes[ id ] = observers.length;
observers.push( fn );
}
},
unobserve: function( fn ) {
var id = PIE.Util.getUID( fn ),
indexes = this.indexes;
if( id && id in indexes ) {
delete this.observers[ indexes[ id ] ];
delete indexes[ id ];
}
},
fire: function() {
var o = this.observers,
i = o.length;
while( i-- ) {
o[ i ] && o[ i ]();
}
}
};/*
* Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
* always firing the onmove and onresize events when elements are moved or resized. We check a few
* times every second to make sure the elements have the correct position and size. See Element.js
* which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
* and false elsewhere.
*/
PIE.Heartbeat = new PIE.Observable();
PIE.Heartbeat.run = function() {
var me = this,
interval;
if( !me.running ) {
interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
(function beat() {
me.fire();
setTimeout(beat, interval);
})();
me.running = 1;
}
};
/**
* Create an observable listener for the onunload event
*/
(function() {
PIE.OnUnload = new PIE.Observable();
function handleUnload() {
PIE.OnUnload.fire();
win.detachEvent( 'onunload', handleUnload );
win[ 'PIE' ] = null;
}
win.attachEvent( 'onunload', handleUnload );
/**
* Attach an event which automatically gets detached onunload
*/
PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
target.attachEvent( name, handler );
this.observe( function() {
target.detachEvent( name, handler );
} );
};
})()/**
* Create a single observable listener for window resize events.
*/
PIE.OnResize = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( win, 'onresize', function() { PIE.OnResize.fire(); } );
/**
* Create a single observable listener for scroll events. Used for lazy loading based
* on the viewport, and for fixed position backgrounds.
*/
(function() {
PIE.OnScroll = new PIE.Observable();
function scrolled() {
PIE.OnScroll.fire();
}
PIE.OnUnload.attachManagedEvent( win, 'onscroll', scrolled );
PIE.OnResize.observe( scrolled );
})();
/**
* Listen for printing events, destroy all active PIE instances when printing, and
* restore them afterward.
*/
(function() {
var elements;
function beforePrint() {
elements = PIE.Element.destroyAll();
}
function afterPrint() {
if( elements ) {
for( var i = 0, len = elements.length; i < len; i++ ) {
PIE[ 'attach' ]( elements[i] );
}
elements = 0;
}
}
PIE.OnUnload.attachManagedEvent( win, 'onbeforeprint', beforePrint );
PIE.OnUnload.attachManagedEvent( win, 'onafterprint', afterPrint );
})();/**
* Create a single observable listener for document mouseup events.
*/
PIE.OnMouseup = new PIE.Observable();
PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
/**
* Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
* value is returned from PIE.getLength() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.Length = (function() {
var lengthCalcEl = doc.createElement( 'length-calc' ),
parent = doc.body || doc.documentElement,
s = lengthCalcEl.style,
conversions = {},
units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
i = units.length,
instances = {};
s.position = 'absolute';
s.top = s.left = '-9999px';
parent.appendChild( lengthCalcEl );
while( i-- ) {
s.width = '100' + units[i];
conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
}
parent.removeChild( lengthCalcEl );
// All calcs from here on will use 1em
s.width = '1em';
function Length( val ) {
this.val = val;
}
Length.prototype = {
/**
* Regular expression for matching the length unit
* @private
*/
unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
/**
* Get the numeric value of the length
* @return {number} The value
*/
getNumber: function() {
var num = this.num,
UNDEF;
if( num === UNDEF ) {
num = this.num = parseFloat( this.val );
}
return num;
},
/**
* Get the unit of the length
* @return {string} The unit
*/
getUnit: function() {
var unit = this.unit,
m;
if( !unit ) {
m = this.val.match( this.unitRE );
unit = this.unit = ( m && m[0] ) || 'px';
}
return unit;
},
/**
* Determine whether this is a percentage length value
* @return {boolean}
*/
isPercentage: function() {
return this.getUnit() === '%';
},
/**
* Resolve this length into a number of pixels.
* @param {Element} el - the context element, used to resolve font-relative values
* @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
* function which will be called to return the number.
*/
pixels: function( el, pct100 ) {
var num = this.getNumber(),
unit = this.getUnit();
switch( unit ) {
case "px":
return num;
case "%":
return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
case "em":
return num * this.getEmPixels( el );
case "ex":
return num * this.getEmPixels( el ) / 2;
default:
return num * conversions[ unit ];
}
},
/**
* The em and ex units are relative to the font-size of the current element,
* however if the font-size is set using non-pixel units then we get that value
* rather than a pixel conversion. To get around this, we keep a floating element
* with width:1em which we insert into the target element and then read its offsetWidth.
* For elements that won't accept a child we insert into the parent node and perform
* additional calculation. If the font-size *is* specified in pixels, then we use that
* directly to avoid the expensive DOM manipulation.
* @param {Element} el
* @return {number}
*/
getEmPixels: function( el ) {
var fs = el.currentStyle.fontSize,
px, parent, me;
if( fs.indexOf( 'px' ) > 0 ) {
return parseFloat( fs );
}
else if( el.tagName in PIE.childlessElements ) {
me = this;
parent = el.parentNode;
return PIE.getLength( fs ).pixels( parent, function() {
return me.getEmPixels( parent );
} );
}
else {
el.appendChild( lengthCalcEl );
px = lengthCalcEl.offsetWidth;
if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
el.removeChild( lengthCalcEl );
}
return px;
}
}
};
/**
* Convert a pixel length into a point length
*/
Length.pxToPt = function( px ) {
return px / conversions[ 'pt' ];
};
/**
* Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the length. It is assumed that this will already have
* been validated as a valid length or percentage syntax.
*/
PIE.getLength = function( val ) {
return instances[ val ] || ( instances[ val ] = new Length( val ) );
};
return Length;
})();
/**
* Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
* @constructor
* @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
*/
PIE.BgPosition = (function() {
var length_fifty = PIE.getLength( '50%' ),
vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
function BgPosition( tokens ) {
this.tokens = tokens;
}
BgPosition.prototype = {
/**
* Normalize the values into the form:
* [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
* where: xOffsetSide is either 'left' or 'right',
* yOffsetSide is either 'top' or 'bottom',
* and x/yOffsetLength are both PIE.Length objects.
* @return {Array}
*/
getValues: function() {
if( !this._values ) {
var tokens = this.tokens,
len = tokens.length,
Tokenizer = PIE.Tokenizer,
identType = Tokenizer.Type,
length_zero = PIE.getLength( '0' ),
type_ident = identType.IDENT,
type_length = identType.LENGTH,
type_percent = identType.PERCENT,
type, value,
vals = [ 'left', length_zero, 'top', length_zero ];
// If only one value, the second is assumed to be 'center'
if( len === 1 ) {
tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
len++;
}
// Two values - CSS2
if( len === 2 ) {
// If both idents, they can appear in either order, so switch them if needed
if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
tokens.push( tokens.shift() );
}
if( tokens[0].tokenType & type_ident ) {
if( tokens[0].tokenValue === 'center' ) {
vals[1] = length_fifty;
} else {
vals[0] = tokens[0].tokenValue;
}
}
else if( tokens[0].isLengthOrPercent() ) {
vals[1] = PIE.getLength( tokens[0].tokenValue );
}
if( tokens[1].tokenType & type_ident ) {
if( tokens[1].tokenValue === 'center' ) {
vals[3] = length_fifty;
} else {
vals[2] = tokens[1].tokenValue;
}
}
else if( tokens[1].isLengthOrPercent() ) {
vals[3] = PIE.getLength( tokens[1].tokenValue );
}
}
// Three or four values - CSS3
else {
// TODO
}
this._values = vals;
}
return this._values;
},
/**
* Find the coordinates of the background image from the upper-left corner of the background area.
* Note that these coordinate values are not rounded.
* @param {Element} el
* @param {number} width - the width for percentages (background area width minus image width)
* @param {number} height - the height for percentages (background area height minus image height)
* @return {Object} { x: Number, y: Number }
*/
coords: function( el, width, height ) {
var vals = this.getValues(),
pxX = vals[1].pixels( el, width ),
pxY = vals[3].pixels( el, height );
return {
x: vals[0] === 'right' ? width - pxX : pxX,
y: vals[2] === 'bottom' ? height - pxY : pxY
};
}
};
return BgPosition;
})();
/**
* Wrapper for a CSS3 background-size value.
* @constructor
* @param {String|PIE.Length} w The width parameter
* @param {String|PIE.Length} h The height parameter, if any
*/
PIE.BgSize = (function() {
var CONTAIN = 'contain',
COVER = 'cover',
AUTO = 'auto';
function BgSize( w, h ) {
this.w = w;
this.h = h;
}
BgSize.prototype = {
pixels: function( el, areaW, areaH, imgW, imgH ) {
var me = this,
w = me.w,
h = me.h,
areaRatio = areaW / areaH,
imgRatio = imgW / imgH;
if ( w === CONTAIN ) {
w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === COVER ) {
w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
}
else if ( w === AUTO ) {
h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
w = h * imgRatio;
}
else {
w = w.pixels( el, areaW );
h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
}
return { w: w, h: h };
}
};
BgSize.DEFAULT = new BgSize( AUTO, AUTO );
return BgSize;
})();
/**
* Wrapper for angle values; handles conversion to degrees from all allowed angle units
* @constructor
* @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
*/
PIE.Angle = (function() {
function Angle( val ) {
this.val = val;
}
Angle.prototype = {
unitRE: /[a-z]+$/i,
/**
* @return {string} The unit of the angle value
*/
getUnit: function() {
return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
},
/**
* Get the numeric value of the angle in degrees.
* @return {number} The degrees value
*/
degrees: function() {
var deg = this._deg, u, n;
if( deg === undefined ) {
u = this.getUnit();
n = parseFloat( this.val, 10 );
deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
}
return deg;
}
};
return Angle;
})();/**
* Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
* value is returned from PIE.getColor() - always use that instead of instantiating directly.
* @constructor
* @param {string} val The raw CSS string value for the color
*/
PIE.Color = (function() {
/*
* hsl2rgb from http://codingforums.com/showthread.php?t=11156
* code by Jason Karl Davis (http://www.jasonkarldavis.com)
* swiped from cssSandpaper by Zoltan Hawryluk (http://www.useragentman.com/blog/csssandpaper-a-css3-javascript-library/)
* modified for formatting and size optimizations
*/
function hsl2rgb( h, s, l ) {
var m1, m2, r, g, b,
round = Math.round;
s /= 100;
l /= 100;
if ( !s ) { r = g = b = l * 255; }
else {
if ( l <= 0.5 ) { m2 = l * ( s + 1 ); }
else { m2 = l + s - l * s; }
m1 = l * 2 - m2;
h = ( h % 360 ) / 360;
r = hueToRgb( m1, m2, h + 1/3 );
g = hueToRgb( m1, m2, h );
b = hueToRgb( m1, m2, h - 1/3 );
}
return { r: round( r ), g: round( g ), b: round( b ) };
}
function hueToRgb( m1, m2, hue ) {
var v;
if ( hue < 0 ) { hue += 1; }
else if ( hue > 1 ) { hue -= 1; }
if ( 6 * hue < 1 ) { v = m1 + ( m2 - m1 ) * hue * 6; }
else if ( 2 * hue < 1 ) { v = m2; }
else if ( 3 * hue < 2 ) { v = m1 + ( m2 - m1 ) * ( 2/3 - hue ) * 6; }
else { v = m1; }
return 255 * v;
}
var instances = {};
function Color( val ) {
this.val = val;
}
/**
* Regular expression for matching rgba colors and extracting their components
* @type {RegExp}
*/
Color.rgbOrRgbaRE = /\s*rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/;
Color.hslOrHslaRE = /\s*hsla?\(\s*(\d*\.?\d+)\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/;
/**
* Hash of color keyword names to their corresponding hex values. Encoded for
* small size and expanded into a hash on startup.
*/
Color.names = {};
var names = 'black|0|navy|3k|darkblue|b|mediumblue|1u|blue|1e|darkgreen|jk1|green|5j4|teal|3k|darkcyan|26j|deepskyblue|ad0|darkturquoise|2xe|mediumspringgreen|8nd|lime|va|springgreen|3j|aqua|3k|cyan|0|midnightblue|xunl|dodgerblue|7ogf|lightseagreen|2zsb|forestgreen|2lbs|seagreen|guut|darkslategray|12pk|limegreen|4wkj|mediumseagreen|dwlb|turquoise|5v8f|royalblue|r2p|steelblue|75qr|darkslateblue|2fh3|mediumturquoise|ta9|indigo|32d2|darkolivegreen|emr1|cadetblue|ebu9|cornflowerblue|6z4d|mediumaquamarine|3459|dimgray|3nwf|slateblue|1bok|olivedrab|1opi|slategray|6y5p|lightslategray|9vk9|mediumslateblue|5g0l|lawngreen|27ma|chartreuse|48ao|aquamarine|5w|maroon|18|purple|3k|olive|p6o|gray|3k|lightslateblue|5j7j|skyblue|4q98|lightskyblue|f|blueviolet|3bhk|darkred|15we|darkmagenta|3v|saddlebrown|djc|darkseagreen|69vg|lightgreen|1og1|mediumpurple|3ivc|darkviolet|sfv|palegreen|6zt1|darkorchid|awk|yellowgreen|292e|sienna|7r3v|brown|6sxp|darkgray|6bgf|lightblue|5vlp|greenyellow|7k9|paleturquoise|2pxb|lightsteelblue|169c|powderblue|5jc|firebrick|1rgc|darkgoldenrod|8z55|mediumorchid|2jm0|rosybrown|34jg|darkkhaki|1mfw|silver|49jp|mediumvioletred|8w5h|indianred|8tef|peru|82r|violetred|3ntd|feldspar|212d|chocolate|16eh|tan|ewe|lightgrey|1kqv|palevioletred|6h8g|metle|fnp|orchid|2dj2|goldenrod|abu|crimson|20ik|gainsboro|13mo|plum|12pt|burlywood|1j8q|lightcyan|3794|lavender|8agr|darksalmon|3rsw|violet|6wz8|palegoldenrod|k3g|lightcoral|28k6|khaki|k5o|aliceblue|3n7|honeydew|1dd|azure|f|sandybrown|5469|wheat|1q37|beige|4kp|whitesmoke|p|mintcream|1z9|ghostwhite|46bp|salmon|25bn|antiquewhite|l7p|linen|zz|lightgoldenrodyellow|1yk|oldlace|46qc|red|1gka|magenta|73|fuchsia|0|deeppink|3v8|orangered|9kd|tomato|5zb|hotpink|19p|coral|49o|darkorange|2i8|lightsalmon|41m|orange|w6|lightpink|3i9|pink|1ze|gold|4dx|peachpuff|qh|navajowhite|s4|moccasin|16w|bisque|f|mistyrose|t|blanchedalmond|1d8|papayawhip|so|lavenderblush|80|seashell|zd|cornsilk|ku|lemonchiffon|dt|floralwhite|z|snow|a|yellow|sm|lightyellow|68|ivory|g|white|f'.split('|'),
i = 0, len = names.length, color = 0, hexColor;
for(; i < len; i += 2) {
color += parseInt(names[i + 1], 36);
hexColor = color.toString(16);
Color.names[names[i]] = '#000000'.slice(0, -hexColor.length) + hexColor;
}
Color.prototype = {
/**
* @private
*/
parse: function() {
if( !this._color ) {
var me = this,
color = me.val,
alpha, vLower, m, rgb;
// RGB or RGBA colors
if( m = color.match( Color.rgbOrRgbaRE ) ) {
color = me.rgbToHex( +m[1], +m[2], +m[3] );
alpha = m[5] ? +m[5] : 1;
}
// HSL or HSLA colors
else if( m = color.match( Color.hslOrHslaRE ) ) {
rgb = hsl2rgb( m[1], m[2], m[3] );
color = me.rgbToHex( rgb.r, rgb.g, rgb.b );
alpha = m[5] ? +m[5] : 1;
}
else {
if( Color.names.hasOwnProperty( vLower = color.toLowerCase() ) ) {
color = Color.names[vLower];
}
alpha = ( color === 'transparent' ? 0 : 1 );
}
me._color = color;
me._alpha = alpha;
}
},
/**
* Converts RGB color channels to a hex value string
*/
rgbToHex: function( r, g, b ) {
return '#' + ( r < 16 ? '0' : '' ) + r.toString( 16 ) +
( g < 16 ? '0' : '' ) + g.toString( 16 ) +
( b < 16 ? '0' : '' ) + b.toString( 16 );
},
/**
* Retrieve the value of the color in a format usable by IE natively. This will be the same as
* the raw input value, except for rgb(a) and hsl(a) values which will be converted to a hex value.
* @param {Element} el The context element, used to get 'currentColor' keyword value.
* @return {string} Color value
*/
colorValue: function( el ) {
this.parse();
return this._color === 'currentColor' ? PIE.getColor( el.currentStyle.color ).colorValue( el ) : this._color;
},
/**
* Retrieve the value of the color in a normalized six-digit hex format.
* @param el
*/
hexValue: function( el ) {
var color = this.colorValue( el );
// At this point the color should be either a 3- or 6-digit hex value, or the string "transparent".
function ch( i ) {
return color.charAt( i );
}
// Fudge transparent to black - should be ignored anyway since its alpha will be 0
if( color === 'transparent' ) {
color = '#000';
}
// Expand 3-digit to 6-digit hex
if( ch(0) === '#' && color.length === 4 ) {
color = '#' + ch(1) + ch(1) + ch(2) + ch(2) + ch(3) + ch(3);
}
return color;
},
/**
* Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
* with an alpha component.
* @return {number} The alpha value, from 0 to 1.
*/
alpha: function() {
this.parse();
return this._alpha;
}
};
/**
* Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
* @param {string} val The CSS string representing the color. It is assumed that this will already have
* been validated as a valid color syntax.
*/
PIE.getColor = function(val) {
return instances[ val ] || ( instances[ val ] = new Color( val ) );
};
return Color;
})();/**
* A tokenizer for CSS value strings.
* @constructor
* @param {string} css The CSS value string
*/
PIE.Tokenizer = (function() {
function Tokenizer( css ) {
this.css = css;
this.ch = 0;
this.tokens = [];
this.tokenIndex = 0;
}
/**
* Enumeration of token type constants.
* @enum {number}
*/
var Type = Tokenizer.Type = {
ANGLE: 1,
CHARACTER: 2,
COLOR: 4,
DIMEN: 8,
FUNCTION: 16,
IDENT: 32,
LENGTH: 64,
NUMBER: 128,
OPERATOR: 256,
PERCENT: 512,
STRING: 1024,
URL: 2048
};
/**
* A single token
* @constructor
* @param {number} type The type of the token - see PIE.Tokenizer.Type
* @param {string} value The value of the token
*/
Tokenizer.Token = function( type, value ) {
this.tokenType = type;
this.tokenValue = value;
};
Tokenizer.Token.prototype = {
isLength: function() {
return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
},
isLengthOrPercent: function() {
return this.isLength() || this.tokenType & Type.PERCENT;
}
};
Tokenizer.prototype = {
whitespace: /\s/,
number: /^[\+\-]?(\d*\.)?\d+/,
url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
ident: /^\-?[_a-z][\w-]*/i,
string: /^("([^"]*)"|'([^']*)')/,
operator: /^[\/,]/,
hash: /^#[\w]+/,
hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
unitTypes: {
'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
'pt': Type.LENGTH, 'pc': Type.LENGTH,
'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
},
colorFunctions: {
'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
},
/**
* Advance to and return the next token in the CSS string. If the end of the CSS string has
* been reached, null will be returned.
* @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
* @return {PIE.Tokenizer.Token}
*/
next: function( forget ) {
var css, ch, firstChar, match, val,
me = this;
function newToken( type, value ) {
var tok = new Tokenizer.Token( type, value );
if( !forget ) {
me.tokens.push( tok );
me.tokenIndex++;
}
return tok;
}
function failure() {
me.tokenIndex++;
return null;
}
// In case we previously backed up, return the stored token in the next slot
if( this.tokenIndex < this.tokens.length ) {
return this.tokens[ this.tokenIndex++ ];
}
// Move past leading whitespace characters
while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
this.ch++;
}
if( this.ch >= this.css.length ) {
return failure();
}
ch = this.ch;
css = this.css.substring( this.ch );
firstChar = css.charAt( 0 );
switch( firstChar ) {
case '#':
if( match = css.match( this.hashColor ) ) {
this.ch += match[0].length;
return newToken( Type.COLOR, match[0] );
}
break;
case '"':
case "'":
if( match = css.match( this.string ) ) {
this.ch += match[0].length;
return newToken( Type.STRING, match[2] || match[3] || '' );
}
break;
case "/":
case ",":
this.ch++;
return newToken( Type.OPERATOR, firstChar );
case 'u':
if( match = css.match( this.url ) ) {
this.ch += match[0].length;
return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
}
}
// Numbers and values starting with numbers
if( match = css.match( this.number ) ) {
val = match[0];
this.ch += val.length;
// Check if it is followed by a unit
if( css.charAt( val.length ) === '%' ) {
this.ch++;
return newToken( Type.PERCENT, val + '%' );
}
if( match = css.substring( val.length ).match( this.ident ) ) {
val += match[0];
this.ch += match[0].length;
return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
}
// Plain ol' number
return newToken( Type.NUMBER, val );
}
// Identifiers
if( match = css.match( this.ident ) ) {
val = match[0];
this.ch += val.length;
// Named colors
if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
return newToken( Type.COLOR, val );
}
// Functions
if( css.charAt( val.length ) === '(' ) {
this.ch++;
// Color values in function format: rgb, rgba, hsl, hsla
if( val.toLowerCase() in this.colorFunctions ) {
function isNum( tok ) {
return tok && tok.tokenType & Type.NUMBER;
}
function isNumOrPct( tok ) {
return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
}
function isValue( tok, val ) {
return tok && tok.tokenValue === val;
}
function next() {
return me.next( 1 );
}
if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
isValue( next(), ',' ) &&
isNumOrPct( next() ) &&
( val === 'rgb' || val === 'hsa' || (
isValue( next(), ',' ) &&
isNum( next() )
) ) &&
isValue( next(), ')' ) ) {
return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
}
return failure();
}
return newToken( Type.FUNCTION, val );
}
// Other identifier
return newToken( Type.IDENT, val );
}
// Standalone character
this.ch++;
return newToken( Type.CHARACTER, firstChar );
},
/**
* Determine whether there is another token
* @return {boolean}
*/
hasNext: function() {
var next = this.next();
this.prev();
return !!next;
},
/**
* Back up and return the previous token
* @return {PIE.Tokenizer.Token}
*/
prev: function() {
return this.tokens[ this.tokenIndex-- - 2 ];
},
/**
* Retrieve all the tokens in the CSS string
* @return {Array.<PIE.Tokenizer.Token>}
*/
all: function() {
while( this.next() ) {}
return this.tokens;
},
/**
* Return a list of tokens from the current position until the given function returns
* true. The final token will not be included in the list.
* @param {function():boolean} func - test function
* @param {boolean} require - if true, then if the end of the CSS string is reached
* before the test function returns true, null will be returned instead of the
* tokens that have been found so far.
* @return {Array.<PIE.Tokenizer.Token>}
*/
until: function( func, require ) {
var list = [], t, hit;
while( t = this.next() ) {
if( func( t ) ) {
hit = true;
this.prev();
break;
}
list.push( t );
}
return require && !hit ? null : list;
}
};
return Tokenizer;
})();/**
* Handles calculating, caching, and detecting changes to size and position of the element.
* @constructor
* @param {Element} el the target element
*/
PIE.BoundsInfo = function( el ) {
this.targetElement = el;
};
PIE.BoundsInfo.prototype = {
_locked: 0,
/**
* Determines if the element's position has changed since the last update.
* TODO this does a simple getBoundingClientRect comparison for detecting the
* changes in position, which may not always be accurate; it's possible that
* an element will actually move relative to its positioning parent, but its position
* relative to the viewport will stay the same. Need to come up with a better way to
* track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
* but that is a more expensive operation since it performs DOM walking, and we want this
* check to be as fast as possible. Perhaps introduce a -pie-* flag to trigger the slower
* but more accurate method?
*/
positionChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
},
sizeChanged: function() {
var last = this._lastBounds,
bounds;
return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
},
getLiveBounds: function() {
var el = this.targetElement,
rect = el.getBoundingClientRect(),
isIE9 = PIE.ieDocMode === 9,
isIE7 = PIE.ieVersion === 7,
width = rect.right - rect.left;
return {
x: rect.left,
y: rect.top,
// In some cases scrolling the page will cause IE9 to report incorrect dimensions
// in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
// instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
// so we must calculate the ratio and use it in certain places as a position adjustment.
w: isIE9 || isIE7 ? el.offsetWidth : width,
h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
};
},
getBounds: function() {
return this._locked ?
( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
this.getLiveBounds();
},
hasBeenQueried: function() {
return !!this._lastBounds;
},
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
this._lockedBounds = null;
}
}
};
(function() {
function cacheWhenLocked( fn ) {
var uid = PIE.Util.getUID( fn );
return function() {
if( this._locked ) {
var cache = this._lockedValues || ( this._lockedValues = {} );
return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
} else {
return fn.call( this );
}
}
}
PIE.StyleInfoBase = {
_locked: 0,
/**
* Create a new StyleInfo class, with the standard constructor, and augmented by
* the StyleInfoBase's members.
* @param proto
*/
newStyleInfo: function( proto ) {
function StyleInfo( el ) {
this.targetElement = el;
this._lastCss = this.getCss();
}
PIE.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
StyleInfo._propsCache = {};
return StyleInfo;
},
/**
* Get an object representation of the target CSS style, caching it for each unique
* CSS value string.
* @return {Object}
*/
getProps: function() {
var css = this.getCss(),
cache = this.constructor._propsCache;
return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
},
/**
* Get the raw CSS value for the target style
* @return {string}
*/
getCss: cacheWhenLocked( function() {
var el = this.targetElement,
ctor = this.constructor,
s = el.style,
cs = el.currentStyle,
cssProp = this.cssProperty,
styleProp = this.styleProperty,
prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
} ),
/**
* Determine whether the target CSS style is active.
* @return {boolean}
*/
isActive: cacheWhenLocked( function() {
return !!this.getProps();
} ),
/**
* Determine whether the target CSS style has changed since the last time it was used.
* @return {boolean}
*/
changed: cacheWhenLocked( function() {
var currentCss = this.getCss(),
changed = currentCss !== this._lastCss;
this._lastCss = currentCss;
return changed;
} ),
cacheWhenLocked: cacheWhenLocked,
lock: function() {
++this._locked;
},
unlock: function() {
if( !--this._locked ) {
delete this._lockedValues;
}
}
};
})();/**
* Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: PIE.CSS_PREFIX + 'background',
styleProperty: PIE.STYLE_PREFIX + 'Background',
attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
sizeIdents: { 'contain':1, 'cover':1 },
tbIdents: { 'top': 1, 'bottom': 1 },
lrIdents: { 'left': 1, 'right': 1 },
propertyNames: {
CLIP: 'backgroundClip',
COLOR: 'backgroundColor',
IMAGE: 'backgroundImage',
ORIGIN: 'backgroundOrigin',
POSITION: 'backgroundPosition',
REPEAT: 'backgroundRepeat',
SIZE: 'backgroundSize'
},
/**
* For background styles, we support the -pie-background property but fall back to the standard
* backround* properties. The reason we have to use the prefixed version is that IE natively
* parses the standard properties and if it sees something it doesn't know how to parse, for example
* multiple values or gradient definitions, it will throw that away and not make it available through
* currentStyle.
*
* Format of return object:
* {
* color: <PIE.Color>,
* colorClip: <'border-box' | 'padding-box'>,
* bgImages: [
* {
* imgType: 'image',
* imgUrl: 'image.png',
* imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
* bgPosition: <PIE.BgPosition>,
* bgAttachment: <'scroll' | 'fixed' | 'local'>,
* bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
* bgClip: <'border-box' | 'padding-box'>,
* bgSize: <PIE.BgSize>,
* origString: 'url(img.png) no-repeat top left'
* },
* {
* imgType: 'linear-gradient',
* gradientTo: [<'top' | 'bottom'>, <'left' | 'right'>?],
* angle: <PIE.Angle>,
* stops: [
* { color: <PIE.Color>, offset: <PIE.Length> },
* { color: <PIE.Color>, offset: <PIE.Length> }, ...
* ]
* }
* ]
* }
* @param {String} css
* @override
*/
parseCss: function( css ) {
var el = this.targetElement,
cs = el.currentStyle,
tokenizer, token, image,
tok_type = PIE.Tokenizer.Type,
type_operator = tok_type.OPERATOR,
type_ident = tok_type.IDENT,
type_color = tok_type.COLOR,
tokType, tokVal,
beginCharIndex = 0,
positionIdents = this.positionIdents,
gradient, stop, width, height, gradientTo, len, tbIdents, lrIdents,
props = { bgImages: [] };
function isBgPosToken( token ) {
return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
}
function sizeToken( token ) {
return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
}
// If the CSS3-specific -pie-background property is present, parse it
if( this.getCss3() ) {
tokenizer = new PIE.Tokenizer( css );
image = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
gradient = { stops: [], imgType: tokVal };
stop = {};
while( token = tokenizer.next() ) {
tokType = token.tokenType;
tokVal = token.tokenValue;
// If we reached the end of the function and had at least 2 stops, flush the info
if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
if( stop.color ) {
gradient.stops.push( stop );
}
if( gradient.stops.length > 1 ) {
PIE.merge( image, gradient );
}
break;
}
// Color stop - must start with color
if( tokType & type_color ) {
// if we already have an angle/position, make sure that the previous token was a comma
if( gradient.angle || gradient.gradientTo ) {
token = tokenizer.prev();
if( token.tokenType !== type_operator ) {
break; //fail
}
tokenizer.next();
}
stop = {
color: PIE.getColor( tokVal )
};
// check for offset following color
token = tokenizer.next();
if( token.isLengthOrPercent() ) {
stop.offset = PIE.getLength( token.tokenValue );
} else {
tokenizer.prev();
}
}
// Angle - can only appear in first spot
else if( tokType & tok_type.ANGLE && !gradient.angle && !gradient.gradientTo && !stop.color && !gradient.stops.length ) {
gradient.angle = new PIE.Angle( token.tokenValue );
}
// "to <side-or-corner>" - can only appear in first spot
else if( tokType & tok_type.IDENT && tokVal === 'to' && !gradient.gradientTo && !gradient.angle && !stop.color && !gradient.stops.length ) {
tbIdents = this.tbIdents;
lrIdents = this.lrIdents;
gradientTo = tokenizer.until( function( t ) {
return !(t && t.tokenType & tok_type.IDENT && ( t.tokenValue in tbIdents || t.tokenValue in lrIdents ));
} );
len = gradientTo.length;
gradientTo = [ gradientTo[0] && gradientTo[0].tokenValue, gradientTo[1] && gradientTo[1].tokenValue ];
// bail unless there are 1 or 2 values, or if the 2 values are from the same pair of sides
if ( len < 1 || len > 2 || ( len > 1 && (
( gradientTo[0] in tbIdents && gradientTo[1] in tbIdents ) ||
( gradientTo[0] in lrIdents && gradientTo[1] in lrIdents )
) ) ) {
break;
}
gradient.gradientTo = gradientTo;
}
else if( tokType & type_operator && tokVal === ',' ) {
if( stop.color ) {
gradient.stops.push( stop );
stop = {};
}
}
else {
// Found something we didn't recognize; fail without adding image
break;
}
}
}
else if( !image.imgType && tokType & tok_type.URL ) {
image.imgUrl = tokVal;
image.imgType = 'image';
}
else if( isBgPosToken( token ) && !image.bgPosition ) {
tokenizer.prev();
image.bgPosition = new PIE.BgPosition(
tokenizer.until( function( t ) {
return !isBgPosToken( t );
}, false )
);
}
else if( tokType & type_ident ) {
if( tokVal in this.repeatIdents && !image.imgRepeat ) {
image.imgRepeat = tokVal;
}
else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
image.bgOrigin = tokVal;
if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
token.tokenValue in this.originAndClipIdents ) {
image.bgClip = token.tokenValue;
} else {
image.bgClip = tokVal;
tokenizer.prev();
}
}
else if( tokVal in this.attachIdents && !image.bgAttachment ) {
image.bgAttachment = tokVal;
}
else {
return null;
}
}
else if( tokType & type_color && !props.color ) {
props.color = PIE.getColor( tokVal );
}
else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
// background size
token = tokenizer.next();
if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
image.bgSize = new PIE.BgSize( token.tokenValue );
}
else if( width = sizeToken( token ) ) {
height = sizeToken( tokenizer.next() );
if ( !height ) {
height = width;
tokenizer.prev();
}
image.bgSize = new PIE.BgSize( width, height );
}
else {
return null;
}
}
// new layer
else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
beginCharIndex = tokenizer.ch;
props.bgImages.push( image );
image = {};
}
else {
// Found something unrecognized; chuck everything
return null;
}
}
// leftovers
if( image.imgType ) {
image.origString = css.substring( beginCharIndex );
props.bgImages.push( image );
}
props.colorClip = image.bgClip;
}
// Otherwise, use the standard background properties; let IE give us the values rather than parsing them
else {
this.withActualBg( PIE.ieDocMode < 9 ?
function() {
var propNames = this.propertyNames,
posX = cs[propNames.POSITION + 'X'],
posY = cs[propNames.POSITION + 'Y'],
img = cs[propNames.IMAGE],
color = cs[propNames.COLOR];
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
if( img !== 'none' ) {
props.bgImages = [ {
imgType: 'image',
imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
imgRepeat: cs[propNames.REPEAT],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
} ];
}
} :
function() {
var propNames = this.propertyNames,
splitter = /\s*,\s*/,
images = cs[propNames.IMAGE].split( splitter ),
color = cs[propNames.COLOR],
repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
if( color !== 'transparent' ) {
props.color = PIE.getColor( color )
}
len = images.length;
if( len && images[0] !== 'none' ) {
repeats = cs[propNames.REPEAT].split( splitter );
positions = cs[propNames.POSITION].split( splitter );
origins = cs[propNames.ORIGIN].split( splitter );
clips = cs[propNames.CLIP].split( splitter );
sizes = cs[propNames.SIZE].split( splitter );
props.bgImages = [];
for( i = 0; i < len; i++ ) {
image = images[ i ];
if( image && image !== 'none' ) {
sizeParts = sizes[i].split( ' ' );
props.bgImages.push( {
origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
origins[ i ] + ' ' + clips[ i ],
imgType: 'image',
imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
imgRepeat: repeats[ i ],
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
bgOrigin: origins[ i ],
bgClip: clips[ i ],
bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
} );
}
}
}
}
);
}
return ( props.color || props.bgImages[0] ) ? props : null;
},
/**
* Execute a function with the actual background styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBg: function( fn ) {
var isIE9 = PIE.ieDocMode > 8,
propNames = this.propertyNames,
rs = this.targetElement.runtimeStyle,
rsImage = rs[propNames.IMAGE],
rsColor = rs[propNames.COLOR],
rsRepeat = rs[propNames.REPEAT],
rsClip, rsOrigin, rsSize, rsPosition, ret;
if( rsImage ) rs[propNames.IMAGE] = '';
if( rsColor ) rs[propNames.COLOR] = '';
if( rsRepeat ) rs[propNames.REPEAT] = '';
if( isIE9 ) {
rsClip = rs[propNames.CLIP];
rsOrigin = rs[propNames.ORIGIN];
rsPosition = rs[propNames.POSITION];
rsSize = rs[propNames.SIZE];
if( rsClip ) rs[propNames.CLIP] = '';
if( rsOrigin ) rs[propNames.ORIGIN] = '';
if( rsPosition ) rs[propNames.POSITION] = '';
if( rsSize ) rs[propNames.SIZE] = '';
}
ret = fn.call( this );
if( rsImage ) rs[propNames.IMAGE] = rsImage;
if( rsColor ) rs[propNames.COLOR] = rsColor;
if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
if( isIE9 ) {
if( rsClip ) rs[propNames.CLIP] = rsClip;
if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
if( rsPosition ) rs[propNames.POSITION] = rsPosition;
if( rsSize ) rs[propNames.SIZE] = rsSize;
}
return ret;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
return this.getCss3() ||
this.withActualBg( function() {
var cs = this.targetElement.currentStyle,
propNames = this.propertyNames;
return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
} );
} ),
getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement;
return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
} ),
/**
* For a given background-origin value, return the dimensions of the background area.
* @param {String} bgOrigin
* @param {PIE.BoundsInfo} boundsInfo
* @param {PIE.BorderStyleInfo} borderInfo
*/
getBgAreaSize: function( bgOrigin, boundsInfo, borderInfo, paddingInfo ) {
var el = this.targetElement,
bounds = boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
borders, paddings;
if( bgOrigin !== 'border-box' ) {
borders = borderInfo.getProps();
if( borders && ( borders = borders.widths ) ) {
w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
}
}
if ( bgOrigin === 'content-box' ) {
paddings = paddingInfo.getProps();
if ( paddings ) {
w -= paddings[ 'l' ].pixels( el ) + paddings[ 'l' ].pixels( el );
h -= paddings[ 't' ].pixels( el ) + paddings[ 'b' ].pixels( el );
}
}
return { w: w, h: h };
},
/**
* Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
*/
isPngFix: function() {
var val = 0, el;
if( PIE.ieVersion < 7 ) {
el = this.targetElement;
val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
}
return val;
},
/**
* The isActive logic is slightly different, because getProps() always returns an object
* even if it is just falling back to the native background properties. But we only want
* to report is as being "active" if either the -pie-background override property is present
* and parses successfully or '-pie-png-fix' is set to true in IE6.
*/
isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
return (this.getCss3() || this.isPngFix()) && !!this.getProps();
} )
} );/**
* Handles parsing, caching, and detecting changes to border CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
namedWidths: {
'thin': '1px',
'medium': '3px',
'thick': '5px'
},
parseCss: function( css ) {
var w = {},
s = {},
c = {},
active = false,
colorsSame = true,
stylesSame = true,
widthsSame = true;
this.withActualBorder( function() {
var el = this.targetElement,
cs = el.currentStyle,
i = 0,
style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
for( ; i < 4; i++ ) {
side = this.sides[ i ];
ltr = side.charAt(0).toLowerCase();
style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
color = cs[ 'border' + side + 'Color' ];
width = cs[ 'border' + side + 'Width' ];
if( i > 0 ) {
if( style !== lastStyle ) { stylesSame = false; }
if( color !== lastColor ) { colorsSame = false; }
if( width !== lastWidth ) { widthsSame = false; }
}
lastStyle = style;
lastColor = color;
lastWidth = width;
c[ ltr ] = PIE.getColor( color );
width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
if( width.pixels( this.targetElement ) > 0 ) {
active = true;
}
}
} );
return active ? {
widths: w,
styles: s,
colors: c,
widthsSame: widthsSame,
colorsSame: colorsSame,
stylesSame: stylesSame
} : null;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement,
cs = el.currentStyle,
css;
// Don't redraw or hide borders for cells in border-collapse:collapse tables
if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
this.withActualBorder( function() {
css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
} );
}
return css;
} ),
/**
* Execute a function with the actual border styles (not overridden with runtimeStyle
* properties set by the renderers) available via currentStyle.
* @param fn
*/
withActualBorder: function( fn ) {
var rs = this.targetElement.runtimeStyle,
rsWidth = rs.borderWidth,
rsColor = rs.borderColor,
ret;
if( rsWidth ) rs.borderWidth = '';
if( rsColor ) rs.borderColor = '';
ret = fn.call( this );
if( rsWidth ) rs.borderWidth = rsWidth;
if( rsColor ) rs.borderColor = rsColor;
return ret;
}
} );
/**
* Handles parsing, caching, and detecting changes to border-radius CSS
* @constructor
* @param {Element} el the target element
*/
(function() {
PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'border-radius',
styleProperty: 'borderRadius',
parseCss: function( css ) {
var p = null, x, y,
tokenizer, token, length,
hasNonZero = false;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
function collectLengths() {
var arr = [], num;
while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
length = PIE.getLength( token.tokenValue );
num = length.getNumber();
if( num < 0 ) {
return null;
}
if( num > 0 ) {
hasNonZero = true;
}
arr.push( length );
}
return arr.length > 0 && arr.length < 5 ? {
'tl': arr[0],
'tr': arr[1] || arr[0],
'br': arr[2] || arr[0],
'bl': arr[3] || arr[1] || arr[0]
} : null;
}
// Grab the initial sequence of lengths
if( x = collectLengths() ) {
// See if there is a slash followed by more lengths, for the y-axis radii
if( token ) {
if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) {
y = collectLengths();
}
} else {
y = x;
}
// Treat all-zero values the same as no value
if( hasNonZero && x && y ) {
p = { x: x, y : y };
}
}
}
return p;
}
} );
var zero = PIE.getLength( '0' ),
zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero };
PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros };
})();/**
* Handles parsing, caching, and detecting changes to border-image CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'border-image',
styleProperty: 'borderImage',
repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
parseCss: function( css ) {
var p = null, tokenizer, token, type, value,
slices, widths, outsets,
slashCount = 0,
Type = PIE.Tokenizer.Type,
IDENT = Type.IDENT,
NUMBER = Type.NUMBER,
PERCENT = Type.PERCENT;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
p = {};
function isSlash( token ) {
return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
}
function isFillIdent( token ) {
return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
}
function collectSlicesEtc() {
slices = tokenizer.until( function( tok ) {
return !( tok.tokenType & ( NUMBER | PERCENT ) );
} );
if( isFillIdent( tokenizer.next() ) && !p.fill ) {
p.fill = true;
} else {
tokenizer.prev();
}
if( isSlash( tokenizer.next() ) ) {
slashCount++;
widths = tokenizer.until( function( token ) {
return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
} );
if( isSlash( tokenizer.next() ) ) {
slashCount++;
outsets = tokenizer.until( function( token ) {
return !token.isLength();
} );
}
} else {
tokenizer.prev();
}
}
while( token = tokenizer.next() ) {
type = token.tokenType;
value = token.tokenValue;
// Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
if( type & ( NUMBER | PERCENT ) && !slices ) {
tokenizer.prev();
collectSlicesEtc();
}
else if( isFillIdent( token ) && !p.fill ) {
p.fill = true;
collectSlicesEtc();
}
// Idents: one or values for 'repeat'
else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
p.repeat = { h: value };
if( token = tokenizer.next() ) {
if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
p.repeat.v = token.tokenValue;
} else {
tokenizer.prev();
}
}
}
// URL of the image
else if( ( type & Type.URL ) && !p.src ) {
p.src = value;
}
// Found something unrecognized; exit.
else {
return null;
}
}
// Validate what we collected
if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
return null;
}
// Fill in missing values
if( !p.repeat ) {
p.repeat = { h: 'stretch' };
}
if( !p.repeat.v ) {
p.repeat.v = p.repeat.h;
}
function distributeSides( tokens, convertFn ) {
return {
't': convertFn( tokens[0] ),
'r': convertFn( tokens[1] || tokens[0] ),
'b': convertFn( tokens[2] || tokens[0] ),
'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
};
}
p.slice = distributeSides( slices, function( tok ) {
return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
} );
if( widths && widths[0] ) {
p.widths = distributeSides( widths, function( tok ) {
return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
if( outsets && outsets[0] ) {
p.outset = distributeSides( outsets, function( tok ) {
return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
} );
}
}
return p;
}
} );/**
* Handles parsing, caching, and detecting changes to box-shadow CSS
* @constructor
* @param {Element} el the target element
*/
PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
cssProperty: 'box-shadow',
styleProperty: 'boxShadow',
parseCss: function( css ) {
var props,
getLength = PIE.getLength,
Type = PIE.Tokenizer.Type,
tokenizer;
if( css ) {
tokenizer = new PIE.Tokenizer( css );
props = { outset: [], inset: [] };
function parseItem() {
var token, type, value, color, lengths, inset, len;
while( token = tokenizer.next() ) {
value = token.tokenValue;
type = token.tokenType;
if( type & Type.OPERATOR && value === ',' ) {
break;
}
else if( token.isLength() && !lengths ) {
tokenizer.prev();
lengths = tokenizer.until( function( token ) {
return !token.isLength();
} );
}
else if( type & Type.COLOR && !color ) {
color = value;
}
else if( type & Type.IDENT && value === 'inset' && !inset ) {
inset = true;
}
else { //encountered an unrecognized token; fail.
return false;
}
}
len = lengths && lengths.length;
if( len > 1 && len < 5 ) {
( inset ? props.inset : props.outset ).push( {
xOffset: getLength( lengths[0].tokenValue ),
yOffset: getLength( lengths[1].tokenValue ),
blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ),
spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ),
color: PIE.getColor( color || 'currentColor' )
} );
return true;
}
return false;
}
while( parseItem() ) {}
}
return props && ( props.inset.length || props.outset.length ) ? props : null;
}
} );
/**
* Handles parsing, caching, and detecting changes to padding CSS
* @constructor
* @param {Element} el the target element
*/
PIE.PaddingStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
parseCss: function( css ) {
var tokenizer = new PIE.Tokenizer( css ),
arr = [],
token;
while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
arr.push( PIE.getLength( token.tokenValue ) );
}
return arr.length > 0 && arr.length < 5 ? {
't': arr[0],
'r': arr[1] || arr[0],
'b': arr[2] || arr[0],
'l': arr[3] || arr[1] || arr[0]
} : null;
},
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement,
rs = el.runtimeStyle,
rsPadding = rs.padding,
padding;
if( rsPadding ) rs.padding = '';
padding = el.currentStyle.padding;
if( rsPadding ) rs.padding = rsPadding;
return padding;
} )
} );
/**
* Retrieves the state of the element's visibility and display
* @constructor
* @param {Element} el the target element
*/
PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
var el = this.targetElement,
rs = el.runtimeStyle,
cs = el.currentStyle,
rsVis = rs.visibility,
ret;
rs.visibility = '';
ret = cs.visibility + '|' + cs.display;
rs.visibility = rsVis;
return ret;
} ),
parseCss: function() {
var info = this.getCss().split('|');
return {
visible: info[0] !== 'hidden',
displayed: info[1] !== 'none'
};
},
/**
* Always return false for isActive, since this property alone will not trigger
* a renderer to do anything.
*/
isActive: function() {
return false;
}
} );
/**
* Abstraction for a VML shape element. Allows assembling a VML shape's properties in
* a non-DOM structure, which can then both generate itself as a single HTML string, and/or
* update itself incrementally if its DOM element already exists.
*/
PIE.VmlShape = (function() {
var nsPrefix = 'pievml',
attrsPrefix = '_attrs_',
objectSetters = {
'colors': function( fill, name, value ) {
if( fill[ name ] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?)
fill[ name ].value = value;
} else {
fill[ name ] = value;
}
},
'size': function( fill, name, value ) {
if ( !value ) {
delete fill[ name ];
} else {
fill[ name ][ 'x' ] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird!
fill[ name ] = value;
}
},
'o:opacity2': function( fill, name, value ) {
// The VML DOM does not allow dynamic setting of o:opacity2, so we must regenerate
// the entire shape from markup instead.
var me = this;
if( value !== me.lastOpacity2 ) {
me.getShape().insertAdjacentHTML( 'afterEnd', me.getMarkup() );
me.destroy();
me.lastOpacity2 = value;
}
}
};
function createSetter( objName ) {
return function() {
var args = arguments,
i, len = args.length,
obj, name, setter;
// Store the property locally
obj = this[ attrsPrefix + objName ] || ( this[ attrsPrefix + objName ] = {} );
for( i = 0; i < len; i += 2 ) {
obj[ args[ i ] ] = args[ i + 1 ];
}
// If there is a rendered VML shape already, set the property directly via the VML DOM
obj = this.getShape();
if( obj ) {
if( objName ) {
obj = obj[ objName ];
}
for( i = 0; i < len; i += 2 ) {
name = args[ i ];
setter = objectSetters[ name ]; //if there is a custom setter for this property, use it
if ( setter ) {
setter.call( this, obj, name, args[ i + 1 ]);
} else {
obj[ name ] = args[ i + 1 ];
}
}
}
}
}
/**
* The VML namespace has to be registered with the document, or the shapes will be invisible
* on initial render sometimes. This results in the infamous "Unspecified error" if called
* at certain times, so catch that and retry after a delay.
*/
(function addVmlNamespace() {
try {
doc.namespaces.add(nsPrefix, 'urn:schemas-microsoft-com:vml', '#default#VML');
}
catch (e) {
setTimeout(addVmlNamespace, 1);
}
})();
function VmlShape( idSeed, ordinalGroup ) {
this.elId = '_pie_' + ( idSeed || 'shape' ) + PIE.Util.getUID(this);
this.ordinalGroup = ordinalGroup || 0;
}
VmlShape.prototype = {
behaviorStyle: 'behavior:url(#default#VML);',
defaultStyles: 'position:absolute;top:0px;left:0px;',
defaultAttrs: 'coordorigin="1,1" stroked="false" ',
tagName: 'shape',
mightBeRendered: 0,
getShape: function() {
return this.mightBeRendered ?
( this._shape || ( this._shape = doc.getElementById( this.elId ) ) ) : null;
},
setAttrs: createSetter( '' ),
setStyles: createSetter( 'style' ),
setFillAttrs: createSetter( 'fill' ),
setSize: function( w, h ) {
this.setStyles(
'width', w + 'px',
'height', h + 'px'
);
this.setAttrs(
'coordsize', w * 2 + ',' + h * 2
);
},
getStyleCssText: function() {
var styles = this[ attrsPrefix + 'style' ] || {},
cssText = [], p;
for( p in styles ) {
if( styles.hasOwnProperty( p ) ) {
cssText.push( p + ':' + styles[p] );
}
}
return this.behaviorStyle + this.defaultStyles + cssText.join( ';' );
},
getMarkup: function() {
var m,
me = this,
tag = me.tagName,
tagStart = '<' + nsPrefix + ':',
subElEnd = ' style="' + me.behaviorStyle + '" />';
me.mightBeRendered = 1;
function pushAttrs( keyVals ) {
if( keyVals ) {
for( var key in keyVals ) {
if( keyVals.hasOwnProperty( key ) ) {
m.push( ' ' + key + '="' + keyVals[key] + '"' );
}
}
}
}
function pushElement( name ) {
var attrs = me[ attrsPrefix + name ];
if( attrs ) {
m.push( tagStart + name );
pushAttrs( attrs );
m.push( subElEnd );
}
}
m = [ tagStart, tag, ' id="', me.elId, '" style="', me.getStyleCssText(), '" ', me.defaultAttrs ];
pushAttrs( me[ attrsPrefix ] );
m.push( '>' );
pushElement( 'fill' );
m.push( '</' + nsPrefix + ':' + tag + '>' );
return m.join( '' );
},
destroy: function() {
var shape = this.getShape(),
par = shape && shape.parentNode;
if( par ) {
par.removeChild(shape);
delete this._shape;
}
}
};
return VmlShape;
})();PIE.RendererBase = {
/**
* Create a new Renderer class, with the standard constructor, and augmented by
* the RendererBase's members.
* @param proto
*/
newRenderer: function( proto ) {
function Renderer( el, boundsInfo, styleInfos, parent ) {
this.targetElement = el;
this.boundsInfo = boundsInfo;
this.styleInfos = styleInfos;
this.parent = parent;
}
PIE.merge( Renderer.prototype, PIE.RendererBase, proto );
return Renderer;
},
/**
* Determine if the renderer needs to be updated
* @return {boolean}
*/
needsUpdate: function() {
return false;
},
/**
* Run any preparation logic that would affect the main update logic of this
* renderer or any of the other renderers, e.g. things that might affect the
* element's size or style properties.
*/
prepareUpdate: PIE.emptyFn,
/**
* Tell the renderer to update based on modified properties or element dimensions
*/
updateRendering: function() {
if( this.isActive() ) {
this.draw();
} else {
this.destroy();
}
},
/**
* Hide the target element's border
*/
hideBorder: function() {
this.targetElement.runtimeStyle.borderColor = 'transparent';
},
/**
* Destroy the rendered objects. This is a base implementation which handles common renderer
* structures, but individual renderers may override as necessary.
*/
destroy: function() {
}
};
PIE.merge(PIE.RendererBase, {
/**
* Get a VmlShape by name, creating it if necessary.
* @param {string} name A name identifying the element
* @param {number} zIndex Specifies the target z-index of the shape. This will be used when rendering
* the shape to ensure it is inserted in the correct order with other shapes to give
* correct stacking order without using actual CSS z-index.
* @return {PIE.VmlShape}
*/
getShape: function( name, zIndex ) {
var shapes = this._shapes || ( this._shapes = {} ),
shape = shapes[ name ];
if( !shape ) {
shape = shapes[ name ] = new PIE.VmlShape( name, zIndex );
this.parent.enqueueShapeForRender( shape );
}
return shape;
},
/**
* Delete a named shape which was created by getShape(). Returns true if a shape with the
* given name was found and deleted, or false if there was no shape of that name.
* @param {string} name
* @return {boolean}
*/
deleteShape: function( name ) {
var shapes = this._shapes,
shape = shapes && shapes[ name ];
if( shape ) {
shape.destroy();
this.parent.removeShape( shape );
delete shapes[ name ];
}
return !!shape;
},
/**
* For a given set of border radius length/percentage values, convert them to concrete pixel
* values based on the current size of the target element.
* @param {Object} radii
* @return {Object}
*/
getRadiiPixels: function( radii ) {
var el = this.targetElement,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
tlX, tlY, trX, trY, brX, brY, blX, blY, f;
tlX = radii.x['tl'].pixels( el, w );
tlY = radii.y['tl'].pixels( el, h );
trX = radii.x['tr'].pixels( el, w );
trY = radii.y['tr'].pixels( el, h );
brX = radii.x['br'].pixels( el, w );
brY = radii.y['br'].pixels( el, h );
blX = radii.x['bl'].pixels( el, w );
blY = radii.y['bl'].pixels( el, h );
// If any corner ellipses overlap, reduce them all by the appropriate factor. This formula
// is taken straight from the CSS3 Backgrounds and Borders spec.
f = Math.min(
w / ( tlX + trX ),
h / ( trY + brY ),
w / ( blX + brX ),
h / ( tlY + blY )
);
if( f < 1 ) {
tlX *= f;
tlY *= f;
trX *= f;
trY *= f;
brX *= f;
brY *= f;
blX *= f;
blY *= f;
}
return {
x: {
'tl': tlX,
'tr': trX,
'br': brX,
'bl': blX
},
y: {
'tl': tlY,
'tr': trY,
'br': brY,
'bl': blY
}
}
},
/**
* Return the VML path string for the element's background box, with corners rounded.
* @param {number} shrinkT - number of pixels to shrink the box path inward from the element's top side.
* @param {number} shrinkR - number of pixels to shrink the box path inward from the element's right side.
* @param {number} shrinkB - number of pixels to shrink the box path inward from the element's bottom side.
* @param {number} shrinkL - number of pixels to shrink the box path inward from the element's left side.
* @param {number} mult All coordinates will be multiplied by this number
* @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
* from this renderer's borderRadiusInfo object.
* @return {string} the VML path
*/
getBoxPath: function( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii ) {
var coords = this.getBoxPathCoords( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii );
return 'm' + coords[ 0 ] + ',' + coords[ 1 ] +
'qy' + coords[ 2 ] + ',' + coords[ 3 ] +
'l' + coords[ 4 ] + ',' + coords[ 5 ] +
'qx' + coords[ 6 ] + ',' + coords[ 7 ] +
'l' + coords[ 8 ] + ',' + coords[ 9 ] +
'qy' + coords[ 10 ] + ',' + coords[ 11 ] +
'l' + coords[ 12 ] + ',' + coords[ 13 ] +
'qx' + coords[ 14 ] + ',' + coords[ 15 ] +
'x';
},
/**
* Return the VML coordinates for all the vertices in the rounded box path.
* @param {number} shrinkT - number of pixels to shrink the box path inward from the element's top side.
* @param {number} shrinkR - number of pixels to shrink the box path inward from the element's right side.
* @param {number} shrinkB - number of pixels to shrink the box path inward from the element's bottom side.
* @param {number} shrinkL - number of pixels to shrink the box path inward from the element's left side.
* @param {number=} mult If specified, all coordinates will be multiplied by this number
* @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
* from this renderer's borderRadiusInfo object.
* @return {Array.<number>} all the coordinates going clockwise, starting with the top-left corner's lower vertex
*/
getBoxPathCoords: function( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii ) {
var bounds = this.boundsInfo.getBounds(),
w = bounds.w * mult,
h = bounds.h * mult,
M = Math,
floor = M.floor, ceil = M.ceil,
max = M.max, min = M.min,
coords;
shrinkT *= mult;
shrinkR *= mult;
shrinkB *= mult;
shrinkL *= mult;
if ( !radii ) {
radii = this.styleInfos.borderRadiusInfo.getProps();
}
if ( radii ) {
radii = this.getRadiiPixels( radii );
var tlRadiusX = radii.x['tl'] * mult,
tlRadiusY = radii.y['tl'] * mult,
trRadiusX = radii.x['tr'] * mult,
trRadiusY = radii.y['tr'] * mult,
brRadiusX = radii.x['br'] * mult,
brRadiusY = radii.y['br'] * mult,
blRadiusX = radii.x['bl'] * mult,
blRadiusY = radii.y['bl'] * mult;
coords = [
floor( shrinkL ), // top-left lower x
floor( min( max( tlRadiusY, shrinkT ), h - shrinkB ) ), // top-left lower y
floor( min( max( tlRadiusX, shrinkL ), w - shrinkR ) ), // top-left upper x
floor( shrinkT ), // top-left upper y
ceil( max( shrinkL, w - max( trRadiusX, shrinkR ) ) ), // top-right upper x
floor( shrinkT ), // top-right upper y
ceil( w - shrinkR ), // top-right lower x
floor( min( max( trRadiusY, shrinkT ), h - shrinkB ) ), // top-right lower y
ceil( w - shrinkR ), // bottom-right upper x
ceil( max( shrinkT, h - max( brRadiusY, shrinkB ) ) ), // bottom-right upper y
ceil( max( shrinkL, w - max( brRadiusX, shrinkR ) ) ), // bottom-right lower x
ceil( h - shrinkB ), // bottom-right lower y
floor( min( max( blRadiusX, shrinkL ), w - shrinkR ) ), // bottom-left lower x
ceil( h - shrinkB ), // bottom-left lower y
floor( shrinkL ), // bottom-left upper x
ceil( max( shrinkT, h - max( blRadiusY, shrinkB ) ) ) // bottom-left upper y
];
} else {
// Skip most of the heavy math for a simple non-rounded box
var t = floor( shrinkT ),
r = ceil( w - shrinkR ),
b = ceil( h - shrinkB ),
l = floor( shrinkL );
coords = [ l, t, l, t, r, t, r, t, r, b, r, b, l, b, l, b ];
}
return coords;
},
/**
* Hide the actual border of the element. In IE7 and up we can just set its color to transparent;
* however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements
* like form buttons require removing the border width altogether, so for those we increase the padding
* by the border size.
*/
hideBorder: function() {
var el = this.targetElement,
cs = el.currentStyle,
rs = el.runtimeStyle,
tag = el.tagName,
isIE6 = PIE.ieVersion === 6,
sides, side, i;
if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) ||
tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) {
rs.borderWidth = '';
sides = this.styleInfos.borderInfo.sides;
for( i = sides.length; i--; ) {
side = sides[ i ];
rs[ 'padding' + side ] = '';
rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) +
( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) +
( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away
}
rs.borderWidth = 0;
}
else if( isIE6 ) {
// Wrap all the element's children in a custom element, set the element to visiblity:hidden,
// and set the wrapper element to visiblity:visible. This hides the outer element's decorations
// (background and border) but displays all the contents.
// TODO find a better way to do this that doesn't mess up the DOM parent-child relationship,
// as this can interfere with other author scripts which add/modify/delete children. Also, this
// won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into
// using a compositor filter or some other filter which masks the border.
if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) {
var cont = doc.createElement( 'ie6-mask' ),
s = cont.style, child;
s.visibility = 'visible';
s.zoom = 1;
while( child = el.firstChild ) {
cont.appendChild( child );
}
el.appendChild( cont );
rs.visibility = 'hidden';
}
}
else {
rs.borderColor = 'transparent';
}
},
unhideBorder: function() {
},
/**
* Destroy the rendered objects. This is a base implementation which handles common renderer
* structures, but individual renderers may override as necessary.
*/
destroy: function() {
var shapes = this._shapes, s;
if ( shapes ) {
for( s in shapes ) {
if( shapes.hasOwnProperty( s ) ) {
this.deleteShape( s );
}
}
}
}
});
/**
* Root renderer; creates the outermost container element and handles keeping it aligned
* with the target element's size and position.
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
*/
PIE.RootRenderer = PIE.RendererBase.newRenderer( {
isActive: function() {
var children = this.childRenderers;
for( var i in children ) {
if( children.hasOwnProperty( i ) && children[ i ].isActive() ) {
return true;
}
}
return false;
},
getBoxCssText: function() {
var el = this.getPositioningElement(),
par = el,
docEl,
parRect,
tgtCS = el.currentStyle,
tgtPos = tgtCS.position,
boxPos,
cs,
x = 0, y = 0,
elBounds = this.boundsInfo.getBounds(),
vis = this.styleInfos.visibilityInfo.getProps(),
logicalZoomRatio = elBounds.logicalZoomRatio;
if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) {
x = elBounds.x * logicalZoomRatio;
y = elBounds.y * logicalZoomRatio;
boxPos = tgtPos;
} else {
// Get the element's offsets from its nearest positioned ancestor. Uses
// getBoundingClientRect for accuracy and speed.
do {
par = par.offsetParent;
} while( par && ( par.currentStyle.position === 'static' ) );
if( par ) {
parRect = par.getBoundingClientRect();
cs = par.currentStyle;
x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 );
y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 );
} else {
docEl = doc.documentElement;
x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio;
y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio;
}
boxPos = 'absolute';
}
return 'direction:ltr;' +
'position:absolute;' +
'behavior:none !important;' +
'position:' + boxPos + ';' +
'left:' + x + 'px;' +
'top:' + y + 'px;' +
'z-index:' + ( tgtPos === 'static' ? -1 : tgtCS.zIndex ) + ';' +
'display:' + ( vis.visible && vis.displayed ? 'block' : 'none' );
},
updateBoxStyles: function() {
var me = this,
boxEl = me.getBoxEl();
if( boxEl && ( me.boundsInfo.positionChanged() || me.styleInfos.visibilityInfo.changed() ) ) {
boxEl.style.cssText = me.getBoxCssText();
}
},
getPositioningElement: function() {
var el = this.targetElement;
return el.tagName in PIE.tableCellTags ? el.offsetParent : el;
},
/**
* Get a reference to the css3pie container element that contains the VML shapes,
* if it has been inserted.
*/
getBoxEl: function() {
var box = this._box;
if( !box ) {
box = this._box = doc.getElementById( '_pie' + PIE.Util.getUID( this ) );
}
return box;
},
/**
* Render any child rendrerer shapes which have not already been rendered into the DOM.
*/
updateRendering: function() {
var me = this,
queue = me._shapeRenderQueue,
renderedShapes, markup, i, len, j,
ref, pos, vis;
if (me.isActive()) {
if( queue ) {
// We've already rendered something once, so do incremental insertion of new shapes
renderedShapes = me._renderedShapes;
if( renderedShapes ) {
for( i = 0, len = queue.length; i < len; i++ ) {
for( j = renderedShapes.length; j--; ) {
if( renderedShapes[ j ].ordinalGroup < queue[ i ].ordinalGroup ) {
break;
}
}
if ( j < 0 ) {
ref = me.getBoxEl();
pos = 'afterBegin';
} else {
ref = renderedShapes[ j ].getShape();
pos = 'afterEnd';
}
ref.insertAdjacentHTML( pos, queue[ i ].getMarkup() );
renderedShapes.splice( j < 0 ? 0 : j, 0, queue[ i ] );
}
me._shapeRenderQueue = 0;
me.updateBoxStyles();
}
// This is the first render, so build up a single markup string and insert it all at once
else {
vis = me.styleInfos.visibilityInfo.getProps();
if( vis.visible && vis.displayed ) {
queue.sort( me.shapeSorter );
markup = [ '<css3pie id="_pie' + PIE.Util.getUID( me ) + '" style="' + me.getBoxCssText() + '">' ];
for( i = 0, len = queue.length; i < len; i++ ) {
markup.push( queue[ i ].getMarkup() );
}
markup.push( '</css3pie>' );
me.getPositioningElement().insertAdjacentHTML( 'beforeBegin', markup.join( '' ) );
me._renderedShapes = queue;
me._shapeRenderQueue = 0;
}
}
} else {
me.updateBoxStyles();
}
} else {
me.destroy();
}
},
shapeSorter: function( shape1, shape2 ) {
return shape1.ordinalGroup - shape2.ordinalGroup;
},
/**
* Add a VmlShape into the queue to get rendered in finishUpdate
*/
enqueueShapeForRender: function( shape ) {
var me = this,
queue = me._shapeRenderQueue || ( me._shapeRenderQueue = [] );
queue.push( shape );
},
/**
* Remove a VmlShape from the DOM and also from the internal list of rendered shapes.
*/
removeShape: function( shape ) {
var shapes = this._renderedShapes, i;
if ( shapes ) {
for( i = shapes.length; i--; ) {
if( shapes[ i ] === shape ) {
shapes.splice( i, 1 );
break;
}
}
}
},
destroy: function() {
var box = this._box, par;
if( box && ( par = box.parentNode ) ) {
par.removeChild( box );
}
delete this._box;
delete this._renderedShapes;
}
} );
// Prime IE for recognizing the custom <css3pie> element
doc.createElement( 'css3pie' );
/**
* Renderer for element backgrounds.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( {
shapeZIndex: 2,
needsUpdate: function() {
var si = this.styleInfos;
return si.backgroundInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderImageInfo.isActive() ||
si.borderRadiusInfo.isActive() ||
si.backgroundInfo.isActive() ||
( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset );
},
/**
* Draw the shapes
*/
draw: function() {
var bounds = this.boundsInfo.getBounds();
if( bounds.w && bounds.h ) {
this.drawBgColor();
this.drawBgImages();
}
},
/**
* Draw the background color shape
*/
drawBgColor: function() {
var props = this.styleInfos.backgroundInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
el = this.targetElement,
color = props && props.color,
shape, alpha;
if( color && color.alpha() > 0 ) {
this.hideBackground();
shape = this.getShape( 'bgColor', this.shapeZIndex );
shape.setSize( bounds.w, bounds.h );
shape.setAttrs(
'path', this.getBgClipPath( bounds, props.colorClip )
);
shape.setFillAttrs( 'color', color.colorValue( el ) );
alpha = color.alpha();
if( alpha < 1 ) {
shape.setFillAttrs( 'opacity', alpha );
}
} else {
this.deleteShape( 'bgColor' );
}
},
/**
* Draw all the background image layers
*/
drawBgImages: function() {
var props = this.styleInfos.backgroundInfo.getProps(),
bounds = this.boundsInfo.getBounds(),
images = props && props.bgImages,
img, shape, w, h, i;
if( images ) {
this.hideBackground();
w = bounds.w;
h = bounds.h;
i = images.length;
while( i-- ) {
img = images[i];
shape = this.getShape( 'bgImage' + i, this.shapeZIndex + ( .5 - i / 1000 ) );
shape.setAttrs(
'path', this.getBgClipPath( bounds, img.bgClip )
);
shape.setSize( w, h );
if( img.imgType === 'linear-gradient' ) {
this.addLinearGradient( shape, img );
}
else {
shape.setFillAttrs(
'type', 'tile',
'color', 'none'
);
this.positionBgImage( shape, img.imgUrl, i );
}
}
}
// Delete any bgImage shapes previously created which weren't used above
i = images ? images.length : 0;
while( this.deleteShape( 'bgImage' + i++ ) ) {}
},
/**
* Set the position and clipping of the background image for a layer
* @param {Element} shape
* @param {String} src
* @param {number} index
*/
positionBgImage: function( shape, src, index ) {
PIE.Util.withImageSize( src, function( imgSize ) {
var me = this,
el = me.targetElement,
bounds = me.boundsInfo.getBounds(),
elW = bounds.w,
elH = bounds.h;
// It's possible that the element dimensions are zero now but weren't when the original
// update executed, make sure that's not the case to avoid divide-by-zero error
if( elW && elH ) {
var styleInfos = me.styleInfos,
bgInfo = styleInfos.backgroundInfo,
bg = bgInfo.getProps().bgImages[ index ],
bgAreaSize = bgInfo.getBgAreaSize( bg.bgOrigin, me.boundsInfo, styleInfos.borderInfo, styleInfos.paddingInfo ),
adjustedImgSize = ( bg.bgSize || PIE.BgSize.DEFAULT ).pixels(
me.targetElement, bgAreaSize.w, bgAreaSize.h, imgSize.w, imgSize.h
),
bgOriginXY = me.getBgOriginXY( bg.bgOrigin ),
bgPos = bg.bgPosition ? bg.bgPosition.coords( el, bgAreaSize.w - adjustedImgSize.w, bgAreaSize.h - adjustedImgSize.h ) : { x:0, y:0 },
repeat = bg.imgRepeat,
pxX, pxY,
clipT = 0, clipL = 0,
clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel)
clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region
// Positioning - find the pixel offset from the top/left and convert to a ratio
// The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is
// needed to fix antialiasing but makes the bg image fuzzy.
pxX = Math.round( bgOriginXY.x + bgPos.x ) + 0.5;
pxY = Math.round( bgOriginXY.y + bgPos.y ) + 0.5;
shape.setFillAttrs(
'src', src,
'position', ( pxX / elW ) + ',' + ( pxY / elH ),
// Set the size of the image. We only set it if the image is scaled via background-size or by
// the user changing the browser zoom level, to avoid fuzzy images at normal size. For some reason
// using px units doesn't work in VML markup so we must convert to pt.
'size', ( adjustedImgSize.w !== imgSize.w || adjustedImgSize.h !== imgSize.h ||
bounds.logicalZoomRatio !== 1 || screen['logicalXDPI'] / screen['deviceXDPI'] !== 1 ) ?
PIE.Length.pxToPt( adjustedImgSize.w ) + 'pt,' + PIE.Length.pxToPt( adjustedImgSize.h ) + 'pt' : ''
);
// Repeating - clip the image shape
if( repeat && repeat !== 'repeat' ) {
if( repeat === 'repeat-x' || repeat === 'no-repeat' ) {
clipT = pxY + 1;
clipB = pxY + adjustedImgSize.h + clipAdjust;
}
if( repeat === 'repeat-y' || repeat === 'no-repeat' ) {
clipL = pxX + 1;
clipR = pxX + adjustedImgSize.w + clipAdjust;
}
shape.setStyles( 'clip', 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)' );
}
}
}, this );
},
/**
* For a given background-clip value, return the VML path for that clip area.
* @param {Object} bounds
* @param {String} bgClip
*/
getBgClipPath: function( bounds, bgClip ) {
var me = this,
shrinkT = 0,
shrinkR = 0,
shrinkB = 0,
shrinkL = 0,
el = me.targetElement,
styleInfos = me.styleInfos,
borders, paddings;
if ( bgClip && bgClip !== 'border-box' ) {
borders = styleInfos.borderInfo.getProps();
if ( borders && ( borders = borders.widths ) ) {
shrinkT += borders[ 't' ].pixels( el );
shrinkR += borders[ 'r' ].pixels( el );
shrinkB += borders[ 'b' ].pixels( el );
shrinkL += borders[ 'l' ].pixels( el );
}
}
if ( bgClip === 'content-box' ) {
paddings = styleInfos.paddingInfo.getProps();
if( paddings ) {
shrinkT += paddings[ 't' ].pixels( el );
shrinkR += paddings[ 'r' ].pixels( el );
shrinkB += paddings[ 'b' ].pixels( el );
shrinkL += paddings[ 'l' ].pixels( el );
}
}
// Add points at 0,0 and w,h so that the image size/position will still be
// based on the full element area.
return 'm0,0r0,0m' + bounds.w * 2 + ',' + bounds.h * 2 + 'r0,0' +
me.getBoxPath( shrinkT, shrinkR, shrinkB, shrinkL, 2 );
},
/**
* For a given background-origin value, return the x/y position of the origin
* from the top-left of the element bounds.
* @param {String} bgOrigin
*/
getBgOriginXY: function( bgOrigin ) {
var me = this,
el = me.targetElement,
styleInfos = me.styleInfos,
x = 0,
y = 0,
borders, paddings;
if( bgOrigin !== 'border-box' ) {
borders = styleInfos.borderInfo.getProps();
if( borders && ( borders = borders.widths ) ) {
x += borders[ 'l' ].pixels( el );
y += borders[ 't' ].pixels( el );
}
}
if ( bgOrigin === 'content-box' ) {
paddings = styleInfos.paddingInfo.getProps();
if( paddings ) {
x += paddings[ 'l' ].pixels( el );
y += paddings[ 't' ].pixels( el );
}
}
return { x: x, y: y };
},
/**
* Draw the linear gradient for a gradient layer
* @param {Element} shape
* @param {Object} info The object holding the information about the gradient
*/
addLinearGradient: function( shape, info ) {
var el = this.targetElement,
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
stops = info.stops,
stopCount = stops.length,
PI = Math.PI,
metrics = PIE.GradientUtil.getGradientMetrics( el, w, h, info ),
angle = metrics.angle,
lineLength = metrics.lineLength,
vmlAngle, vmlColors,
stopPx, i, j, before, after;
// In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's
// bounding box; for example specifying a 45 deg angle actually results in a gradient
// drawn diagonally from one corner to its opposite corner, which will only appear to the
// viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas
// between the start and end points, multiply one of them by the shape's aspect ratio,
// and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly
// horizontal or vertical then we don't need to do this conversion.
// VML angles go in the opposite direction from CSS angles.
vmlAngle = ( angle % 90 ) ?
Math.atan2( metrics.startY - metrics.endY, ( metrics.endX - metrics.startX ) * w / h ) / PI * 180 - 90 :
-angle;
while( vmlAngle < 0 ) {
vmlAngle += 360;
}
vmlAngle = vmlAngle % 360;
// Add all the stops to the VML 'colors' list, including the first and last stops.
// For each, we find its pixel offset along the gradient-line; if the offset of a stop is less
// than that of its predecessor we increase it to be equal.
vmlColors = [];
// Find the pixel offsets along the CSS3 gradient-line for each stop.
stopPx = [];
for( i = 0; i < stopCount; i++ ) {
stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) :
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
}
// Fill in gaps with evenly-spaced offsets
for( i = 1; i < stopCount; i++ ) {
if( stopPx[ i ] === null ) {
before = stopPx[ i - 1 ];
j = i;
do {
after = stopPx[ ++j ];
} while( after === null );
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
}
// Make sure each stop's offset is no less than the one before it
stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] );
}
// Convert to percentage along the gradient line and add to the VML 'colors' value
for( i = 0; i < stopCount; i++ ) {
vmlColors.push(
( stopPx[ i ] / lineLength * 100 ) + '% ' + stops[i].color.colorValue( el )
);
}
// Now, finally, we're ready to render the gradient fill. Set the start and end colors to
// the first and last stop colors; this just sets outer bounds for the gradient.
shape.setFillAttrs(
'angle', vmlAngle,
'type', 'gradient',
'method', 'sigma',
'color', stops[0].color.colorValue( el ),
'color2', stops[stopCount - 1].color.colorValue( el ),
'colors', vmlColors.join( ',' )
);
// Set opacity; right now we only support this for two-stop gradients, multi-stop
// opacity will require chopping up each segment into its own shape.
// Note these seem backwards but they must be that way since VML strangely reverses
// them when the 'colors' property is present.
if ( stopCount === 2 ) {
shape.setFillAttrs(
'opacity', stops[1].color.alpha(),
'o:opacity2', stops[0].color.alpha()
);
}
},
/**
* Hide the actual background image and color of the element.
*/
hideBackground: function() {
var rs = this.targetElement.runtimeStyle;
rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events
rs.backgroundColor = 'transparent';
},
destroy: function() {
PIE.RendererBase.destroy.call( this );
var rs = this.targetElement.runtimeStyle;
rs.backgroundImage = rs.backgroundColor = '';
}
} );
/**
* Renderer for element borders.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BorderRenderer = PIE.RendererBase.newRenderer( {
shapeZIndex: 4,
/**
* Single definition of arguments for use by the per-side creation loop in
* getBorderSegmentsInfo. Arguments are, in order:
* centerX1, centerY1, outerX1, outerY1, centerX2, centerY2, outerX2, outerY2, baseAngle
*/
sideArgs: {
't': [ 2, 1, 0, 3, 4, 7, 6, 5, 90 ],
'r': [ 4, 7, 6, 5, 10, 9, 8, 11, 0 ],
'b': [ 10, 9, 8, 11, 12, 15, 14, 13, 270 ],
'l': [ 12, 15, 14, 13, 2, 1, 0, 3, 180 ]
},
dashedStyles: {
'dotted': 1,
'dashed': 1
},
colorManipStyles: {
'groove': 1,
'ridge': 1,
'inset': 1,
'outset': 1
},
doubleStyles: {
'groove': 1,
'ridge': 1,
'double': 1
},
needsUpdate: function() {
var si = this.styleInfos;
return si.borderInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderRadiusInfo.isActive() &&
!si.borderImageInfo.isActive() &&
si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive
},
/**
* Draw the border shape(s)
*/
draw: function() {
var me = this,
props = me.styleInfos.borderInfo.getProps(),
bounds = me.boundsInfo.getBounds(),
shape, segmentsInfo, i, j, len;
if( props ) {
me.hideBorder();
segmentsInfo = me.getBorderSegmentsInfo();
for( i = j = 0, len = segmentsInfo.length; i < len; i += 2) {
shape = me.getShape( 'border' + j++, me.shapeZIndex );
shape.setSize( bounds.w, bounds.h );
shape.setAttrs(
'path', segmentsInfo[ i ]
);
shape.setFillAttrs(
'color', segmentsInfo[ i + 1 ]
);
}
// remove any previously-created border shapes which didn't get used above
while( me.deleteShape( 'border' + j++ ) ) {}
}
},
/**
* Adds rectangular sub-paths at intervals along a given side which serve to "cut out"
* those areas, forming the spaces in a dashed or dotted border.
* @param {Array.<string>} path The path string array to which the extra sub-paths will be added
* @param {number} startCoord The x or y coordinate at which the dashing starts
* @param {number} endCoord The x or y coordinate at which the dashing ends
* @param {number} sideWidth The width of the border on the target side
* @param {number} shift A shift of the perpendicular coordinate
* @param {boolean} isVertical True if this is a vertical border (left or right)
* @param {string} style The border style, either 'dotted' or 'dashed'
*/
dashify: function( path, startCoord, endCoord, sideWidth, shift, isVertical, style ) {
var dashLength = sideWidth * ( style === 'dashed' ? 3 : 1 ),
shift2 = shift + sideWidth,
dashEndCoord;
// If dash is longer than the box edge, don't make any cutouts
if( dashLength < endCoord - startCoord ) {
// adjust the start to keep the dash pattern centered on the box edge, favoring full
// spaces over full dashes, like WebKit does.
startCoord += ( endCoord - startCoord - dashLength ) / 2 % dashLength;
// add rectangular sub-paths to cut out each dash's space
while( startCoord < endCoord ) {
dashEndCoord = Math.min( startCoord + dashLength, endCoord );
path.push(
isVertical ? (
'm' + shift + ',' + startCoord +
'l' + shift + ',' + dashEndCoord +
'l' + shift2 + ',' + dashEndCoord +
'l' + shift2 + ',' + startCoord + 'x'
) : (
'm' + startCoord + ',' + shift +
'l' + dashEndCoord + ',' + shift +
'l' + dashEndCoord + ',' + shift2 +
'l' + startCoord + ',' + shift2 + 'x'
)
);
startCoord += dashLength * 2;
}
}
},
/**
* Get the VML path definitions for the border segment(s).
* @return {Array.<string>} Pairs of segment info: 1st item in each pair is the path string, 2nd is the fill color
*/
getBorderSegmentsInfo: function() {
var me = this,
borderInfo = me.styleInfos.borderInfo,
segmentsInfo = [];
if( borderInfo.isActive() ) {
var mult = 2,
el = me.targetElement,
bounds = me.boundsInfo.getBounds(),
borderProps = borderInfo.getProps(),
widths = borderProps.widths,
styles = borderProps.styles,
colors = borderProps.colors,
M = Math,
abs = M.abs,
round = M.round,
wT = round( widths['t'].pixels( el ) ),
wR = round( widths['r'].pixels( el ) ),
wB = round( widths['b'].pixels( el ) ),
wL = round( widths['l'].pixels( el ) ),
path = [],
innerCoords, outerCoords, doubleOuterCoords, doubleInnerCoords,
sideArgs = me.sideArgs,
side,
deg = 65535,
dashedStyles = me.dashedStyles,
style, color;
// When the border has uniform color and style all the way around, we can get
// away with a single VML path shape, otherwise we need four separate shapes.
if ( borderProps.stylesSame && borderProps.colorsSame && !( styles[ 't' ] in me.colorManipStyles ) ) {
if( colors['t'].alpha() > 0 ) {
// Outer path
path[ 0 ] = me.getBoxPath( 0, 0, 0, 0, mult );
// If double style, add the middle cutout sub-paths
style = styles[ 't' ];
if( style === 'double' ) {
path.push(
me.getBoxPath( wT / 3, wR / 3, wB / 3, wL / 3, mult ) +
me.getBoxPath( wT * 2 / 3, wR * 2 / 3, wB * 2 / 3, wL * 2 / 3, mult )
);
}
// If dashed, add the dash cutout sub-paths
else if( style in dashedStyles ) {
innerCoords = me.getBoxPathCoords( wT, wR, wB, wL, mult );
me.dashify( path, innerCoords[ 2 ], innerCoords[ 4 ], wT * mult, 0, 0, styles[ 't' ] );
me.dashify( path, innerCoords[ 7 ], innerCoords[ 9 ], wR * mult, ( bounds.w - wR ) * mult, 1, styles[ 'r' ] );
me.dashify( path, innerCoords[ 12 ], innerCoords[ 10 ], wB * mult, ( bounds.h - wB ) * mult, 0, styles[ 'b' ] );
me.dashify( path, innerCoords[ 1 ], innerCoords[ 15 ], wL * mult, 0, 1, styles[ 'l' ] );
}
// Inner path
path.push( me.getBoxPath( wT, wR, wB, wL, mult ) );
segmentsInfo.push( path.join( '' ), colors['t'].colorValue( el ) );
}
}
else {
outerCoords = me.getBoxPathCoords( 0, 0, 0, 0, mult );
innerCoords = me.getBoxPathCoords( wT, wR, wB, wL, mult );
// Build the segment for each side
for( side in sideArgs ) {
if ( sideArgs.hasOwnProperty( side ) && colors[ side ].alpha() > 0 ) {
var args = sideArgs[ side ],
centerX1 = args[ 0 ],
centerY1 = args[ 1 ],
outerX1 = args[ 2 ],
outerY1 = args[ 3 ],
centerX2 = args[ 4 ],
centerY2 = args[ 5 ],
outerX2 = args[ 6 ],
outerY2 = args[ 7 ],
baseAngle = args[ 8 ],
isTopLeft = side === 't' || side === 'l';
style = styles[ side ];
// Outer edge
path[ 0 ] = 'al' + outerCoords[ centerX1 ] + ',' + outerCoords[ centerY1 ] + ',' +
abs( outerCoords[ outerX1 ] - outerCoords[ centerX1 ] ) + ',' +
abs( outerCoords[ outerY1 ] - outerCoords[ centerY1 ] ) + ',' +
( baseAngle + 45 ) * deg + ',' + -45 * deg +
'ae' + outerCoords[ centerX2 ] + ',' + outerCoords[ centerY2 ] + ',' +
abs( outerCoords[ outerX2 ] - outerCoords[ centerX2 ] ) + ',' +
abs( outerCoords[ outerY2 ] - outerCoords[ centerY2 ] ) + ',' +
baseAngle * deg + ',' + -45 * deg;
// If double style, add the middle sub-paths
if( style in me.doubleStyles ) {
if( !doubleOuterCoords ) {
if ( style === 'double' ) {
doubleOuterCoords = me.getBoxPathCoords( wT / 3, wR / 3, wB / 3, wL / 3, mult );
doubleInnerCoords = me.getBoxPathCoords( wT * 2 / 3, wR * 2 / 3, wB * 2 / 3, wL * 2 / 3, mult );
} else {
doubleOuterCoords = doubleInnerCoords = me.getBoxPathCoords( wT / 2, wR / 2, wB / 2, wL / 2, mult );
}
}
path.push(
'ae' + doubleOuterCoords[ centerX2 ] + ',' + doubleOuterCoords[ centerY2 ] + ',' +
abs( doubleOuterCoords[ outerX2 ] - doubleOuterCoords[ centerX2 ] ) + ',' +
abs( doubleOuterCoords[ outerY2 ] - doubleOuterCoords[ centerY2 ] ) + ',' +
( baseAngle - 45 ) * deg + ',' + 45 * deg +
'ae' + doubleOuterCoords[ centerX1 ] + ',' + doubleOuterCoords[ centerY1 ] + ',' +
abs( doubleOuterCoords[ outerX1 ] - doubleOuterCoords[ centerX1 ] ) + ',' +
abs( doubleOuterCoords[ outerY1 ] - doubleOuterCoords[ centerY1 ] ) + ',' +
baseAngle * deg + ',' + 45 * deg +
'x'
);
// Actual 'double' style with have both paths as a single shape, but 'ridge' and
// 'groove' need separate shapes for the different colors
if( style !== 'double' ) {
color = colors[ side ].colorValue( el ) + (
( style === 'groove' ? isTopLeft : !isTopLeft ) ? ' darken(128)' : ' lighten(128)'
);
segmentsInfo.push( path.join( '' ), color );
path.length = 0; //reuse same array for next loop
}
path.push(
'al' + doubleInnerCoords[ centerX1 ] + ',' + doubleInnerCoords[ centerY1 ] + ',' +
abs( doubleInnerCoords[ outerX1 ] - doubleInnerCoords[ centerX1 ] ) + ',' +
abs( doubleInnerCoords[ outerY1 ] - doubleInnerCoords[ centerY1 ] ) + ',' +
( baseAngle + 45 ) * deg + ',' + -45 * deg +
'ae' + doubleInnerCoords[ centerX2 ] + ',' + doubleInnerCoords[ centerY2 ] + ',' +
abs( doubleInnerCoords[ outerX2 ] - doubleInnerCoords[ centerX2 ] ) + ',' +
abs( doubleInnerCoords[ outerY2 ] - doubleInnerCoords[ centerY2 ] ) + ',' +
baseAngle * deg + ',' + -45 * deg
);
}
// Inner edge
path.push(
'ae' + innerCoords[ centerX2 ] + ',' + innerCoords[ centerY2 ] + ',' +
abs( innerCoords[ outerX2 ] - innerCoords[ centerX2 ] ) + ',' +
abs( innerCoords[ outerY2 ] - innerCoords[ centerY2 ] ) + ',' +
( baseAngle - 45 ) * deg + ',' + 45 * deg +
'ae' + innerCoords[ centerX1 ] + ',' + innerCoords[ centerY1 ] + ',' +
abs( innerCoords[ outerX1 ] - innerCoords[ centerX1 ] ) + ',' +
abs( innerCoords[ outerY1 ] - innerCoords[ centerY1 ] ) + ',' +
baseAngle * deg + ',' + 45 * deg +
'x'
);
// For dashed/dotted styles, add the dash cutout sub-paths
if ( style in dashedStyles ) {
side === 't' ?
me.dashify( path, innerCoords[ 2 ], innerCoords[ 4 ], wT * mult, 0, 0, style ) :
side === 'r' ?
me.dashify( path, innerCoords[ 7 ], innerCoords[ 9 ], wR * mult, ( bounds.w - wR ) * mult, 1, style ) :
side === 'b' ?
me.dashify( path, innerCoords[ 12 ], innerCoords[ 10 ], wB * mult, ( bounds.h - wB ) * mult, 0, style ) :
//side === 'l' ?
me.dashify( path, innerCoords[ 1 ], innerCoords[ 15 ], wL * mult, 0, 1, style );
}
color = colors[ side ].colorValue( el );
if ( style in me.colorManipStyles ) {
// lighten or darken as appropriate
color += (
( ( style === 'groove' || style === 'outset' ) ? isTopLeft : !isTopLeft ) ?
' lighten(128)' : ' darken(128)'
);
}
segmentsInfo.push( path.join( '' ), color );
path.length = 0; //reuse same array for next loop
}
}
}
}
return segmentsInfo;
},
destroy: function() {
var me = this;
if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) {
me.targetElement.runtimeStyle.borderColor = '';
}
PIE.RendererBase.destroy.call( me );
}
} );
/**
* Renderer for border-image
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( {
shapeZIndex: 5,
needsUpdate: function() {
return this.styleInfos.borderImageInfo.changed();
},
isActive: function() {
return this.styleInfos.borderImageInfo.isActive();
},
draw: function() {
var me = this,
props = me.styleInfos.borderImageInfo.getProps(),
borderProps = me.styleInfos.borderInfo.getProps(),
bounds = me.boundsInfo.getBounds(),
el = me.targetElement;
PIE.Util.withImageSize( props.src, function( imgSize ) {
var me = this,
elW = bounds.w,
elH = bounds.h,
zero = PIE.getLength( '0' ),
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
widthT = widths['t'].pixels( el ),
widthR = widths['r'].pixels( el ),
widthB = widths['b'].pixels( el ),
widthL = widths['l'].pixels( el ),
slices = props.slice,
sliceT = slices['t'].pixels( el ),
sliceR = slices['r'].pixels( el ),
sliceB = slices['b'].pixels( el ),
sliceL = slices['l'].pixels( el ),
src = props.src,
imgW = imgSize.w,
imgH = imgSize.h;
function setSizeAndPos( rect, rectX, rectY, rectW, rectH, sliceX, sliceY, sliceW, sliceH ) {
// Hide the piece entirely if we have zero dimensions for the image, the rect, or the slice
var max = Math.max;
if ( !imgW || !imgH || !rectW || !rectH || !sliceW || !sliceH ) {
rect.setStyles( 'display', 'none' );
} else {
rectW = max( rectW, 0 );
rectH = max( rectH, 0 );
rect.setAttrs(
'path', 'm0,0l' + rectW * 2 + ',0l' + rectW * 2 + ',' + rectH * 2 + 'l0,' + rectH * 2 + 'x'
);
rect.setFillAttrs(
'src', src,
'type', 'tile',
'position', '0,0',
'origin', ( ( sliceX - 0.5 ) / imgW ) + ',' + ( ( sliceY - 0.5 ) / imgH ),
// For some reason using px units doesn't work in VML markup so we must convert to pt.
'size', PIE.Length.pxToPt( rectW * imgW / sliceW ) + 'pt,' + PIE.Length.pxToPt( rectH * imgH / sliceH ) + 'pt'
);
rect.setSize( rectW, rectH );
rect.setStyles(
'left', rectX + 'px',
'top', rectY + 'px',
'display', ''
);
}
}
// Piece positions and sizes
// TODO right now this treats everything like 'stretch', need to support other schemes
setSizeAndPos( me.getRect( 'tl' ), 0, 0, widthL, widthT, 0, 0, sliceL, sliceT );
setSizeAndPos( me.getRect( 't' ), widthL, 0, elW - widthL - widthR, widthT, sliceL, 0, imgW - sliceL - sliceR, sliceT );
setSizeAndPos( me.getRect( 'tr' ), elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT );
setSizeAndPos( me.getRect( 'r' ), elW - widthR, widthT, widthR, elH - widthT - widthB, imgW - sliceR, sliceT, sliceR, imgH - sliceT - sliceB );
setSizeAndPos( me.getRect( 'br' ), elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB );
setSizeAndPos( me.getRect( 'b' ), widthL, elH - widthB, elW - widthL - widthR, widthB, sliceL, imgH - sliceB, imgW - sliceL - sliceR, sliceB );
setSizeAndPos( me.getRect( 'bl' ), 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB );
setSizeAndPos( me.getRect( 'l' ), 0, widthT, widthL, elH - widthT - widthB, 0, sliceT, sliceL, imgH - sliceT - sliceB );
setSizeAndPos( me.getRect( 'c' ), widthL, widthT, elW - widthL - widthR, elH - widthT - widthB, sliceL, sliceT, props.fill ? imgW - sliceL - sliceR : 0, imgH - sliceT - sliceB );
}, me );
},
getRect: function( name ) {
return this.getShape( 'borderImage_' + name, this.shapeZIndex );
},
prepareUpdate: function() {
if (this.isActive()) {
var me = this,
el = me.targetElement,
rs = el.runtimeStyle,
widths = me.styleInfos.borderImageInfo.getProps().widths;
// Force border-style to solid so it doesn't collapse
rs.borderStyle = 'solid';
// If widths specified in border-image shorthand, override border-width
if ( widths ) {
rs.borderTopWidth = widths['t'].pixels( el );
rs.borderRightWidth = widths['r'].pixels( el );
rs.borderBottomWidth = widths['b'].pixels( el );
rs.borderLeftWidth = widths['l'].pixels( el );
}
// Make the border transparent
me.hideBorder();
}
},
destroy: function() {
var me = this,
rs = me.targetElement.runtimeStyle;
rs.borderStyle = '';
if (me.finalized || !me.styleInfos.borderInfo.isActive()) {
rs.borderColor = rs.borderWidth = '';
}
PIE.RendererBase.destroy.call( me );
}
} );
/**
* Renderer for outset box-shadows
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( {
shapeZIndex: 1,
needsUpdate: function() {
var si = this.styleInfos;
return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed();
},
isActive: function() {
var boxShadowInfo = this.styleInfos.boxShadowInfo;
return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0];
},
draw: function() {
var me = this,
el = me.targetElement,
styleInfos = me.styleInfos,
shadowInfos = styleInfos.boxShadowInfo.getProps().outset,
radii = styleInfos.borderRadiusInfo.getProps(),
len = shadowInfos.length,
i = len,
bounds = me.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
shadowInfo, shape, xOff, yOff, spread, blur, shrink, color, alpha, path,
totalW, totalH, focusX, focusY, focusAdjustRatio;
while( i-- ) {
shadowInfo = shadowInfos[ i ];
xOff = shadowInfo.xOffset.pixels( el );
yOff = shadowInfo.yOffset.pixels( el );
spread = shadowInfo.spread.pixels( el );
blur = shadowInfo.blur.pixels( el );
color = shadowInfo.color;
alpha = color.alpha();
color = color.colorValue( el );
// Shape path
shrink = -spread - blur;
if( !radii && blur ) {
// If blurring, use a non-null border radius info object so that getBoxPath will
// round the corners of the expanded shadow shape rather than squaring them off.
radii = PIE.BorderRadiusStyleInfo.ALL_ZERO;
}
path = me.getBoxPath( shrink, shrink, shrink, shrink, 2, radii );
// Create the shape object
shape = me.getShape( 'shadow' + i, me.shapeZIndex + ( .5 - i / 1000 ) );
if( blur ) {
totalW = ( spread + blur ) * 2 + w;
totalH = ( spread + blur ) * 2 + h;
focusX = totalW ? blur * 2 / totalW : 0;
focusY = totalH ? blur * 2 / totalH : 0;
// If the blur is larger than half the element's narrowest dimension, then its focussize
// will to be less than zero which results in ugly artifacts. To get around this, we adjust
// the focus to keep it centered and then bump the center opacity down to match.
if (focusX > 0.5 || focusY > 0.5) {
focusAdjustRatio = 0.5 / Math.max(focusX, focusY);
focusX *= focusAdjustRatio;
focusY *= focusAdjustRatio;
alpha *= focusAdjustRatio * focusAdjustRatio; //this is a rough eyeball-adjustment, could be refined
}
shape.setFillAttrs(
'type', 'gradienttitle', //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?!
'color2', color,
'focusposition', focusX + ',' + focusY,
'focussize', ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 ),
'opacity', 0,
'o:opacity2', alpha
);
} else {
shape.setFillAttrs(
'type', 'solid',
'opacity', alpha
);
}
shape.setAttrs(
'path', path
);
shape.setFillAttrs( 'color', color );
shape.setStyles(
'left', xOff + 'px',
'top', yOff + 'px'
);
shape.setSize( w, h );
}
// Delete any shadow shapes previously created which weren't reused above
while( me.deleteShape( 'shadow' + len++ ) ) {}
}
} );
/**
* Renderer for re-rendering img elements using VML. Kicks in if the img has
* a border-radius applied, or if the -pie-png-fix flag is set.
* @constructor
* @param {Element} el The target element
* @param {Object} styleInfos The StyleInfo objects
* @param {PIE.RootRenderer} parent
*/
PIE.ImgRenderer = PIE.RendererBase.newRenderer( {
shapeZIndex: 6,
needsUpdate: function() {
var si = this.styleInfos;
return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed();
},
isActive: function() {
var si = this.styleInfos;
return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix();
},
draw: function() {
this._lastSrc = src;
this.hideActualImg();
var shape = this.getShape( 'img', this.shapeZIndex ),
bounds = this.boundsInfo.getBounds(),
w = bounds.w,
h = bounds.h,
borderProps = this.styleInfos.borderInfo.getProps(),
borderWidths = borderProps && borderProps.widths,
el = this.targetElement,
src = el.src,
round = Math.round,
paddings = this.styleInfos.paddingInfo.getProps(),
zero;
// In IE6, the BorderRenderer will have hidden the border by moving the border-width to
// the padding; therefore we want to pretend the borders have no width so they aren't doubled
// when adding in the current padding value below.
if( !borderWidths || PIE.ieVersion < 7 ) {
zero = PIE.getLength( '0' );
borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero };
}
shape.setAttrs(
'path', this.getBoxPath(
round( borderWidths['t'].pixels( el ) + paddings[ 't' ].pixels( el ) ),
round( borderWidths['r'].pixels( el ) + paddings[ 'r' ].pixels( el ) ),
round( borderWidths['b'].pixels( el ) + paddings[ 'b' ].pixels( el ) ),
round( borderWidths['l'].pixels( el ) + paddings[ 'l' ].pixels( el ) ),
2
)
);
shape.setFillAttrs(
'type', 'frame',
'src', src,
'position', (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0)
);
shape.setSize( w, h );
},
hideActualImg: function() {
this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)';
},
destroy: function() {
PIE.RendererBase.destroy.call( this );
this.targetElement.runtimeStyle.filter = '';
}
} );
PIE.Element = (function() {
var wrappers = {},
lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
pollCssProp = PIE.CSS_PREFIX + 'poll',
trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
hoverClass = PIE.CLASS_PREFIX + 'hover',
activeClass = PIE.CLASS_PREFIX + 'active',
focusClass = PIE.CLASS_PREFIX + 'focus',
firstChildClass = PIE.CLASS_PREFIX + 'first-child',
ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
classNameRegExes = {},
dummyArray = [];
function addClass( el, className ) {
el.className += ' ' + className;
}
function removeClass( el, className ) {
var re = classNameRegExes[ className ] ||
( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
el.className = el.className.replace( re, '' );
}
function delayAddClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
addClass( el, classes[ i ] );
}
}
}, 0 );
}
function delayRemoveClass( el, className /*, className2*/ ) {
var classes = dummyArray.slice.call( arguments, 1 ),
i = classes.length;
setTimeout( function() {
if( el ) {
while( i-- ) {
removeClass( el, classes[ i ] );
}
}
}, 0 );
}
function Element( el ) {
var me = this,
childRenderers,
rootRenderer,
boundsInfo = new PIE.BoundsInfo( el ),
styleInfos,
styleInfosArr,
initializing,
initialized,
eventsAttached,
eventListeners = [],
delayed,
destroyed,
poll;
me.el = el;
/**
* Initialize PIE for this element.
*/
function init() {
if( !initialized ) {
var docEl,
bounds,
ieDocMode = PIE.ieDocMode,
cs = el.currentStyle,
lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false';
// Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
poll = cs.getAttribute( pollCssProp );
poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
// Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
// after load, but make sure it only gets called the first time through to avoid recursive calls to init().
if( !initializing ) {
initializing = 1;
el.runtimeStyle.zoom = 1;
initFirstChildPseudoClass();
}
boundsInfo.lock();
// If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
if( !delayed ) {
delayed = 1;
PIE.OnScroll.observe( init );
}
} else {
initialized = 1;
delayed = initializing = 0;
PIE.OnScroll.unobserve( init );
// Create the style infos and renderers
if ( ieDocMode === 9 ) {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el ),
paddingInfo: new PIE.PaddingStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderInfo,
styleInfos.borderImageInfo,
styleInfos.paddingInfo
];
rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
} else {
styleInfos = {
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
borderInfo: new PIE.BorderStyleInfo( el ),
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
paddingInfo: new PIE.PaddingStyleInfo( el ),
visibilityInfo: new PIE.VisibilityStyleInfo( el )
};
styleInfosArr = [
styleInfos.backgroundInfo,
styleInfos.borderInfo,
styleInfos.borderImageInfo,
styleInfos.borderRadiusInfo,
styleInfos.boxShadowInfo,
styleInfos.paddingInfo,
styleInfos.visibilityInfo
];
rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
childRenderers = [
new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
//new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
];
if( el.tagName === 'IMG' ) {
childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
}
rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
}
// Add property change listeners to ancestors if requested
initAncestorEventListeners();
// Add to list of polled elements when -pie-poll:true
if( poll ) {
PIE.Heartbeat.observe( update );
PIE.Heartbeat.run();
}
// Trigger rendering
update( 0, 1 );
}
if( !eventsAttached ) {
eventsAttached = 1;
if( ieDocMode < 9 ) {
addListener( el, 'onmove', handleMoveOrResize );
}
addListener( el, 'onresize', handleMoveOrResize );
addListener( el, 'onpropertychange', propChanged );
if( trackHover ) {
addListener( el, 'onmouseenter', mouseEntered );
}
if( trackHover || trackActive ) {
addListener( el, 'onmouseleave', mouseLeft );
}
if( trackActive ) {
addListener( el, 'onmousedown', mousePressed );
}
if( el.tagName in PIE.focusableElements ) {
addListener( el, 'onfocus', focused );
addListener( el, 'onblur', blurred );
}
PIE.OnResize.observe( handleMoveOrResize );
PIE.OnUnload.observe( removeEventListeners );
}
boundsInfo.unlock();
}
}
/**
* Event handler for onmove and onresize events. Invokes update() only if the element's
* bounds have previously been calculated, to prevent multiple runs during page load when
* the element has no initial CSS3 properties.
*/
function handleMoveOrResize() {
if( boundsInfo && boundsInfo.hasBeenQueried() ) {
update();
}
}
/**
* Update position and/or size as necessary. Both move and resize events call
* this rather than the updatePos/Size functions because sometimes, particularly
* during page load, one will fire but the other won't.
*/
function update( isPropChange, force ) {
if( !destroyed ) {
if( initialized ) {
lockAll();
var i = 0, len = childRenderers.length,
sizeChanged = boundsInfo.sizeChanged();
for( ; i < len; i++ ) {
childRenderers[i].prepareUpdate();
}
for( i = 0; i < len; i++ ) {
if( force || sizeChanged || ( isPropChange && childRenderers[i].needsUpdate() ) ) {
childRenderers[i].updateRendering();
}
}
if( force || sizeChanged || isPropChange || boundsInfo.positionChanged() ) {
rootRenderer.updateRendering();
}
unlockAll();
}
else if( !initializing ) {
init();
}
}
}
/**
* Handle property changes to trigger update when appropriate.
*/
function propChanged() {
// Some elements like <table> fire onpropertychange events for old-school background properties
// ('background', 'bgColor') when runtimeStyle background properties are changed, which
// results in an infinite loop; therefore we filter out those property names. Also, 'display'
// is ignored because size calculations don't work correctly immediately when its onpropertychange
// event fires, and because it will trigger an onresize event anyway.
if( initialized && !( event && event.propertyName in ignorePropertyNames ) ) {
update( 1 );
}
}
/**
* Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
* hover styles to non-link elements, and to trigger a propertychange update.
*/
function mouseEntered() {
//must delay this because the mouseenter event fires before the :hover styles are added.
delayAddClass( el, hoverClass );
}
/**
* Handle mouseleave events
*/
function mouseLeft() {
//must delay this because the mouseleave event fires before the :hover styles are removed.
delayRemoveClass( el, hoverClass, activeClass );
}
/**
* Handle mousedown events. Adds a custom class to the element to allow IE6 to add
* active styles to non-link elements, and to trigger a propertychange update.
*/
function mousePressed() {
//must delay this because the mousedown event fires before the :active styles are added.
delayAddClass( el, activeClass );
// listen for mouseups on the document; can't just be on the element because the user might
// have dragged out of the element while the mouse button was held down
PIE.OnMouseup.observe( mouseReleased );
}
/**
* Handle mouseup events
*/
function mouseReleased() {
//must delay this because the mouseup event fires before the :active styles are removed.
delayRemoveClass( el, activeClass );
PIE.OnMouseup.unobserve( mouseReleased );
}
/**
* Handle focus events. Adds a custom class to the element to trigger a propertychange update.
*/
function focused() {
//must delay this because the focus event fires before the :focus styles are added.
delayAddClass( el, focusClass );
}
/**
* Handle blur events
*/
function blurred() {
//must delay this because the blur event fires before the :focus styles are removed.
delayRemoveClass( el, focusClass );
}
/**
* Handle property changes on ancestors of the element; see initAncestorEventListeners()
* which adds these listeners as requested with the -pie-watch-ancestors CSS property.
*/
function ancestorPropChanged() {
var name = event.propertyName;
if( name === 'className' || name === 'id' || name.indexOf( 'style.' ) === 0 ) {
propChanged();
}
}
function lockAll() {
boundsInfo.lock();
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].lock();
}
}
function unlockAll() {
for( var i = styleInfosArr.length; i--; ) {
styleInfosArr[i].unlock();
}
boundsInfo.unlock();
}
function addListener( targetEl, type, handler ) {
targetEl.attachEvent( type, handler );
eventListeners.push( [ targetEl, type, handler ] );
}
/**
* Remove all event listeners from the element and any monitored ancestors.
*/
function removeEventListeners() {
if (eventsAttached) {
var i = eventListeners.length,
listener;
while( i-- ) {
listener = eventListeners[ i ];
listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
}
PIE.OnUnload.unobserve( removeEventListeners );
eventsAttached = 0;
eventListeners = [];
}
}
/**
* Clean everything up when the behavior is removed from the element, or the element
* is manually destroyed.
*/
function destroy() {
if( !destroyed ) {
var i, len;
removeEventListeners();
destroyed = 1;
// destroy any active renderers
if( childRenderers ) {
for( i = 0, len = childRenderers.length; i < len; i++ ) {
childRenderers[i].finalized = 1;
childRenderers[i].destroy();
}
}
rootRenderer.destroy();
// Remove from list of polled elements in IE8
if( poll ) {
PIE.Heartbeat.unobserve( update );
}
// Stop onresize listening
PIE.OnResize.unobserve( update );
// Kill references
childRenderers = rootRenderer = boundsInfo = styleInfos = styleInfosArr = el = null;
me.el = me = 0;
}
}
/**
* If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
* other event listeners to ancestor(s) of the element so we can pick up style changes
* based on CSS rules using descendant selectors.
*/
function initAncestorEventListeners() {
var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
i, a;
if( watch ) {
watch = parseInt( watch, 10 );
i = 0;
a = el.parentNode;
while( a && ( watch === 'NaN' || i++ < watch ) ) {
addListener( a, 'onpropertychange', ancestorPropChanged );
addListener( a, 'onmouseenter', mouseEntered );
addListener( a, 'onmouseleave', mouseLeft );
addListener( a, 'onmousedown', mousePressed );
if( a.tagName in PIE.focusableElements ) {
addListener( a, 'onfocus', focused );
addListener( a, 'onblur', blurred );
}
a = a.parentNode;
}
}
}
/**
* If the target element is a first child, add a pie_first-child class to it. This allows using
* the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
* pseudo-class selector.
*/
function initFirstChildPseudoClass() {
var tmpEl = el,
isFirst = 1;
while( tmpEl = tmpEl.previousSibling ) {
if( tmpEl.nodeType === 1 ) {
isFirst = 0;
break;
}
}
if( isFirst ) {
addClass( el, firstChildClass );
}
}
// These methods are all already bound to this instance so there's no need to wrap them
// in a closure to maintain the 'this' scope object when calling them.
me.init = init;
me.destroy = destroy;
}
Element.getInstance = function( el ) {
var id = el[ 'uniqueID' ];
return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
};
Element.destroy = function( el ) {
var id = el[ 'uniqueID' ],
wrapper = wrappers[ id ];
if( wrapper ) {
wrapper.destroy();
delete wrappers[ id ];
}
};
Element.destroyAll = function() {
var els = [], wrapper;
if( wrappers ) {
for( var w in wrappers ) {
if( wrappers.hasOwnProperty( w ) ) {
wrapper = wrappers[ w ];
els.push( wrapper.el );
wrapper.destroy();
}
}
wrappers = {};
}
return els;
};
return Element;
})();
/*
* This file exposes the public API for invoking PIE.
*/
/**
* The version number of this PIE build.
*/
PIE[ 'version' ] = '2.0beta1';
/**
* @property supportsVML
* True if the current IE browser environment has a functioning VML engine. Should be true
* in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
* attached to an element (for IE<9) to prevent errors; this property may also be used for
* debugging or by external scripts to perform some special action when VML support is absent.
* @type {boolean}
*/
PIE[ 'supportsVML' ] = PIE.supportsVML;
/**
* Programatically attach PIE to a single element.
* @param {Element} el
*/
PIE[ 'attach' ] = function( el ) {
if ( PIE.ieDocMode === 9 || ( PIE.ieDocMode < 9 && PIE.supportsVML ) ) {
PIE.Element.getInstance( el ).init();
}
};
/**
* Programatically detach PIE from a single element.
* @param {Element} el
*/
PIE[ 'detach' ] = function( el ) {
PIE.Element.destroy( el );
};
})( window, document ); | JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Folder related functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initFolders = function() {
$('#folders').scroll(function() {
browser.hideDialog();
});
$('div.folder > a').unbind();
$('div.folder > a').bind('click', function() {
browser.hideDialog();
return false;
});
$('div.folder > a > span.brace').unbind();
$('div.folder > a > span.brace').click(function() {
if ($(this).hasClass('opened') || $(this).hasClass('closed'))
browser.expandDir($(this).parent());
});
$('div.folder > a > span.folder').unbind();
$('div.folder > a > span.folder').click(function() {
browser.changeDir($(this).parent());
});
$('div.folder > a > span.folder').rightClick(function(e) {
_.unselect();
browser.menuDir($(this).parent(), e);
});
if ($.browser.msie && $.browser.version &&
(parseInt($.browser.version.substr(0, 1)) < 8)
) {
var fls = $('div.folder').get();
var body = $('body').get(0);
var div;
$.each(fls, function(i, folder) {
div = document.createElement('div');
div.style.display = 'inline';
div.style.margin = div.style.border = div.style.padding = '0';
div.innerHTML='<table style="border-collapse:collapse;border:0;margin:0;width:0"><tr><td nowrap="nowrap" style="white-space:nowrap;padding:0;border:0">' + $(folder).html() + "</td></tr></table>";
body.appendChild(div);
$(folder).css('width', $(div).innerWidth() + 'px');
body.removeChild(div);
});
}
};
browser.setTreeData = function(data, path) {
if (!path)
path = '';
else if (path.length && (path.substr(path.length - 1, 1) != '/'))
path += '/';
path += data.name;
var selector = '#folders a[href="kcdir:/' + _.escapeDirs(path) + '"]';
$(selector).data({
name: data.name,
path: path,
readable: data.readable,
writable: data.writable,
removable: data.removable,
hasDirs: data.hasDirs
});
$(selector + ' span.folder').addClass(data.current ? 'current' : 'regular');
if (data.dirs && data.dirs.length) {
$(selector + ' span.brace').addClass('opened');
$.each(data.dirs, function(i, cdir) {
browser.setTreeData(cdir, path + '/');
});
} else if (data.hasDirs)
$(selector + ' span.brace').addClass('closed');
};
browser.buildTree = function(root, path) {
if (!path) path = "";
path += root.name;
var html = '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path) + '"><span class="brace"> </span><span class="folder">' + _.htmlData(root.name) + '</span></a>';
if (root.dirs) {
html += '<div class="folders">';
for (var i = 0; i < root.dirs.length; i++) {
cdir = root.dirs[i];
html += browser.buildTree(cdir, path + '/');
}
html += '</div>';
}
html += '</div>';
return html;
};
browser.expandDir = function(dir) {
var path = dir.data('path');
if (dir.children('.brace').hasClass('opened')) {
dir.parent().children('.folders').hide(500, function() {
if (path == browser.dir.substr(0, path.length))
browser.changeDir(dir);
});
dir.children('.brace').removeClass('opened');
dir.children('.brace').addClass('closed');
} else {
if (dir.parent().children('.folders').get(0)) {
dir.parent().children('.folders').show(500);
dir.children('.brace').removeClass('closed');
dir.children('.brace').addClass('opened');
} else if (!$('#loadingDirs').get(0)) {
dir.parent().append('<div id="loadingDirs">' + this.label("Loading folders...") + '</div>');
$('#loadingDirs').css('display', 'none');
$('#loadingDirs').show(200, function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('expand'),
data: {dir:path},
async: false,
success: function(data) {
$('#loadingDirs').hide(200, function() {
$('#loadingDirs').detach();
});
if (browser.check4errors(data))
return;
var html = '';
$.each(data.dirs, function(i, cdir) {
html += '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path + '/' + cdir.name) + '"><span class="brace"> </span><span class="folder">' + _.htmlData(cdir.name) + '</span></a></div>';
});
if (html.length) {
dir.parent().append('<div class="folders">' + html + '</div>');
var folders = $(dir.parent().children('.folders').first());
folders.css('display', 'none');
$(folders).show(500);
$.each(data.dirs, function(i, cdir) {
browser.setTreeData(cdir, path);
});
}
if (data.dirs.length) {
dir.children('.brace').removeClass('closed');
dir.children('.brace').addClass('opened');
} else {
dir.children('.brace').removeClass('opened');
dir.children('.brace').removeClass('closed');
}
browser.initFolders();
browser.initDropUpload();
},
error: function() {
$('#loadingDirs').detach();
browser.alert(browser.label("Unknown error."));
}
});
});
}
}
};
browser.changeDir = function(dir) {
if (dir.children('span.folder').hasClass('regular')) {
$('div.folder > a > span.folder').removeClass('current');
$('div.folder > a > span.folder').removeClass('regular');
$('div.folder > a > span.folder').addClass('regular');
dir.children('span.folder').removeClass('regular');
dir.children('span.folder').addClass('current');
$('#files').html(browser.label("Loading files..."));
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('chDir'),
data: {dir:dir.data('path')},
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.files = data.files;
browser.orderFiles();
browser.dir = dir.data('path');
browser.dirWritable = data.dirWritable;
var title = "KCFinder: /" + browser.dir;
document.title = title;
if (browser.opener.TinyMCE)
tinyMCEPopup.editor.windowManager.setTitle(window, title);
browser.statusDir();
},
error: function() {
$('#files').html(browser.label("Unknown error."));
}
});
}
};
browser.statusDir = function() {
for (var i = 0, size = 0; i < this.files.length; i++)
size += parseInt(this.files[i].size);
size = this.humanSize(size);
$('#fileinfo').html(this.files.length + ' ' + this.label("files") + ' (' + size + ')');
};
browser.menuDir = function(dir, e) {
var data = dir.data();
var html = '<div class="menu">';
if (this.clipboard && this.clipboard.length) {
if (this.access.files.copy)
html += '<a href="kcact:cpcbd"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Copy {count} files", {count: this.clipboard.length}) + '</a>';
if (this.access.files.move)
html += '<a href="kcact:mvcbd"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Move {count} files", {count: this.clipboard.length}) + '</a>';
if (this.access.files.copy || this.access.files.move)
html += '<div class="delimiter"></div>';
}
html +=
'<a href="kcact:refresh">' + this.label("Refresh") + '</a>';
if (this.support.zip) html+=
'<div class="delimiter"></div>' +
'<a href="kcact:download">' + this.label("Download") + '</a>';
if (this.access.dirs.create || this.access.dirs.rename || this.access.dirs['delete'])
html += '<div class="delimiter"></div>';
if (this.access.dirs.create)
html += '<a href="kcact:mkdir"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("New Subfolder...") + '</a>';
if (this.access.dirs.rename)
html += '<a href="kcact:mvdir"' + (!data.removable ? ' class="denied"' : '') + '>' +
this.label("Rename...") + '</a>';
if (this.access.dirs['delete'])
html += '<a href="kcact:rmdir"' + (!data.removable ? ' class="denied"' : '') + '>' +
this.label("Delete") + '</a>';
html += '</div>';
$('#dialog').html(html);
this.showMenu(e);
$('div.folder > a > span.folder').removeClass('context');
if (dir.children('span.folder').hasClass('regular'))
dir.children('span.folder').addClass('context');
if (this.clipboard && this.clipboard.length && data.writable) {
$('.menu a[href="kcact:cpcbd"]').click(function() {
browser.hideDialog();
browser.copyClipboard(data.path);
return false;
});
$('.menu a[href="kcact:mvcbd"]').click(function() {
browser.hideDialog();
browser.moveClipboard(data.path);
return false;
});
}
$('.menu a[href="kcact:refresh"]').click(function() {
browser.hideDialog();
browser.refreshDir(dir);
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
browser.post(browser.baseGetData('downloadDir'), {dir:data.path});
return false;
});
$('.menu a[href="kcact:mkdir"]').click(function(e) {
if (!data.writable) return false;
browser.hideDialog();
browser.fileNameDialog(
e, {dir: data.path},
'newDir', '', browser.baseGetData('newDir'), {
title: "New folder name:",
errEmpty: "Please enter new folder name.",
errSlash: "Unallowable characters in folder name.",
errDot: "Folder name shouldn't begins with '.'"
}, function() {
browser.refreshDir(dir);
browser.initDropUpload();
if (!data.hasDirs) {
dir.data('hasDirs', true);
dir.children('span.brace').addClass('closed');
}
}
);
return false;
});
$('.menu a[href="kcact:mvdir"]').click(function(e) {
if (!data.removable) return false;
browser.hideDialog();
browser.fileNameDialog(
e, {dir: data.path},
'newName', data.name, browser.baseGetData('renameDir'), {
title: "New folder name:",
errEmpty: "Please enter new folder name.",
errSlash: "Unallowable characters in folder name.",
errDot: "Folder name shouldn't begins with '.'"
}, function(dt) {
if (!dt.name) {
browser.alert(browser.label("Unknown error."));
return;
}
var currentDir = (data.path == browser.dir);
dir.children('span.folder').html(_.htmlData(dt.name));
dir.data('name', dt.name);
dir.data('path', _.dirname(data.path) + '/' + dt.name);
if (currentDir)
browser.dir = dir.data('path');
browser.initDropUpload();
},
true
);
return false;
});
$('.menu a[href="kcact:rmdir"]').click(function() {
if (!data.removable) return false;
browser.hideDialog();
browser.confirm(
"Are you sure you want to delete this folder and all its content?",
function(callBack) {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('deleteDir'),
data: {dir: data.path},
async: false,
success: function(data) {
if (callBack) callBack();
if (browser.check4errors(data))
return;
dir.parent().hide(500, function() {
var folders = dir.parent().parent();
var pDir = folders.parent().children('a').first();
dir.parent().detach();
if (!folders.children('div.folder').get(0)) {
pDir.children('span.brace').first().removeClass('opened');
pDir.children('span.brace').first().removeClass('closed');
pDir.parent().children('.folders').detach();
pDir.data('hasDirs', false);
}
if (pDir.data('path') == browser.dir.substr(0, pDir.data('path').length))
browser.changeDir(pDir);
browser.initDropUpload();
});
},
error: function() {
if (callBack) callBack();
browser.alert(browser.label("Unknown error."));
}
});
}
);
return false;
});
};
browser.refreshDir = function(dir) {
var path = dir.data('path');
if (dir.children('.brace').hasClass('opened') || dir.children('.brace').hasClass('closed')) {
dir.children('.brace').removeClass('opened');
dir.children('.brace').addClass('closed');
}
dir.parent().children('.folders').first().detach();
if (path == browser.dir.substr(0, path.length))
browser.changeDir(dir);
browser.expandDir(dir);
return true;
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc File related functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initFiles = function() {
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
$('#files').unbind();
$('#files').scroll(function() {
browser.hideDialog();
});
$('.file').unbind();
$('.file').click(function(e) {
_.unselect();
browser.selectFile($(this), e);
});
$('.file').rightClick(function(e) {
_.unselect();
browser.menuFile($(this), e);
});
$('.file').dblclick(function() {
_.unselect();
browser.returnFile($(this));
});
$('.file').mouseup(function() {
_.unselect();
});
$('.file').mouseout(function() {
_.unselect();
});
$.each(this.shows, function(i, val) {
var display = (_.kuki.get('show' + val) == 'off')
? 'none' : 'block';
$('#files .file div.' + val).css('display', display);
});
this.statusDir();
};
browser.showFiles = function(callBack, selected) {
this.fadeFiles();
setTimeout(function() {
var html = '';
$.each(browser.files, function(i, file) {
var stamp = [];
$.each(file, function(key, val) {
stamp[stamp.length] = key + "|" + val;
});
stamp = _.md5(stamp.join('|'));
if (_.kuki.get('view') == 'list') {
if (!i) html += '<table summary="list">';
var icon = _.getFileExtension(file.name);
if (file.thumb)
icon = '.image';
else if (!icon.length || !file.smallIcon)
icon = '.';
icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png';
html += '<tr class="file">' +
'<td class="name" style="background-image:url(' + icon + ')">' + _.htmlData(file.name) + '</td>' +
'<td class="time">' + file.date + '</td>' +
'<td class="size">' + browser.humanSize(file.size) + '</td>' +
'</tr>';
if (i == browser.files.length - 1) html += '</table>';
} else {
if (file.thumb)
var icon = browser.baseGetData('thumb') + '&file=' + encodeURIComponent(file.name) + '&dir=' + encodeURIComponent(browser.dir) + '&stamp=' + stamp;
else if (file.smallThumb) {
var icon = browser.uploadURL + '/' + browser.dir + '/' + file.name;
icon = _.escapeDirs(icon).replace(/\'/g, "%27");
} else {
var icon = file.bigIcon ? _.getFileExtension(file.name) : '.';
if (!icon.length) icon = '.';
icon = 'themes/' + browser.theme + '/img/files/big/' + icon + '.png';
}
html += '<div class="file">' +
'<div class="thumb" style="background-image:url(\'' + icon + '\')" ></div>' +
'<div class="name">' + _.htmlData(file.name) + '</div>' +
'<div class="time">' + file.date + '</div>' +
'<div class="size">' + browser.humanSize(file.size) + '</div>' +
'</div>';
}
});
$('#files').html('<div>' + html + '<div>');
$.each(browser.files, function(i, file) {
var item = $('#files .file').get(i);
$(item).data(file);
if (_.inArray(file.name, selected) ||
((typeof selected != 'undefined') && !selected.push && (file.name == selected))
)
$(item).addClass('selected');
});
$('#files > div').css({opacity:'', filter:''});
if (callBack) callBack();
browser.initFiles();
}, 200);
};
browser.selectFile = function(file, e) {
if (e.ctrlKey || e.metaKey) {
if (file.hasClass('selected'))
file.removeClass('selected');
else
file.addClass('selected');
var files = $('.file.selected').get();
var size = 0;
if (!files.length)
this.statusDir();
else {
$.each(files, function(i, cfile) {
size += parseInt($(cfile).data('size'));
});
size = this.humanSize(size);
if (files.length > 1)
$('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')');
else {
var data = $(files[0]).data();
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
}
}
} else {
var data = file.data();
$('.file').removeClass('selected');
file.addClass('selected');
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
}
};
browser.selectAll = function(e) {
if ((!e.ctrlKey && !e.metaKey) || ((e.keyCode != 65) && (e.keyCode != 97)))
return false;
var files = $('.file').get();
if (files.length) {
var size = 0;
$.each(files, function(i, file) {
if (!$(file).hasClass('selected'))
$(file).addClass('selected');
size += parseInt($(file).data('size'));
});
size = this.humanSize(size);
$('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')');
}
return true;
};
browser.returnFile = function(file) {
var fileURL = file.substr
? file : browser.uploadURL + '/' + browser.dir + '/' + file.data('name');
fileURL = _.escapeDirs(fileURL);
if (this.opener.CKEditor) {
this.opener.CKEditor.object.tools.callFunction(this.opener.CKEditor.funcNum, fileURL, '');
window.close();
} else if (this.opener.FCKeditor) {
window.opener.SetUrl(fileURL) ;
window.close() ;
} else if (this.opener.TinyMCE) {
var win = tinyMCEPopup.getWindowArg('window');
win.document.getElementById(tinyMCEPopup.getWindowArg('input')).value = fileURL;
if (win.getImageData) win.getImageData();
if (typeof(win.ImageDialog) != "undefined") {
if (win.ImageDialog.getImageData)
win.ImageDialog.getImageData();
if (win.ImageDialog.showPreviewImage)
win.ImageDialog.showPreviewImage(fileURL);
}
tinyMCEPopup.close();
} else if (this.opener.callBack) {
if (window.opener && window.opener.KCFinder) {
this.opener.callBack(fileURL);
window.close();
}
if (window.parent && window.parent.KCFinder) {
var button = $('#toolbar a[href="kcact:maximize"]');
if (button.hasClass('selected'))
this.maximize(button);
this.opener.callBack(fileURL);
}
} else if (this.opener.callBackMultiple) {
if (window.opener && window.opener.KCFinder) {
this.opener.callBackMultiple([fileURL]);
window.close();
}
if (window.parent && window.parent.KCFinder) {
var button = $('#toolbar a[href="kcact:maximize"]');
if (button.hasClass('selected'))
this.maximize(button);
this.opener.callBackMultiple([fileURL]);
}
}
};
browser.returnFiles = function(files) {
if (this.opener.callBackMultiple && files.length) {
var rfiles = [];
$.each(files, function(i, file) {
rfiles[i] = browser.uploadURL + '/' + browser.dir + '/' + $(file).data('name');
rfiles[i] = _.escapeDirs(rfiles[i]);
});
this.opener.callBackMultiple(rfiles);
if (window.opener) window.close()
}
};
browser.returnThumbnails = function(files) {
if (this.opener.callBackMultiple) {
var rfiles = [];
var j = 0;
$.each(files, function(i, file) {
if ($(file).data('thumb')) {
rfiles[j] = browser.thumbsURL + '/' + browser.dir + '/' + $(file).data('name');
rfiles[j] = _.escapeDirs(rfiles[j++]);
}
});
this.opener.callBackMultiple(rfiles);
if (window.opener) window.close()
}
};
browser.menuFile = function(file, e) {
var data = file.data();
var path = this.dir + '/' + data.name;
var files = $('.file.selected').get();
var html = '';
if (file.hasClass('selected') && files.length && (files.length > 1)) {
var thumb = false;
var notWritable = 0;
var cdata;
$.each(files, function(i, cfile) {
cdata = $(cfile).data();
if (cdata.thumb) thumb = true;
if (!data.writable) notWritable++;
});
if (this.opener.callBackMultiple) {
html += '<a href="kcact:pick">' + this.label("Select") + '</a>';
if (thumb) html +=
'<a href="kcact:pick_thumb">' + this.label("Select Thumbnails") + '</a>';
}
if (data.thumb || data.smallThumb || this.support.zip) {
html += (html.length ? '<div class="delimiter"></div>' : '');
if (data.thumb || data.smallThumb)
html +='<a href="kcact:view">' + this.label("View") + '</a>';
if (this.support.zip) html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:download">' + this.label("Download") + '</a>';
}
if (this.access.files.copy || this.access.files.move)
html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>';
if (this.access.files['delete'])
html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:rm"' + ((notWritable == files.length) ? ' class="denied"' : '') +
'>' + this.label("Delete") + '</a>';
if (html.length) {
html = '<div class="menu">' + html + '</div>';
$('#dialog').html(html);
this.showMenu(e);
} else
return;
$('.menu a[href="kcact:pick"]').click(function() {
browser.returnFiles(files);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:pick_thumb"]').click(function() {
browser.returnThumbnails(files);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
var pfiles = [];
$.each(files, function(i, cfile) {
pfiles[i] = $(cfile).data('name');
});
browser.post(browser.baseGetData('downloadSelected'), {dir:browser.dir, files:pfiles});
return false;
});
$('.menu a[href="kcact:clpbrdadd"]').click(function() {
browser.hideDialog();
var msg = '';
$.each(files, function(i, cfile) {
var cdata = $(cfile).data();
var failed = false;
for (i = 0; i < browser.clipboard.length; i++)
if ((browser.clipboard[i].name == cdata.name) &&
(browser.clipboard[i].dir == browser.dir)
) {
failed = true
msg += cdata.name + ": " + browser.label("This file is already added to the Clipboard.") + "\n";
break;
}
if (!failed) {
cdata.dir = browser.dir;
browser.clipboard[browser.clipboard.length] = cdata;
}
});
browser.initClipboard();
if (msg.length) browser.alert(msg.substr(0, msg.length - 1));
return false;
});
$('.menu a[href="kcact:rm"]').click(function() {
if ($(this).hasClass('denied')) return false;
browser.hideDialog();
var failed = 0;
var dfiles = [];
$.each(files, function(i, cfile) {
var cdata = $(cfile).data();
if (!cdata.writable)
failed++;
else
dfiles[dfiles.length] = browser.dir + "/" + cdata.name;
});
if (failed == files.length) {
browser.alert(browser.label("The selected files are not removable."));
return false;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('rm_cbd'),
data: {files:dfiles},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} selected files are not removable. Do you want to delete the rest?", {count:failed}),
go
)
else
browser.confirm(
browser.label("Are you sure you want to delete all selected files?"),
go
);
return false;
});
} else {
html += '<div class="menu">';
$('.file').removeClass('selected');
file.addClass('selected');
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
if (this.opener.callBack || this.opener.callBackMultiple) {
html += '<a href="kcact:pick">' + this.label("Select") + '</a>';
if (data.thumb) html +=
'<a href="kcact:pick_thumb">' + this.label("Select Thumbnail") + '</a>';
html += '<div class="delimiter"></div>';
}
if (data.thumb || data.smallThumb)
html +='<a href="kcact:view">' + this.label("View") + '</a>';
html +=
'<a href="kcact:download">' + this.label("Download") + '</a>';
if (this.access.files.copy || this.access.files.move)
html += '<div class="delimiter"></div>' +
'<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>';
if (this.access.files.rename || this.access.files['delete'])
html += '<div class="delimiter"></div>';
if (this.access.files.rename)
html += '<a href="kcact:mv"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Rename...") + '</a>';
if (this.access.files['delete'])
html += '<a href="kcact:rm"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Delete") + '</a>';
html += '</div>';
$('#dialog').html(html);
this.showMenu(e);
$('.menu a[href="kcact:pick"]').click(function() {
browser.returnFile(file);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:pick_thumb"]').click(function() {
var path = browser.thumbsURL + '/' + browser.dir + '/' + data.name;
browser.returnFile(path);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
var html = '<form id="downloadForm" method="post" action="' + browser.baseGetData('download') + '">' +
'<input type="hidden" name="dir" />' +
'<input type="hidden" name="file" />' +
'</form>';
$('#dialog').html(html);
$('#downloadForm input').get(0).value = browser.dir;
$('#downloadForm input').get(1).value = data.name;
$('#downloadForm').submit();
return false;
});
$('.menu a[href="kcact:clpbrdadd"]').click(function() {
for (i = 0; i < browser.clipboard.length; i++)
if ((browser.clipboard[i].name == data.name) &&
(browser.clipboard[i].dir == browser.dir)
) {
browser.hideDialog();
browser.alert(browser.label("This file is already added to the Clipboard."));
return false;
}
var cdata = data;
cdata.dir = browser.dir;
browser.clipboard[browser.clipboard.length] = cdata;
browser.initClipboard();
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:mv"]').click(function(e) {
if (!data.writable) return false;
browser.fileNameDialog(
e, {dir: browser.dir, file: data.name},
'newName', data.name, browser.baseGetData('rename'), {
title: "New file name:",
errEmpty: "Please enter new file name.",
errSlash: "Unallowable characters in file name.",
errDot: "File name shouldn't begins with '.'"
},
function() {
browser.refresh();
}
);
return false;
});
$('.menu a[href="kcact:rm"]').click(function() {
if (!data.writable) return false;
browser.hideDialog();
browser.confirm(browser.label("Are you sure you want to delete this file?"),
function(callBack) {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('delete'),
data: {dir:browser.dir, file:data.name},
async: false,
success: function(data) {
if (callBack) callBack();
browser.clearClipboard();
if (browser.check4errors(data))
return;
browser.refresh();
},
error: function() {
if (callBack) callBack();
browser.alert(browser.label("Unknown error."));
}
});
}
);
return false;
});
}
$('.menu a[href="kcact:view"]').click(function() {
browser.hideDialog();
var ts = new Date().getTime();
var showImage = function(data) {
url = _.escapeDirs(browser.uploadURL + '/' + browser.dir + '/' + data.name) + '?ts=' + ts,
$('#loading').html(browser.label("Loading image..."));
$('#loading').css('display', 'inline');
var img = new Image();
img.src = url;
img.onerror = function() {
browser.lock = false;
$('#loading').css('display', 'none');
browser.alert(browser.label("Unknown error."));
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
browser.refresh();
};
var onImgLoad = function() {
browser.lock = false;
$('#files .file').each(function() {
if ($(this).data('name') == data.name)
browser.ssImage = this;
});
$('#loading').css('display', 'none');
$('#dialog').html('<div class="slideshow"><img /></div>');
$('#dialog img').attr({
src: url,
title: data.name
}).fadeIn('fast', function() {
var o_w = $('#dialog').outerWidth();
var o_h = $('#dialog').outerHeight();
var f_w = $(window).width() - 30;
var f_h = $(window).height() - 30;
if ((o_w > f_w) || (o_h > f_h)) {
if ((f_w / f_h) > (o_w / o_h))
f_w = parseInt((o_w * f_h) / o_h);
else if ((f_w / f_h) < (o_w / o_h))
f_h = parseInt((o_h * f_w) / o_w);
$('#dialog img').attr({
width: f_w,
height: f_h
});
}
$('#dialog').unbind('click');
$('#dialog').click(function(e) {
browser.hideDialog();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
if (browser.ssImage) {
browser.selectFile($(browser.ssImage), e);
}
});
browser.showDialog();
var images = [];
$.each(browser.files, function(i, file) {
if (file.thumb || file.smallThumb)
images[images.length] = file;
});
if (images.length)
$.each(images, function(i, image) {
if (image.name == data.name) {
$(document).unbind('keydown');
$(document).keydown(function(e) {
if (images.length > 1) {
if (!browser.lock && (e.keyCode == 37)) {
var nimg = i
? images[i - 1]
: images[images.length - 1];
browser.lock = true;
showImage(nimg);
}
if (!browser.lock && (e.keyCode == 39)) {
var nimg = (i >= images.length - 1)
? images[0]
: images[i + 1];
browser.lock = true;
showImage(nimg);
}
}
if (e.keyCode == 27) {
browser.hideDialog();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
}
});
}
});
});
};
if (img.complete)
onImgLoad();
else
img.onload = onImgLoad;
};
showImage(data);
return false;
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Toolbar functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initToolbar = function() {
$('#toolbar a').click(function() {
browser.hideDialog();
});
if (!_.kuki.isSet('displaySettings'))
_.kuki.set('displaySettings', 'off');
if (_.kuki.get('displaySettings') == 'on') {
$('#toolbar a[href="kcact:settings"]').addClass('selected');
$('#settings').css('display', 'block');
browser.resize();
}
$('#toolbar a[href="kcact:settings"]').click(function () {
if ($('#settings').css('display') == 'none') {
$(this).addClass('selected');
_.kuki.set('displaySettings', 'on');
$('#settings').css('display', 'block');
browser.fixFilesHeight();
} else {
$(this).removeClass('selected');
_.kuki.set('displaySettings', 'off');
$('#settings').css('display', 'none');
browser.fixFilesHeight();
}
return false;
});
$('#toolbar a[href="kcact:refresh"]').click(function() {
browser.refresh();
return false;
});
if (window.opener || this.opener.TinyMCE || $('iframe', window.parent.document).get(0))
$('#toolbar a[href="kcact:maximize"]').click(function() {
browser.maximize(this);
return false;
});
else
$('#toolbar a[href="kcact:maximize"]').css('display', 'none');
$('#toolbar a[href="kcact:about"]').click(function() {
var html = '<div class="box about">' +
'<div class="head"><a href="http://kcfinder.sunhater.com" target="_blank">KCFinder</a> ' + browser.version + '</div>';
if (browser.support.check4Update)
html += '<div id="checkver"><span class="loading"><span>' + browser.label("Checking for new version...") + '</span></span></div>';
html +=
'<div>' + browser.label("Licenses:") + ' GPLv2 & LGPLv2</div>' +
'<div>Copyright ©2010, 2011 Pavel Tzonkov</div>' +
'<button>' + browser.label("OK") + '</button>' +
'</div>';
$('#dialog').html(html);
$('#dialog').data('title', browser.label("About"));
browser.showDialog();
var close = function() {
browser.hideDialog();
browser.unshadow();
}
$('#dialog button').click(close);
var span = $('#checkver > span');
setTimeout(function() {
$.ajax({
dataType: 'json',
url: browser.baseGetData('check4Update'),
async: true,
success: function(data) {
if (!$('#dialog').html().length)
return;
span.removeClass('loading');
if (!data.version) {
span.html(browser.label("Unable to connect!"));
browser.showDialog();
return;
}
if (browser.version < data.version)
span.html('<a href="http://kcfinder.sunhater.com/download" target="_blank">' + browser.label("Download version {version} now!", {version: data.version}) + '</a>');
else
span.html(browser.label("KCFinder is up to date!"));
browser.showDialog();
},
error: function() {
if (!$('#dialog').html().length)
return;
span.removeClass('loading');
span.html(browser.label("Unable to connect!"));
browser.showDialog();
}
});
}, 1000);
$('#dialog').unbind();
return false;
});
this.initUploadButton();
};
browser.initUploadButton = function() {
var btn = $('#toolbar a[href="kcact:upload"]');
if (!this.access.files.upload) {
btn.css('display', 'none');
return;
}
var top = btn.get(0).offsetTop;
var width = btn.outerWidth();
var height = btn.outerHeight();
$('#toolbar').prepend('<div id="upload" style="top:' + top + 'px;width:' + width + 'px;height:' + height + 'px">' +
'<form enctype="multipart/form-data" method="post" target="uploadResponse" action="' + browser.baseGetData('upload') + '">' +
'<input type="file" name="upload[]" onchange="browser.uploadFile(this.form)" style="height:' + height + 'px" multiple="multiple" />' +
'<input type="hidden" name="dir" value="" />' +
'</form>' +
'</div>');
$('#upload input').css('margin-left', "-" + ($('#upload input').outerWidth() - width) + 'px');
$('#upload').mouseover(function() {
$('#toolbar a[href="kcact:upload"]').addClass('hover');
});
$('#upload').mouseout(function() {
$('#toolbar a[href="kcact:upload"]').removeClass('hover');
});
};
browser.uploadFile = function(form) {
if (!this.dirWritable) {
browser.alert(this.label("Cannot write to upload folder."));
$('#upload').detach();
browser.initUploadButton();
return;
}
form.elements[1].value = browser.dir;
$('<iframe id="uploadResponse" name="uploadResponse" src="javascript:;"></iframe>').prependTo(document.body);
$('#loading').html(this.label("Uploading file..."));
$('#loading').css('display', 'inline');
form.submit();
$('#uploadResponse').load(function() {
var response = $(this).contents().find('body').html();
$('#loading').css('display', 'none');
response = response.split("\n");
var selected = [], errors = [];
$.each(response, function(i, row) {
if (row.substr(0, 1) == '/')
selected[selected.length] = row.substr(1, row.length - 1)
else
errors[errors.length] = row;
});
if (errors.length)
browser.alert(errors.join("\n"));
if (!selected.length)
selected = null
browser.refresh(selected);
$('#upload').detach();
setTimeout(function() {
$('#uploadResponse').detach();
}, 1);
browser.initUploadButton();
});
};
browser.maximize = function(button) {
if (window.opener) {
window.moveTo(0, 0);
width = screen.availWidth;
height = screen.availHeight;
if ($.browser.opera)
height -= 50;
window.resizeTo(width, height);
} else if (browser.opener.TinyMCE) {
var win, ifr, id;
$('iframe', window.parent.document).each(function() {
if (/^mce_\d+_ifr$/.test($(this).attr('id'))) {
id = parseInt($(this).attr('id').replace(/^mce_(\d+)_ifr$/, "$1"));
win = $('#mce_' + id, window.parent.document);
ifr = $('#mce_' + id + '_ifr', window.parent.document);
}
});
if ($(button).hasClass('selected')) {
$(button).removeClass('selected');
win.css({
left: browser.maximizeMCE.left + 'px',
top: browser.maximizeMCE.top + 'px',
width: browser.maximizeMCE.width + 'px',
height: browser.maximizeMCE.height + 'px'
});
ifr.css({
width: browser.maximizeMCE.width - browser.maximizeMCE.Hspace + 'px',
height: browser.maximizeMCE.height - browser.maximizeMCE.Vspace + 'px'
});
} else {
$(button).addClass('selected')
browser.maximizeMCE = {
width: _.nopx(win.css('width')),
height: _.nopx(win.css('height')),
left: win.position().left,
top: win.position().top,
Hspace: _.nopx(win.css('width')) - _.nopx(ifr.css('width')),
Vspace: _.nopx(win.css('height')) - _.nopx(ifr.css('height'))
};
var width = $(window.parent).width();
var height = $(window.parent).height();
win.css({
left: $(window.parent).scrollLeft() + 'px',
top: $(window.parent).scrollTop() + 'px',
width: width + 'px',
height: height + 'px'
});
ifr.css({
width: width - browser.maximizeMCE.Hspace + 'px',
height: height - browser.maximizeMCE.Vspace + 'px'
});
}
} else if ($('iframe', window.parent.document).get(0)) {
var ifrm = $('iframe[name="' + window.name + '"]', window.parent.document);
var parent = ifrm.parent();
var width, height;
if ($(button).hasClass('selected')) {
$(button).removeClass('selected');
if (browser.maximizeThread) {
clearInterval(browser.maximizeThread);
browser.maximizeThread = null;
}
if (browser.maximizeW) browser.maximizeW = null;
if (browser.maximizeH) browser.maximizeH = null;
$.each($('*', window.parent.document).get(), function(i, e) {
e.style.display = browser.maximizeDisplay[i];
});
ifrm.css({
display: browser.maximizeCSS.display,
position: browser.maximizeCSS.position,
left: browser.maximizeCSS.left,
top: browser.maximizeCSS.top,
width: browser.maximizeCSS.width,
height: browser.maximizeCSS.height
});
$(window.parent).scrollLeft(browser.maximizeLest);
$(window.parent).scrollTop(browser.maximizeTop);
} else {
$(button).addClass('selected');
browser.maximizeCSS = {
display: ifrm.css('display'),
position: ifrm.css('position'),
left: ifrm.css('left'),
top: ifrm.css('top'),
width: ifrm.outerWidth() + 'px',
height: ifrm.outerHeight() + 'px'
};
browser.maximizeTop = $(window.parent).scrollTop();
browser.maximizeLeft = $(window.parent).scrollLeft();
browser.maximizeDisplay = [];
$.each($('*', window.parent.document).get(), function(i, e) {
browser.maximizeDisplay[i] = $(e).css('display');
$(e).css('display', 'none');
});
ifrm.css('display', 'block');
ifrm.parents().css('display', 'block');
var resize = function() {
width = $(window.parent).width();
height = $(window.parent).height();
if (!browser.maximizeW || (browser.maximizeW != width) ||
!browser.maximizeH || (browser.maximizeH != height)
) {
browser.maximizeW = width;
browser.maximizeH = height;
ifrm.css({
width: width + 'px',
height: height + 'px'
});
browser.resize();
}
}
ifrm.css('position', 'absolute');
if ((ifrm.offset().left == ifrm.position().left) &&
(ifrm.offset().top == ifrm.position().top)
)
ifrm.css({left: '0', top: '0'});
else
ifrm.css({
left: - ifrm.offset().left + 'px',
top: - ifrm.offset().top + 'px'
});
resize();
browser.maximizeThread = setInterval(resize, 250);
}
}
};
browser.refresh = function(selected) {
this.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('chDir'),
data: {dir:browser.dir},
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.dirWritable = data.dirWritable;
browser.files = data.files ? data.files : [];
browser.orderFiles(null, selected);
browser.statusDir();
},
error: function() {
$('#files > div').css({opacity:'', filter:''});
$('#files').html(browser.label("Unknown error."));
}
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Clipboard functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var size = 0;
$.each(this.clipboard, function(i, val) {
size += parseInt(val.size);
});
size = this.humanSize(size);
$('#clipboard').html('<div title="' + this.label("Clipboard") + ' (' + this.clipboard.length + ' ' + this.label("files") + ', ' + size + ')" onclick="browser.openClipboard()"></div>');
var resize = function() {
$('#clipboard').css({
left: $(window).width() - $('#clipboard').outerWidth() + 'px',
top: $(window).height() - $('#clipboard').outerHeight() + 'px'
});
};
resize();
$('#clipboard').css('display', 'block');
$(window).unbind();
$(window).resize(function() {
browser.resize();
resize();
});
};
browser.openClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
if ($('.menu a[href="kcact:cpcbd"]').html()) {
$('#clipboard').removeClass('selected');
this.hideDialog();
return;
}
var html = '<div class="menu"><div class="list">';
$.each(this.clipboard, function(i, val) {
icon = _.getFileExtension(val.name);
if (val.thumb)
icon = '.image';
else if (!val.smallIcon || !icon.length)
icon = '.';
var icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png';
html += '<a style="background-image:url(' + _.escapeDirs(icon) + ')" title="' + browser.label("Click to remove from the Clipboard") + '" onclick="browser.removeFromClipboard(' + i + ')">' + _.htmlData(_.basename(val.name)) + '</a>';
});
html += '</div><div class="delimiter"></div>';
if (this.support.zip) html+=
'<a href="kcact:download">' + this.label("Download files") + '</a>';
if (this.access.files.copy || this.access.files.move || this.access.files['delete'])
html += '<div class="delimiter"></div>';
if (this.access.files.copy)
html += '<a href="kcact:cpcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Copy files here") + '</a>';
if (this.access.files.move)
html += '<a href="kcact:mvcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Move files here") + '</a>';
if (this.access.files['delete'])
html += '<a href="kcact:rmcbd">' + this.label("Delete files") + '</a>';
html += '<div class="delimiter"></div>' +
'<a href="kcact:clrcbd">' + this.label("Clear the Clipboard") + '</a>' + '</div>';
setTimeout(function() {
$('#clipboard').addClass('selected');
$('#dialog').html(html);
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
browser.downloadClipboard();
return false;
});
$('.menu a[href="kcact:cpcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.copyClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:mvcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.moveClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:rmcbd"]').click(function() {
browser.hideDialog();
browser.confirm(
browser.label("Are you sure you want to delete all files in the Clipboard?"),
function(callBack) {
if (callBack) callBack();
browser.deleteClipboard();
}
);
return false;
});
$('.menu a[href="kcact:clrcbd"]').click(function() {
browser.hideDialog();
browser.clearClipboard();
return false;
});
var left = $(window).width() - $('#dialog').outerWidth();
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
var lheight = top + _.outerTopSpace('#dialog');
$('.menu .list').css('max-height', lheight + 'px');
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
$('#dialog').css({
left: (left - 4) + 'px',
top: top + 'px'
});
$('#dialog').fadeIn();
}, 1);
};
browser.removeFromClipboard = function(i) {
if (!this.clipboard || !this.clipboard[i]) return false;
if (this.clipboard.length == 1) {
this.clearClipboard();
this.hideDialog();
return;
}
if (i < this.clipboard.length - 1) {
var last = this.clipboard.slice(i + 1);
this.clipboard = this.clipboard.slice(0, i);
this.clipboard = this.clipboard.concat(last);
} else
this.clipboard.pop();
this.initClipboard();
this.hideDialog();
this.openClipboard();
return true;
};
browser.copyClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not readable."));
return;
}
var go = function(callBack) {
if (dir == browser.dir)
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('cp_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
if (dir == browser.dir)
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not readable. Do you want to copy the rest?", {count:failed}),
go
)
else
go();
};
browser.moveClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + "/" + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not movable."))
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('mv_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not movable. Do you want to move the rest?", {count: failed}),
go
);
else
go();
};
browser.deleteClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not removable."))
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('rm_cbd'),
data: {files:files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter:''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not removable. Do you want to delete the rest?", {count: failed}),
go
);
else
go();
};
browser.downloadClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
if (files.length)
this.post(this.baseGetData('downloadClipboard'), {files:files});
};
browser.clearClipboard = function() {
$('#clipboard').html('');
this.clipboard = [];
};
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.