code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* Translated default messages for the jQuery validation plugin.
* Locale: UA (Ukrainian)
*/
jQuery.extend(jQuery.validator.messages, {
required: "Це поле необхідно заповнити.",
remote: "Будь ласка, введіть правильне значення.",
email: "Будь ласка, введіть коректну адресу електронної пошти.",
url: "Будь ласка, введіть коректний URL.",
date: "Будь ласка, введіть коректну дату.",
dateISO: "Будь ласка, введіть коректну дату у форматі ISO.",
number: "Будь ласка, введіть число.",
digits: "Вводите потрібно лише цифри.",
creditcard: "Будь ласка, введіть правильний номер кредитної карти.",
equalTo: "Будь ласка, введіть таке ж значення ще раз.",
accept: "Будь ласка, виберіть файл з правильним розширенням.",
maxlength: jQuery.validator.format("Будь ласка, введіть не більше {0} символів."),
minlength: jQuery.validator.format("Будь ласка, введіть не менше {0} символів."),
rangelength: jQuery.validator.format("Будь ласка, введіть значення довжиною від {0} до {1} символів."),
range: jQuery.validator.format("Будь ласка, введіть число від {0} до {1}."),
max: jQuery.validator.format("Будь ласка, введіть число, менше або рівно {0}."),
min: jQuery.validator.format("Будь ласка, введіть число, більше або рівно {0}.")
});
| JavaScript |
/*
* Localized default methods for the jQuery validation plugin.
* Locale: NL
*/
jQuery.extend(jQuery.validator.methods, {
date: function(value, element) {
return this.optional(element) || /^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(value);
}
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: SR
*/
jQuery.extend(jQuery.validator.messages, {
required: "Поље је обавезно.",
remote: "Средите ово поље.",
email: "Унесите исправну и-мејл адресу",
url: "Унесите исправан URL.",
date: "Унесите исправан датум.",
dateISO: "Унесите исправан датум (ISO).",
number: "Унесите исправан број.",
digits: "Унесите само цифе.",
creditcard: "Унесите исправан број кредитне картице.",
equalTo: "Унесите исту вредност поново.",
accept: "Унесите вредност са одговарајућом екстензијом.",
maxlength: $.validator.format("Унесите мање од {0}карактера."),
minlength: $.validator.format("Унесите барем {0} карактера."),
rangelength: $.validator.format("Унесите вредност дугачку између {0} и {1} карактера."),
range: $.validator.format("Унесите вредност између {0} и {1}."),
max: $.validator.format("Унесите вредност мању или једнаку {0}."),
min: $.validator.format("Унесите вредност већу или једнаку {0}.")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: PL
*/
jQuery.extend(jQuery.validator.messages, {
required: "To pole jest wymagane.",
remote: "Proszę o wypełnienie tego pola.",
email: "Proszę o podanie prawidłowego adresu email.",
url: "Proszę o podanie prawidłowego URL.",
date: "Proszę o podanie prawidłowej daty.",
dateISO: "Proszę o podanie prawidłowej daty (ISO).",
number: "Proszę o podanie prawidłowej liczby.",
digits: "Proszę o podanie samych cyfr.",
creditcard: "Proszę o podanie prawidłowej karty kredytowej.",
equalTo: "Proszę o podanie tej samej wartości ponownie.",
accept: "Proszę o podanie wartości z prawidłowym rozszerzeniem.",
maxlength: jQuery.validator.format("Proszę o podanie nie więcej niż {0} znaków."),
minlength: jQuery.validator.format("Proszę o podanie przynajmniej {0} znaków."),
rangelength: jQuery.validator.format("Proszę o podanie wartości o długości od {0} do {1} znaków."),
range: jQuery.validator.format("Proszę o podanie wartości z przedziału od {0} do {1}."),
max: jQuery.validator.format("Proszę o podanie wartości mniejszej bądź równej {0}."),
min: jQuery.validator.format("Proszę o podanie wartości większej bądź równej {0}.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: NL
*/
jQuery.extend(jQuery.validator.messages, {
required: "Dit is een verplicht veld.",
remote: "Controleer dit veld.",
email: "Vul hier een geldig e-mailadres in.",
url: "Vul hier een geldige URL in.",
date: "Vul hier een geldige datum in.",
dateISO: "Vul hier een geldige datum in (ISO-formaat).",
number: "Vul hier een geldig getal in.",
digits: "Vul hier alleen getallen in.",
creditcard: "Vul hier een geldig creditcardnummer in.",
equalTo: "Vul hier dezelfde waarde in.",
accept: "Vul hier een waarde in met een geldige extensie.",
maxlength: jQuery.validator.format("Vul hier maximaal {0} tekens in."),
minlength: jQuery.validator.format("Vul hier minimaal {0} tekens in."),
rangelength: jQuery.validator.format("Vul hier een waarde in van minimaal {0} en maximaal {1} tekens."),
range: jQuery.validator.format("Vul hier een waarde in van minimaal {0} en maximaal {1}."),
max: jQuery.validator.format("Vul hier een waarde in kleiner dan of gelijk aan {0}."),
min: jQuery.validator.format("Vul hier een waarde in groter dan of gelijk aan {0}.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin into arabic.
* Locale: AR
*/
jQuery.extend(jQuery.validator.messages, {
required: "هذا الحقل إلزامي",
remote: "يرجى تصحيح هذا الحقل للمتابعة",
email: "رجاء إدخال عنوان بريد إلكتروني صحيح",
url: "رجاء إدخال عنوان موقع إلكتروني صحيح",
date: "رجاء إدخال تاريخ صحيح",
dateISO: "رجاء إدخال تاريخ صحيح (ISO)",
number: "رجاء إدخال عدد بطريقة صحيحة",
digits: "رجاء إدخال أرقام فقط",
creditcard: "رجاء إدخال رقم بطاقة ائتمان صحيح",
equalTo: "رجاء إدخال نفس القيمة",
accept: "رجاء إدخال ملف بامتداد موافق عليه",
maxlength: jQuery.validator.format("الحد الأقصى لعدد الحروف هو {0}"),
minlength: jQuery.validator.format("الحد الأدنى لعدد الحروف هو {0}"),
rangelength: jQuery.validator.format("عدد الحروف يجب أن يكون بين {0} و {1}"),
range: jQuery.validator.format("رجاء إدخال عدد قيمته بين {0} و {1}"),
max: jQuery.validator.format("رجاء إدخال عدد أقل من أو يساوي (0}"),
min: jQuery.validator.format("رجاء إدخال عدد أكبر من أو يساوي (0}")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: TH (Thai)
*/
jQuery.extend(jQuery.validator.messages, {
required: "โปรดระบุ",
remote: "โปรดแก้ไขให้ถูกต้อง",
email: "โปรดระบุที่อยู่อีเมล์ที่ถูกต้อง",
url: "โปรดระบุ URL ที่ถูกต้อง",
date: "โปรดระบุวันที่ ที่ถูกต้อง",
dateISO: "โปรดระบุวันที่ ที่ถูกต้อง (ระบบ ISO).",
number: "โปรดระบุทศนิยมที่ถูกต้อง",
digits: "โปรดระบุจำนวนเต็มที่ถูกต้อง",
creditcard: "โปรดระบุรหัสบัตรเครดิตที่ถูกต้อง",
equalTo: "โปรดระบุค่าเดิมอีกครั้ง",
accept: "โปรดระบุค่าที่มีส่วนขยายที่ถูกต้อง",
maxlength: jQuery.validator.format("โปรดอย่าระบุค่าที่ยาวกว่า {0} อักขระ"),
minlength: jQuery.validator.format("โปรดอย่าระบุค่าที่สั้นกว่า {0} อักขระ"),
rangelength: jQuery.validator.format("โปรดอย่าระบุค่าความยาวระหว่าง {0} ถึง {1} อักขระ"),
range: jQuery.validator.format("โปรดระบุค่าระหว่าง {0} และ {1}"),
max: jQuery.validator.format("โปรดระบุค่าน้อยกว่าหรือเท่ากับ {0}"),
min: jQuery.validator.format("โปรดระบุค่ามากกว่าหรือเท่ากับ {0}")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: FI
*/
jQuery.extend(jQuery.validator.messages, {
required: "Tämä kenttä on pakollinen.",
maxlength: jQuery.validator.format("Voit syöttää enintään {0} merkkiä."),
minlength: jQuery.validator.format("Vähintään {0} merkkiä."),
rangelength: jQuery.validator.format("Syötä vähintään {0} ja enintään {1} merkkiä."),
email: "Syötä oikea sähköpostiosoite.",
url: "Syötä oikea URL osoite.",
date: "Syötä oike päivämäärä.",
dateISO: "Syötä oike päivämäärä (VVVV-MM-DD).",
number: "Syötä numero.",
digits: "Syötä pelkästään numeroita.",
equalTo: "Syötä sama arvo uudestaan.",
range: jQuery.validator.format("Syötä arvo {0} ja {1} väliltä."),
max: jQuery.validator.format("Syötä arvo joka on yhtä suuri tai suurempi kuin {0}."),
min: jQuery.validator.format("Syötä arvo joka on pienempi tai yhtä suuri kuin {0}."),
creditcard: "Syötä voimassa oleva luottokorttinumero."
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: CS
*/
jQuery.extend(jQuery.validator.messages, {
required: "Tento údaj je povinný.",
remote: "Prosím, opravte tento údaj.",
email: "Prosím, zadejte platný e-mail.",
url: "Prosím, zadejte platné URL.",
date: "Prosím, zadejte platné datum.",
dateISO: "Prosím, zadejte platné datum (ISO).",
number: "Prosím, zadejte číslo.",
digits: "Prosím, zadávejte pouze číslice.",
creditcard: "Prosím, zadejte číslo kreditní karty.",
equalTo: "Prosím, zadejte znovu stejnou hodnotu.",
accept: "Prosím, zadejte soubor se správnou příponou.",
maxlength: jQuery.validator.format("Prosím, zadejte nejvíce {0} znaků."),
minlength: jQuery.validator.format("Prosím, zadejte nejméně {0} znaků."),
rangelength: jQuery.validator.format("Prosím, zadejte od {0} do {1} znaků."),
range: jQuery.validator.format("Prosím, zadejte hodnotu od {0} do {1}."),
max: jQuery.validator.format("Prosím, zadejte hodnotu menší nebo rovnu {0}."),
min: jQuery.validator.format("Prosím, zadejte hodnotu větší nebo rovnu {0}.")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: RU
*/
jQuery.extend(jQuery.validator.messages, {
required: "Это поле необходимо заполнить.",
remote: "Пожалуйста, введите правильное значение.",
email: "Пожалуйста, введите корректный адрес электронной почты.",
url: "Пожалуйста, введите корректный URL.",
date: "Пожалуйста, введите корректную дату.",
dateISO: "Пожалуйста, введите корректную дату в формате ISO.",
number: "Пожалуйста, введите число.",
digits: "Пожалуйста, вводите только цифры.",
creditcard: "Пожалуйста, введите правильный номер кредитной карты.",
equalTo: "Пожалуйста, введите такое же значение ещё раз.",
accept: "Пожалуйста, выберите файл с правильным расширением.",
maxlength: jQuery.validator.format("Пожалуйста, введите не больше {0} символов."),
minlength: jQuery.validator.format("Пожалуйста, введите не меньше {0} символов."),
rangelength: jQuery.validator.format("Пожалуйста, введите значение длиной от {0} до {1} символов."),
range: jQuery.validator.format("Пожалуйста, введите число от {0} до {1}."),
max: jQuery.validator.format("Пожалуйста, введите число, меньшее или равное {0}."),
min: jQuery.validator.format("Пожалуйста, введите число, большее или равное {0}.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: GE
*/
jQuery.extend(jQuery.validator.messages, {
required: "ამ ველის შევსება აუცილებელია.",
remote: "გთხოვთ მიუთითოთ სწორი მნიშვნელობა.",
email: "გთხოვთ მიუთითოთ ელ-ფოსტის კორექტული მისამართი.",
url: "გთხოვთ მიუთითოთ კორექტული URL.",
date: "გთხოვთ მიუთითოთ კორექტული თარიღი.",
dateISO: "გთხოვთ მიუთითოთ კორექტული თარიღი ISO ფორმატში.",
number: "გთხოვთ მიუთითოთ ციფრი.",
digits: "გთხოვთ მიუთითოთ მხოლოდ ციფრები.",
creditcard: "გთხოვთ მიუთითოთ საკრედიტო ბარათის კორექტული ნომერი.",
equalTo: "გთხოვთ მიუთითოთ ასეთივე მნიშვნელობა კიდევ ერთხელ.",
accept: "გთხოვთ აირჩიოთ ფაილი კორექტული გაფართოებით.",
maxlength: jQuery.validator.format("დასაშვებია არაუმეტეს {0} სიმბოლო."),
minlength: jQuery.validator.format("აუცილებელია შეიყვანოთ მინიმუმ {0} სიმბოლო."),
rangelength: jQuery.validator.format("ტექსტში სიმბოლოების რაოდენობა უნდა იყოს {0}-დან {1}-მდე."),
range: jQuery.validator.format("გთხოვთ შეიყვანოთ ციფრი {0}-დან {1}-მდე."),
max: jQuery.validator.format("გთხოვთ შეიყვანოთ ციფრი რომელიც ნაკლებია ან უდრის {0}-ს."),
min: jQuery.validator.format("გთხოვთ შეიყვანოთ ციფრი რომელიც მეტია ან უდრის {0}-ს.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: HE
*/
jQuery.extend(jQuery.validator.messages, {
required: ".השדה הזה הינו שדה חובה",
remote: "נא לתקן שדה זה.",
email: "נא למלא כתובת דוא\"ל חוקית",
url: "נא למלא כתובת אינטרנט חוקית.",
date: "נא למלא תאריך חוקי",
dateISO: "נא למלא תאריך חוקי (ISO).",
number: "נא למלא מספר.",
digits: ".נא למלא רק מספרים",
creditcard: "נא למלא מספר כרטיס אשראי חוקי.",
equalTo: "נא למלא את אותו ערך שוב.",
accept: "נא למלא ערך עם סיומת חוקית.",
maxlength: jQuery.validator.format(".נא לא למלא יותר מ- {0} תווים"),
minlength: jQuery.validator.format("נא למלא לפחות {0} תווים."),
rangelength: jQuery.validator.format("נא למלא ערך בין {0} ל- {1} תווים."),
range: jQuery.validator.format("נא למלא ערך בין {0} ל- {1}."),
max: jQuery.validator.format("נא למלא ערך קטן או שווה ל- {0}."),
min: jQuery.validator.format("נא למלא ערך גדול או שווה ל- {0}.")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: HU
*/
jQuery.extend(jQuery.validator.messages, {
required: "Kötelező megadni.",
maxlength: jQuery.validator.format("Legfeljebb {0} karakter hosszú legyen."),
minlength: jQuery.validator.format("Legalább {0} karakter hosszú legyen."),
rangelength: jQuery.validator.format("Legalább {0} és legfeljebb {1} karakter hosszú legyen."),
email: "Érvényes e-mail címnek kell lennie.",
url: "Érvényes URL-nek kell lennie.",
date: "Dátumnak kell lennie.",
number: "Számnak kell lennie.",
digits: "Csak számjegyek lehetnek.",
equalTo: "Meg kell egyeznie a két értéknek.",
range: jQuery.validator.format("{0} és {1} közé kell esnie."),
max: jQuery.validator.format("Nem lehet nagyobb, mint {0}."),
min: jQuery.validator.format("Nem lehet kisebb, mint {0}."),
creditcard: "Érvényes hitelkártyaszámnak kell lennie."
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: PT_BR
*/
jQuery.extend(jQuery.validator.messages, {
required: "Este campo é requerido.",
remote: "Por favor, corrija este campo.",
email: "Por favor, forneça um endereço eletrônico válido.",
url: "Por favor, forneça uma URL válida.",
date: "Por favor, forneça uma data válida.",
dateISO: "Por favor, forneça uma data válida (ISO).",
number: "Por favor, forneça um número válido.",
digits: "Por favor, forneça somente dígitos.",
creditcard: "Por favor, forneça um cartão de crédito válido.",
equalTo: "Por favor, forneça o mesmo valor novamente.",
accept: "Por favor, forneça um valor com uma extensão válida.",
maxlength: jQuery.validator.format("Por favor, forneça não mais que {0} caracteres."),
minlength: jQuery.validator.format("Por favor, forneça ao menos {0} caracteres."),
rangelength: jQuery.validator.format("Por favor, forneça um valor entre {0} e {1} caracteres de comprimento."),
range: jQuery.validator.format("Por favor, forneça um valor entre {0} e {1}."),
max: jQuery.validator.format("Por favor, forneça um valor menor ou igual a {0}."),
min: jQuery.validator.format("Por favor, forneça um valor maior ou igual a {0}.")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: EU (Basque)
*/
jQuery.extend(jQuery.validator.messages, {
required: "Eremu hau beharrezkoa da.",
remote: "Mesedez, bete eremu hau.",
email: "Mesedez, idatzi baliozko posta helbide bat.",
url: "Mesedez, idatzi baliozko URL bat.",
date: "Mesedez, idatzi baliozko data bat.",
dateISO: "Mesedez, idatzi baliozko (ISO) data bat.",
number: "Mesedez, idatzi baliozko zenbaki oso bat.",
digits: "Mesedez, idatzi digituak soilik.",
creditcard: "Mesedez, idatzi baliozko txartel zenbaki bat.",
equalTo: "Mesedez, idatzi berdina berriro ere.",
accept: "Mesedez, idatzi onartutako luzapena duen balio bat.",
maxlength: jQuery.validator.format("Mesedez, ez idatzi {0} karaktere baino gehiago."),
minlength: jQuery.validator.format("Mesedez, ez idatzi {0} karaktere baino gutxiago."),
rangelength: jQuery.validator.format("Mesedez, idatzi {0} eta {1} karaktere arteko balio bat."),
range: jQuery.validator.format("Mesedez, idatzi {0} eta {1} arteko balio bat."),
max: jQuery.validator.format("Mesedez, idatzi {0} edo txikiagoa den balio bat."),
min: jQuery.validator.format("Mesedez, idatzi {0} edo handiagoa den balio bat.")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: RO
*/
jQuery.extend(jQuery.validator.messages, {
required: "Acest câmp este obligatoriu.",
remote: "Te rugăm să completezi acest câmp.",
email: "Te rugăm să introduci o adresă de email validă",
url: "Te rugăm sa introduci o adresă URL validă.",
date: "Te rugăm să introduci o dată corectă.",
dateISO: "Te rugăm să introduci o dată (ISO) corectă.",
number: "Te rugăm să introduci un număr întreg valid.",
digits: "Te rugăm să introduci doar cifre.",
creditcard: "Te rugăm să introduci un numar de carte de credit valid.",
equalTo: "Te rugăm să reintroduci valoarea.",
accept: "Te rugăm să introduci o valoare cu o extensie validă.",
maxlength: jQuery.validator.format("Te rugăm să nu introduci mai mult de {0} caractere."),
minlength: jQuery.validator.format("Te rugăm să introduci cel puțin {0} caractere."),
rangelength: jQuery.validator.format("Te rugăm să introduci o valoare între {0} și {1} caractere."),
range: jQuery.validator.format("Te rugăm să introduci o valoare între {0} și {1}."),
max: jQuery.validator.format("Te rugăm să introduci o valoare egal sau mai mică decât {0}."),
min: jQuery.validator.format("Te rugăm să introduci o valoare egal sau mai mare decât {0}.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: KK
*/
jQuery.extend(jQuery.validator.messages, {
required: "Бұл өрісті міндетті түрде толтырыңыз.",
remote: "Дұрыс мағына енгізуіңізді сұраймыз.",
email: "Нақты электронды поштаңызды енгізуіңізді сұраймыз.",
url: "Нақты URL-ды енгізуіңізді сұраймыз.",
date: "Нақты URL-ды енгізуіңізді сұраймыз.",
dateISO: "Нақты ISO форматымен сәйкес датасын енгізуіңізді сұраймыз.",
number: "Күнді енгізуіңізді сұраймыз.",
digits: "Тек қана сандарды енгізуіңізді сұраймыз.",
creditcard: "Несие картасының нөмірін дұрыс енгізуіңізді сұраймыз.",
equalTo: "Осы мәнді қайта енгізуіңізді сұраймыз.",
accept: "Файлдың кеңейтуін дұрыс таңдаңыз.",
maxlength: jQuery.format("Ұзындығы {0} символдан көр болмасын."),
minlength: jQuery.format("Ұзындығы {0} символдан аз болмасын."),
rangelength: jQuery.format("Ұзындығы {0}-{1} дейін мән енгізуіңізді сұраймыз."),
range: jQuery.format("Пожалуйста, введите число от {0} до {1}. - {0} - {1} санын енгізуіңізді сұраймыз."),
max: jQuery.format("{0} аз немесе тең санын енгізуіңіді сұраймыз."),
min: jQuery.format("{0} көп немесе тең санын енгізуіңізді сұраймыз.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: NO (Norwegian)
*/
jQuery.extend(jQuery.validator.messages, {
required: "Dette feltet er obligatorisk.",
maxlength: jQuery.validator.format("Maksimalt {0} tegn."),
minlength: jQuery.validator.format("Minimum {0} tegn."),
rangelength: jQuery.validator.format("Angi minimum {0} og maksimum {1} tegn."),
email: "Oppgi en gyldig epostadresse.",
url: "Angi en gyldig URL.",
date: "Angi en gyldig dato.",
dateISO: "Angi en gyldig dato (ÅÅÅÅ-MM-DD).",
dateSE: "Angi en gyldig dato.",
number: "Angi et gyldig nummer.",
numberSE: "Angi et gyldig nummer.",
digits: "Skriv kun tall.",
equalTo: "Skriv samme verdi igjen.",
range: jQuery.validator.format("Angi en verdi mellom {0} og {1}."),
max: jQuery.validator.format("Angi en verdi som er mindre eller lik {0}."),
min: jQuery.validator.format("Angi en verdi som er større eller lik {0}."),
creditcard: "Angi et gyldig kredittkortnummer."
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: VI (Vietnamese)
*/
jQuery.extend(jQuery.validator.messages, {
required: "Hãy nhập.",
remote: "Hãy sửa cho đúng.",
email: "Hãy nhập email.",
url: "Hãy nhập URL.",
date: "Hãy nhập ngày.",
dateISO: "Hãy nhập ngày (ISO).",
number: "Hãy nhập số.",
digits: "Hãy nhập chữ số.",
creditcard: "Hãy nhập số thẻ tín dụng.",
equalTo: "Hãy nhập thêm lần nữa.",
accept: "Phần mở rộng không đúng.",
maxlength: jQuery.format("Hãy nhập từ {0} kí tự trở xuống."),
minlength: jQuery.format("Hãy nhập từ {0} kí tự trở lên."),
rangelength: jQuery.format("Hãy nhập từ {0} đến {1} kí tự."),
range: jQuery.format("Hãy nhập từ {0} đến {1}."),
max: jQuery.format("Hãy nhập từ {0} trở xuống."),
min: jQuery.format("Hãy nhập từ {1} trở lên.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: LV
*/
jQuery.extend(jQuery.validator.messages, {
required: "Šis lauks ir obligāts.",
remote: "Lūdzu, pārbaudiet šo lauku.",
email: "Lūdzu, ievadiet derīgu e-pasta adresi.",
url: "Lūdzu, ievadiet derīgu URL adresi.",
date: "Lūdzu, ievadiet derīgu datumu.",
dateISO: "Lūdzu, ievadiet derīgu datumu (ISO).",
number: "Lūdzu, ievadiet derīgu numuru.",
digits: "Lūdzu, ievadiet tikai ciparus.",
creditcard: "Lūdzu, ievadiet derīgu kredītkartes numuru.",
equalTo: "Lūdzu, ievadiet to pašu vēlreiz.",
accept: "Lūdzu, ievadiet vērtību ar derīgu paplašinājumu.",
maxlength: jQuery.validator.format("Lūdzu, ievadiet ne vairāk kā {0} rakstzīmes."),
minlength: jQuery.validator.format("Lūdzu, ievadiet vismaz {0} rakstzīmes."),
rangelength: jQuery.validator.format("Lūdzu ievadiet {0} līdz {1} rakstzīmes."),
range: jQuery.validator.format("Lūdzu, ievadiet skaitli no {0} līdz {1}."),
max: jQuery.validator.format("Lūdzu, ievadiet skaitli, kurš ir mazāks vai vienāds ar {0}."),
min: jQuery.validator.format("Lūdzu, ievadiet skaitli, kurš ir lielāks vai vienāds ar {0}.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: DA
*/
jQuery.extend(jQuery.validator.messages, {
required: "Dette felt er påkrævet.",
maxlength: jQuery.validator.format("Indtast højst {0} tegn."),
minlength: jQuery.validator.format("Indtast mindst {0} tegn."),
rangelength: jQuery.validator.format("Indtast mindst {0} og højst {1} tegn."),
email: "Indtast en gyldig email-adresse.",
url: "Indtast en gyldig URL.",
date: "Indtast en gyldig dato.",
number: "Indtast et tal.",
digits: "Indtast kun cifre.",
equalTo: "Indtast den samme værdi igen.",
range: jQuery.validator.format("Angiv en værdi mellem {0} og {1}."),
max: jQuery.validator.format("Angiv en værdi der højst er {0}."),
min: jQuery.validator.format("Angiv en værdi der mindst er {0}."),
creditcard: "Indtast et gyldigt kreditkortnummer."
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Language: SL
*/
jQuery.extend(jQuery.validator.messages, {
required: "To polje je obvezno.",
remote: "Prosimo popravite to polje.",
email: "Prosimo vnesite veljaven email naslov.",
url: "Prosimo vnesite veljaven URL naslov.",
date: "Prosimo vnesite veljaven datum.",
dateISO: "Prosimo vnesite veljaven ISO datum.",
number: "Prosimo vnesite veljavno število.",
digits: "Prosimo vnesite samo števila.",
creditcard: "Prosimo vnesite veljavno številko kreditne kartice.",
equalTo: "Prosimo ponovno vnesite vrednost.",
accept: "Prosimo vnesite vrednost z veljavno končnico.",
maxlength: jQuery.validator.format("Prosimo vnesite največ {0} znakov."),
minlength: jQuery.validator.format("Prosimo vnesite najmanj {0} znakov."),
rangelength: jQuery.validator.format("Prosimo vnesite najmanj {0} in največ {1} znakov."),
range: jQuery.validator.format("Prosimo vnesite vrednost med {0} in {1}."),
max: jQuery.validator.format("Prosimo vnesite vrednost manjše ali enako {0}."),
min: jQuery.validator.format("Prosimo vnesite vrednost večje ali enako {0}.")
});
| JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: TR
*/
jQuery.extend(jQuery.validator.messages, {
required: "Bu alanın doldurulması zorunludur.",
remote: "Lütfen bu alanı düzeltin.",
email: "Lütfen geçerli bir e-posta adresi giriniz.",
url: "Lütfen geçerli bir web adresi (URL) giriniz.",
date: "Lütfen geçerli bir tarih giriniz.",
dateISO: "Lütfen geçerli bir tarih giriniz(ISO formatında)",
number: "Lütfen geçerli bir sayı giriniz.",
digits: "Lütfen sadece sayısal karakterler giriniz.",
creditcard: "Lütfen geçerli bir kredi kartı giriniz.",
equalTo: "Lütfen aynı değeri tekrar giriniz.",
accept: "Lütfen geçerli uzantıya sahip bir değer giriniz.",
maxlength: jQuery.validator.format("Lütfen en fazla {0} karakter uzunluğunda bir değer giriniz."),
minlength: jQuery.validator.format("Lütfen en az {0} karakter uzunluğunda bir değer giriniz."),
rangelength: jQuery.validator.format("Lütfen en az {0} ve en fazla {1} uzunluğunda bir değer giriniz."),
range: jQuery.validator.format("Lütfen {0} ile {1} arasında bir değer giriniz."),
max: jQuery.validator.format("Lütfen {0} değerine eşit ya da daha küçük bir değer giriniz."),
min: jQuery.validator.format("Lütfen {0} değerine eşit ya da daha büyük bir değer giriniz.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: CA
*/
jQuery.extend(jQuery.validator.messages, {
required: "Aquest camp és obligatori.",
remote: "Si us plau, omple aquest camp.",
email: "Si us plau, escriu una adreça de correu-e vàlida",
url: "Si us plau, escriu una URL vàlida.",
date: "Si us plau, escriu una data vàlida.",
dateISO: "Si us plau, escriu una data (ISO) vàlida.",
number: "Si us plau, escriu un número enter vàlid.",
digits: "Si us plau, escriu només dígits.",
creditcard: "Si us plau, escriu un número de tarjeta vàlid.",
equalTo: "Si us plau, escriu el maateix valor de nou.",
accept: "Si us plau, escriu un valor amb una extensió acceptada.",
maxlength: jQuery.validator.format("Si us plau, no escriguis més de {0} caracters."),
minlength: jQuery.validator.format("Si us plau, no escriguis menys de {0} caracters."),
rangelength: jQuery.validator.format("Si us plau, escriu un valor entre {0} i {1} caracters."),
range: jQuery.validator.format("Si us plau, escriu un valor entre {0} i {1}."),
max: jQuery.validator.format("Si us plau, escriu un valor menor o igual a {0}."),
min: jQuery.validator.format("Si us plau, escriu un valor major o igual a {0}.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: FR
*/
jQuery.extend(jQuery.validator.messages, {
required: "Ce champ est requis.",
remote: "Veuillez remplir ce champ pour continuer.",
email: "Veuillez entrer une adresse email valide.",
url: "Veuillez entrer une URL valide.",
date: "Veuillez entrer une date valide.",
dateISO: "Veuillez entrer une date valide (ISO).",
number: "Veuillez entrer un nombre valide.",
digits: "Veuillez entrer (seulement) une valeur numérique.",
creditcard: "Veuillez entrer un numéro de carte de crédit valide.",
equalTo: "Veuillez entrer une nouvelle fois la même valeur.",
accept: "Veuillez entrer une valeur avec une extension valide.",
maxlength: jQuery.validator.format("Veuillez ne pas entrer plus de {0} caractères."),
minlength: jQuery.validator.format("Veuillez entrer au moins {0} caractères."),
rangelength: jQuery.validator.format("Veuillez entrer entre {0} et {1} caractères."),
range: jQuery.validator.format("Veuillez entrer une valeur entre {0} et {1}."),
max: jQuery.validator.format("Veuillez entrer une valeur inférieure ou égale à {0}."),
min: jQuery.validator.format("Veuillez entrer une valeur supérieure ou égale à {0}.")
}); | JavaScript |
/*
* Translated default messages for the jQuery validation plugin.
* Locale: DE
*/
jQuery.extend(jQuery.validator.messages, {
required: "Dieses Feld ist ein Pflichtfeld.",
maxlength: jQuery.validator.format("Geben Sie bitte maximal {0} Zeichen ein."),
minlength: jQuery.validator.format("Geben Sie bitte mindestens {0} Zeichen ein."),
rangelength: jQuery.validator.format("Geben Sie bitte mindestens {0} und maximal {1} Zeichen ein."),
email: "Geben Sie bitte eine gültige E-Mail Adresse ein.",
url: "Geben Sie bitte eine gültige URL ein.",
date: "Bitte geben Sie ein gültiges Datum ein.",
number: "Geben Sie bitte eine Nummer ein.",
digits: "Geben Sie bitte nur Ziffern ein.",
equalTo: "Bitte denselben Wert wiederholen.",
range: jQuery.validator.format("Geben Sie bitten einen Wert zwischen {0} und {1}."),
max: jQuery.validator.format("Geben Sie bitte einen Wert kleiner oder gleich {0} ein."),
min: jQuery.validator.format("Geben Sie bitte einen Wert größer oder gleich {0} ein."),
creditcard: "Geben Sie bitte ein gültige Kreditkarten-Nummer ein."
}); | JavaScript |
/**
* jQuery Validation Plugin 1.9.0
*
* http://bassistance.de/jquery-plugins/jquery-plugin-validation/
* http://docs.jquery.com/Plugins/Validation
*
* Copyright (c) 2006 - 2011 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function() {
function stripHtml(value) {
// remove html tags and space chars
return value.replace(/<.[^<>]*?>/g, ' ').replace(/ | /gi, ' ')
// remove numbers and punctuation
.replace(/[0-9.(),;:!?%#$'"_+=\/-]*/g,'');
}
jQuery.validator.addMethod("maxWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length < params;
}, jQuery.validator.format("Please enter {0} words or less."));
jQuery.validator.addMethod("minWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params;
}, jQuery.validator.format("Please enter at least {0} words."));
jQuery.validator.addMethod("rangeWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params[0] && value.match(/bw+b/g).length < params[1];
}, jQuery.validator.format("Please enter between {0} and {1} words."));
})();
jQuery.validator.addMethod("letterswithbasicpunc", function(value, element) {
return this.optional(element) || /^[a-z-.,()'\"\s]+$/i.test(value);
}, "Letters or punctuation only please");
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, spaces or underscores only please");
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
jQuery.validator.addMethod("nowhitespace", function(value, element) {
return this.optional(element) || /^\S+$/i.test(value);
}, "No white space please");
jQuery.validator.addMethod("ziprange", function(value, element) {
return this.optional(element) || /^90[2-5]\d\{2}-\d{4}$/.test(value);
}, "Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx");
jQuery.validator.addMethod("integer", function(value, element) {
return this.optional(element) || /^-?\d+$/.test(value);
}, "A positive or negative non-decimal number please");
/**
* Return true, if the value is a valid vehicle identification number (VIN).
*
* Works with all kind of text inputs.
*
* @example <input type="text" size="20" name="VehicleID" class="{required:true,vinUS:true}" />
* @desc Declares a required input element whose value must be a valid vehicle identification number.
*
* @name jQuery.validator.methods.vinUS
* @type Boolean
* @cat Plugins/Validate/Methods
*/
jQuery.validator.addMethod(
"vinUS",
function(v){
if (v.length != 17)
return false;
var i, n, d, f, cd, cdv;
var LL = ["A","B","C","D","E","F","G","H","J","K","L","M","N","P","R","S","T","U","V","W","X","Y","Z"];
var VL = [1,2,3,4,5,6,7,8,1,2,3,4,5,7,9,2,3,4,5,6,7,8,9];
var FL = [8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];
var rs = 0;
for(i = 0; i < 17; i++){
f = FL[i];
d = v.slice(i,i+1);
if(i == 8){
cdv = d;
}
if(!isNaN(d)){
d *= f;
}
else{
for(n = 0; n < LL.length; n++){
if(d.toUpperCase() === LL[n]){
d = VL[n];
d *= f;
if(isNaN(cdv) && n == 8){
cdv = LL[n];
}
break;
}
}
}
rs += d;
}
cd = rs % 11;
if(cd == 10){cd = "X";}
if(cd == cdv){return true;}
return false;
},
"The specified vehicle identification number (VIN) is invalid."
);
/**
* Return true, if the value is a valid date, also making this formal check dd/mm/yyyy.
*
* @example jQuery.validator.methods.date("01/01/1900")
* @result true
*
* @example jQuery.validator.methods.date("01/13/1990")
* @result false
*
* @example jQuery.validator.methods.date("01.01.1900")
* @result false
*
* @example <input name="pippo" class="{dateITA:true}" />
* @desc Declares an optional input element whose value must be a valid date.
*
* @name jQuery.validator.methods.dateITA
* @type Boolean
* @cat Plugins/Validate/Methods
*/
jQuery.validator.addMethod(
"dateITA",
function(value, element) {
var check = false;
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if( re.test(value)){
var adata = value.split('/');
var gg = parseInt(adata[0],10);
var mm = parseInt(adata[1],10);
var aaaa = parseInt(adata[2],10);
var xdata = new Date(aaaa,mm-1,gg);
if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
check = true;
else
check = false;
} else
check = false;
return this.optional(element) || check;
},
"Please enter a correct date"
);
jQuery.validator.addMethod("dateNL", function(value, element) {
return this.optional(element) || /^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(value);
}, "Vul hier een geldige datum in."
);
jQuery.validator.addMethod("time", function(value, element) {
return this.optional(element) || /^([01]\d|2[0-3])(:[0-5]\d){0,2}$/.test(value);
}, "Please enter a valid time, between 00:00 and 23:59");
jQuery.validator.addMethod("time12h", function(value, element) {
return this.optional(element) || /^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$/i.test(value);
}, "Please enter a valid time, between 00:00 am and 12:00 pm");
/**
* matches US phone number format
*
* where the area code may not start with 1 and the prefix may not start with 1
* allows '-' or ' ' as a separator and allows parens around area code
* some people may want to put a '1' in front of their number
*
* 1(212)-999-2345
* or
* 212 999 2344
* or
* 212-999-0983
*
* but not
* 111-123-5434
* and not
* 212 123 4567
*/
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
jQuery.validator.addMethod('phoneUK', function(phone_number, element) {
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/);
}, 'Please specify a valid phone number');
jQuery.validator.addMethod('mobileUK', function(phone_number, element) {
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^((0|\+44)7(5|6|7|8|9){1}\d{2}\s?\d{6})$/);
}, 'Please specify a valid mobile number');
// TODO check if value starts with <, otherwise don't try stripping anything
jQuery.validator.addMethod("strippedminlength", function(value, element, param) {
return jQuery(value).text().length >= param;
}, jQuery.validator.format("Please enter at least {0} characters"));
// same as email, but TLD is optional
jQuery.validator.addMethod("email2", function(value, element, param) {
return this.optional(element) || /^((([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.test(value);
}, jQuery.validator.messages.email);
// same as url, but TLD is optional
jQuery.validator.addMethod("url2", function(value, element, param) {
return this.optional(element) || /^(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.test(value);
}, jQuery.validator.messages.url);
// NOTICE: Modified version of Castle.Components.Validator.CreditCardValidator
// Redistributed under the the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0
// Valid Types: mastercard, visa, amex, dinersclub, enroute, discover, jcb, unknown, all (overrides all other settings)
jQuery.validator.addMethod("creditcardtypes", function(value, element, param) {
if (/[^0-9-]+/.test(value))
return false;
value = value.replace(/\D/g, "");
var validTypes = 0x0000;
if (param.mastercard)
validTypes |= 0x0001;
if (param.visa)
validTypes |= 0x0002;
if (param.amex)
validTypes |= 0x0004;
if (param.dinersclub)
validTypes |= 0x0008;
if (param.enroute)
validTypes |= 0x0010;
if (param.discover)
validTypes |= 0x0020;
if (param.jcb)
validTypes |= 0x0040;
if (param.unknown)
validTypes |= 0x0080;
if (param.all)
validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080;
if (validTypes & 0x0001 && /^(51|52|53|54|55)/.test(value)) { //mastercard
return value.length == 16;
}
if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
return value.length == 16;
}
if (validTypes & 0x0004 && /^(34|37)/.test(value)) { //amex
return value.length == 15;
}
if (validTypes & 0x0008 && /^(300|301|302|303|304|305|36|38)/.test(value)) { //dinersclub
return value.length == 14;
}
if (validTypes & 0x0010 && /^(2014|2149)/.test(value)) { //enroute
return value.length == 15;
}
if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover
return value.length == 16;
}
if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb
return value.length == 16;
}
if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb
return value.length == 15;
}
if (validTypes & 0x0080) { //unknown
return true;
}
return false;
}, "Please enter a valid credit card number.");
jQuery.validator.addMethod("ipv4", function(value, element, param) {
return this.optional(element) || /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i.test(value);
}, "Please enter a valid IP v4 address.");
jQuery.validator.addMethod("ipv6", function(value, element, param) {
return this.optional(element) || /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/i.test(value);
}, "Please enter a valid IP v6 address.");
/**
* Return true if the field value matches the given format RegExp
*
* @example jQuery.validator.methods.pattern("AR1004",element,/^AR\d{4}$/)
* @result true
*
* @example jQuery.validator.methods.pattern("BR1004",element,/^AR\d{4}$/)
* @result false
*
* @name jQuery.validator.methods.pattern
* @type Boolean
* @cat Plugins/Validate/Methods
*/
jQuery.validator.addMethod("pattern", function(value, element, param) {
return this.optional(element) || param.test(value);
}, "Invalid format.");
| JavaScript |
/*!
* MockJax - jQuery Plugin to Mock Ajax requests
*
* Version: 1.4.0
* Released: 2011-02-04
* Source: http://github.com/appendto/jquery-mockjax
* Docs: http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development
* Plugin: mockjax
* Author: Jonathan Sharp (http://jdsharp.com)
* License: MIT,GPL
*
* Copyright (c) 2010 appendTo LLC.
* Dual licensed under the MIT or GPL licenses.
* http://appendto.com/open-source-licenses
*/
(function($) {
var _ajax = $.ajax,
mockHandlers = [];
function parseXML(xml) {
if ( window['DOMParser'] == undefined && window.ActiveXObject ) {
DOMParser = function() { };
DOMParser.prototype.parseFromString = function( xmlString ) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML( xmlString );
return doc;
};
}
try {
var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
if ( $.isXMLDoc( xmlDoc ) ) {
var err = $('parsererror', xmlDoc);
if ( err.length == 1 ) {
throw('Error: ' + $(xmlDoc).text() );
}
} else {
throw('Unable to parse XML');
}
} catch( e ) {
var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
$(document).trigger('xmlParseError', [ msg ]);
return undefined;
}
return xmlDoc;
}
$.extend({
ajax: function(origSettings) {
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
mock = false;
// Iterate over our mock handlers (in registration order) until we find
// one that is willing to intercept the request
$.each(mockHandlers, function(k, v) {
if ( !mockHandlers[k] ) {
return;
}
var m = null;
// If the mock was registered with a function, let the function decide if we
// want to mock this request
if ( $.isFunction(mockHandlers[k]) ) {
m = mockHandlers[k](s);
} else {
m = mockHandlers[k];
// Inspect the URL of the request and check if the mock handler's url
// matches the url for this ajax request
if ( $.isFunction(m.url.test) ) {
// The user provided a regex for the url, test it
if ( !m.url.test( s.url ) ) {
m = null;
}
} else {
// Look for a simple wildcard '*' or a direct URL match
var star = m.url.indexOf('*');
if ( ( m.url != '*' && m.url != s.url && star == -1 ) ||
( star > -1 && m.url.substr(0, star) != s.url.substr(0, star) ) ) {
// The url we tested did not match the wildcard *
m = null;
}
}
if ( m ) {
// Inspect the data submitted in the request (either POST body or GET query string)
if ( m.data && s.data ) {
var identical = false;
// Deep inspect the identity of the objects
(function ident(mock, live) {
// Test for situations where the data is a querystring (not an object)
if (typeof live === 'string') {
// Querystring may be a regex
identical = $.isFunction( mock.test ) ? mock.test(live) : mock == live;
return identical;
}
$.each(mock, function(k, v) {
if ( live[k] === undefined ) {
identical = false;
return false;
} else {
identical = true;
if ( typeof live[k] == 'object' ) {
return ident(mock[k], live[k]);
} else {
if ( $.isFunction( mock[k].test ) ) {
identical = mock[k].test(live[k]);
} else {
identical = ( mock[k] == live[k] );
}
return identical;
}
}
});
})(m.data, s.data);
// They're not identical, do not mock this request
if ( identical == false ) {
m = null;
}
}
// Inspect the request type
if ( m && m.type && m.type != s.type ) {
// The request type doesn't match (GET vs. POST)
m = null;
}
}
}
if ( m ) {
mock = true;
// Handle console logging
var c = $.extend({}, $.mockjaxSettings, m);
if ( c.log && $.isFunction(c.log) ) {
c.log('MOCK ' + s.type.toUpperCase() + ': ' + s.url, $.extend({}, s));
}
var jsre = /=\?(&|$)/, jsc = (new Date()).getTime();
// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
// because there isn't an easy hook for the cross domain script tag of jsonp
if ( s.dataType === "jsonp" ) {
if ( s.type.toUpperCase() === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
}
var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
// Test if we are going to create a script tag (if so, intercept & mock)
if ( s.dataType === "script" && s.type.toUpperCase() === "GET" && remote ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || s;
function success() {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( callbackContext, ( m.response ? m.response.toString() : m.responseText || ''), status, {} );
}
// Fire the global callback
if ( s.global ) {
trigger( "ajaxSuccess", [{}, s] );
}
}
function complete() {
// Process result
if ( s.complete ) {
s.complete.call( callbackContext, {} , status );
}
// The request was completed
if ( s.global ) {
trigger( "ajaxComplete", [{}, s] );
}
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
}
function trigger(type, args) {
(s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
}
if ( m.response && $.isFunction(m.response) ) {
m.response(origSettings);
} else {
$.globalEval(m.responseText);
}
success();
complete();
return false;
}
mock = _ajax.call($, $.extend(true, {}, origSettings, {
// Mock the XHR object
xhr: function() {
// Extend with our default mockjax settings
m = $.extend({}, $.mockjaxSettings, m);
if ( m.contentType ) {
m.headers['content-type'] = m.contentType;
}
// Return our mock xhr object
return {
status: m.status,
readyState: 1,
open: function() { },
send: function() {
// This is a substitute for < 1.4 which lacks $.proxy
var process = (function(that) {
return function() {
return (function() {
// The request has returned
this.status = m.status;
this.readyState = 4;
// We have an executable function, call it to give
// the mock handler a chance to update it's data
if ( $.isFunction(m.response) ) {
m.response(origSettings);
}
// Copy over our mock to our xhr object before passing control back to
// jQuery's onreadystatechange callback
if ( s.dataType == 'json' && ( typeof m.responseText == 'object' ) ) {
this.responseText = JSON.stringify(m.responseText);
} else if ( s.dataType == 'xml' ) {
if ( typeof m.responseXML == 'string' ) {
this.responseXML = parseXML(m.responseXML);
} else {
this.responseXML = m.responseXML;
}
} else {
this.responseText = m.responseText;
}
// jQuery < 1.4 doesn't have onreadystate change for xhr
if ( $.isFunction(this.onreadystatechange) ) {
this.onreadystatechange( m.isTimeout ? 'timeout' : undefined );
}
}).apply(that);
};
})(this);
if ( m.proxy ) {
// We're proxying this request and loading in an external file instead
_ajax({
global: false,
url: m.proxy,
type: m.proxyType,
data: m.data,
dataType: s.dataType,
complete: function(xhr, txt) {
m.responseXML = xhr.responseXML;
m.responseText = xhr.responseText;
this.responseTimer = setTimeout(process, m.responseTime || 0);
}
});
} else {
// type == 'POST' || 'GET' || 'DELETE'
if ( s.async === false ) {
// TODO: Blocking delay
process();
} else {
this.responseTimer = setTimeout(process, m.responseTime || 50);
}
}
},
abort: function() {
clearTimeout(this.responseTimer);
},
setRequestHeader: function() { },
getResponseHeader: function(header) {
// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
if ( m.headers && m.headers[header] ) {
// Return arbitrary headers
return m.headers[header];
} else if ( header.toLowerCase() == 'last-modified' ) {
return m.lastModified || (new Date()).toString();
} else if ( header.toLowerCase() == 'etag' ) {
return m.etag || '';
} else if ( header.toLowerCase() == 'content-type' ) {
return m.contentType || 'text/plain';
}
},
getAllResponseHeaders: function() {
var headers = '';
$.each(m.headers, function(k, v) {
headers += k + ': ' + v + "\n";
});
return headers;
}
};
}
}));
return false;
}
});
// We don't have a mock request, trigger a normal request
if ( !mock ) {
return _ajax.apply($, arguments);
} else {
return mock;
}
}
});
$.mockjaxSettings = {
//url: null,
//type: 'GET',
log: function(msg) {
window['console'] && window.console.log && window.console.log(msg);
},
status: 200,
responseTime: 500,
isTimeout: false,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
};
$.mockjax = function(settings) {
var i = mockHandlers.length;
mockHandlers[i] = settings;
return i;
};
$.mockjaxClear = function(i) {
if ( arguments.length == 1 ) {
mockHandlers[i] = null;
} else {
mockHandlers = [];
}
};
})(jQuery); | JavaScript |
/*
* Metadata - jQuery plugin for parsing metadata from elements
*
* Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $
*
*/
/**
* Sets the type of metadata to use. Metadata is encoded in JSON, and each property
* in the JSON will become a property of the element itself.
*
* There are three supported types of metadata storage:
*
* attr: Inside an attribute. The name parameter indicates *which* attribute.
*
* class: Inside the class attribute, wrapped in curly braces: { }
*
* elem: Inside a child element (e.g. a script tag). The
* name parameter indicates *which* element.
*
* The metadata for an element is loaded the first time the element is accessed via jQuery.
*
* As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
* matched by expr, then redefine the metadata type and run another $(expr) for other elements.
*
* @name $.metadata.setType
*
* @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("class")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from the class attribute
*
* @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("attr", "data")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a "data" attribute
*
* @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
* @before $.metadata.setType("elem", "script")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a nested script element
*
* @param String type The encoding type
* @param String name The name of the attribute to be used to get metadata (optional)
* @cat Plugins/Metadata
* @descr Sets the type of encoding to be used when loading metadata for the first time
* @type undefined
* @see metadata()
*/
(function($) {
$.extend({
metadata : {
defaults : {
type: 'class',
name: 'metadata',
cre: /({.*})/,
single: 'metadata'
},
setType: function( type, name ){
this.defaults.type = type;
this.defaults.name = name;
},
get: function( elem, opts ){
var settings = $.extend({},this.defaults,opts);
// check for empty string in single property
if ( !settings.single.length ) settings.single = 'metadata';
var data = $.data(elem, settings.single);
// returned cached data if it already exists
if ( data ) return data;
data = "{}";
if ( settings.type == "class" ) {
var m = settings.cre.exec( elem.className );
if ( m )
data = m[1];
} else if ( settings.type == "elem" ) {
if( !elem.getElementsByTagName )
return undefined;
var e = elem.getElementsByTagName(settings.name);
if ( e.length )
data = $.trim(e[0].innerHTML);
} else if ( elem.getAttribute != undefined ) {
var attr = elem.getAttribute( settings.name );
if ( attr )
data = attr;
}
if ( data.indexOf( '{' ) <0 )
data = "{" + data + "}";
data = eval("(" + data + ")");
$.data( elem, settings.single, data );
return data;
}
}
});
/**
* Returns the metadata object for the first member of the jQuery object.
*
* @name metadata
* @descr Returns element's metadata object
* @param Object opts An object contianing settings to override the defaults
* @type jQuery
* @cat Plugins/Metadata
*/
$.fn.metadata = function( opts ){
return $.metadata.get( this[0], opts );
};
})(jQuery); | JavaScript |
/*
* jQuery Form Plugin
* version: 2.36 (07-NOV-2009)
* @requires jQuery v1.2.6 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are intended to be exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').bind('submit', function() {
$(this).ajaxSubmit({
target: '#output'
});
return false; // <-- important!
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
var url = $.trim(this.attr('action'));
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
url = url || window.location.href || '';
options = $.extend({
url: url,
type: this.attr('method') || 'GET',
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options || {});
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } );
}
else
a.push( { name: n, value: options.data[n] } );
}
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else
options.data = q; // data is the query string for 'post'
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};
// are there files to upload?
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
var multipart = false;
// var mp = 'multipart/form-data';
// multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if ((files.length && options.iframe !== false) || options.iframe || found || multipart) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
if ($(':input[name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" />');
var io = $io[0];
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() {
this.aborted = 1;
$io.attr('src', opts.iframeSrc); // abort op in progress
}
};
var g = opts.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && $.active--;
return;
}
if (xhr.aborted)
return;
var cbInvoked = 0;
var timedOut = 0;
// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
// take a breath so that pending repaints get some cpu time before the upload starts
setTimeout(function() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (form.getAttribute('method') != 'POST')
form.setAttribute('method', 'POST');
if (form.getAttribute('action') != opts.url)
form.setAttribute('action', opts.url);
// ie borks in some cases when setting encoding
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
t ? form.setAttribute('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
var domCheckCount = 50;
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var ok = true;
try {
if (timedOut) throw 'timeout';
// extract the server response from the iframe
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
cbInvoked = 0;
setTimeout(cb, 100);
return;
}
log('Could not access iframe DOM after 50 tries.');
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta)
xhr.responseText = ta.value;
else {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
if (pre)
xhr.responseText = pre.innerHTML;
}
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin', function() {
$(this).ajaxSubmit(options);
return false;
}).bind('click.form-plugin', function(e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest(':submit');
if (t.length == 0)
return;
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el) {
a.push({name: n, value: $(el).val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0], n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $(':text').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
| JavaScript |
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3_3.js
// ==/ClosureCompiler==
/**
* @name MarkerClusterer for Google Maps v3
* @version version 1.0
* @author Luke Mahe
* @fileoverview
* The library creates and manages per-zoom-level clusters for large amounts of
* markers.
* <br/>
* This is a v3 implementation of the
* <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
* >v2 MarkerClusterer</a>.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A Marker Clusterer that clusters markers.
*
* @param {google.maps.Map} map The Google map to attach to.
* @param {Array.<google.maps.Marker>=} opt_markers Optional markers to add to
* the cluster.
* @param {Object=} opt_options support the following options:
* 'gridSize': (number) The grid size of a cluster in pixels.
* 'maxZoom': (number) The maximum zoom level that a marker can be part of a
* cluster.
* 'zoomOnClick': (boolean) Whether the default behaviour of clicking on a
* cluster is to zoom into it.
* 'averageCenter': (boolean) Wether the center of each cluster should be
* the average of all markers in the cluster.
* 'minimumClusterSize': (number) The minimum number of markers to be in a
* cluster before the markers are hidden and a count
* is shown.
* 'styles': (object) An object that has style properties:
* 'url': (string) The image url.
* 'height': (number) The image height.
* 'width': (number) The image width.
* 'anchor': (Array) The anchor position of the label text.
* 'textColor': (string) The text color.
* 'textSize': (number) The text size.
* 'backgroundPosition': (string) The position of the backgound x, y.
* @constructor
* @extends google.maps.OverlayView
*/
function MarkerClusterer(map, opt_markers, opt_options) {
// MarkerClusterer implements google.maps.OverlayView interface. We use the
// extend function to extend MarkerClusterer with google.maps.OverlayView
// because it might not always be available when the code is defined so we
// look for it at the last possible moment. If it doesn't exist now then
// there is no point going ahead :)
this.extend(MarkerClusterer, google.maps.OverlayView);
this.map_ = map;
/**
* @type {Array.<google.maps.Marker>}
* @private
*/
this.markers_ = [];
/**
* @type {Array.<Cluster>}
*/
this.clusters_ = [];
this.sizes = [53, 56, 66, 78, 90];
/**
* @private
*/
this.styles_ = [];
/**
* @type {boolean}
* @private
*/
this.ready_ = false;
var options = opt_options || {};
/**
* @type {number}
* @private
*/
this.gridSize_ = options['gridSize'] || 60;
/**
* @private
*/
this.minClusterSize_ = options['minimumClusterSize'] || 2;
/**
* @type {?number}
* @private
*/
this.maxZoom_ = options['maxZoom'] || null;
this.styles_ = options['styles'] || [];
/**
* @type {string}
* @private
*/
this.imagePath_ = options['imagePath'] ||
this.MARKER_CLUSTER_IMAGE_PATH_;
/**
* @type {string}
* @private
*/
this.imageExtension_ = options['imageExtension'] ||
this.MARKER_CLUSTER_IMAGE_EXTENSION_;
/**
* @type {boolean}
* @private
*/
this.zoomOnClick_ = true;
if (options['zoomOnClick'] != undefined) {
this.zoomOnClick_ = options['zoomOnClick'];
}
/**
* @type {boolean}
* @private
*/
this.averageCenter_ = false;
if (options['averageCenter'] != undefined) {
this.averageCenter_ = options['averageCenter'];
}
this.setupStyles_();
this.setMap(map);
/**
* @type {number}
* @private
*/
this.prevZoom_ = this.map_.getZoom();
// Add the map event listeners
var that = this;
google.maps.event.addListener(this.map_, 'zoom_changed', function() {
var zoom = that.map_.getZoom();
if (that.prevZoom_ != zoom) {
that.prevZoom_ = zoom;
that.resetViewport();
}
});
google.maps.event.addListener(this.map_, 'idle', function() {
that.redraw();
});
// Finally, add the markers
if (opt_markers && opt_markers.length) {
this.addMarkers(opt_markers, false);
}
}
/**
* The marker cluster image path.
*
* @type {string}
* @private
*/
MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_ =
'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/' +
'images/m';
/**
* The marker cluster image path.
*
* @type {string}
* @private
*/
MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_EXTENSION_ = 'png';
/**
* Extends a objects prototype by anothers.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
MarkerClusterer.prototype.extend = function(obj1, obj2) {
return (function(object) {
for (var property in object.prototype) {
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
/**
* Implementaion of the interface method.
* @ignore
*/
MarkerClusterer.prototype.onAdd = function() {
this.setReady_(true);
};
/**
* Implementaion of the interface method.
* @ignore
*/
MarkerClusterer.prototype.draw = function() {};
/**
* Sets up the styles object.
*
* @private
*/
MarkerClusterer.prototype.setupStyles_ = function() {
if (this.styles_.length) {
return;
}
for (var i = 0, size; size = this.sizes[i]; i++) {
this.styles_.push({
url: this.imagePath_ + (i + 1) + '.' + this.imageExtension_,
height: size,
width: size
});
}
};
/**
* Fit the map to the bounds of the markers in the clusterer.
*/
MarkerClusterer.prototype.fitMapToMarkers = function() {
var markers = this.getMarkers();
var bounds = new google.maps.LatLngBounds();
for (var i = 0, marker; marker = markers[i]; i++) {
bounds.extend(marker.getPosition());
}
this.map_.fitBounds(bounds);
};
/**
* Sets the styles.
*
* @param {Object} styles The style to set.
*/
MarkerClusterer.prototype.setStyles = function(styles) {
this.styles_ = styles;
};
/**
* Gets the styles.
*
* @return {Object} The styles object.
*/
MarkerClusterer.prototype.getStyles = function() {
return this.styles_;
};
/**
* Whether zoom on click is set.
*
* @return {boolean} True if zoomOnClick_ is set.
*/
MarkerClusterer.prototype.isZoomOnClick = function() {
return this.zoomOnClick_;
};
/**
* Whether average center is set.
*
* @return {boolean} True if averageCenter_ is set.
*/
MarkerClusterer.prototype.isAverageCenter = function() {
return this.averageCenter_;
};
/**
* Returns the array of markers in the clusterer.
*
* @return {Array.<google.maps.Marker>} The markers.
*/
MarkerClusterer.prototype.getMarkers = function() {
return this.markers_;
};
/**
* Returns the number of markers in the clusterer
*
* @return {Number} The number of markers.
*/
MarkerClusterer.prototype.getTotalMarkers = function() {
return this.markers_.length;
};
/**
* Sets the max zoom for the clusterer.
*
* @param {number} maxZoom The max zoom level.
*/
MarkerClusterer.prototype.setMaxZoom = function(maxZoom) {
this.maxZoom_ = maxZoom;
};
/**
* Gets the max zoom for the clusterer.
*
* @return {number} The max zoom level.
*/
MarkerClusterer.prototype.getMaxZoom = function() {
return this.maxZoom_;
};
/**
* The function for calculating the cluster icon image.
*
* @param {Array.<google.maps.Marker>} markers The markers in the clusterer.
* @param {number} numStyles The number of styles available.
* @return {Object} A object properties: 'text' (string) and 'index' (number).
* @private
*/
MarkerClusterer.prototype.calculator_ = function(markers, numStyles) {
var index = 0;
var count = markers.length;
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index++;
}
index = Math.min(index, numStyles);
return {
text: count,
index: index
};
};
/**
* Set the calculator function.
*
* @param {function(Array, number)} calculator The function to set as the
* calculator. The function should return a object properties:
* 'text' (string) and 'index' (number).
*
*/
MarkerClusterer.prototype.setCalculator = function(calculator) {
this.calculator_ = calculator;
};
/**
* Get the calculator function.
*
* @return {function(Array, number)} the calculator function.
*/
MarkerClusterer.prototype.getCalculator = function() {
return this.calculator_;
};
/**
* Add an array of markers to the clusterer.
*
* @param {Array.<google.maps.Marker>} markers The markers to add.
* @param {boolean=} opt_nodraw Whether to redraw the clusters.
*/
MarkerClusterer.prototype.addMarkers = function(markers, opt_nodraw) {
for (var i = 0, marker; marker = markers[i]; i++) {
this.pushMarkerTo_(marker);
}
if (!opt_nodraw) {
this.redraw();
}
};
/**
* Pushes a marker to the clusterer.
*
* @param {google.maps.Marker} marker The marker to add.
* @private
*/
MarkerClusterer.prototype.pushMarkerTo_ = function(marker) {
marker.isAdded = false;
if (marker['draggable']) {
// If the marker is draggable add a listener so we update the clusters on
// the drag end.
var that = this;
google.maps.event.addListener(marker, 'dragend', function() {
marker.isAdded = false;
that.repaint();
});
}
this.markers_.push(marker);
};
/**
* Adds a marker to the clusterer and redraws if needed.
*
* @param {google.maps.Marker} marker The marker to add.
* @param {boolean=} opt_nodraw Whether to redraw the clusters.
*/
MarkerClusterer.prototype.addMarker = function(marker, opt_nodraw) {
this.pushMarkerTo_(marker);
if (!opt_nodraw) {
this.redraw();
}
};
/**
* Removes a marker and returns true if removed, false if not
*
* @param {google.maps.Marker} marker The marker to remove
* @return {boolean} Whether the marker was removed or not
* @private
*/
MarkerClusterer.prototype.removeMarker_ = function(marker) {
var index = -1;
if (this.markers_.indexOf) {
index = this.markers_.indexOf(marker);
} else {
for (var i = 0, m; m = this.markers_[i]; i++) {
if (m == marker) {
index = i;
break;
}
}
}
if (index == -1) {
// Marker is not in our list of markers.
return false;
}
marker.setMap(null);
this.markers_.splice(index, 1);
return true;
};
/**
* Remove a marker from the cluster.
*
* @param {google.maps.Marker} marker The marker to remove.
* @param {boolean=} opt_nodraw Optional boolean to force no redraw.
* @return {boolean} True if the marker was removed.
*/
MarkerClusterer.prototype.removeMarker = function(marker, opt_nodraw) {
var removed = this.removeMarker_(marker);
if (!opt_nodraw && removed) {
this.resetViewport();
this.redraw();
return true;
} else {
return false;
}
};
/**
* Removes an array of markers from the cluster.
*
* @param {Array.<google.maps.Marker>} markers The markers to remove.
* @param {boolean=} opt_nodraw Optional boolean to force no redraw.
*/
MarkerClusterer.prototype.removeMarkers = function(markers, opt_nodraw) {
var removed = false;
for (var i = 0, marker; marker = markers[i]; i++) {
var r = this.removeMarker_(marker);
removed = removed || r;
}
if (!opt_nodraw && removed) {
this.resetViewport();
this.redraw();
return true;
}
};
/**
* Sets the clusterer's ready state.
*
* @param {boolean} ready The state.
* @private
*/
MarkerClusterer.prototype.setReady_ = function(ready) {
if (!this.ready_) {
this.ready_ = ready;
this.createClusters_();
}
};
/**
* Returns the number of clusters in the clusterer.
*
* @return {number} The number of clusters.
*/
MarkerClusterer.prototype.getTotalClusters = function() {
return this.clusters_.length;
};
/**
* Returns the google map that the clusterer is associated with.
*
* @return {google.maps.Map} The map.
*/
MarkerClusterer.prototype.getMap = function() {
return this.map_;
};
/**
* Sets the google map that the clusterer is associated with.
*
* @param {google.maps.Map} map The map.
*/
MarkerClusterer.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* Returns the size of the grid.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getGridSize = function() {
return this.gridSize_;
};
/**
* Sets the size of the grid.
*
* @param {number} size The grid size.
*/
MarkerClusterer.prototype.setGridSize = function(size) {
this.gridSize_ = size;
};
/**
* Returns the min cluster size.
*
* @return {number} The grid size.
*/
MarkerClusterer.prototype.getMinClusterSize = function() {
return this.minClusterSize_;
};
/**
* Sets the min cluster size.
*
* @param {number} size The grid size.
*/
MarkerClusterer.prototype.setMinClusterSize = function(size) {
this.minClusterSize_ = size;
};
/**
* Extends a bounds object by the grid size.
*
* @param {google.maps.LatLngBounds} bounds The bounds to extend.
* @return {google.maps.LatLngBounds} The extended bounds.
*/
MarkerClusterer.prototype.getExtendedBounds = function(bounds) {
var projection = this.getProjection();
// Turn the bounds into latlng.
var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
bounds.getNorthEast().lng());
var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
bounds.getSouthWest().lng());
// Convert the points to pixels and the extend out by the grid size.
var trPix = projection.fromLatLngToDivPixel(tr);
trPix.x += this.gridSize_;
trPix.y -= this.gridSize_;
var blPix = projection.fromLatLngToDivPixel(bl);
blPix.x -= this.gridSize_;
blPix.y += this.gridSize_;
// Convert the pixel points back to LatLng
var ne = projection.fromDivPixelToLatLng(trPix);
var sw = projection.fromDivPixelToLatLng(blPix);
// Extend the bounds to contain the new bounds.
bounds.extend(ne);
bounds.extend(sw);
return bounds;
};
/**
* Determins if a marker is contained in a bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @param {google.maps.LatLngBounds} bounds The bounds to check against.
* @return {boolean} True if the marker is in the bounds.
* @private
*/
MarkerClusterer.prototype.isMarkerInBounds_ = function(marker, bounds) {
return bounds.contains(marker.getPosition());
};
/**
* Clears all clusters and markers from the clusterer.
*/
MarkerClusterer.prototype.clearMarkers = function() {
this.resetViewport(true);
// Set the markers a empty array.
this.markers_ = [];
};
/**
* Clears all existing clusters and recreates them.
* @param {boolean} opt_hide To also hide the marker.
*/
MarkerClusterer.prototype.resetViewport = function(opt_hide) {
// Remove all the clusters
for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
cluster.remove();
}
// Reset the markers to not be added and to be invisible.
for (var i = 0, marker; marker = this.markers_[i]; i++) {
marker.isAdded = false;
if (opt_hide) {
marker.setMap(null);
}
}
this.clusters_ = [];
};
/**
*
*/
MarkerClusterer.prototype.repaint = function() {
var oldClusters = this.clusters_.slice();
this.clusters_.length = 0;
this.resetViewport();
this.redraw();
// Remove the old clusters.
// Do it in a timeout so the other clusters have been drawn first.
window.setTimeout(function() {
for (var i = 0, cluster; cluster = oldClusters[i]; i++) {
cluster.remove();
}
}, 0);
};
/**
* Redraws the clusters.
*/
MarkerClusterer.prototype.redraw = function() {
this.createClusters_();
};
/**
* Calculates the distance between two latlng locations in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @private
*/
MarkerClusterer.prototype.distanceBetweenPoints_ = function(p1, p2) {
if (!p1 || !p2) {
return 0;
}
var R = 6371; // Radius of the Earth in km
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
};
/**
* Add a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
* @private
*/
MarkerClusterer.prototype.addToClosestCluster_ = function(marker) {
var distance = 40000; // Some large number
var clusterToAddTo = null;
var pos = marker.getPosition();
for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
var center = cluster.getCenter();
if (center) {
var d = this.distanceBetweenPoints_(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
var cluster = new Cluster(this);
cluster.addMarker(marker);
this.clusters_.push(cluster);
}
};
/**
* Creates the clusters.
*
* @private
*/
MarkerClusterer.prototype.createClusters_ = function() {
if (!this.ready_) {
return;
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
var mapBounds = new google.maps.LatLngBounds(this.map_.getBounds().getSouthWest(),
this.map_.getBounds().getNorthEast());
var bounds = this.getExtendedBounds(mapBounds);
for (var i = 0, marker; marker = this.markers_[i]; i++) {
if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
this.addToClosestCluster_(marker);
}
}
};
/**
* A cluster that contains markers.
*
* @param {MarkerClusterer} markerClusterer The markerclusterer that this
* cluster is associated with.
* @constructor
* @ignore
*/
function Cluster(markerClusterer) {
this.markerClusterer_ = markerClusterer;
this.map_ = markerClusterer.getMap();
this.gridSize_ = markerClusterer.getGridSize();
this.minClusterSize_ = markerClusterer.getMinClusterSize();
this.averageCenter_ = markerClusterer.isAverageCenter();
this.center_ = null;
this.markers_ = [];
this.bounds_ = null;
this.clusterIcon_ = new ClusterIcon(this, markerClusterer.getStyles(),
markerClusterer.getGridSize());
}
/**
* Determins if a marker is already added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker is already added.
*/
Cluster.prototype.isMarkerAlreadyAdded = function(marker) {
if (this.markers_.indexOf) {
return this.markers_.indexOf(marker) != -1;
} else {
for (var i = 0, m; m = this.markers_[i]; i++) {
if (m == marker) {
return true;
}
}
}
return false;
};
/**
* Add a marker the cluster.
*
* @param {google.maps.Marker} marker The marker to add.
* @return {boolean} True if the marker was added.
*/
Cluster.prototype.addMarker = function(marker) {
if (this.isMarkerAlreadyAdded(marker)) {
return false;
}
if (!this.center_) {
this.center_ = marker.getPosition();
this.calculateBounds_();
} else {
if (this.averageCenter_) {
var l = this.markers_.length + 1;
var lat = (this.center_.lat() * (l-1) + marker.getPosition().lat()) / l;
var lng = (this.center_.lng() * (l-1) + marker.getPosition().lng()) / l;
this.center_ = new google.maps.LatLng(lat, lng);
this.calculateBounds_();
}
}
marker.isAdded = true;
this.markers_.push(marker);
var len = this.markers_.length;
if (len < this.minClusterSize_ && marker.getMap() != this.map_) {
// Min cluster size not reached so show the marker.
marker.setMap(this.map_);
}
if (len == this.minClusterSize_) {
// Hide the markers that were showing.
for (var i = 0; i < len; i++) {
this.markers_[i].setMap(null);
}
}
if (len >= this.minClusterSize_) {
marker.setMap(null);
}
this.updateIcon();
return true;
};
/**
* Returns the marker clusterer that the cluster is associated with.
*
* @return {MarkerClusterer} The associated marker clusterer.
*/
Cluster.prototype.getMarkerClusterer = function() {
return this.markerClusterer_;
};
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
*/
Cluster.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
var markers = this.getMarkers();
for (var i = 0, marker; marker = markers[i]; i++) {
bounds.extend(marker.getPosition());
}
return bounds;
};
/**
* Removes the cluster
*/
Cluster.prototype.remove = function() {
this.clusterIcon_.remove();
this.markers_.length = 0;
delete this.markers_;
};
/**
* Returns the center of the cluster.
*
* @return {number} The cluster center.
*/
Cluster.prototype.getSize = function() {
return this.markers_.length;
};
/**
* Returns the center of the cluster.
*
* @return {Array.<google.maps.Marker>} The cluster center.
*/
Cluster.prototype.getMarkers = function() {
return this.markers_;
};
/**
* Returns the center of the cluster.
*
* @return {google.maps.LatLng} The cluster center.
*/
Cluster.prototype.getCenter = function() {
return this.center_;
};
/**
* Calculated the extended bounds of the cluster with the grid.
*
* @private
*/
Cluster.prototype.calculateBounds_ = function() {
var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
};
/**
* Determines if a marker lies in the clusters bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker lies in the bounds.
*/
Cluster.prototype.isMarkerInClusterBounds = function(marker) {
return this.bounds_.contains(marker.getPosition());
};
/**
* Returns the map that the cluster is associated with.
*
* @return {google.maps.Map} The map.
*/
Cluster.prototype.getMap = function() {
return this.map_;
};
/**
* Updates the cluster icon
*/
Cluster.prototype.updateIcon = function() {
var zoom = this.map_.getZoom();
var mz = this.markerClusterer_.getMaxZoom();
if (mz && zoom > mz) {
// The zoom is greater than our max zoom so show all the markers in cluster.
for (var i = 0, marker; marker = this.markers_[i]; i++) {
marker.setMap(this.map_);
}
return;
}
if (this.markers_.length < this.minClusterSize_) {
// Min cluster size not yet reached.
this.clusterIcon_.hide();
return;
}
var numStyles = this.markerClusterer_.getStyles().length;
var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
this.clusterIcon_.setCenter(this.center_);
this.clusterIcon_.setSums(sums);
this.clusterIcon_.show();
};
/**
* A cluster icon
*
* @param {Cluster} cluster The cluster to be associated with.
* @param {Object} styles An object that has style properties:
* 'url': (string) The image url.
* 'height': (number) The image height.
* 'width': (number) The image width.
* 'anchor': (Array) The anchor position of the label text.
* 'textColor': (string) The text color.
* 'textSize': (number) The text size.
* 'backgroundPosition: (string) The background postition x, y.
* @param {number=} opt_padding Optional padding to apply to the cluster icon.
* @constructor
* @extends google.maps.OverlayView
* @ignore
*/
function ClusterIcon(cluster, styles, opt_padding) {
cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
this.styles_ = styles;
this.padding_ = opt_padding || 0;
this.cluster_ = cluster;
this.center_ = null;
this.map_ = cluster.getMap();
this.div_ = null;
this.sums_ = null;
this.visible_ = false;
this.setMap(this.map_);
}
/**
* Triggers the clusterclick event and zoom's if the option is set.
*/
ClusterIcon.prototype.triggerClusterClick = function() {
var markerClusterer = this.cluster_.getMarkerClusterer();
// Trigger the clusterclick event.
google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_);
if (markerClusterer.isZoomOnClick()) {
// Zoom into the cluster.
this.map_.fitBounds(this.cluster_.getBounds());
}
};
/**
* Adding the cluster icon to the dom.
* @ignore
*/
ClusterIcon.prototype.onAdd = function() {
this.div_ = document.createElement('DIV');
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
this.div_.innerHTML = this.sums_.text;
}
var panes = this.getPanes();
panes.overlayMouseTarget.appendChild(this.div_);
var that = this;
google.maps.event.addDomListener(this.div_, 'click', function() {
that.triggerClusterClick();
});
};
/**
* Returns the position to place the div dending on the latlng.
*
* @param {google.maps.LatLng} latlng The position in latlng.
* @return {google.maps.Point} The position in pixels.
* @private
*/
ClusterIcon.prototype.getPosFromLatLng_ = function(latlng) {
var pos = this.getProjection().fromLatLngToDivPixel(latlng);
pos.x -= parseInt(this.width_ / 2, 10);
pos.y -= parseInt(this.height_ / 2, 10);
return pos;
};
/**
* Draw the icon.
* @ignore
*/
ClusterIcon.prototype.draw = function() {
if (this.visible_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.top = pos.y + 'px';
this.div_.style.left = pos.x + 'px';
}
};
/**
* Hide the icon.
*/
ClusterIcon.prototype.hide = function() {
if (this.div_) {
this.div_.style.display = 'none';
}
this.visible_ = false;
};
/**
* Position and show the icon.
*/
ClusterIcon.prototype.show = function() {
if (this.div_) {
var pos = this.getPosFromLatLng_(this.center_);
this.div_.style.cssText = this.createCss(pos);
this.div_.style.display = '';
}
this.visible_ = true;
};
/**
* Remove the icon from the map
*/
ClusterIcon.prototype.remove = function() {
this.setMap(null);
};
/**
* Implementation of the onRemove interface.
* @ignore
*/
ClusterIcon.prototype.onRemove = function() {
if (this.div_ && this.div_.parentNode) {
this.hide();
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
/**
* Set the sums of the icon.
*
* @param {Object} sums The sums containing:
* 'text': (string) The text to display in the icon.
* 'index': (number) The style index of the icon.
*/
ClusterIcon.prototype.setSums = function(sums) {
this.sums_ = sums;
this.text_ = sums.text;
this.index_ = sums.index;
if (this.div_) {
this.div_.innerHTML = sums.text;
}
this.useStyle();
};
/**
* Sets the icon to the the styles.
*/
ClusterIcon.prototype.useStyle = function() {
var index = Math.max(0, this.sums_.index - 1);
index = Math.min(this.styles_.length - 1, index);
var style = this.styles_[index];
this.url_ = style['url'];
this.height_ = style['height'];
this.width_ = style['width'];
this.textColor_ = style['textColor'];
this.anchor_ = style['anchor'];
this.textSize_ = style['textSize'];
this.backgroundPosition_ = style['backgroundPosition'];
};
/**
* Sets the center of the icon.
*
* @param {google.maps.LatLng} center The latlng to set as the center.
*/
ClusterIcon.prototype.setCenter = function(center) {
this.center_ = center;
};
/**
* Create the css text based on the position of the icon.
*
* @param {google.maps.Point} pos The position.
* @return {string} The css style text.
*/
ClusterIcon.prototype.createCss = function(pos) {
var style = [];
style.push('background-image:url(' + this.url_ + ');');
var backgroundPosition = this.backgroundPosition_ ? this.backgroundPosition_ : '0 0';
style.push('background-position:' + backgroundPosition + ';');
if (typeof this.anchor_ === 'object') {
if (typeof this.anchor_[0] === 'number' && this.anchor_[0] > 0 &&
this.anchor_[0] < this.height_) {
style.push('height:' + (this.height_ - this.anchor_[0]) +
'px; padding-top:' + this.anchor_[0] + 'px;');
} else {
style.push('height:' + this.height_ + 'px; line-height:' + this.height_ +
'px;');
}
if (typeof this.anchor_[1] === 'number' && this.anchor_[1] > 0 &&
this.anchor_[1] < this.width_) {
style.push('width:' + (this.width_ - this.anchor_[1]) +
'px; padding-left:' + this.anchor_[1] + 'px;');
} else {
style.push('width:' + this.width_ + 'px; text-align:center;');
}
} else {
style.push('height:' + this.height_ + 'px; line-height:' +
this.height_ + 'px; width:' + this.width_ + 'px; text-align:center;');
}
var txtColor = this.textColor_ ? this.textColor_ : 'black';
var txtSize = this.textSize_ ? this.textSize_ : 11;
style.push('cursor:pointer; top:' + pos.y + 'px; left:' +
pos.x + 'px; color:' + txtColor + '; position:absolute; font-size:' +
txtSize + 'px; font-family:Arial,sans-serif; font-weight:bold');
return style.join('');
};
// Export Symbols for Closure
// If you are not going to compile with closure then you can remove the
// code below.
window['MarkerClusterer'] = MarkerClusterer;
MarkerClusterer.prototype['addMarker'] = MarkerClusterer.prototype.addMarker;
MarkerClusterer.prototype['addMarkers'] = MarkerClusterer.prototype.addMarkers;
MarkerClusterer.prototype['clearMarkers'] =
MarkerClusterer.prototype.clearMarkers;
MarkerClusterer.prototype['fitMapToMarkers'] =
MarkerClusterer.prototype.fitMapToMarkers;
MarkerClusterer.prototype['getCalculator'] =
MarkerClusterer.prototype.getCalculator;
MarkerClusterer.prototype['getGridSize'] =
MarkerClusterer.prototype.getGridSize;
MarkerClusterer.prototype['getExtendedBounds'] =
MarkerClusterer.prototype.getExtendedBounds;
MarkerClusterer.prototype['getMap'] = MarkerClusterer.prototype.getMap;
MarkerClusterer.prototype['getMarkers'] = MarkerClusterer.prototype.getMarkers;
MarkerClusterer.prototype['getMaxZoom'] = MarkerClusterer.prototype.getMaxZoom;
MarkerClusterer.prototype['getStyles'] = MarkerClusterer.prototype.getStyles;
MarkerClusterer.prototype['getTotalClusters'] =
MarkerClusterer.prototype.getTotalClusters;
MarkerClusterer.prototype['getTotalMarkers'] =
MarkerClusterer.prototype.getTotalMarkers;
MarkerClusterer.prototype['redraw'] = MarkerClusterer.prototype.redraw;
MarkerClusterer.prototype['removeMarker'] =
MarkerClusterer.prototype.removeMarker;
MarkerClusterer.prototype['removeMarkers'] =
MarkerClusterer.prototype.removeMarkers;
MarkerClusterer.prototype['resetViewport'] =
MarkerClusterer.prototype.resetViewport;
MarkerClusterer.prototype['repaint'] =
MarkerClusterer.prototype.repaint;
MarkerClusterer.prototype['setCalculator'] =
MarkerClusterer.prototype.setCalculator;
MarkerClusterer.prototype['setGridSize'] =
MarkerClusterer.prototype.setGridSize;
MarkerClusterer.prototype['setMaxZoom'] =
MarkerClusterer.prototype.setMaxZoom;
MarkerClusterer.prototype['onAdd'] = MarkerClusterer.prototype.onAdd;
MarkerClusterer.prototype['draw'] = MarkerClusterer.prototype.draw;
Cluster.prototype['getCenter'] = Cluster.prototype.getCenter;
Cluster.prototype['getSize'] = Cluster.prototype.getSize;
Cluster.prototype['getMarkers'] = Cluster.prototype.getMarkers;
ClusterIcon.prototype['onAdd'] = ClusterIcon.prototype.onAdd;
ClusterIcon.prototype['draw'] = ClusterIcon.prototype.draw;
ClusterIcon.prototype['onRemove'] = ClusterIcon.prototype.onRemove;
| JavaScript |
///////////////////////////////////////
////// Map Related Functions //////
///////////////////////////////////////
/////////////////////////
////// Globals //////
/////////////////////////
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;
var crosshairShape = {coords:[0,0,0,0],type:'rect'};
var currentInfoBubble;
var infoWindow;
var infoWindowMarker;
var markerCluster;
// html containers for side bar use
var msg_bar_html = "";
var my_msg_bar_html = "";
var event_bar_html = "";
var my_event_bar_html = "";
var my_reg_bar_html = "";
var src_bar_html = "";
// arrays to hold the markers
var msgMarkers = [];
var myMsgs =[];
var eventMarkers = [];
var myEvents =[];
var myRegMarkers=[];
var srcMarkers = [];
var reopenFunc = undefined;
var _defaultTab = undefined;
var CON_TAB = 4;
var EDIT_TAB = 2;
var REG_TAB = 1;
///////////////////////////////////////
////// Map Geo Autocomplete ///////
///////////////////////////////////////
$().ready(function() {
$('#location').geo_autocomplete(new google.maps.Geocoder, {
mapkey: 'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBTIx7cuHpcaq3fYV4NM0BaZl8OxDxS9pQpgJkMv0RxjVl6cDGhDNERjaQ',
selectFirst: false,
minChars: 3,
cacheLength: 50,
width: 300,
scroll: true,
scrollHeight: 330
}).result(function(_event, _data) {
if (_data) map.fitBounds(_data.geometry.viewport);
});
});
////////////////////////////////
////// Manage Map //////
////////////////////////////////
function initialize() {
var latlng = new google.maps.LatLng(32.049975637218985, 34.81020566406257);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor:'crosshair'
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var center = new google.maps.Marker({
map: map,
icon: 'img/crosshair.gif',
shape: crosshairShape
});
center.bindTo('position', map, 'center');
//create a global infoWindow for search results
infoWindow = new google.maps.InfoWindow({
disableAutoPan: false
});
//create the global markerClusterer
markerCluster = new MarkerClusterer(map);
setupEvents();
addMine();
}
function setupEvents() {
reverseGeocodedLast = new Date();
centerChangedLast = new Date(new Date().getTime() - 2000);
setInterval(function() {
if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
reverseGeocode();
}
}, 1000);
google.maps.event.addListener(map, 'zoom_changed', function() {
document.getElementById("zoom_level").innerHTML = map.getZoom();
});
google.maps.event.addListener(map, 'idle', centerChanged);
}
function getCenterLatLngText() {
return '(' + map.getCenter().lat() +', '+ map.getCenter().lng() +')';
}
function centerChanged() {
var now = new Date();
if (centerChangedLast !== undefined && now.getTime() - centerChangedLast.getTime() < 1500) {
return;
}
centerChangedLast = new Date();
var latlng = getCenterLatLngText();
document.getElementById('latlng').innerHTML = latlng;
document.getElementById('formatedAddress').innerHTML = '';
currentReverseGeocodeResponse = null;
addFromDB();
}
function reverseGeocode() {
reverseGeocodedLast = new Date();
geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
}
function reverseGeocodeResult(results, status) {
currentReverseGeocodeResponse = results;
if(status == 'OK') {
if(results.length == 0) {
document.getElementById('formatedAddress').innerHTML = 'None';
} else {
document.getElementById('formatedAddress').innerHTML = results[0].formatted_address;
}
} else {
document.getElementById('formatedAddress').innerHTML = 'Error';
}
}
function geocode() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
function geocodeResult(results, status) {
if (status == 'OK' && results.length > 0) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}
///////////////////////////////////////////
////// General Marker Management //////
///////////////////////////////////////////
//close the infobubble
function closeBubble(reopen) {
if (currentInfoBubble !== undefined) {
currentInfoBubble.close();
currentInfoBubble.removeTab(0);
currentInfoBubble.removeTab(0);
currentInfoBubble.removeTab(0);
currentInfoBubble.removeTab(0);
currentInfoBubble.removeTab(0);
}
}
//add all my information to the side bar
function addMine() {
my_msg_bar_html = "";
my_event_bar_html = "";
myMsgs = [];
myEvents = [];
addMyRegistrations();
document.getElementById("my-msg-bar").innerHTML = my_msg_bar_html;
document.getElementById("my-event-bar").innerHTML = my_event_bar_html;
var getRequest = '/'+context+'/resources/users/'+myUser+'/events?past='+showPastEvents;
if (sinceDate > 0) {
getRequest += '&since='+sinceDate;
}
$.get(getRequest
).success(function(data){
$.each(data, function(index, event) {
var content = event.content;
var id = event.id;
var location = event.location;
var latlng = new google.maps.LatLng(location.lat,location.long);
addMyEvent(latlng, id, content);
});
}).error(function(data){
alert ("Can't retrieve my events! "+data.responseText);
});
var getRequest = '/'+context+'/resources/users/'+myUser+'/messages';
if (sinceDate > 0) {
getRequest += '?since='+sinceDate;
}
$.get(getRequest
).success(function(data){
$.each(data, function(index, msg) {
var content = msg.content;
var id = msg.id;
var location = msg.location;
var latlng = new google.maps.LatLng(location.lat,location.long);
addMyMsg(latlng, id, content);
});
}).error(function(data){
alert ("Can't retrieve my messages! "+data.responseText);
});
}
//add event & msg markers from db
function addFromDB() {
msg_bar_html = "";
event_bar_html = "";
markerCluster.clearMarkers();
msgMarkers = [];
eventMarkers = [];
document.getElementById("msg-bar").innerHTML = msg_bar_html;
document.getElementById("event-bar").innerHTML = event_bar_html;
var bounds = map.getBounds();
var center = bounds.getCenter();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var getRequest = '/'+context+'/resources/events/inRadius?'+
'lat='+center.lat()+'&'+
'long='+center.lng()+'&'+
'n='+ne.lng()+'&'+
's='+sw.lng()+'&'+
'w='+sw.lat()+'&'+
'e='+ne.lat()+'&'+
'past='+showPastEvents;
if (sinceDate > 0) {
getRequest += '&since='+sinceDate;
}
$.get(getRequest
).success(function(events){
$.each(events, function(index, event) {
var content = event.content;
var id = event.id;
var location = event.location;
var latlng = new google.maps.LatLng(location.lat,location.long);
var poster = event.poster;
var time = new Date(event.time);
var addr = location.address;
var capacity = event.capacity;
var name = event.name;
addEvent(id, poster, name, latlng, addr, content, time, capacity);
});
}).error(function(events){
alert ("Can't retrieve events! "+events.responseText);
});
var getRequest = '/'+context+'/resources/messages/inRadius?'+
'lat='+center.lat()+'&'+
'long='+center.lng()+'&'+
'n='+ne.lng()+'&'+
's='+sw.lng()+'&'+
'w='+sw.lat()+'&'+
'e='+ne.lat()+'&'+
'past='+showPastEvents;
if (sinceDate > 0) {
getRequest += '&since='+sinceDate;
}
$.get(getRequest
).success(function(msgs){
$.each(msgs, function(index, msg) {
var content = msg.content;
var id = msg.id;
var location = msg.location;
var latlng = new google.maps.LatLng(location.lat,location.long);
var poster = msg.poster;
var time = new Date(msg.time);
var addr = location.address;
var name = msg.name;
addMsg(id, poster, name, latlng, addr, content, time);
});
}).error(function(msgs){
alert ("Can't retrieve messages! "+msgs.responseText);
});
}
////////////////////////////////////////////
////// Search Related Functions //////
////////////////////////////////////////////
//add search result to the map
function addSearch(latlng, content, searchType) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
if (searchType == "Location") {
marker.setIcon('img/purple_MarkerS.png');
} else if (searchType == "Keywords") {
marker.setIcon('img/pink_MarkerS.png');
}
//build msg body
var body = '<div id="content">'+
'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
searchType+' Search Result </h2>'+
'<h3 style="text-align: center;">Content</h3>'+
'<p>'+content+'</p>'+
'</div>';
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(body);
infoWindow.open(map,marker);
});
// save the info we need to use later for the side_bar
srcMarkers.push(marker);
}
//add all search results to the map
function addSearchResults(resultsArray, searchType) {
var count = 0;
var tmp_bar_html = "";
$.each(resultsArray, function(index1, resultSource) {
$.each(resultSource, function(index2, result) {
var res = result.split("||");
var lat = res[1];
var lng = res[0];
var content = res[2];
var latlng = new google.maps.LatLng(lat, lng);
addSearch(latlng, content, searchType);
count += 1;
tmp_bar_html += '<a href="javascript:myLatLngClick(' + lat + ',' + lng + ')">' + count + '. ' + content + '<\/a><br\/>';
});
});
if (count > 0) {
tmp_bar_html = '<br/><span id="search-results">'+searchType+' Search Results:</span><br/>' + tmp_bar_html;
src_bar_html += tmp_bar_html;
document.getElementById("src-results-bar").innerHTML = src_bar_html;
}
alert(count+" search results from WS were added to the map");
}
//clear all search results from the map
function clearSearchResults() {
$.each(srcMarkers, function(index, marker) {
marker.setMap(null);
});
srcMarkers = [];
src_bar_html = "";
document.getElementById("src-results-bar").innerHTML = src_bar_html;
}
////////////////////////////////////////////
////// Messages Related Functions //////
////////////////////////////////////////////
//picks up the click and opens the corresponding window
function msgClick(i) {
google.maps.event.trigger(msgMarkers[i], "click");
}
//move the center to my msg
function myMsgClick(i) {
map.setCenter(myMsgs[i]);
}
//add my message to the side bar
function addMyMsg(ll, id, content) {
myMsgs.push(ll);
my_msg_bar_html = '<a href="javascript:myMsgClick(' + (myMsgs.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + my_msg_bar_html;
document.getElementById("my-msg-bar").innerHTML = my_msg_bar_html;
}
//add a msg from server to the center of the map
function addMsgAtCenter(msgLoc) {
$.get(
msgLoc
).success(function(data){
var content = data.content;
var id = data.id;
var location = data.location;
var latlng = new google.maps.LatLng(location.lat,location.long);
var poster = data.poster;
var time = new Date(data.time);
var addr = location.address;
var name = data.name;
var marker = addMsg(id, poster, name, latlng, addr, content, time);
addMyMsg(marker.getPosition(), id, content);
alert("Message posted successfuly!");
}).error(function(data){
alert ("Can't get the added msg! "+data.responseText);
});
}
//add a msg to the map
function addMsg(id, poster, name, latlng, addr, content, time) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
if (myUser == poster) {
marker.setIcon('img/darkgreen_MarkerM.png');
} else {
marker.setIcon('img/green_MarkerM.png');
}
marker.poster = poster;
marker.id = id;
marker.latlng = latlng;
marker.addr = addr;
marker.content = content;
marker.time = time;
marker.name = name;
google.maps.event.addListener(marker, 'click', function() {
closeBubble();
currentInfoBubble = new InfoBubble({
maxWidth: 310,
maxHeight: 380
});
//build msg body
var msgContent = '<div id="content">'+
'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
name+"'s Message </h2>"+
'<h3 style="text-align: center;">Content</h3>'+
'<p>'+content+'</p>'+
'</div>';
var details = '<div id="content">'+
'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
'Message Details </h2>'+
'<p>Message id: '+id+'</p>'+
'<h3 style="text-align: center;">Time</h3>'+
'<p>'+time+'</p>'+
'<h3 style="text-align: center;">Location</h3>'+
'<p>'+addr+'</p>'+
'</div>';
currentInfoBubble.addTab('Content', msgContent);
currentInfoBubble.addTab('Details', details);
if (marker.poster == myUser) {
var edit = document.createElement('DIV');
edit.innerHTML = '<div id="content">'+
'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
'Edit Message</h2>'+
'<h3 style="text-align: center;">Actions</h3>'+
'<div style="text-align:center;">'+
'<button align="center" onclick="deleteMsg('+marker.id+')">Delete Message</button>'+
'</div>'+
'</div>';
currentInfoBubble.addTab('Edit', edit);
}
currentInfoBubble.open(map, marker);
google.maps.event.addListener(currentInfoBubble,'closeclick',function(){
closeBubble();
});
});
// save the info we need to use later for the side_bar
msgMarkers.push(marker);
markerCluster.addMarker(marker);
// add a line to the side_bar html
msg_bar_html = '<a href="javascript:msgClick(' + (msgMarkers.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + msg_bar_html;
document.getElementById("msg-bar").innerHTML = msg_bar_html;
return marker;
}
//delete a msg
function deleteMsg(id) {
closeBubble();
$.delete('/'+context+'/resources/messages/'+id)
.success(function (data, resultText, result) {
alert("Message deleted successfully!");
addMine();
google.maps.event.trigger(map, "idle");
}).error(function(data) {
alert("Cannot delete! "+data.responseText);
});
}
//////////////////////////////////////////
////// Events Related Functions //////
//////////////////////////////////////////
//picks the click and open the event
function eventClick(i) {
google.maps.event.trigger(eventMarkers[i], "click");
}
//picks the click and move the center to the event
function myEventClick(i) {
map.setCenter(myEvents[i]);
}
//move the center to the latlng
function myLatLngClick(lat,lng) {
var newCenter = new google.maps.LatLng(lat, lng);
map.setCenter(newCenter);
}
//add my events registrations
function addMyRegistrations() {
myRegMarkers = [];
my_reg_bar_html = "";
$.get('/'+context+'/resources/users/'+myUser+'/registrations?past='+showPastEvents
).success(function(data,status,result) {
$.each(data, function(index, reg) {
var id = reg.id;
var content = reg.content;
var location = reg.location;
var lat = location.lat;
var lng = location.long;
myRegMarkers[id]=new google.maps.LatLng(lat, lng);
my_reg_bar_html = '<a href="javascript:myLatLngClick(' + myRegMarkers[id].lat() +','+ myRegMarkers[id].lng() + ')">' + id + '. ' + content + '<\/a><br\/>' + my_reg_bar_html;
});
document.getElementById("my-reg-bar").innerHTML = my_reg_bar_html;
}).error(function(data,status,result) {
alert("Unable to get my registrations! "+data.responseText);
});
}
//add my event to the side bar
function addMyEvent(ll, id, content) {
myEvents.push(ll);
my_event_bar_html = '<a href="javascript:myEventClick(' + (myEvents.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + my_event_bar_html;
document.getElementById("my-event-bar").innerHTML = my_event_bar_html;
}
//add an event from the server to the center of the map
function addEventAtCenter(eventLoc) {
$.get(
eventLoc
).success(function(data){
var content = data.content;
var id = data.id;
var location = data.location;
var latlng = new google.maps.LatLng(location.lat,location.long);
var poster = data.poster;
var time = new Date(data.time);
var addr = location.address;
var capacity = data.capacity;
var name = data.name;
addEvent(id, poster, name, latlng, addr, content, time, capacity);
addMyEvent(latlng, id, content);
}).error(function(data){
alert ("Can't get the added event! "+data.responseText);
});
}
//add an event to the map
function addEvent(id, poster, name, latlng, addr, content, time, capacity) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
if (myUser == poster) {
marker.setIcon('img/blue_MarkerE.png');
} else {
marker.setIcon('img/paleblue_MarkerE.png');
}
marker.id = id;
marker.poster = poster;
marker.name = name;
marker.latlng = latlng;
marker.addr = addr;
marker.content = content;
marker.time = time;
marker.capacity = capacity;
//add click listener
google.maps.event.addListener(marker, 'click', function() {
reopenFunc = arguments.callee;
closeBubble();
$.get('/'+context+'/resources/events/'+id+'/registered'
).success(function(data) {
currentInfoBubble = new InfoBubble({
maxWidth: 310,
maxHeight: 380
});
if (marker.name == myName) {
marker.status = '<p style="color:blue; text-align:center">You are the CREATOR of this event</p>';
} else {
marker.status = '<p style="text-align:center">You are NOT REGISTERED to this event</p>';
}
marker.guests = data;
var guestNames = '<p>';
$.each(marker.guests, function(index, guest) {
if (guest.name == myName) {
marker.status = '<p style="color:green; text-align:center">You are REGISTERED to this event</p>';
}
guestNames += guest.name;
if (index < (marker.guests.length - 1)) {
guestNames += ', ';
}
});
guestNames += '</p>';
var status = '<div id="content">'+
'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
marker.name+"'s Event </h2>"+
'<p>Event id: '+marker.id+'</p>'+
'<h3 style="text-align: center;">Status</h3>'+
marker.status+
'<h3 style="text-align: center;">Time</h3>'+
'<p>'+marker.time+'</p>'+
'<h3 style="text-align: center;">Location</h3>'+
'<p>'+marker.addr+'</p>'+
'<h3 style="text-align: center;">Capacity</h3>'+
'<p>'+marker.guests.length+'/'+marker.capacity+'</p>'+
'<h3 style="text-align: center;">Actions</h3>'+
'<div style="text-align:center;">'+
'<button align="center" onclick="register('+marker.id+','+marker.latlng.lat()+','+marker.latlng.lng()+',\''+marker.content+'\')">Register</button>'+
'<button onclick="unregister('+marker.id+')">Unregister</button>'+
'</div>'+
'</div>';
var info = document.createElement('DIV');
info.innerHTML ='<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
"Event Information</h2>"+marker.content;
var guests = document.createElement('DIV');
guests.innerHTML ='<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
"Registered Guests</h2>"+
'<h3>Creator: </h3>'+marker.name+
'<h3>Guests: </h3>'+guestNames;
currentInfoBubble.addTab('Event Status', status);
if (marker.poster == myUser) {
var edit = document.createElement('DIV');
edit.innerHTML = '<div id="content">'+
'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
"Edit Event</h2>"+
'<h3 style="text-align: center;">Actions</h3>'+
'<div style="text-align:center;">'+
'<button align="center" onclick="deleteEvent('+marker.id+')">Delete Event</button>'+
'</div>'+
'<h3 style="text-align: center;">Consensuses</h3>'+
'<div style="text-align:center;">'+
'<input class="con_content" type="text" id="con" value=""/>'+
'<button onclick="addCon('+marker.id+')">Add Consensus</button>'+
'</div>'+
'</div>';
currentInfoBubble.addTab('Edit', edit);
CON_TAB = 5;
} else {
CON_TAB = 4;
}
currentInfoBubble.addTab('Information', info);
currentInfoBubble.addTab('Guests', guests);
$.get('/'+context+'/resources/events/'+id+'/cons'
).success(function(data,status,response) {
var cons = document.createElement('DIV');
cons.innerHTML = '<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
"Event Consensuses</h2>";
$.each(data, function(index,con) {
var conId = con.id;
var conName = con.name;
var myVote = con.myVote;
var currStatus = con.currStatus;
var numVotes = con.numVotes;
var status = '<span>UNDECIDED</span>';
if (currStatus == true) {
status = '<span style="color: #009933">APPLIED</span>';
} else if (currStatus == false) {
status = '<span style="color: #E60000">NOT APPLIED</span>';
}
var vote = "";
if (myVote == true) {
vote = '<p>Your current vote is YES</p>';
}
if (myVote == false) {
vote = '<p>Your current vote is NO</p>';
}
cons.innerHTML +=
'<h3 style="text-align: center;">Consensus '+conId+': '+status+' ('+numVotes+' votes)</h3>'+
'<p>'+conName+'</p>'+
'<div style="text-align:center;">'+
vote+
'<button onclick="voteCon('+conId+')">Yes</button>'+
'<button onclick="unvoteCon('+conId+')">No</button>'+
'</div><hr/>';
});
currentInfoBubble.addTab('Consensus', cons);
if (_defaultTab == CON_TAB) {
currentInfoBubble.setTabActive(CON_TAB);
}
}).error(function(data) {
alert("Can't retrieve consensuses! "+data.responseText);
});
currentInfoBubble.open(map, marker);
google.maps.event.addListener(currentInfoBubble,'closeclick',function(){
reopenFunc = function() {
// do nothing, prevents accidental callings of this()
};
closeBubble();
});
// var infowindow = new google.maps.InfoWindow({ content: marker.body });
//infowindow.open(map,marker);
}).error(function(data) {
alert("Can't get event's memebers! "+data.responseText);
});
});
eventMarkers.push(marker);
markerCluster.addMarker(marker);
event_bar_html = '<a href="javascript:eventClick(' + (eventMarkers.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + event_bar_html;
document.getElementById("event-bar").innerHTML = event_bar_html;
}
//add consensus
function addCon(id) {
var cons = document.getElementsByClassName("con_content");
var con = cons[cons.length - 1].value;
if (con.length == 0) {
alert("Please enter a name for the consensus");
return;
}
$.post('/'+context+'/resources/events/'+id+'/cons', JSON.stringify({name: con})
).success(function(data,status,result) {
alert("Consensus added successfully");
closeBubble();
_defaultTab = EDIT_TAB;
reopenFunc();
}).error(function(data) {
alert("Unable to added consensus! "+data.responseText);
});
}
//vote YES for consensus
function voteCon(id) {
$.post('/'+context+'/resources/cons/'+id+'/votes',
JSON.stringify({vote: true})
).success(function(data) {
alert("Voted YES");
closeBubble();
reopenFunc();
_defaultTab = CON_TAB;
}).error(function(data) {
alert("Unable to vote! "+data.responseText);
});
}
//vote NO for consensus
function unvoteCon(id) {
$.post('/'+context+'/resources/cons/'+id+'/votes',
JSON.stringify({vote: false})
).success(function(data) {
alert("Voted NO");
closeBubble();
_defaultTab = CON_TAB;
reopenFunc();
}).error(function(data) {
alert("Unable to vote! "+data.responseText);
});
}
//register to event
function register(id,lat,lng,content) {
$.post('/'+context+'/resources/events/'+id+'/register')
.success(function (data, resultText, result) {
if (result.status == 204) {
alert("You're already registered...");
} else {
alert("You've been successfully registered to the event!");
myRegMarkers[id]=new google.maps.LatLng(lat, lng);
my_reg_bar_html = '<a href="javascript:myLatLngClick(' + myRegMarkers[id].lat() +','+ myRegMarkers[id].lng() + ')">' + id + '. ' + content + '<\/a><br\/>' + my_reg_bar_html;
document.getElementById("my-reg-bar").innerHTML = my_reg_bar_html;
closeBubble();
_defaultTab = REG_TAB;
reopenFunc();
}
}).error(function(data) {
alert("Unable to register! "+data.responseText);
});
}
//unregister from event
function unregister(id) {
$.delete('/'+context+'/resources/events/'+id+'/register')
.success(function (data, resultText, result) {
if (result.status == 204) {
alert("You're not registered to this event...");
} else {
alert("You've been unregistered from the event...");
addMyRegistrations();
closeBubble();
_defaultTab = REG_TAB;
reopenFunc();
}
}).error(function(data) {
alert("Unable to unregister! "+data.responseText);
});
}
//delete an event
function deleteEvent(id) {
closeBubble();
$.delete('/'+context+'/resources/events/'+id)
.success(function (data, resultText, result) {
alert("Event deleted successfully!");
addMine();
google.maps.event.trigger(map, "idle");
}).error(function(data) {
alert("Cannot delete! "+data.responseText);
});
}
| JavaScript |
/*jshint eqnull:true */
/*!
* jQuery Cookie Plugin v1.2
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2011, Klaus Hartl
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/GPL-2.0
*/
(function ($, document, undefined) {
var pluses = /\+/g;
function raw(s) {
return s;
}
function decoded(s) {
return decodeURIComponent(s.replace(pluses, ' '));
}
$.cookie = function (key, value, options) {
// key and at least value given, set cookie...
if (value !== undefined && !/Object/.test(Object.prototype.toString.call(value))) {
options = $.extend({}, $.cookie.defaults, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = String(value);
return (document.cookie = [
encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || $.cookie.defaults || {};
var decode = options.raw ? raw : decoded;
var cookies = document.cookie.split('; ');
for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
if (decode(parts.shift()) === key) {
return decode(parts.join('='));
}
}
return null;
};
$.cookie.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key, options) !== null) {
$.cookie(key, null, options);
return true;
}
return false;
};
})(jQuery, document); | JavaScript |
var context = location.pathname.split("/")[1];
| JavaScript |
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3.js
// ==/ClosureCompiler==
/**
* @name CSS3 InfoBubble with tabs for Google Maps API V3
* @version 0.8
* @author Luke Mahe
* @fileoverview
* This library is a CSS Infobubble with tabs. It uses css3 rounded corners and
* drop shadows and animations. It also allows tabs
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A CSS3 InfoBubble v0.8
* @param {Object.<string, *>=} opt_options Optional properties to set.
* @extends {google.maps.OverlayView}
* @constructor
*/
function InfoBubble(opt_options) {
this.extend(InfoBubble, google.maps.OverlayView);
this.tabs_ = [];
this.activeTab_ = null;
this.baseZIndex_ = 100;
this.isOpen_ = false;
var options = opt_options || {};
if (options['backgroundColor'] == undefined) {
options['backgroundColor'] = this.BACKGROUND_COLOR_;
}
if (options['borderColor'] == undefined) {
options['borderColor'] = this.BORDER_COLOR_;
}
if (options['borderRadius'] == undefined) {
options['borderRadius'] = this.BORDER_RADIUS_;
}
if (options['borderWidth'] == undefined) {
options['borderWidth'] = this.BORDER_WIDTH_;
}
if (options['padding'] == undefined) {
options['padding'] = this.PADDING_;
}
if (options['arrowPosition'] == undefined) {
options['arrowPosition'] = this.ARROW_POSITION_;
}
if (options['disableAutoPan'] == undefined) {
options['disableAutoPan'] = false;
}
if (options['disableAnimation'] == undefined) {
options['disableAnimation'] = false;
}
if (options['minWidth'] == undefined) {
options['minWidth'] = this.MIN_WIDTH_;
}
if (options['shadowStyle'] == undefined) {
options['shadowStyle'] = this.SHADOW_STYLE_;
}
if (options['arrowSize'] == undefined) {
options['arrowSize'] = this.ARROW_SIZE_;
}
if (options['arrowStyle'] == undefined) {
options['arrowStyle'] = this.ARROW_STYLE_;
}
this.buildDom_();
this.setValues(options);
}
window['InfoBubble'] = InfoBubble;
/**
* Default arrow size
* @const
* @private
*/
InfoBubble.prototype.ARROW_SIZE_ = 15;
/**
* Default arrow style
* @const
* @private
*/
InfoBubble.prototype.ARROW_STYLE_ = 0;
/**
* Default shadow style
* @const
* @private
*/
InfoBubble.prototype.SHADOW_STYLE_ = 1;
/**
* Default min width
* @const
* @private
*/
InfoBubble.prototype.MIN_WIDTH_ = 50;
/**
* Default arrow position
* @const
* @private
*/
InfoBubble.prototype.ARROW_POSITION_ = 50;
/**
* Default padding
* @const
* @private
*/
InfoBubble.prototype.PADDING_ = 10;
/**
* Default border width
* @const
* @private
*/
InfoBubble.prototype.BORDER_WIDTH_ = 1;
/**
* Default border color
* @const
* @private
*/
InfoBubble.prototype.BORDER_COLOR_ = '#ccc';
/**
* Default border radius
* @const
* @private
*/
InfoBubble.prototype.BORDER_RADIUS_ = 10;
/**
* Default background color
* @const
* @private
*/
InfoBubble.prototype.BACKGROUND_COLOR_ = '#fff';
/**
* Extends a objects prototype by anothers.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
InfoBubble.prototype.extend = function(obj1, obj2) {
return (function(object) {
for (var property in object.prototype) {
this.prototype[property] = object.prototype[property];
}
return this;
}).apply(obj1, [obj2]);
};
/**
* Builds the InfoBubble dom
* @private
*/
InfoBubble.prototype.buildDom_ = function() {
var bubble = this.bubble_ = document.createElement('DIV');
bubble.style['position'] = 'absolute';
bubble.style['zIndex'] = this.baseZIndex_;
var tabsContainer = this.tabsContainer_ = document.createElement('DIV');
tabsContainer.style['position'] = 'relative';
// Close button
var close = this.close_ = document.createElement('IMG');
close.style['position'] = 'absolute';
close.style['width'] = this.px(12);
close.style['height'] = this.px(12);
close.style['border'] = 0;
close.style['zIndex'] = this.baseZIndex_ + 1;
close.style['cursor'] = 'pointer';
close.src = 'http://maps.gstatic.com/intl/en_us/mapfiles/iw_close.gif';
var that = this;
google.maps.event.addDomListener(close, 'click', function() {
that.close();
google.maps.event.trigger(that, 'closeclick');
});
// Content area
var contentContainer = this.contentContainer_ = document.createElement('DIV');
contentContainer.style['overflowX'] = 'auto';
contentContainer.style['overflowY'] = 'auto';
contentContainer.style['cursor'] = 'default';
contentContainer.style['clear'] = 'both';
contentContainer.style['position'] = 'relative';
var content = this.content_ = document.createElement('DIV');
contentContainer.appendChild(content);
// Arrow
var arrow = this.arrow_ = document.createElement('DIV');
arrow.style['position'] = 'relative';
var arrowOuter = this.arrowOuter_ = document.createElement('DIV');
var arrowInner = this.arrowInner_ = document.createElement('DIV');
var arrowSize = this.getArrowSize_();
arrowOuter.style['position'] = arrowInner.style['position'] = 'absolute';
arrowOuter.style['left'] = arrowInner.style['left'] = '50%';
arrowOuter.style['height'] = arrowInner.style['height'] = '0';
arrowOuter.style['width'] = arrowInner.style['width'] = '0';
arrowOuter.style['marginLeft'] = this.px(-arrowSize);
arrowOuter.style['borderWidth'] = this.px(arrowSize);
arrowOuter.style['borderBottomWidth'] = 0;
// Shadow
var bubbleShadow = this.bubbleShadow_ = document.createElement('DIV');
bubbleShadow.style['position'] = 'absolute';
// Hide the InfoBubble by default
bubble.style['display'] = bubbleShadow.style['display'] = 'none';
bubble.appendChild(this.tabsContainer_);
bubble.appendChild(close);
bubble.appendChild(contentContainer);
arrow.appendChild(arrowOuter);
arrow.appendChild(arrowInner);
bubble.appendChild(arrow);
var stylesheet = document.createElement('style');
stylesheet.setAttribute('type', 'text/css');
/**
* The animation for the infobubble
* @type {string}
*/
this.animationName_ = '_ibani_' + Math.round(Math.random() * 10000);
var css = '.' + this.animationName_ + '{-webkit-animation-name:' +
this.animationName_ + ';-webkit-animation-duration:0.5s;' +
'-webkit-animation-iteration-count:1;}' +
'@-webkit-keyframes ' + this.animationName_ + ' {from {' +
'-webkit-transform: scale(0)}50% {-webkit-transform: scale(1.2)}90% ' +
'{-webkit-transform: scale(0.95)}to {-webkit-transform: scale(1)}}';
stylesheet.textContent = css;
document.getElementsByTagName('head')[0].appendChild(stylesheet);
};
/**
* Sets the background class name
*
* @param {string} className The class name to set.
*/
InfoBubble.prototype.setBackgroundClassName = function(className) {
this.set('backgroundClassName', className);
};
InfoBubble.prototype['setBackgroundClassName'] =
InfoBubble.prototype.setBackgroundClassName;
/**
* changed MVC callback
*/
InfoBubble.prototype.backgroundClassName_changed = function() {
this.content_.className = this.get('backgroundClassName');
};
InfoBubble.prototype['backgroundClassName_changed'] =
InfoBubble.prototype.backgroundClassName_changed;
/**
* Sets the class of the tab
*
* @param {string} className the class name to set.
*/
InfoBubble.prototype.setTabClassName = function(className) {
this.set('tabClassName', className);
};
InfoBubble.prototype['setTabClassName'] =
InfoBubble.prototype.setTabClassName;
/**
* tabClassName changed MVC callback
*/
InfoBubble.prototype.tabClassName_changed = function() {
this.updateTabStyles_();
};
InfoBubble.prototype['tabClassName_changed'] =
InfoBubble.prototype.tabClassName_changed;
/**
* Gets the style of the arrow
*
* @private
* @return {number} The style of the arrow.
*/
InfoBubble.prototype.getArrowStyle_ = function() {
return parseInt(this.get('arrowStyle'), 10) || 0;
};
/**
* Sets the style of the arrow
*
* @param {number} style The style of the arrow.
*/
InfoBubble.prototype.setArrowStyle = function(style) {
this.set('arrowStyle', style);
};
InfoBubble.prototype['setArrowStyle'] =
InfoBubble.prototype.setArrowStyle;
/**
* Arrow style changed MVC callback
*/
InfoBubble.prototype.arrowStyle_changed = function() {
this.arrowSize_changed();
};
InfoBubble.prototype['arrowStyle_changed'] =
InfoBubble.prototype.arrowStyle_changed;
/**
* Gets the size of the arrow
*
* @private
* @return {number} The size of the arrow.
*/
InfoBubble.prototype.getArrowSize_ = function() {
return parseInt(this.get('arrowSize'), 10) || 0;
};
/**
* Sets the size of the arrow
*
* @param {number} size The size of the arrow.
*/
InfoBubble.prototype.setArrowSize = function(size) {
this.set('arrowSize', size);
};
InfoBubble.prototype['setArrowSize'] =
InfoBubble.prototype.setArrowSize;
/**
* Arrow size changed MVC callback
*/
InfoBubble.prototype.arrowSize_changed = function() {
this.borderWidth_changed();
};
InfoBubble.prototype['arrowSize_changed'] =
InfoBubble.prototype.arrowSize_changed;
/**
* Set the position of the InfoBubble arrow
*
* @param {number} pos The position to set.
*/
InfoBubble.prototype.setArrowPosition = function(pos) {
this.set('arrowPosition', pos);
};
InfoBubble.prototype['setArrowPosition'] =
InfoBubble.prototype.setArrowPosition;
/**
* Get the position of the InfoBubble arrow
*
* @private
* @return {number} The position..
*/
InfoBubble.prototype.getArrowPosition_ = function() {
return parseInt(this.get('arrowPosition'), 10) || 0;
};
/**
* arrowPosition changed MVC callback
*/
InfoBubble.prototype.arrowPosition_changed = function() {
var pos = this.getArrowPosition_();
this.arrowOuter_.style['left'] = this.arrowInner_.style['left'] = pos + '%';
this.redraw_();
};
InfoBubble.prototype['arrowPosition_changed'] =
InfoBubble.prototype.arrowPosition_changed;
/**
* Set the zIndex of the InfoBubble
*
* @param {number} zIndex The zIndex to set.
*/
InfoBubble.prototype.setZIndex = function(zIndex) {
this.set('zIndex', zIndex);
};
InfoBubble.prototype['setZIndex'] = InfoBubble.prototype.setZIndex;
/**
* Get the zIndex of the InfoBubble
*
* @return {number} The zIndex to set.
*/
InfoBubble.prototype.getZIndex = function() {
return parseInt(this.get('zIndex'), 10) || this.baseZIndex_;
};
/**
* zIndex changed MVC callback
*/
InfoBubble.prototype.zIndex_changed = function() {
var zIndex = this.getZIndex();
this.bubble_.style['zIndex'] = this.baseZIndex_ = zIndex;
this.close_.style['zIndex'] = zIndex + 1;
};
InfoBubble.prototype['zIndex_changed'] = InfoBubble.prototype.zIndex_changed;
/**
* Set the style of the shadow
*
* @param {number} shadowStyle The style of the shadow.
*/
InfoBubble.prototype.setShadowStyle = function(shadowStyle) {
this.set('shadowStyle', shadowStyle);
};
InfoBubble.prototype['setShadowStyle'] = InfoBubble.prototype.setShadowStyle;
/**
* Get the style of the shadow
*
* @private
* @return {number} The style of the shadow.
*/
InfoBubble.prototype.getShadowStyle_ = function() {
return parseInt(this.get('shadowStyle'), 10) || 0;
};
/**
* shadowStyle changed MVC callback
*/
InfoBubble.prototype.shadowStyle_changed = function() {
var shadowStyle = this.getShadowStyle_();
var display = '';
var shadow = '';
var backgroundColor = '';
switch (shadowStyle) {
case 0:
display = 'none';
break;
case 1:
shadow = '40px 15px 10px rgba(33,33,33,0.3)';
backgroundColor = 'transparent';
break;
case 2:
shadow = '0 0 2px rgba(33,33,33,0.3)';
backgroundColor = 'rgba(33,33,33,0.35)';
break;
}
this.bubbleShadow_.style['boxShadow'] =
this.bubbleShadow_.style['webkitBoxShadow'] =
this.bubbleShadow_.style['MozBoxShadow'] = shadow;
this.bubbleShadow_.style['backgroundColor'] = backgroundColor;
if (this.isOpen_) {
this.bubbleShadow_.style['display'] = display;
this.draw();
}
};
InfoBubble.prototype['shadowStyle_changed'] =
InfoBubble.prototype.shadowStyle_changed;
/**
* Show the close button
*/
InfoBubble.prototype.showCloseButton = function() {
this.set('hideCloseButton', false);
};
InfoBubble.prototype['showCloseButton'] = InfoBubble.prototype.showCloseButton;
/**
* Hide the close button
*/
InfoBubble.prototype.hideCloseButton = function() {
this.set('hideCloseButton', true);
};
InfoBubble.prototype['hideCloseButton'] = InfoBubble.prototype.hideCloseButton;
/**
* hideCloseButton changed MVC callback
*/
InfoBubble.prototype.hideCloseButton_changed = function() {
this.close_.style['display'] = this.get('hideCloseButton') ? 'none' : '';
};
InfoBubble.prototype['hideCloseButton_changed'] =
InfoBubble.prototype.hideCloseButton_changed;
/**
* Set the background color
*
* @param {string} color The color to set.
*/
InfoBubble.prototype.setBackgroundColor = function(color) {
if (color) {
this.set('backgroundColor', color);
}
};
InfoBubble.prototype['setBackgroundColor'] =
InfoBubble.prototype.setBackgroundColor;
/**
* backgroundColor changed MVC callback
*/
InfoBubble.prototype.backgroundColor_changed = function() {
var backgroundColor = this.get('backgroundColor');
this.contentContainer_.style['backgroundColor'] = backgroundColor;
this.arrowInner_.style['borderColor'] = backgroundColor +
' transparent transparent';
this.updateTabStyles_();
};
InfoBubble.prototype['backgroundColor_changed'] =
InfoBubble.prototype.backgroundColor_changed;
/**
* Set the border color
*
* @param {string} color The border color.
*/
InfoBubble.prototype.setBorderColor = function(color) {
if (color) {
this.set('borderColor', color);
}
};
InfoBubble.prototype['setBorderColor'] = InfoBubble.prototype.setBorderColor;
/**
* borderColor changed MVC callback
*/
InfoBubble.prototype.borderColor_changed = function() {
var borderColor = this.get('borderColor');
var contentContainer = this.contentContainer_;
var arrowOuter = this.arrowOuter_;
contentContainer.style['borderColor'] = borderColor;
arrowOuter.style['borderColor'] = borderColor +
' transparent transparent';
contentContainer.style['borderStyle'] =
arrowOuter.style['borderStyle'] =
this.arrowInner_.style['borderStyle'] = 'solid';
this.updateTabStyles_();
};
InfoBubble.prototype['borderColor_changed'] =
InfoBubble.prototype.borderColor_changed;
/**
* Set the radius of the border
*
* @param {number} radius The radius of the border.
*/
InfoBubble.prototype.setBorderRadius = function(radius) {
this.set('borderRadius', radius);
};
InfoBubble.prototype['setBorderRadius'] = InfoBubble.prototype.setBorderRadius;
/**
* Get the radius of the border
*
* @private
* @return {number} The radius of the border.
*/
InfoBubble.prototype.getBorderRadius_ = function() {
return parseInt(this.get('borderRadius'), 10) || 0;
};
/**
* borderRadius changed MVC callback
*/
InfoBubble.prototype.borderRadius_changed = function() {
var borderRadius = this.getBorderRadius_();
var borderWidth = this.getBorderWidth_();
this.contentContainer_.style['borderRadius'] =
this.contentContainer_.style['MozBorderRadius'] =
this.contentContainer_.style['webkitBorderRadius'] =
this.bubbleShadow_.style['borderRadius'] =
this.bubbleShadow_.style['MozBorderRadius'] =
this.bubbleShadow_.style['webkitBorderRadius'] = this.px(borderRadius);
this.tabsContainer_.style['paddingLeft'] =
this.tabsContainer_.style['paddingRight'] =
this.px(borderRadius + borderWidth);
this.redraw_();
};
InfoBubble.prototype['borderRadius_changed'] =
InfoBubble.prototype.borderRadius_changed;
/**
* Get the width of the border
*
* @private
* @return {number} width The width of the border.
*/
InfoBubble.prototype.getBorderWidth_ = function() {
return parseInt(this.get('borderWidth'), 10) || 0;
};
/**
* Set the width of the border
*
* @param {number} width The width of the border.
*/
InfoBubble.prototype.setBorderWidth = function(width) {
this.set('borderWidth', width);
};
InfoBubble.prototype['setBorderWidth'] = InfoBubble.prototype.setBorderWidth;
/**
* borderWidth change MVC callback
*/
InfoBubble.prototype.borderWidth_changed = function() {
var borderWidth = this.getBorderWidth_();
this.contentContainer_.style['borderWidth'] = this.px(borderWidth);
this.tabsContainer_.style['top'] = this.px(borderWidth);
this.updateArrowStyle_();
this.updateTabStyles_();
this.borderRadius_changed();
this.redraw_();
};
InfoBubble.prototype['borderWidth_changed'] =
InfoBubble.prototype.borderWidth_changed;
/**
* Update the arrow style
* @private
*/
InfoBubble.prototype.updateArrowStyle_ = function() {
var borderWidth = this.getBorderWidth_();
var arrowSize = this.getArrowSize_();
var arrowStyle = this.getArrowStyle_();
var arrowOuterSizePx = this.px(arrowSize);
var arrowInnerSizePx = this.px(Math.max(0, arrowSize - borderWidth));
var outer = this.arrowOuter_;
var inner = this.arrowInner_;
this.arrow_.style['marginTop'] = this.px(-borderWidth);
outer.style['borderTopWidth'] = arrowOuterSizePx;
inner.style['borderTopWidth'] = arrowInnerSizePx;
// Full arrow or arrow pointing to the left
if (arrowStyle == 0 || arrowStyle == 1) {
outer.style['borderLeftWidth'] = arrowOuterSizePx;
inner.style['borderLeftWidth'] = arrowInnerSizePx;
} else {
outer.style['borderLeftWidth'] = inner.style['borderLeftWidth'] = 0;
}
// Full arrow or arrow pointing to the right
if (arrowStyle == 0 || arrowStyle == 2) {
outer.style['borderRightWidth'] = arrowOuterSizePx;
inner.style['borderRightWidth'] = arrowInnerSizePx;
} else {
outer.style['borderRightWidth'] = inner.style['borderRightWidth'] = 0;
}
if (arrowStyle < 2) {
outer.style['marginLeft'] = this.px(-(arrowSize));
inner.style['marginLeft'] = this.px(-(arrowSize - borderWidth));
} else {
outer.style['marginLeft'] = inner.style['marginLeft'] = 0;
}
// If there is no border then don't show thw outer arrow
if (borderWidth == 0) {
outer.style['display'] = 'none';
} else {
outer.style['display'] = '';
}
};
/**
* Set the padding of the InfoBubble
*
* @param {number} padding The padding to apply.
*/
InfoBubble.prototype.setPadding = function(padding) {
this.set('padding', padding);
};
InfoBubble.prototype['setPadding'] = InfoBubble.prototype.setPadding;
/**
* Set the padding of the InfoBubble
*
* @private
* @return {number} padding The padding to apply.
*/
InfoBubble.prototype.getPadding_ = function() {
return parseInt(this.get('padding'), 10) || 0;
};
/**
* padding changed MVC callback
*/
InfoBubble.prototype.padding_changed = function() {
var padding = this.getPadding_();
this.contentContainer_.style['padding'] = this.px(padding);
this.updateTabStyles_();
this.redraw_();
};
InfoBubble.prototype['padding_changed'] = InfoBubble.prototype.padding_changed;
/**
* Add px extention to the number
*
* @param {number} num The number to wrap.
* @return {string|number} A wrapped number.
*/
InfoBubble.prototype.px = function(num) {
if (num) {
// 0 doesn't need to be wrapped
return num + 'px';
}
return num;
};
/**
* Add events to stop propagation
* @private
*/
InfoBubble.prototype.addEvents_ = function() {
// We want to cancel all the events so they do not go to the map
var events = ['mousedown', 'mousemove', 'mouseover', 'mouseout', 'mouseup',
'mousewheel', 'DOMMouseScroll', 'touchstart', 'touchend', 'touchmove',
'dblclick', 'contextmenu', 'click'];
var bubble = this.bubble_;
this.listeners_ = [];
for (var i = 0, event; event = events[i]; i++) {
this.listeners_.push(
google.maps.event.addDomListener(bubble, event, function(e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
})
);
}
};
/**
* On Adding the InfoBubble to a map
* Implementing the OverlayView interface
*/
InfoBubble.prototype.onAdd = function() {
if (!this.bubble_) {
this.buildDom_();
}
this.addEvents_();
var panes = this.getPanes();
if (panes) {
panes.floatPane.appendChild(this.bubble_);
panes.floatShadow.appendChild(this.bubbleShadow_);
}
};
InfoBubble.prototype['onAdd'] = InfoBubble.prototype.onAdd;
/**
* Draw the InfoBubble
* Implementing the OverlayView interface
*/
InfoBubble.prototype.draw = function() {
var projection = this.getProjection();
if (!projection) {
// The map projection is not ready yet so do nothing
return;
}
var latLng = /** @type {google.maps.LatLng} */ (this.get('position'));
if (!latLng) {
this.close();
return;
}
var tabHeight = 0;
if (this.activeTab_) {
tabHeight = this.activeTab_.offsetHeight;
}
var anchorHeight = this.getAnchorHeight_();
var arrowSize = this.getArrowSize_();
var arrowPosition = this.getArrowPosition_();
arrowPosition = arrowPosition / 100;
var pos = projection.fromLatLngToDivPixel(latLng);
var width = this.contentContainer_.offsetWidth;
var height = this.bubble_.offsetHeight;
if (!width) {
return;
}
// Adjust for the height of the info bubble
var top = pos.y - (height + arrowSize);
if (anchorHeight) {
// If there is an anchor then include the height
top -= anchorHeight;
}
var left = pos.x - (width * arrowPosition);
this.bubble_.style['top'] = this.px(top);
this.bubble_.style['left'] = this.px(left);
var shadowStyle = parseInt(this.get('shadowStyle'), 10);
switch (shadowStyle) {
case 1:
// Shadow is behind
this.bubbleShadow_.style['top'] = this.px(top + tabHeight - 1);
this.bubbleShadow_.style['left'] = this.px(left);
this.bubbleShadow_.style['width'] = this.px(width);
this.bubbleShadow_.style['height'] =
this.px(this.contentContainer_.offsetHeight - arrowSize);
break;
case 2:
// Shadow is below
width = width * 0.8;
if (anchorHeight) {
this.bubbleShadow_.style['top'] = this.px(pos.y);
} else {
this.bubbleShadow_.style['top'] = this.px(pos.y + arrowSize);
}
this.bubbleShadow_.style['left'] = this.px(pos.x - width * arrowPosition);
this.bubbleShadow_.style['width'] = this.px(width);
this.bubbleShadow_.style['height'] = this.px(2);
break;
}
};
InfoBubble.prototype['draw'] = InfoBubble.prototype.draw;
/**
* Removing the InfoBubble from a map
*/
InfoBubble.prototype.onRemove = function() {
if (this.bubble_ && this.bubble_.parentNode) {
this.bubble_.parentNode.removeChild(this.bubble_);
}
if (this.bubbleShadow_ && this.bubbleShadow_.parentNode) {
this.bubbleShadow_.parentNode.removeChild(this.bubbleShadow_);
}
for (var i = 0, listener; listener = this.listeners_[i]; i++) {
google.maps.event.removeListener(listener);
}
};
InfoBubble.prototype['onRemove'] = InfoBubble.prototype.onRemove;
/**
* Is the InfoBubble open
*
* @return {boolean} If the InfoBubble is open.
*/
InfoBubble.prototype.isOpen = function() {
return this.isOpen_;
};
InfoBubble.prototype['isOpen'] = InfoBubble.prototype.isOpen;
/**
* Close the InfoBubble
*/
InfoBubble.prototype.close = function() {
if (this.bubble_) {
this.bubble_.style['display'] = 'none';
// Remove the animation so we next time it opens it will animate again
this.bubble_.className =
this.bubble_.className.replace(this.animationName_, '');
}
if (this.bubbleShadow_) {
this.bubbleShadow_.style['display'] = 'none';
this.bubbleShadow_.className =
this.bubbleShadow_.className.replace(this.animationName_, '');
}
this.isOpen_ = false;
};
InfoBubble.prototype['close'] = InfoBubble.prototype.close;
/**
* Open the InfoBubble (asynchronous).
*
* @param {google.maps.Map=} opt_map Optional map to open on.
* @param {google.maps.MVCObject=} opt_anchor Optional anchor to position at.
*/
InfoBubble.prototype.open = function(opt_map, opt_anchor) {
var that = this;
window.setTimeout(function() {
that.open_(opt_map, opt_anchor);
if (_defaultTab !== undefined) {
that.setTabActive(_defaultTab);
}
}, 0);
};
/**
* Open the InfoBubble
* @private
* @param {google.maps.Map=} opt_map Optional map to open on.
* @param {google.maps.MVCObject=} opt_anchor Optional anchor to position at.
*/
InfoBubble.prototype.open_ = function(opt_map, opt_anchor) {
this.updateContent_();
if (opt_map) {
this.setMap(opt_map);
}
if (opt_anchor) {
this.set('anchor', opt_anchor);
this.bindTo('anchorPoint', opt_anchor);
this.bindTo('position', opt_anchor);
}
// Show the bubble and the show
this.bubble_.style['display'] = this.bubbleShadow_.style['display'] = '';
var animation = !this.get('disableAnimation');
if (animation) {
// Add the animation
this.bubble_.className += ' ' + this.animationName_;
this.bubbleShadow_.className += ' ' + this.animationName_;
}
this.redraw_();
this.isOpen_ = true;
var pan = !this.get('disableAutoPan');
if (pan) {
var that = this;
window.setTimeout(function() {
// Pan into view, done in a time out to make it feel nicer :)
that.panToView();
}, 200);
}
};
InfoBubble.prototype['open'] = InfoBubble.prototype.open;
/**
* Set the position of the InfoBubble
*
* @param {google.maps.LatLng} position The position to set.
*/
InfoBubble.prototype.setPosition = function(position) {
if (position) {
this.set('position', position);
}
};
InfoBubble.prototype['setPosition'] = InfoBubble.prototype.setPosition;
/**
* Returns the position of the InfoBubble
*
* @return {google.maps.LatLng} the position.
*/
InfoBubble.prototype.getPosition = function() {
return /** @type {google.maps.LatLng} */ (this.get('position'));
};
InfoBubble.prototype['getPosition'] = InfoBubble.prototype.getPosition;
/**
* position changed MVC callback
*/
InfoBubble.prototype.position_changed = function() {
this.draw();
};
InfoBubble.prototype['position_changed'] =
InfoBubble.prototype.position_changed;
/**
* Pan the InfoBubble into view
*/
InfoBubble.prototype.panToView = function() {
var projection = this.getProjection();
if (!projection) {
// The map projection is not ready yet so do nothing
return;
}
if (!this.bubble_) {
// No Bubble yet so do nothing
return;
}
var anchorHeight = this.getAnchorHeight_();
var height = this.bubble_.offsetHeight + anchorHeight;
var map = this.get('map');
var mapDiv = map.getDiv();
var mapHeight = mapDiv.offsetHeight;
var latLng = this.getPosition();
var centerPos = projection.fromLatLngToContainerPixel(map.getCenter());
var pos = projection.fromLatLngToContainerPixel(latLng);
// Find out how much space at the top is free
var spaceTop = centerPos.y - height;
// Fine out how much space at the bottom is free
var spaceBottom = mapHeight - centerPos.y;
var needsTop = spaceTop < 0;
var deltaY = 0;
if (needsTop) {
spaceTop *= -1;
deltaY = (spaceTop + spaceBottom) / 2;
}
pos.y -= deltaY;
latLng = projection.fromContainerPixelToLatLng(pos);
if (map.getCenter() != latLng) {
map.panTo(latLng);
}
};
InfoBubble.prototype['panToView'] = InfoBubble.prototype.panToView;
/**
* Converts a HTML string to a document fragment.
*
* @param {string} htmlString The HTML string to convert.
* @return {Node} A HTML document fragment.
* @private
*/
InfoBubble.prototype.htmlToDocumentFragment_ = function(htmlString) {
htmlString = htmlString.replace(/^\s*([\S\s]*)\b\s*$/, '$1');
var tempDiv = document.createElement('DIV');
tempDiv.innerHTML = htmlString;
if (tempDiv.childNodes.length == 1) {
return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild));
} else {
var fragment = document.createDocumentFragment();
while (tempDiv.firstChild) {
fragment.appendChild(tempDiv.firstChild);
}
return fragment;
}
};
/**
* Removes all children from the node.
*
* @param {Node} node The node to remove all children from.
* @private
*/
InfoBubble.prototype.removeChildren_ = function(node) {
if (!node) {
return;
}
var child;
while (child = node.firstChild) {
node.removeChild(child);
}
};
/**
* Sets the content of the infobubble.
*
* @param {string|Node} content The content to set.
*/
InfoBubble.prototype.setContent = function(content) {
this.set('content', content);
};
InfoBubble.prototype['setContent'] = InfoBubble.prototype.setContent;
/**
* Get the content of the infobubble.
*
* @return {string|Node} The marker content.
*/
InfoBubble.prototype.getContent = function() {
return /** @type {Node|string} */ (this.get('content'));
};
InfoBubble.prototype['getContent'] = InfoBubble.prototype.getContent;
/**
* Sets the marker content and adds loading events to images
*/
InfoBubble.prototype.updateContent_ = function() {
if (!this.content_) {
// The Content area doesnt exist.
return;
}
this.removeChildren_(this.content_);
var content = this.getContent();
if (content) {
if (typeof content == 'string') {
content = this.htmlToDocumentFragment_(content);
}
this.content_.appendChild(content);
var that = this;
var images = this.content_.getElementsByTagName('IMG');
for (var i = 0, image; image = images[i]; i++) {
// Because we don't know the size of an image till it loads, add a
// listener to the image load so the marker can resize and reposition
// itself to be the correct height.
google.maps.event.addDomListener(image, 'load', function() {
that.imageLoaded_();
});
}
google.maps.event.trigger(this, 'domready');
}
this.redraw_();
};
/**
* Image loaded
* @private
*/
InfoBubble.prototype.imageLoaded_ = function() {
var pan = !this.get('disableAutoPan');
this.redraw_();
if (pan && (this.tabs_.length == 0 || this.activeTab_.index == 0)) {
this.panToView();
}
};
/**
* Updates the styles of the tabs
* @private
*/
InfoBubble.prototype.updateTabStyles_ = function() {
if (this.tabs_ && this.tabs_.length) {
for (var i = 0, tab; tab = this.tabs_[i]; i++) {
this.setTabStyle_(tab.tab);
}
this.activeTab_.style['zIndex'] = this.baseZIndex_;
var borderWidth = this.getBorderWidth_();
var padding = this.getPadding_() / 2;
this.activeTab_.style['borderBottomWidth'] = 0;
this.activeTab_.style['paddingBottom'] = this.px(padding + borderWidth);
}
};
/**
* Sets the style of a tab
* @private
* @param {Element} tab The tab to style.
*/
InfoBubble.prototype.setTabStyle_ = function(tab) {
var backgroundColor = this.get('backgroundColor');
var borderColor = this.get('borderColor');
var borderRadius = this.getBorderRadius_();
var borderWidth = this.getBorderWidth_();
var padding = this.getPadding_();
var marginRight = this.px(-(Math.max(padding, borderRadius)));
var borderRadiusPx = this.px(borderRadius);
var index = this.baseZIndex_;
if (tab.index) {
index -= tab.index;
}
// The styles for the tab
var styles = {
'cssFloat': 'left',
'position': 'relative',
'cursor': 'pointer',
'backgroundColor': backgroundColor,
'border': this.px(borderWidth) + ' solid ' + borderColor,
'padding': this.px(padding / 2) + ' ' + this.px(padding),
'marginRight': marginRight,
'whiteSpace': 'nowrap',
'borderRadiusTopLeft': borderRadiusPx,
'MozBorderRadiusTopleft': borderRadiusPx,
'webkitBorderTopLeftRadius': borderRadiusPx,
'borderRadiusTopRight': borderRadiusPx,
'MozBorderRadiusTopright': borderRadiusPx,
'webkitBorderTopRightRadius': borderRadiusPx,
'zIndex': index,
'display': 'inline'
};
for (var style in styles) {
tab.style[style] = styles[style];
}
var className = this.get('tabClassName');
if (className != undefined) {
tab.className += ' ' + className;
}
};
/**
* Add user actions to a tab
* @private
* @param {Object} tab The tab to add the actions to.
*/
InfoBubble.prototype.addTabActions_ = function(tab) {
var that = this;
tab.listener_ = google.maps.event.addDomListener(tab, 'click', function() {
that.setTabActive_(this);
});
};
/**
* Set a tab at a index to be active
*
* @param {number} index The index of the tab.
*/
InfoBubble.prototype.setTabActive = function(index) {
var tab = this.tabs_[index - 1];
if (tab) {
this.setTabActive_(tab.tab);
}
};
InfoBubble.prototype['setTabActive'] = InfoBubble.prototype.setTabActive;
/**
* Set a tab to be active
* @private
* @param {Object} tab The tab to set active.
*/
InfoBubble.prototype.setTabActive_ = function(tab) {
if (!tab) {
this.setContent('');
this.updateContent_();
return;
}
var padding = this.getPadding_() / 2;
var borderWidth = this.getBorderWidth_();
if (this.activeTab_) {
var activeTab = this.activeTab_;
activeTab.style['zIndex'] = this.baseZIndex_ - activeTab.index;
activeTab.style['paddingBottom'] = this.px(padding);
activeTab.style['borderBottomWidth'] = this.px(borderWidth);
}
tab.style['zIndex'] = this.baseZIndex_;
tab.style['borderBottomWidth'] = 0;
tab.style['marginBottomWidth'] = '-10px';
tab.style['paddingBottom'] = this.px(padding + borderWidth);
this.setContent(this.tabs_[tab.index].content);
this.updateContent_();
this.activeTab_ = tab;
this.redraw_();
};
/**
* Set the max width of the InfoBubble
*
* @param {number} width The max width.
*/
InfoBubble.prototype.setMaxWidth = function(width) {
this.set('maxWidth', width);
};
InfoBubble.prototype['setMaxWidth'] = InfoBubble.prototype.setMaxWidth;
/**
* maxWidth changed MVC callback
*/
InfoBubble.prototype.maxWidth_changed = function() {
this.redraw_();
};
InfoBubble.prototype['maxWidth_changed'] =
InfoBubble.prototype.maxWidth_changed;
/**
* Set the max height of the InfoBubble
*
* @param {number} height The max height.
*/
InfoBubble.prototype.setMaxHeight = function(height) {
this.set('maxHeight', height);
};
InfoBubble.prototype['setMaxHeight'] = InfoBubble.prototype.setMaxHeight;
/**
* maxHeight changed MVC callback
*/
InfoBubble.prototype.maxHeight_changed = function() {
this.redraw_();
};
InfoBubble.prototype['maxHeight_changed'] =
InfoBubble.prototype.maxHeight_changed;
/**
* Set the min width of the InfoBubble
*
* @param {number} width The min width.
*/
InfoBubble.prototype.setMinWidth = function(width) {
this.set('minWidth', width);
};
InfoBubble.prototype['setMinWidth'] = InfoBubble.prototype.setMinWidth;
/**
* minWidth changed MVC callback
*/
InfoBubble.prototype.minWidth_changed = function() {
this.redraw_();
};
InfoBubble.prototype['minWidth_changed'] =
InfoBubble.prototype.minWidth_changed;
/**
* Set the min height of the InfoBubble
*
* @param {number} height The min height.
*/
InfoBubble.prototype.setMinHeight = function(height) {
this.set('minHeight', height);
};
InfoBubble.prototype['setMinHeight'] = InfoBubble.prototype.setMinHeight;
/**
* minHeight changed MVC callback
*/
InfoBubble.prototype.minHeight_changed = function() {
this.redraw_();
};
InfoBubble.prototype['minHeight_changed'] =
InfoBubble.prototype.minHeight_changed;
/**
* Add a tab
*
* @param {string} label The label of the tab.
* @param {string|Element} content The content of the tab.
*/
InfoBubble.prototype.addTab = function(label, content) {
var tab = document.createElement('DIV');
tab.innerHTML = label;
this.setTabStyle_(tab);
this.addTabActions_(tab);
this.tabsContainer_.appendChild(tab);
this.tabs_.push({
label: label,
content: content,
tab: tab
});
tab.index = this.tabs_.length - 1;
tab.style['zIndex'] = this.baseZIndex_ - tab.index;
if (!this.activeTab_) {
this.setTabActive_(tab);
}
tab.className = tab.className + ' ' + this.animationName_;
this.redraw_();
};
InfoBubble.prototype['addTab'] = InfoBubble.prototype.addTab;
/**
* Update a tab at a speicifc index
*
* @param {number} index The index of the tab.
* @param {?string} opt_label The label to change to.
* @param {?string} opt_content The content to update to.
*/
InfoBubble.prototype.updateTab = function(index, opt_label, opt_content) {
if (!this.tabs_.length || index < 0 || index >= this.tabs_.length) {
return;
}
var tab = this.tabs_[index];
if (opt_label != undefined) {
tab.tab.innerHTML = tab.label = opt_label;
}
if (opt_content != undefined) {
tab.content = opt_content;
}
if (this.activeTab_ == tab.tab) {
this.setContent(tab.content);
this.updateContent_();
}
this.redraw_();
};
InfoBubble.prototype['updateTab'] = InfoBubble.prototype.updateTab;
/**
* Remove a tab at a specific index
*
* @param {number} index The index of the tab to remove.
*/
InfoBubble.prototype.removeTab = function(index) {
if (!this.tabs_.length || index < 0 || index >= this.tabs_.length) {
return;
}
var tab = this.tabs_[index];
tab.tab.parentNode.removeChild(tab.tab);
google.maps.event.removeListener(tab.tab.listener_);
this.tabs_.splice(index, 1);
delete tab;
for (var i = 0, t; t = this.tabs_[i]; i++) {
t.tab.index = i;
}
if (tab.tab == this.activeTab_) {
// Removing the current active tab
if (this.tabs_[index]) {
// Show the tab to the right
this.activeTab_ = this.tabs_[index].tab;
} else if (this.tabs_[index - 1]) {
// Show a tab to the left
this.activeTab_ = this.tabs_[index - 1].tab;
} else {
// No tabs left to sho
this.activeTab_ = undefined;
}
this.setTabActive_(this.activeTab_);
}
this.redraw_();
};
InfoBubble.prototype['removeTab'] = InfoBubble.prototype.removeTab;
/**
* Get the size of an element
* @private
* @param {Node|string} element The element to size.
* @param {number=} opt_maxWidth Optional max width of the element.
* @param {number=} opt_maxHeight Optional max height of the element.
* @return {google.maps.Size} The size of the element.
*/
InfoBubble.prototype.getElementSize_ = function(element, opt_maxWidth,
opt_maxHeight) {
var sizer = document.createElement('DIV');
sizer.style['display'] = 'inline';
sizer.style['position'] = 'absolute';
sizer.style['visibility'] = 'hidden';
if (typeof element == 'string') {
sizer.innerHTML = element;
} else {
sizer.appendChild(element.cloneNode(true));
}
document.body.appendChild(sizer);
var size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);
// If the width is bigger than the max width then set the width and size again
if (opt_maxWidth && size.width > opt_maxWidth) {
sizer.style['width'] = this.px(opt_maxWidth);
size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);
}
// If the height is bigger than the max height then set the height and size
// again
if (opt_maxHeight && size.height > opt_maxHeight) {
sizer.style['height'] = this.px(opt_maxHeight);
size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight);
}
document.body.removeChild(sizer);
delete sizer;
return size;
};
/**
* Redraw the InfoBubble
* @private
*/
InfoBubble.prototype.redraw_ = function() {
this.figureOutSize_();
this.positionCloseButton_();
this.draw();
};
/**
* Figure out the optimum size of the InfoBubble
* @private
*/
InfoBubble.prototype.figureOutSize_ = function() {
var map = this.get('map');
if (!map) {
return;
}
var padding = this.getPadding_();
var borderWidth = this.getBorderWidth_();
var borderRadius = this.getBorderRadius_();
var arrowSize = this.getArrowSize_();
var mapDiv = map.getDiv();
var gutter = arrowSize * 2;
var mapWidth = mapDiv.offsetWidth - gutter;
var mapHeight = mapDiv.offsetHeight - gutter - this.getAnchorHeight_();
var tabHeight = 0;
var width = /** @type {number} */ (this.get('minWidth') || 0);
var height = /** @type {number} */ (this.get('minHeight') || 0);
var maxWidth = /** @type {number} */ (this.get('maxWidth') || 0);
var maxHeight = /** @type {number} */ (this.get('maxHeight') || 0);
maxWidth = Math.min(mapWidth, maxWidth);
maxHeight = Math.min(mapHeight, maxHeight);
var tabWidth = 0;
if (this.tabs_.length) {
// If there are tabs then you need to check the size of each tab's content
for (var i = 0, tab; tab = this.tabs_[i]; i++) {
var tabSize = this.getElementSize_(tab.tab, maxWidth, maxHeight);
var contentSize = this.getElementSize_(tab.content, maxWidth, maxHeight);
if (width < tabSize.width) {
width = tabSize.width;
}
// Add up all the tab widths because they might end up being wider than
// the content
tabWidth += tabSize.width;
if (height < tabSize.height) {
height = tabSize.height;
}
if (tabSize.height > tabHeight) {
tabHeight = tabSize.height;
}
if (width < contentSize.width) {
width = contentSize.width;
}
if (height < contentSize.height) {
height = contentSize.height;
}
}
} else {
var content = /** @type {string|Node} */ (this.get('content'));
if (typeof content == 'string') {
content = this.htmlToDocumentFragment_(content);
}
if (content) {
var contentSize = this.getElementSize_(content, maxWidth, maxHeight);
if (width < contentSize.width) {
width = contentSize.width;
}
if (height < contentSize.height) {
height = contentSize.height;
}
}
}
if (maxWidth) {
width = Math.min(width, maxWidth);
}
if (maxHeight) {
height = Math.min(height, maxHeight);
}
width = Math.max(width, tabWidth);
if (width == tabWidth) {
width = width + 2 * padding;
}
arrowSize = arrowSize * 2;
width = Math.max(width, arrowSize);
// Maybe add this as a option so they can go bigger than the map if the user
// wants
if (width > mapWidth) {
width = mapWidth;
}
if (height > mapHeight) {
height = mapHeight - tabHeight;
}
if (this.tabsContainer_) {
this.tabHeight_ = tabHeight;
this.tabsContainer_.style['width'] = this.px(tabWidth);
}
this.contentContainer_.style['width'] = this.px(width);
this.contentContainer_.style['height'] = this.px(height);
};
/**
* Get the height of the anchor
*
* This function is a hack for now and doesn't really work that good, need to
* wait for pixelBounds to be correctly exposed.
* @private
* @return {number} The height of the anchor.
*/
InfoBubble.prototype.getAnchorHeight_ = function() {
var anchor = this.get('anchor');
if (anchor) {
var anchorPoint = /** @type google.maps.Point */(this.get('anchorPoint'));
if (anchorPoint) {
return -1 * anchorPoint.y;
}
}
return 0;
};
InfoBubble.prototype.anchorPoint_changed = function() {
this.draw();
};
InfoBubble.prototype['anchorPoint_changed'] = InfoBubble.prototype.anchorPoint_changed;
/**
* Position the close button in the right spot.
* @private
*/
InfoBubble.prototype.positionCloseButton_ = function() {
var br = this.getBorderRadius_();
var bw = this.getBorderWidth_();
var right = 2;
var top = 2;
if (this.tabs_.length && this.tabHeight_) {
top += this.tabHeight_;
}
top += bw;
right += bw;
var c = this.contentContainer_;
if (c && c.clientHeight < c.scrollHeight) {
// If there are scrollbars then move the cross in so it is not over
// scrollbar
right += 15;
}
this.close_.style['right'] = this.px(right);
this.close_.style['top'] = this.px(top);
};
| JavaScript |
var showPastEvents = false;
var sinceDate = 0;
var myUser;
var myName;
///////////////////////////////////////
////// General Purpose Functions //////
///////////////////////////////////////
//initiazlie myName and myUser
function getMe() {
$.get(
'/'+context+'/resources/users/me'
).success(function(data){
myName = data.name;
myUser = data.username;
$('#welcome').html("Welcome "+myName);
initialize();
}).error(function(data){
//alert ("Can't retrieve your name! "+data.responseText);
$.cookie("kuki", null);
window.location.replace('index.html');
});
}
//run the functions
$(document).ready(function() {
getMe();
});
////////////////////////////////////////////////
////// jQuery UI Related Button Functions //////
////////////////////////////////////////////////
// jQuery UI Related Button Functions
$(document).ready(function() {
$("#kml-options").buttonset();
$("#ws-keywords-loading").hide();
$("#ws-location-loading").hide();
$("#location").click(function(){
if( $(this).val() == 'Search for an address...'){
$(this).val('');
}
});
$("#logout_button").button().click(function() {
$.cookie("kuki", null);
window.location.replace('index.html');
});
$('#find-button').button().click(function() {
geocode();
});
$('#time').datetimepicker();
$('#sincedate').datepicker();
$( "#show-past-events" ).button().click(function() {
if ($(this).is(':checked')) {
showPastEvents = true;
google.maps.event.trigger(map, "idle");
addMine();
} else {
showPastEvents = false;
google.maps.event.trigger(map, "idle");
addMine();
}
});
$("#set-since").button().click(function(event) {
var since = $("#sincedate");
var sinceTime = since.val();
var tLong = Date.parse(sinceTime,"MM/dd/yyyy HH:MM");
sinceDate = tLong;
google.maps.event.trigger(map, "idle");
addMine();
alert("Since date has been set to "+sinceTime);
});
$("#since-reset").button().click(function(event) {
sinceDate = 0;
$("#sincedate").val("");
google.maps.event.trigger(map, "idle");
addMine();
alert("Since date has been reset");
});
$("#multiaccordion").addClass("ui-accordion ui-widget ui-helper-reset ui-accordion-icons")
.find("h3")
.addClass("ui-accordion-header ui-helper-reset ui-corner-bottom ui-corner-top ui-state-default")
.hover(function() { $(this).toggleClass("ui-state-hover"); })
.prepend('<span class="ui-icon ui-icon-triangle-1-e"/>')
.click(function() {
$(this).toggleClass("ui-accordion-header-active").toggleClass("ui-state-active")
.toggleClass("ui-state-default").toggleClass("ui-corner-bottom")
.find("> .ui-icon").toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-s")
.end().next().slideToggle().toggleClass("ui-accordion-content-active");
return false;
})
.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").hide();
$("#clear-search-results").button().click(function() {
clearSearchResults();
alert("All search results cleared away!");
});
$("#export-xml-button").button().click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = '/'+context+'/resources/messages/xml?noEvents=false';
});
$("#kml-button").button().click(function(e) {
e.preventDefault(); //stop the browser from following
var msg = $("#messages-only");
var evt = $("#events-only");
var path = $("#path");
if (msg.is(":checked")) {
window.location.href = '/'+context+'/resources/messages/kml';
}
if (evt.is(":checked")) {
window.location.href = '/'+context+'/resources/events/kml';
}
if (path.is(":checked")) {
window.location.href = '/'+context+'/resources/messages/allPath';
}
});
$( "#create-msg" ).button().click(function() {
$( "#msg-form" ).dialog( "open" );
});
$( "#create-event" ).button().click(function() {
var now = new Date();
var nowMin = now.getMinutes();
now.setMinutes(nowMin+5);
$("#time").datepicker("setDate", now);
$( "#event-form" ).dialog( "open" );
});
$( "#delete-me" ).button().click(function() {
$( "#delete-me-form" ).dialog( "open" );
});
$( "#ws-keywords-search" ).button().click(function() {
$( "#ws-keywords-form" ).dialog( "open" );
});
$( "#ws-location-search" ).button().click(function() {
$( "#ws-location-form" ).dialog( "open" );
});
$( "#show-users" ).button().click(function() {
$.get('/'+context+'/resources/users'
).success(function(data,status,result) {
var users_html = "";
var count = 1;
$.each(data, function(index,user) {
users_html += '<p>'+count+'. '+user.name+' ('+user.username+')</p>';
count += 1;
});
document.getElementById("users").innerHTML = users_html;
$( "#users-form" ).dialog( "open" );
}).error(function(data) {
alert("Can't retrieve site's users! "+data.responseText);
});
});
});
//////////////////////////////////////////
////// Message UI Related Functions //////
//////////////////////////////////////////
//create new msg form
$(function() {
var content = $( "#content" );
$( "#msg-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Post": function() {
//get address
var addr = 'Not Available';
if(currentReverseGeocodeResponse) {
if(currentReverseGeocodeResponse.length == 0) {
addr = 'Not Available';
} else {
addr = currentReverseGeocodeResponse[0].formatted_address;
}
}
var msg = content.val();
$.post(
'/'+context+'/resources/messages',
JSON.stringify({content: msg, location: {lat: map.getCenter().lat(), long: map.getCenter().lng(), address: addr}})
).success(function(data, status, response){
addMsgAtCenter(response.getResponseHeader("Location"));
}).error(function(data){
alert ("Can't post! "+data.responseText);
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
});
//////////////////////////////////////////
////// Event UI Related Functions //////
//////////////////////////////////////////
function isNumber(n) {
return n.match(/^\d+$/);
}
//create new event form
$(function() {
var info = $( "#info" ),
capacity = $( "#capacity" ),
time = $( "#time" );
$( "#event-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create Event": function() {
var information = info.val();
var cap = capacity.val();
if (cap === "" || !isNumber(cap)) {
alert("Please insert a valid number in capacity");
return;
}
var t = time.val();
var tLong = Date.parse(t,"MM/dd/yyyy HH:MM");
//get address
var addr = '';
if(currentReverseGeocodeResponse) {
if(currentReverseGeocodeResponse.length == 0) {
addr = 'Not Available';
} else {
addr = currentReverseGeocodeResponse[0].formatted_address;
}
}
$.post(
'/'+context+'/resources/events',
JSON.stringify({content: information, location: {lat: map.getCenter().lat(), long: map.getCenter().lng(), address: addr}, capacity: parseInt(cap), time: tLong})
).success(function(data, status, response){
addEventAtCenter(response.getResponseHeader("Location"));
alert("Event created successfuly!");
}).error(function(data){
alert ("Can't create event! "+data.responseText);
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
});
//////////////////////////////////////////
////// Account UI Related Functions //////
//////////////////////////////////////////
//delete my account form
$(function() {
var pass = $( "#password" );
$( "#delete-me-form" ).dialog({
autoOpen: false,
height: 240,
modal: true,
buttons: {
"Delete My Account": function() {
var p = pass.val();
$.post(
'/'+context+'/resources/users/'+myUser+'/unregister',
JSON.stringify({password: p})
).success(function(){
alert("Your account has been deleted successfully!");
$.cookie("kuki", null);
window.location.replace('index.html');
}).error(function(data){
alert ("Can't delete your account! "+data.responseText);
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
});
//see all users
$(function() {
$( "#users-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Close": function() {
$( this ).dialog( "close" );
},
},
close: function() {
document.getElementById("users").innerHTML = "";
}
});
});
//////////////////////////////////////////////
////// WebService UI Related Functions //////
//////////////////////////////////////////////
// WS Keywords Search
$(function() {
var keywords = $( "#keywords" );
$( "#ws-keywords-form" ).dialog({
autoOpen: false,
height: 240,
modal: true,
buttons: {
"Search": function() {
var keywordsString = keywords.val();
var keywordsArray = keywordsString.split(/;\s*/g);
$( "#ws-keywords-search" ).hide();
$("#ws-keywords-loading").show();
$.post(
'/'+context+'/resources/ws/keywords', JSON.stringify(keywordsArray)
).success(function(data,status,respone){
$("#ws-keywords-loading").hide();
$( "#ws-keywords-search" ).show();
addSearchResults(data,"Keywords");
}).error(function(data){
$("#ws-keywords-loading").hide();
$( "#ws-keywords-search" ).show();
alert ("Unable to perform WS search! "+data.responseText);
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
});
// WS Location Search
$(function() {
var radius = $( "#radius" );
$( "#ws-location-form" ).dialog({
autoOpen: false,
height: 240,
modal: true,
buttons: {
"Search": function() {
var r = radius.val();
var center = map.getCenter();
var lat = center.lat();
var lng = center.lng();
$( "#ws-location-search" ).hide();
$("#ws-location-loading").show();
$.post(
'/'+context+'/resources/ws/local',
JSON.stringify({locationX: lng, locationY: lat, distance: parseFloat(r)})
).success(function(data,status,respone){
$("#ws-location-loading").hide();
$( "#ws-location-search" ).show();
addSearchResults(data,"Location");
}).error(function(data){
$("#ws-location-loading").hide();
$( "#ws-location-search" ).show();
alert ("Unable to perform WS search! "+data.responseText);
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
}); | JavaScript |
//check cookie
if($.cookie('kuki') != null) {
window.location.replace('main.html');
} else {
}
$().ready(function() {
//login button function
$("#login_button").button().click(function() {
var login = $(".topbar_login_container input")[0].value;
var password = $(".topbar_login_container input")[1].value;
if (!login || !password) {
alert ("Please enter username and password");
} else {
$.post('/'+context+'/resources/users/login/' + login,
JSON.stringify({password: password}))
.success(function(data){
$.cookie(data["cookie-name"], data.cookie);
window.location = "main.html";})
.error(function(data){
alert (data.responseText);
});
}
});
//join button
$("#join_button").button();
// validate signup form on keyup and submit
$("#join_form").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 3
},
password: {
required: true,
minlength: 4
},
confirm_password: {
required: true,
minlength: 4,
equalTo: "#password"
}
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 3 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 4 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 4 characters long",
equalTo: "Please enter the same password as above"
}
}
});
// propose username
$("#username").focus(function() {
var firstname = $("#firstname").val();
if(firstname && !this.value) {
this.value = firstname;
}
});
});
//registration function
function join() {
var first = $(".loggedout_join_container input")[0].value;
var last = $(".loggedout_join_container input")[1].value;
var name = first + " " + last;
var username = $(".loggedout_join_container input")[2].value;
var password = $(".loggedout_join_container input")[3].value;
$.post(
'/'+context+'/resources/users/' + username,
JSON.stringify({name: name, password: password})
).success(function(data){
$.post(
'/'+context+'/resources/users/login/' + username,
JSON.stringify({password: password})
).success(function(data){
$.cookie(data["cookie-name"], data.cookie);
window.location = "main.html";
}).error(function(data){
alert("Managed to register, but unable to login! "+data.responseText);
});
}).error(function(data){
alert("Unable to register! "+data.responseText);
});
} | JavaScript |
/*
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/
;(function($) {
$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// start geo_Autocomplete mod
// request handler for google geocoder
} else if (options.geocoder) {
var _query = lastWord(term);
options.geocoder.geocode({'address': _query}, function(_results, _status) {
var parsed = options.parse(_results, _status, _query);
cache.add(term, parsed);
success(term, parsed);
});
// end geo_Autocomplete mod
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery); | JavaScript |
/*
* jQuery geo_autocomplete plugin 2.1.1
*
* Copyright (c) 2010 Bob Hitching
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Requires jQuery UI Autocomplete
*
*/
$.widget( "ui.geo_autocomplete", {
// setup the element as an autocomplete widget with some geo goodness added
_init: function() {
this.options._geocoder = new google.maps.Geocoder; // geocoder object
this.options._cache = {}; // cache of geocoder responses
this.element.autocomplete(this.options);
// _renderItem is used to prevent the widget framework from escaping the HTML required to show the static map thumbnail
this.element.data('autocomplete')._renderItem = function(_ul, _item) {
return $('<li></li>').data('item.autocomplete', _item).append(this.options.getItemHTML(_item)).appendTo(_ul);
};
},
// default values
options: {
geocoder_region: '', // filter to a specific region, e.g. 'Europe'
geocoder_types: 'locality,political,sublocality,neighborhood,country', // array of acceptable location types, see http://code.google.com/apis/maps/documentation/javascript/services.html#GeocodingAddressTypes
geocoder_address: false, // true = use the full formatted address, false = use only the segment that matches the search term
mapwidth: 100, // width of static map thumbnail
mapheight: 100, // height of static map thumbnail
maptype: 'terrain', // see http://code.google.com/apis/maps/documentation/staticmaps/#MapTypes
mapsensor: false, // see http://code.google.com/apis/maps/documentation/staticmaps/#Sensor
minLength: 3, // see http://jqueryui.com/demos/autocomplete/#option-minLength
delay: 300, // see http://jqueryui.com/demos/autocomplete/#option-delay
// callback function to get autocomplete results
source: function(_request, _response) {
if (_request.term in this.options._cache) {
_response(this.options._cache[_request.term]);
} else {
var self = this;
var _address = _request.term + (this.options.geocoder_region ? ', ' + this.options.geocoder_region : '');
this.options._geocoder.geocode({'address': _address}, function(_results, _status) {
var _parsed = [];
if (_results && _status && _status == 'OK') {
var _types = self.options.geocoder_types.split(',');
$.each(_results, function(_key, _result) {
// if this is an acceptable location type with a viewport, it's a good result
if ($.map(_result.types, function(_type) {
return $.inArray(_type, _types) != -1 ? _type : null;
}).length && _result.geometry && _result.geometry.viewport) {
if (self.options.geocoder_address) {
_place = _result.formatted_address;
} else {
// place is first matching segment, or first segment
var _place_parts = _result.formatted_address.split(',');
var _place = _place_parts[0];
$.each(_place_parts, function(_key, _part) {
if (_part.toLowerCase().indexOf(_request.term.toLowerCase()) != -1) {
_place = $.trim(_part);
return false; // break
}
});
}
_parsed.push({
value: _place,
label: _result.formatted_address,
viewport: _result.geometry.viewport
});
}
});
}
self.options._cache[_request.term] = _parsed;
_response(_parsed);
});
}
},
// returns the HTML used for each autocomplete list item
getItemHTML: function(_item) {
var _src = 'http://maps.google.com/maps/api/staticmap?visible=' + _item.viewport.getSouthWest().toUrlValue() + '|' + _item.viewport.getNorthEast().toUrlValue() + '&size=' + this.mapwidth + 'x' + this.mapheight + '&maptype=' + this.maptype + '&sensor=' + (this.mapsensor ? 'true' : 'false');
return '<a><img style="float:left;margin-right:5px;" src="' + _src + '" width="' + this.mapwidth + '" height="' + this.mapheight + '" /> ' + _item.label.replace(/,/gi, ',<br/>') + '<br clear="both" /></a>'
}
}
}); | JavaScript |
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
| JavaScript |
try {
var pageTracker = _gat._getTracker("UA-18761191-1");
pageTracker._trackPageview();
} catch(err) {}
| JavaScript |
// Utilities
var Vector3 = {};
var Matrix44 = {};
Vector3.create = function(x, y, z) {
return {'x':x, 'y':y, 'z':z};
};
Vector3.dot = function (v0, v1) {
return v0.x * v1.x + v0.y * v1.y + v0.z * v1.z;
};
Vector3.cross = function (v, v0, v1) {
v.x = v0.y * v1.z - v0.z * v1.y;
v.y = v0.z * v1.x - v0.x * v1.z;
v.z = v0.x * v1.y - v0.y * v1.x;
};
Vector3.normalize = function (v) {
var l = v.x * v.x + v.y * v.y + v.z * v.z;
if(l > 0.00001) {
l = 1.0 / Math.sqrt(l);
v.x *= l;
v.y *= l;
v.z *= l;
}
};
Vector3.arrayForm = function(v) {
if(v.array) {
v.array[0] = v.x;
v.array[1] = v.y;
v.array[2] = v.z;
}
else {
v.array = new Float32Array([v.x, v.y, v.z]);
}
return v.array;
};
Matrix44.createIdentity = function () {
return new Float32Array([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
};
Matrix44.loadProjection = function (m, aspect, vdeg, near, far) {
var h = near * Math.tan(vdeg * Math.PI / 180.0 * 0.5) * 2.0;
var w = h * aspect;
m[0] = 2.0 * near / w;
m[1] = 0.0;
m[2] = 0.0;
m[3] = 0.0;
m[4] = 0.0;
m[5] = 2.0 * near / h;
m[6] = 0.0;
m[7] = 0.0;
m[8] = 0.0;
m[9] = 0.0;
m[10] = -(far + near) / (far - near);
m[11] = -1.0;
m[12] = 0.0;
m[13] = 0.0;
m[14] = -2.0 * far * near / (far - near);
m[15] = 0.0;
};
Matrix44.loadLookAt = function (m, vpos, vlook, vup) {
var frontv = Vector3.create(vpos.x - vlook.x, vpos.y - vlook.y, vpos.z - vlook.z);
Vector3.normalize(frontv);
var sidev = Vector3.create(1.0, 0.0, 0.0);
Vector3.cross(sidev, vup, frontv);
Vector3.normalize(sidev);
var topv = Vector3.create(1.0, 0.0, 0.0);
Vector3.cross(topv, frontv, sidev);
Vector3.normalize(topv);
m[0] = sidev.x;
m[1] = topv.x;
m[2] = frontv.x;
m[3] = 0.0;
m[4] = sidev.y;
m[5] = topv.y;
m[6] = frontv.y;
m[7] = 0.0;
m[8] = sidev.z;
m[9] = topv.z;
m[10] = frontv.z;
m[11] = 0.0;
m[12] = -(vpos.x * m[0] + vpos.y * m[4] + vpos.z * m[8]);
m[13] = -(vpos.x * m[1] + vpos.y * m[5] + vpos.z * m[9]);
m[14] = -(vpos.x * m[2] + vpos.y * m[6] + vpos.z * m[10]);
m[15] = 1.0;
};
//
var timeInfo = {
'start':0, 'prev':0, // Date
'delta':0, 'elapsed':0 // Number(sec)
};
//
var gl;
var renderSpec = {
'width':0,
'height':0,
'aspect':1,
'array':new Float32Array(3),
'halfWidth':0,
'halfHeight':0,
'halfArray':new Float32Array(3)
// and some render targets. see setViewport()
};
renderSpec.setSize = function(w, h) {
renderSpec.width = w;
renderSpec.height = h;
renderSpec.aspect = renderSpec.width / renderSpec.height;
renderSpec.array[0] = renderSpec.width;
renderSpec.array[1] = renderSpec.height;
renderSpec.array[2] = renderSpec.aspect;
renderSpec.halfWidth = Math.floor(w / 2);
renderSpec.halfHeight = Math.floor(h / 2);
renderSpec.halfArray[0] = renderSpec.halfWidth;
renderSpec.halfArray[1] = renderSpec.halfHeight;
renderSpec.halfArray[2] = renderSpec.halfWidth / renderSpec.halfHeight;
};
function deleteRenderTarget(rt) {
gl.deleteFramebuffer(rt.frameBuffer);
gl.deleteRenderbuffer(rt.renderBuffer);
gl.deleteTexture(rt.texture);
}
function createRenderTarget(w, h) {
var ret = {
'width':w,
'height':h,
'sizeArray':new Float32Array([w, h, w / h]),
'dtxArray':new Float32Array([1.0 / w, 1.0 / h])
};
ret.frameBuffer = gl.createFramebuffer();
ret.renderBuffer = gl.createRenderbuffer();
ret.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, ret.texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.bindFramebuffer(gl.FRAMEBUFFER, ret.frameBuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, ret.texture, 0);
gl.bindRenderbuffer(gl.RENDERBUFFER, ret.renderBuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, w, h);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, ret.renderBuffer);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return ret;
}
function compileShader(shtype, shsrc) {
var retsh = gl.createShader(shtype);
gl.shaderSource(retsh, shsrc);
gl.compileShader(retsh);
if(!gl.getShaderParameter(retsh, gl.COMPILE_STATUS)) {
var errlog = gl.getShaderInfoLog(retsh);
gl.deleteShader(retsh);
console.error(errlog);
return null;
}
return retsh;
}
function createShader(vtxsrc, frgsrc, uniformlist, attrlist) {
var vsh = compileShader(gl.VERTEX_SHADER, vtxsrc);
var fsh = compileShader(gl.FRAGMENT_SHADER, frgsrc);
if(vsh == null || fsh == null) {
return null;
}
var prog = gl.createProgram();
gl.attachShader(prog, vsh);
gl.attachShader(prog, fsh);
gl.deleteShader(vsh);
gl.deleteShader(fsh);
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
var errlog = gl.getProgramInfoLog(prog);
console.error(errlog);
return null;
}
if(uniformlist) {
prog.uniforms = {};
for(var i = 0; i < uniformlist.length; i++) {
prog.uniforms[uniformlist[i]] = gl.getUniformLocation(prog, uniformlist[i]);
}
}
if(attrlist) {
prog.attributes = {};
for(var i = 0; i < attrlist.length; i++) {
var attr = attrlist[i];
prog.attributes[attr] = gl.getAttribLocation(prog, attr);
}
}
return prog;
}
function useShader(prog) {
gl.useProgram(prog);
for(var attr in prog.attributes) {
gl.enableVertexAttribArray(prog.attributes[attr]);;
}
}
function unuseShader(prog) {
for(var attr in prog.attributes) {
gl.disableVertexAttribArray(prog.attributes[attr]);;
}
gl.useProgram(null);
}
/////
var projection = {
'angle':60,
'nearfar':new Float32Array([0.1, 100.0]),
'matrix':Matrix44.createIdentity()
};
var camera = {
'position':Vector3.create(0, 0, 100),
'lookat':Vector3.create(0, 0, 0),
'up':Vector3.create(0, 1, 0),
'dof':Vector3.create(10.0, 4.0, 8.0),
'matrix':Matrix44.createIdentity()
};
var pointFlower = {};
var meshFlower = {};
var sceneStandBy = false;
var BlossomParticle = function () {
this.velocity = new Array(3);
this.rotation = new Array(3);
this.position = new Array(3);
this.euler = new Array(3);
this.size = 1.0;
this.alpha = 1.0;
this.zkey = 0.0;
};
BlossomParticle.prototype.setVelocity = function (vx, vy, vz) {
this.velocity[0] = vx;
this.velocity[1] = vy;
this.velocity[2] = vz;
};
BlossomParticle.prototype.setRotation = function (rx, ry, rz) {
this.rotation[0] = rx;
this.rotation[1] = ry;
this.rotation[2] = rz;
};
BlossomParticle.prototype.setPosition = function (nx, ny, nz) {
this.position[0] = nx;
this.position[1] = ny;
this.position[2] = nz;
};
BlossomParticle.prototype.setEulerAngles = function (rx, ry, rz) {
this.euler[0] = rx;
this.euler[1] = ry;
this.euler[2] = rz;
};
BlossomParticle.prototype.setSize = function (s) {
this.size = s;
};
BlossomParticle.prototype.update = function (dt, et) {
this.position[0] += this.velocity[0] * dt;
this.position[1] += this.velocity[1] * dt;
this.position[2] += this.velocity[2] * dt;
this.euler[0] += this.rotation[0] * dt;
this.euler[1] += this.rotation[1] * dt;
this.euler[2] += this.rotation[2] * dt;
};
function createPointFlowers() {
// get point sizes
var prm = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE);
renderSpec.pointSize = {'min':prm[0], 'max':prm[1]};
var vtxsrc = document.getElementById("sakura_point_vsh").textContent;
var frgsrc = document.getElementById("sakura_point_fsh").textContent;
pointFlower.program = createShader(
vtxsrc, frgsrc,
['uProjection', 'uModelview', 'uResolution', 'uOffset', 'uDOF', 'uFade'],
['aPosition', 'aEuler', 'aMisc']
);
useShader(pointFlower.program);
pointFlower.offset = new Float32Array([0.0, 0.0, 0.0]);
pointFlower.fader = Vector3.create(0.0, 10.0, 0.0);
// paramerters: velocity[3], rotate[3]
pointFlower.numFlowers = 1600;
pointFlower.particles = new Array(pointFlower.numFlowers);
// vertex attributes {position[3], euler_xyz[3], size[1]}
pointFlower.dataArray = new Float32Array(pointFlower.numFlowers * (3 + 3 + 2));
pointFlower.positionArrayOffset = 0;
pointFlower.eulerArrayOffset = pointFlower.numFlowers * 3;
pointFlower.miscArrayOffset = pointFlower.numFlowers * 6;
pointFlower.buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, pointFlower.buffer);
gl.bufferData(gl.ARRAY_BUFFER, pointFlower.dataArray, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
unuseShader(pointFlower.program);
for(var i = 0; i < pointFlower.numFlowers; i++) {
pointFlower.particles[i] = new BlossomParticle();
}
}
function initPointFlowers() {
//area
pointFlower.area = Vector3.create(20.0, 20.0, 20.0);
pointFlower.area.x = pointFlower.area.y * renderSpec.aspect;
pointFlower.fader.x = 10.0; //env fade start
pointFlower.fader.y = pointFlower.area.z; //env fade half
pointFlower.fader.z = 0.1; //near fade start
//particles
var PI2 = Math.PI * 2.0;
var tmpv3 = Vector3.create(0, 0, 0);
var tmpv = 0;
var symmetryrand = function() {return (Math.random() * 2.0 - 1.0);};
for(var i = 0; i < pointFlower.numFlowers; i++) {
var tmpprtcl = pointFlower.particles[i];
//velocity
tmpv3.x = symmetryrand() * 0.3 + 0.8;
tmpv3.y = symmetryrand() * 0.2 - 1.0;
tmpv3.z = symmetryrand() * 0.3 + 0.5;
Vector3.normalize(tmpv3);
tmpv = 2.0 + Math.random() * 1.0;
tmpprtcl.setVelocity(tmpv3.x * tmpv, tmpv3.y * tmpv, tmpv3.z * tmpv);
//rotation
tmpprtcl.setRotation(
symmetryrand() * PI2 * 0.5,
symmetryrand() * PI2 * 0.5,
symmetryrand() * PI2 * 0.5
);
//position
tmpprtcl.setPosition(
symmetryrand() * pointFlower.area.x,
symmetryrand() * pointFlower.area.y,
symmetryrand() * pointFlower.area.z
);
//euler
tmpprtcl.setEulerAngles(
Math.random() * Math.PI * 2.0,
Math.random() * Math.PI * 2.0,
Math.random() * Math.PI * 2.0
);
//size
tmpprtcl.setSize(0.9 + Math.random() * 0.1);
}
}
function renderPointFlowers() {
//update
var PI2 = Math.PI * 2.0;
var limit = [pointFlower.area.x, pointFlower.area.y, pointFlower.area.z];
var repeatPos = function (prt, cmp, limit) {
if(Math.abs(prt.position[cmp]) - prt.size * 0.5 > limit) {
//out of area
if(prt.position[cmp] > 0) {
prt.position[cmp] -= limit * 2.0;
}
else {
prt.position[cmp] += limit * 2.0;
}
}
};
var repeatEuler = function (prt, cmp) {
prt.euler[cmp] = prt.euler[cmp] % PI2;
if(prt.euler[cmp] < 0.0) {
prt.euler[cmp] += PI2;
}
};
for(var i = 0; i < pointFlower.numFlowers; i++) {
var prtcl = pointFlower.particles[i];
prtcl.update(timeInfo.delta, timeInfo.elapsed);
repeatPos(prtcl, 0, pointFlower.area.x);
repeatPos(prtcl, 1, pointFlower.area.y);
repeatPos(prtcl, 2, pointFlower.area.z);
repeatEuler(prtcl, 0);
repeatEuler(prtcl, 1);
repeatEuler(prtcl, 2);
prtcl.alpha = 1.0;//(pointFlower.area.z - prtcl.position[2]) * 0.5;
prtcl.zkey = (camera.matrix[2] * prtcl.position[0]
+ camera.matrix[6] * prtcl.position[1]
+ camera.matrix[10] * prtcl.position[2]
+ camera.matrix[14]);
}
// sort
pointFlower.particles.sort(function(p0, p1){return p0.zkey - p1.zkey;});
// update data
var ipos = pointFlower.positionArrayOffset;
var ieuler = pointFlower.eulerArrayOffset;
var imisc = pointFlower.miscArrayOffset;
for(var i = 0; i < pointFlower.numFlowers; i++) {
var prtcl = pointFlower.particles[i];
pointFlower.dataArray[ipos] = prtcl.position[0];
pointFlower.dataArray[ipos + 1] = prtcl.position[1];
pointFlower.dataArray[ipos + 2] = prtcl.position[2];
ipos += 3;
pointFlower.dataArray[ieuler] = prtcl.euler[0];
pointFlower.dataArray[ieuler + 1] = prtcl.euler[1];
pointFlower.dataArray[ieuler + 2] = prtcl.euler[2];
ieuler += 3;
pointFlower.dataArray[imisc] = prtcl.size;
pointFlower.dataArray[imisc + 1] = prtcl.alpha;
imisc += 2;
}
//draw
gl.enable(gl.BLEND);
//gl.disable(gl.DEPTH_TEST);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
var prog = pointFlower.program;
useShader(prog);
gl.uniformMatrix4fv(prog.uniforms.uProjection, false, projection.matrix);
gl.uniformMatrix4fv(prog.uniforms.uModelview, false, camera.matrix);
gl.uniform3fv(prog.uniforms.uResolution, renderSpec.array);
gl.uniform3fv(prog.uniforms.uDOF, Vector3.arrayForm(camera.dof));
gl.uniform3fv(prog.uniforms.uFade, Vector3.arrayForm(pointFlower.fader));
gl.bindBuffer(gl.ARRAY_BUFFER, pointFlower.buffer);
gl.bufferData(gl.ARRAY_BUFFER, pointFlower.dataArray, gl.DYNAMIC_DRAW);
gl.vertexAttribPointer(prog.attributes.aPosition, 3, gl.FLOAT, false, 0, pointFlower.positionArrayOffset * Float32Array.BYTES_PER_ELEMENT);
gl.vertexAttribPointer(prog.attributes.aEuler, 3, gl.FLOAT, false, 0, pointFlower.eulerArrayOffset * Float32Array.BYTES_PER_ELEMENT);
gl.vertexAttribPointer(prog.attributes.aMisc, 2, gl.FLOAT, false, 0, pointFlower.miscArrayOffset * Float32Array.BYTES_PER_ELEMENT);
// doubler
for(var i = 1; i < 2; i++) {
var zpos = i * -2.0;
pointFlower.offset[0] = pointFlower.area.x * -1.0;
pointFlower.offset[1] = pointFlower.area.y * -1.0;
pointFlower.offset[2] = pointFlower.area.z * zpos;
gl.uniform3fv(prog.uniforms.uOffset, pointFlower.offset);
gl.drawArrays(gl.POINT, 0, pointFlower.numFlowers);
pointFlower.offset[0] = pointFlower.area.x * -1.0;
pointFlower.offset[1] = pointFlower.area.y * 1.0;
pointFlower.offset[2] = pointFlower.area.z * zpos;
gl.uniform3fv(prog.uniforms.uOffset, pointFlower.offset);
gl.drawArrays(gl.POINT, 0, pointFlower.numFlowers);
pointFlower.offset[0] = pointFlower.area.x * 1.0;
pointFlower.offset[1] = pointFlower.area.y * -1.0;
pointFlower.offset[2] = pointFlower.area.z * zpos;
gl.uniform3fv(prog.uniforms.uOffset, pointFlower.offset);
gl.drawArrays(gl.POINT, 0, pointFlower.numFlowers);
pointFlower.offset[0] = pointFlower.area.x * 1.0;
pointFlower.offset[1] = pointFlower.area.y * 1.0;
pointFlower.offset[2] = pointFlower.area.z * zpos;
gl.uniform3fv(prog.uniforms.uOffset, pointFlower.offset);
gl.drawArrays(gl.POINT, 0, pointFlower.numFlowers);
}
//main
pointFlower.offset[0] = 0.0;
pointFlower.offset[1] = 0.0;
pointFlower.offset[2] = 0.0;
gl.uniform3fv(prog.uniforms.uOffset, pointFlower.offset);
gl.drawArrays(gl.POINT, 0, pointFlower.numFlowers);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
unuseShader(prog);
gl.enable(gl.DEPTH_TEST);
gl.disable(gl.BLEND);
}
// effects
//common util
function createEffectProgram(vtxsrc, frgsrc, exunifs, exattrs) {
var ret = {};
var unifs = ['uResolution', 'uSrc', 'uDelta'];
if(exunifs) {
unifs = unifs.concat(exunifs);
}
var attrs = ['aPosition'];
if(exattrs) {
attrs = attrs.concat(exattrs);
}
ret.program = createShader(vtxsrc, frgsrc, unifs, attrs);
useShader(ret.program);
ret.dataArray = new Float32Array([
-1.0, -1.0,
1.0, -1.0,
-1.0, 1.0,
1.0, 1.0
]);
ret.buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, ret.buffer);
gl.bufferData(gl.ARRAY_BUFFER, ret.dataArray, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
unuseShader(ret.program);
return ret;
}
// basic usage
// useEffect(prog, srctex({'texture':texid, 'dtxArray':(f32)[dtx, dty]})); //basic initialize
// gl.uniform**(...); //additional uniforms
// drawEffect()
// unuseEffect(prog)
// TEXTURE0 makes src
function useEffect(fxobj, srctex) {
var prog = fxobj.program;
useShader(prog);
gl.uniform3fv(prog.uniforms.uResolution, renderSpec.array);
if(srctex != null) {
gl.uniform2fv(prog.uniforms.uDelta, srctex.dtxArray);
gl.uniform1i(prog.uniforms.uSrc, 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, srctex.texture);
}
}
function drawEffect(fxobj) {
gl.bindBuffer(gl.ARRAY_BUFFER, fxobj.buffer);
gl.vertexAttribPointer(fxobj.program.attributes.aPosition, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
function unuseEffect(fxobj) {
unuseShader(fxobj.program);
}
var effectLib = {};
function createEffectLib() {
var vtxsrc, frgsrc;
//common
var cmnvtxsrc = document.getElementById("fx_common_vsh").textContent;
//background
frgsrc = document.getElementById("bg_fsh").textContent;
effectLib.sceneBg = createEffectProgram(cmnvtxsrc, frgsrc, ['uTimes'], null);
// make brightpixels buffer
frgsrc = document.getElementById("fx_brightbuf_fsh").textContent;
effectLib.mkBrightBuf = createEffectProgram(cmnvtxsrc, frgsrc, null, null);
// direction blur
frgsrc = document.getElementById("fx_dirblur_r4_fsh").textContent;
effectLib.dirBlur = createEffectProgram(cmnvtxsrc, frgsrc, ['uBlurDir'], null);
//final composite
vtxsrc = document.getElementById("pp_final_vsh").textContent;
frgsrc = document.getElementById("pp_final_fsh").textContent;
effectLib.finalComp = createEffectProgram(vtxsrc, frgsrc, ['uBloom'], null);
}
// background
function createBackground() {
//console.log("create background");
}
function initBackground() {
//console.log("init background");
}
function renderBackground() {
gl.disable(gl.DEPTH_TEST);
useEffect(effectLib.sceneBg, null);
gl.uniform2f(effectLib.sceneBg.program.uniforms.uTimes, timeInfo.elapsed, timeInfo.delta);
drawEffect(effectLib.sceneBg);
unuseEffect(effectLib.sceneBg);
gl.enable(gl.DEPTH_TEST);
}
// post process
var postProcess = {};
function createPostProcess() {
//console.log("create post process");
}
function initPostProcess() {
//console.log("init post process");
}
function renderPostProcess() {
gl.enable(gl.TEXTURE_2D);
gl.disable(gl.DEPTH_TEST);
var bindRT = function (rt, isclear) {
gl.bindFramebuffer(gl.FRAMEBUFFER, rt.frameBuffer);
gl.viewport(0, 0, rt.width, rt.height);
if(isclear) {
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
};
//make bright buff
bindRT(renderSpec.wHalfRT0, true);
useEffect(effectLib.mkBrightBuf, renderSpec.mainRT);
drawEffect(effectLib.mkBrightBuf);
unuseEffect(effectLib.mkBrightBuf);
// make bloom
for(var i = 0; i < 2; i++) {
var p = 1.5 + 1 * i;
var s = 2.0 + 1 * i;
bindRT(renderSpec.wHalfRT1, true);
useEffect(effectLib.dirBlur, renderSpec.wHalfRT0);
gl.uniform4f(effectLib.dirBlur.program.uniforms.uBlurDir, p, 0.0, s, 0.0);
drawEffect(effectLib.dirBlur);
unuseEffect(effectLib.dirBlur);
bindRT(renderSpec.wHalfRT0, true);
useEffect(effectLib.dirBlur, renderSpec.wHalfRT1);
gl.uniform4f(effectLib.dirBlur.program.uniforms.uBlurDir, 0.0, p, 0.0, s);
drawEffect(effectLib.dirBlur);
unuseEffect(effectLib.dirBlur);
}
//display
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, renderSpec.width, renderSpec.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
useEffect(effectLib.finalComp, renderSpec.mainRT);
gl.uniform1i(effectLib.finalComp.program.uniforms.uBloom, 1);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, renderSpec.wHalfRT0.texture);
drawEffect(effectLib.finalComp);
unuseEffect(effectLib.finalComp);
gl.enable(gl.DEPTH_TEST);
}
/////
var SceneEnv = {};
function createScene() {
createEffectLib();
createBackground();
createPointFlowers();
createPostProcess();
sceneStandBy = true;
}
function initScene() {
initBackground();
initPointFlowers();
initPostProcess();
//camera.position.z = 17.320508;
camera.position.z = pointFlower.area.z + projection.nearfar[0];
projection.angle = Math.atan2(pointFlower.area.y, camera.position.z + pointFlower.area.z) * 180.0 / Math.PI * 2.0;
Matrix44.loadProjection(projection.matrix, renderSpec.aspect, projection.angle, projection.nearfar[0], projection.nearfar[1]);
}
function renderScene() {
//draw
Matrix44.loadLookAt(camera.matrix, camera.position, camera.lookat, camera.up);
gl.enable(gl.DEPTH_TEST);
//gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, renderSpec.mainRT.frameBuffer);
gl.viewport(0, 0, renderSpec.mainRT.width, renderSpec.mainRT.height);
gl.clearColor(0.005, 0, 0.05, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
renderBackground();
renderPointFlowers();
renderPostProcess();
}
/////
function onResize(e) {
makeCanvasFullScreen(document.getElementById("sakura"));
setViewports();
if(sceneStandBy) {
initScene();
}
}
function setViewports() {
renderSpec.setSize(gl.canvas.width, gl.canvas.height);
gl.clearColor(0.2, 0.2, 0.5, 1.0);
gl.viewport(0, 0, renderSpec.width, renderSpec.height);
var rtfunc = function (rtname, rtw, rth) {
var rt = renderSpec[rtname];
if(rt) deleteRenderTarget(rt);
renderSpec[rtname] = createRenderTarget(rtw, rth);
};
rtfunc('mainRT', renderSpec.width, renderSpec.height);
rtfunc('wFullRT0', renderSpec.width, renderSpec.height);
rtfunc('wFullRT1', renderSpec.width, renderSpec.height);
rtfunc('wHalfRT0', renderSpec.halfWidth, renderSpec.halfHeight);
rtfunc('wHalfRT1', renderSpec.halfWidth, renderSpec.halfHeight);
}
function render() {
renderScene();
}
var animating = true;
function toggleAnimation(elm) {
animating ^= true;
if(animating) animate();
if(elm) {
elm.innerHTML = animating? "Stop":"Start";
}
}
function stepAnimation() {
if(!animating) animate();
}
function animate() {
var curdate = new Date();
timeInfo.elapsed = (curdate - timeInfo.start) / 1000.0;
timeInfo.delta = (curdate - timeInfo.prev) / 1000.0;
timeInfo.prev = curdate;
if(animating) requestAnimationFrame(animate);
render();
}
function makeCanvasFullScreen(canvas) {
var b = document.body;
var d = document.documentElement;
fullw = Math.max(b.clientWidth , b.scrollWidth, d.scrollWidth, d.clientWidth);
fullh = Math.max(b.clientHeight , b.scrollHeight, d.scrollHeight, d.clientHeight);
canvas.width = fullw;
canvas.height = fullh;
}
window.addEventListener('load', function(e) {
var canvas = document.getElementById("sakura");
try {
makeCanvasFullScreen(canvas);
gl = canvas.getContext('experimental-webgl');
} catch(e) {
alert("WebGL not supported." + e);
console.error(e);
return;
}
window.addEventListener('resize', onResize);
setViewports();
createScene();
initScene();
timeInfo.start = new Date();
timeInfo.prev = timeInfo.start;
animate();
});
//set window.requestAnimationFrame
(function (w, r) {
w['r'+r] = w['r'+r] || w['webkitR'+r] || w['mozR'+r] || w['msR'+r] || w['oR'+r] || function(c){ w.setTimeout(c, 1000 / 60); };
})(window, 'equestAnimationFrame'); | JavaScript |
var menuids=["sidebarmenu1"]; //Enter id(s) of each Side Bar Menu's main UL, separated by commas
var menuids2=["sidebarmenu2"];
function initsidebarmenu(){
try {
for (var i=0; i<menuids.length; i++){
var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
for (var t=0; t<ultags.length; t++){
ultags[t].parentNode.getElementsByTagName("a")[0].className+=" subfolderstyle"
if (ultags[t].parentNode.parentNode.id==menuids[i]) //if this is a first level submenu
ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags[t].style.visibility="visible"
ultags[t].style.display="none"
}
}
} catch (e) {
}
try {
for (var i=0; i<menuids2.length; i++){
var ultags2=document.getElementById(menuids2[i]).getElementsByTagName("ul")
for (var t=0; t<ultags2.length; t++){
ultags2[t].parentNode.getElementsByTagName("span")[0].className+=" subfolderstyle"
if (ultags2[t].parentNode.parentNode.id==menuids2[i]) //if this is a first level submenu
ultags2[t].style.left=ultags2[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags2[t].style.left=ultags2[t-1].getElementsByTagName("span")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags2[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags2[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags2.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags2[t].style.visibility="visible"
ultags2[t].style.display="none"
}
}
} catch (e) {
}
}
if (window.addEventListener) window.addEventListener("load", initsidebarmenu, false)
else if (window.attachEvent) window.attachEvent("onload", initsidebarmenu)
| JavaScript |
var menuids=["sidebarmenu1"]; //Enter id(s) of each Side Bar Menu's main UL, separated by commas
var menuids2=["sidebarmenu2"];
function initsidebarmenu(){
try {
for (var i=0; i<menuids.length; i++){
var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
for (var t=0; t<ultags.length; t++){
ultags[t].parentNode.getElementsByTagName("a")[0].className+=" subfolderstyle"
if (ultags[t].parentNode.parentNode.id==menuids[i]) //if this is a first level submenu
ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags[t].style.visibility="visible"
ultags[t].style.display="none"
}
}
} catch (e) {
}
try {
for (var i=0; i<menuids2.length; i++){
var ultags2=document.getElementById(menuids2[i]).getElementsByTagName("ul")
for (var t=0; t<ultags2.length; t++){
ultags2[t].parentNode.getElementsByTagName("span")[0].className+=" subfolderstyle"
if (ultags2[t].parentNode.parentNode.id==menuids2[i]) //if this is a first level submenu
ultags2[t].style.left=ultags2[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags2[t].style.left=ultags2[t-1].getElementsByTagName("span")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags2[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags2[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags2.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags2[t].style.visibility="visible"
ultags2[t].style.display="none"
}
}
} catch (e) {
}
}
if (window.addEventListener) window.addEventListener("load", initsidebarmenu, false)
else if (window.attachEvent) window.attachEvent("onload", initsidebarmenu)
| JavaScript |
var menuids=["sidebarmenu1"]; //Enter id(s) of each Side Bar Menu's main UL, separated by commas
var menuids2=["sidebarmenu2"];
function initsidebarmenu(){
try {
for (var i=0; i<menuids.length; i++){
var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
for (var t=0; t<ultags.length; t++){
ultags[t].parentNode.getElementsByTagName("a")[0].className+=" subfolderstyle"
if (ultags[t].parentNode.parentNode.id==menuids[i]) //if this is a first level submenu
ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags[t].style.visibility="visible"
ultags[t].style.display="none"
}
}
} catch (e) {
}
try {
for (var i=0; i<menuids2.length; i++){
var ultags2=document.getElementById(menuids2[i]).getElementsByTagName("ul")
for (var t=0; t<ultags2.length; t++){
ultags2[t].parentNode.getElementsByTagName("span")[0].className+=" subfolderstyle"
if (ultags2[t].parentNode.parentNode.id==menuids2[i]) //if this is a first level submenu
ultags2[t].style.left=ultags2[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags2[t].style.left=ultags2[t-1].getElementsByTagName("span")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags2[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags2[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags2.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags2[t].style.visibility="visible"
ultags2[t].style.display="none"
}
}
} catch (e) {
}
}
if (window.addEventListener) window.addEventListener("load", initsidebarmenu, false)
else if (window.attachEvent) window.attachEvent("onload", initsidebarmenu)
| JavaScript |
//Drop Down Tabs Menu- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Created: May 16th, 07'
var tabdropdown={
disappeardelay: 200, //set delay in miliseconds before menu disappears onmouseout
disablemenuclick: false, //when user clicks on a menu item with a drop down menu, disable menu item's link?
enableiframeshim: 1, //1 or 0, for true or false
//No need to edit beyond here////////////////////////
dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, previousmenuitem:null,
currentpageurl: window.location.href.replace("http://"+window.location.hostname, "").replace(/^\//, ""), //get current page url (minus hostname, ie: http://www.dynamicdrive.com/)
getposOffset:function(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
},
showhide:function(obj, e, obj2){ //obj refers to drop down menu, obj2 refers to tab menu item mouse is currently over
if (this.ie || this.firefox)
this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
if (obj2.parentNode.className.indexOf("default")==-1) //if tab isn't a default selected one
obj2.parentNode.className="selected"
obj.visibility="visible"
}
else if (e.type=="click")
obj.visibility="hidden"
},
iecompattest:function(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
},
clearbrowseredge:function(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=this.ie && !window.opera? this.standardbody.scrollLeft+this.standardbody.clientWidth-15 : window.pageXOffset+window.innerWidth-15
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure) //move menu to the left?
edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=this.ie && !window.opera? this.standardbody.scrollTop : window.pageYOffset
var windowedge=this.ie && !window.opera? this.standardbody.scrollTop+this.standardbody.clientHeight-15 : window.pageYOffset+window.innerHeight-18
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
}
this.dropmenuobj.firstlink.style.borderTopWidth=(edgeoffset==0)? 0 : "1px" //Add 1px top border to menu if dropping up
}
return edgeoffset
},
dropit:function(obj, e, dropmenuID){
if (this.dropmenuobj!=null){ //hide previous menu
this.dropmenuobj.style.visibility="hidden" //hide menu
if (this.previousmenuitem!=null && this.previousmenuitem!=obj){
if (this.previousmenuitem.parentNode.className.indexOf("default")==-1) //If the tab isn't a default selected one
this.previousmenuitem.parentNode.className=""
}
}
this.clearhidemenu()
if (this.ie||this.firefox){
obj.onmouseout=function(){tabdropdown.delayhidemenu(obj)}
obj.onclick=function(){return !tabdropdown.disablemenuclick} //disable main menu item link onclick?
this.dropmenuobj=document.getElementById(dropmenuID)
this.dropmenuobj.onmouseover=function(){tabdropdown.clearhidemenu()}
this.dropmenuobj.onmouseout=function(e){tabdropdown.dynamichide(e, obj)}
this.dropmenuobj.onclick=function(){tabdropdown.delayhidemenu(obj)}
this.showhide(this.dropmenuobj.style, e, obj)
this.dropmenuobj.x=this.getposOffset(obj, "left")
this.dropmenuobj.y=this.getposOffset(obj, "top")
this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
this.previousmenuitem=obj //remember main menu item mouse moved out from (and into current menu item)
this.positionshim() //call iframe shim function
}
},
contains_firefox:function(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
},
dynamichide:function(e, obj2){ //obj2 refers to tab menu item mouse is currently over
var evtobj=window.event? window.event : e
if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
this.delayhidemenu(obj2)
else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
this.delayhidemenu(obj2)
},
delayhidemenu:function(obj2){
this.delayhide=setTimeout(function(){tabdropdown.dropmenuobj.style.visibility='hidden'; if (obj2.parentNode.className.indexOf('default')==-1) obj2.parentNode.className=''},this.disappeardelay) //hide menu
},
clearhidemenu:function(){
if (this.delayhide!="undefined")
clearTimeout(this.delayhide)
},
positionshim:function(){ //display iframe shim function
if (this.enableiframeshim && typeof this.shimobject!="undefined"){
if (this.dropmenuobj.style.visibility=="visible"){
this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px"
this.shimobject.style.height=this.dropmenuobj.offsetHeight+"px"
this.shimobject.style.left=this.dropmenuobj.style.left
this.shimobject.style.top=this.dropmenuobj.style.top
}
this.shimobject.style.display=(this.dropmenuobj.style.visibility=="visible")? "block" : "none"
}
},
hideshim:function(){
if (this.enableiframeshim && typeof this.shimobject!="undefined")
this.shimobject.style.display='none'
},
isSelected:function(menuurl){
var menuurl=menuurl.replace("http://"+menuurl.hostname, "").replace(/^\//, "")
return (tabdropdown.currentpageurl==menuurl)
},
init:function(menuid, dselected){
this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
var menuitems=document.getElementById(menuid).getElementsByTagName("a")
for (var i=0; i<menuitems.length; i++){
if (menuitems[i].getAttribute("rel")){
var relvalue=menuitems[i].getAttribute("rel")
document.getElementById(relvalue).firstlink=document.getElementById(relvalue).getElementsByTagName("a")[0]
menuitems[i].onmouseover=function(e){
var event=typeof e!="undefined"? e : window.event
tabdropdown.dropit(this, event, this.getAttribute("rel"))
}
}
if (dselected=="auto" && typeof setalready=="undefined" && this.isSelected(menuitems[i].href)){
menuitems[i].parentNode.className+=" selected default"
var setalready=true
}
else if (parseInt(dselected)==i)
menuitems[i].parentNode.className+=" selected default"
}
}
} | JavaScript |
var menuids=["110navigation"]; //Enter id(s) of each Side Bar Menu's main UL, separated by commas
function initsidebarmenu(){
try {
for (var i=0; i<menuids.length; i++){
var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
for (var t=0; t<ultags.length; t++){
ultags[t].parentNode.getElementsByTagName("a")[0].className+=" subfolderstyle"
if (ultags[t].parentNode.parentNode.id==menuids[i]) //if this is a first level submenu
ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags[t].style.visibility="visible"
ultags[t].style.display="none"
}
}
} catch (e) {
}
}
if (window.addEventListener) window.addEventListener("load", initsidebarmenu, false)
else if (window.attachEvent) window.attachEvent("onload", initsidebarmenu)
| JavaScript |
var menuids=["sidebarmenu1"]; //Enter id(s) of each Side Bar Menu's main UL, separated by commas
var menuids2=["sidebarmenu2"];
function initsidebarmenu(){
try {
for (var i=0; i<menuids.length; i++){
var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
for (var t=0; t<ultags.length; t++){
ultags[t].parentNode.getElementsByTagName("a")[0].className+=" subfolderstyle"
if (ultags[t].parentNode.parentNode.id==menuids[i]) //if this is a first level submenu
ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags[t].style.visibility="visible"
ultags[t].style.display="none"
}
}
} catch (e) {
}
try {
for (var i=0; i<menuids2.length; i++){
var ultags2=document.getElementById(menuids2[i]).getElementsByTagName("ul")
for (var t=0; t<ultags2.length; t++){
ultags2[t].parentNode.getElementsByTagName("span")[0].className+=" subfolderstyle"
if (ultags2[t].parentNode.parentNode.id==menuids2[i]) //if this is a first level submenu
ultags2[t].style.left=ultags2[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item
else //else if this is a sub level submenu (ul)
ultags2[t].style.left=ultags2[t-1].getElementsByTagName("span")[0].offsetWidth+"px" //position menu to the right of menu item that activated it
ultags2[t].parentNode.onmouseover=function(){
this.getElementsByTagName("ul")[0].style.display="block"
}
ultags2[t].parentNode.onmouseout=function(){
this.getElementsByTagName("ul")[0].style.display="none"
}
}
for (var t=ultags2.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
ultags2[t].style.visibility="visible"
ultags2[t].style.display="none"
}
}
} catch (e) {
}
}
if (window.addEventListener) window.addEventListener("load", initsidebarmenu, false)
else if (window.attachEvent) window.attachEvent("onload", initsidebarmenu)
| JavaScript |
var oMp3 = {
plugin_path: "",
file_mp3: "TestSong2.mp3",
/***/
requiredMajorVersion: 9, // Major version of Flash required
requiredMinorVersion: 0, // Minor version of Flash required
requiredRevision: 28, // Minor version of Flash required
hasRequestedVersion: false,
isIE: (navigator.appVersion.indexOf("MSIE") != -1) ? true : false,
isWin: (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false,
isOpera: (navigator.userAgent.indexOf("Opera") != -1) ? true : false,
alternateContent: '<div id="brak_plugina_flash"><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></div>',
schow: function(param)
{
oMp3.hasRequestedVersion = oMp3.DetectFlashVer(this.requiredMajorVersion, this.requiredMinorVersion, this.requiredRevision);
var flashvars = false;
var params = {
menu: "false",
wmode: "transparent",
flashvars: 'file_mp3='+oMp3.file_mp3
};
var attributes = {
id: param.tagID,
name: param.tagID
};
if (oMp3.hasRequestedVersion){
swfobject.embedSWF(oMp3.plugin_path, param.tagID,param.width, param.height, "9.0.28", "expressInstall.swf", flashvars, params, attributes);
}else{
document.getElementById(param.tagID).innerHTML = oMp3.alternateContent; // insert non-flash content
}
},
ControlVersion: function (){
var version;
var axo;
var e;
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
version = axo.GetVariable("$version");
} catch (e) {
}
if (!version)
{
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
version = "WIN 6,0,21,0";
axo.AllowScriptAccess = "always";
version = axo.GetVariable("$version");
} catch (e) {
}
}
if (!version){
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
version = axo.GetVariable("$version");
} catch (e) {
}
}
if (!version)
{
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
version = "WIN 3,0,18,0";
} catch (e) {
}
}
if (!version)
{
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
version = "WIN 2,0,0,11";
} catch (e) {
version = -1;
}
}
return version;
},
GetSwfVer: function (){
// NS/Opera version >= 3 check for Flash plugin in plugin array
var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
var descArray = flashDescription.split(" ");
var tempArrayMajor = descArray[2].split(".");
var versionMajor = tempArrayMajor[0];
var versionMinor = tempArrayMajor[1];
var versionRevision = descArray[3];
if (versionRevision == "") {
versionRevision = descArray[4];
}
if (versionRevision[0] == "d") {
versionRevision = versionRevision.substring(1);
} else if (versionRevision[0] == "r") {
versionRevision = versionRevision.substring(1);
if (versionRevision.indexOf("d") > 0) {
versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
}
}
var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
}
}
// MSN/WebTV 2.6 supports Flash 4
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
// WebTV 2.5 supports Flash 3
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
// older WebTV supports Flash 2
else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
else if ( oMp3.isIE && oMp3.isWin && !oMp3.isOpera ) {
flashVer = oMp3.ControlVersion();
}
return flashVer;
},
DetectFlashVer: function (reqMajorVer, reqMinorVer, reqRevision)
{
versionStr = oMp3.GetSwfVer();
if (versionStr == -1 ) {
return false;
} else if (versionStr != 0) {
if(oMp3.isIE && oMp3.isWin && !oMp3.isOpera) {
// Given "WIN 2,0,0,11"
tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"]
tempString = tempArray[1]; // "2,0,0,11"
versionArray = tempString.split(","); // ['2', '0', '0', '11']
} else {
versionArray = versionStr.split(".");
}
var versionMajor = versionArray[0];
var versionMinor = versionArray[1];
var versionRevision = versionArray[2];
if (versionMajor > parseFloat(reqMajorVer)) {
return true;
} else if (versionMajor == parseFloat(reqMajorVer)) {
if (versionMinor > parseFloat(reqMinorVer))
return true;
else if (versionMinor == parseFloat(reqMinorVer)) {
if (versionRevision >= parseFloat(reqRevision))
return true;
}
}
return false;
}
}
} | JavaScript |
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent'];
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0],
transparent: [255,255,255]
};
})(jQuery);
| JavaScript |
/**
* jQuery Lightbox Plugin (balupton edition) - Lightboxes for jQuery
* Copyright (C) 2007-2009 Benjamin Arthur Lupton
* http://jquery.com/plugins/project/jquerylightbox_bal
*
* This file is part of jQuery Lightbox (balupton edition).
*
* jQuery Lightbox (balupton edition) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* jQuery Lightbox (balupton edition) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with jQuery Lightbox (balupton edition). If not, see <http://www.gnu.org/licenses/>.
*
* @name jquery_lightbox: jquery.lightbox.js
* @package jQuery Lightbox Plugin (balupton edition)
* @version 1.3.8-dev
* @date April 25, 2009
* @category jQuery plugin
* @author Benjamin "balupton" Lupton {@link http://www.balupton.com}
* @copyright (c) 2007-2009 Benjamin Arthur Lupton {@link http://www.balupton.com}
* @license GNU Affero General Public License - {@link http://www.gnu.org/licenses/agpl.html}
* @example Visit {@link http://jquery.com/plugins/project/jquerylightbox_bal} for more information.
*/
// Start of our jQuery Plugin
(function($)
{ // Create our Plugin function, with $ as the argument (we pass the jQuery object over later)
// More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
// Debug
if ( typeof $.log === 'undefined' ) {
if ( !$.browser.safari && typeof window.console !== 'undefined' && typeof window.console.log === 'function' )
{ // Use window.console
$.log = function(){
var args = [];
for(var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
window.console.log.apply(window.console, args);
}
$.console = {
log: $.log,
debug: window.console.debug || $.log,
warn: window.console.warn || $.log,
error: window.console.error || $.log,
trace: window.console.trace || $.log
};
$log = $.log;
$debug = $.console.debug;
$warn = $.console.warn;
$error = $.console.error;
$trace = $.console.trace;
}
else
{ // Don't use anything
$.log = function ( ) { };
$.console = {
log: $.log,
debug: $.log,
warn: $.log,
error: alert,
trace: $.log
};
$log = $.log;
$debug = $.console.debug;
$warn = $.console.warn;
$error = $.console.error;
$trace = $.console.trace;
}
}
// Pre-Req
$.params_to_json = $.params_to_json || function ( params )
{ // Turns a params string or url into an array of params
// Adjust
params = String(params);
// Remove url if need be
params = params.substring(params.indexOf('?')+1);
// params = params.substring(params.indexOf('#')+1);
// Change + to %20, the %20 is fixed up later with the decode
params = params.replace(/\+/g, '%20');
// Do we have JSON string
if ( params.substring(0,1) === '{' && params.substring(params.length-1) === '}' )
{ // We have a JSON string
return eval(decodeURIComponent(params));
}
// We have a params string
params = params.split(/\&|\&\;/);
var json = {};
// We have params
for ( var i = 0, n = params.length; i < n; ++i )
{
// Adjust
var param = params[i] || null;
if ( param === null ) { continue; }
param = param.split('=');
if ( param === null ) { continue; }
// ^ We now have "var=blah" into ["var","blah"]
// Get
var key = param[0] || null;
if ( key === null ) { continue; }
if ( typeof param[1] === 'undefined' ) { continue; }
var value = param[1];
// ^ We now have the parts
// Fix
key = decodeURIComponent(key);
value = decodeURIComponent(value);
try {
// value can be converted
value = eval(value);
} catch ( e ) {
// value is a normal string
}
// Set
// console.log({'key':key,'value':value}, split);
var keys = key.split('.');
if ( keys.length === 1 )
{ // Simple
json[key] = value;
}
else
{ // Advanced
var path = '';
for ( ii in keys )
{ //
key = keys[ii];
path += '.'+key;
eval('json'+path+' = json'+path+' || {}');
}
eval('json'+path+' = value');
}
// ^ We now have the parts added to your JSON object
}
return json;
};
var $toArray = function(item){
return ( $type(item) !== 'array' ) ? [item] : item;
}
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
// Array List functions - By Benjamin "balupton" Lupton (MIT Licenced)
Array.prototype.get = function(index, current) {
if ( index === 'first' ) index = 0;
else if ( index === 'last' ) index = this.length-1;
else if ( !index && index !== 0 ) index = this.index;
if ( current !== false ) this.setIndex(index);
return this[index] || undefined;
};
Array.prototype.each = function(fn){
for (var i = 0; i < this.length; ++i) {
if (fn(i, this[i], this) === false)
break;
}
return this;
}
Array.prototype.setIndex = function(index){
if ( index < this.length && index >= 0 ) {
this.index = index;
} else {
this.index = null;
}
return this;
};
Array.prototype.current = function(index){
return this.get(index, true);
};
Array.prototype.isEmpty = function(){
return this.length === 0;
};
Array.prototype.isSingle = function(){
return this.length === 1;
};
Array.prototype.isMany = function(){
return this.length !== 0;
};
Array.prototype.isLast = function(index){
index = typeof index === 'undefined' ? this.index : index;
return !this.isEmpty() && index === this.length-1;
}
Array.prototype.isFirst = function(index){
index = typeof index === 'undefined' ? this.index : index;
return !this.isEmpty() && index === 0;
}
Array.prototype.clear = function(){
this.length = 0;
};
Array.prototype.next = function(update){
return this.get(this.index+1, update);
};
Array.prototype.prev = function(update){
return this.get(this.index-1, update);
};
Array.prototype.reset = function(){
this.index = null;
return this;
};
Array.prototype.set = function(index, item){
// We want to set the item
if ( index < this.length && index >= 0 ) {
this[index] = item;
} else {
$error('index above array length');
return false;
}
return this;
};
Array.prototype.loop = function(){
if ( !this.index && this.index !== 0 ) {
return this.current(0);
}
return this.next();
};
Array.prototype.add = function(){
this.push.apply(this,arguments);
return this;
};
Array.prototype.insert = function(index, item){
if ( typeof index !== 'number' ) {
index = this.length;
}
index = index<=this.length ? index : this.length;
var rest = this.slice(index);
this.length = index;
this.push(item);
this.push.apply(this, rest);
return this;
};
// Declare our class
$.LightboxClass = function ( )
{ // This is the handler for our constructor
this.construct();
};
// Extend jQuery elements for Lightbox
$.fn.lightbox = function ( options )
{ // Init a el for Lightbox
// Eg. $('#gallery a').lightbox();
// If need be: Instantiate $.LightboxClass to $.Lightbox
$.Lightbox = $.Lightbox || new $.LightboxClass();
// Handle IE6 appropriatly
if ( $.Lightbox.ie6 && !$.Lightbox.ie6_support )
{ // We are IE6 and we want to ignore
return this; // chain
}
// Establish options
options = $.extend({start:false,events:true} /* default options */, options);
// Get group
var $group = $(this);
// Events?
if ( options.events )
{ // Add events
$group.unbind('click').click(function(){
// Get obj
var $obj = $(this);
// Get position
var index = $group.index($obj);
// Init group
if ( !$.Lightbox.init(index, $group) )
{ return false; }
// Display lightbox
if ( !$.Lightbox.start() )
{ return false; }
// Cancel href
return false;
});
// Add style
$group.addClass('lightbox-enabled');
}
// Start?
if ( options.start )
{ // Start
// Get obj
var obj = $(this);
// Get rel
// var rel = $(obj).attr('rel');
// Init group
if ( !$.Lightbox.init(0, $group) )
{ return this; }
// Display lightbox
if ( !$.Lightbox.start() )
{ return this; }
}
// And chain
return this;
};
// Define our class
$.extend($.LightboxClass.prototype,
{ // Our LightboxClass definition
// -----------------
// Everything to do with images
images: [],
// -----------------
// Variables
constructed: false,
compressed: null,
// -----------------
// Options
src: null, // the source location of our js file
baseurl: null,
files: {
compressed: {
js: {
lightbox: 'js/jquery.lightbox.min.js',
colorBlend: 'js/jquery.color.min.js'
},
css: {
lightbox: 'css/jquery.lightbox.css'
}
},
uncompressed: {
js: {
lightbox: 'js/jquery.lightbox.js',
colorBlend: 'js/jquery.color.js'
},
css: {
lightbox: 'css/jquery.lightbox.css'
}
},
images: {
prev: 'images/prev.gif',
next: 'images/next.gif',
blank: 'images/blank.gif',
loading: 'images/loading.gif'
}
},
text: {
// For translating
image: 'Image',
of: 'of',
close: 'Close X',
closeInfo: 'You can also click anywhere outside the image to close.',
download: 'Download.',
help: {
close: 'Click to close',
interact: 'Hover to interact'
},
about: {
text: 'jQuery Lightbox Plugin (balupton edition)',
title: 'Licenced under the GNU Affero General Public License.',
link: 'http://jquery.com/plugins/project/jquerylightbox_bal'
}
},
keys: {
close: 'c',
prev: 'p',
next: 'n'
},
handlers: {
// For custom actions
show: null
},
opacity: 0.9,
padding: null, // if null - autodetect
speed: 400, // Duration of effect, milliseconds
rel: 'lightbox', // What to look for in the rels
auto_relify: true, // should we automaticly do the rels?
auto_scroll: 'follow', // should the lightbox scroll with the page? follow, disabled, ignore
auto_resize: true, // true or false
ie6: null, // are we ie6?
ie6_support: true, // have ie6 support
ie6_upgrade: true, // show ie6 upgrade message
colorBlend: null, // null - auto-detect, true - force, false - no
download_link: true, // Display the download link
show_helper_text: true, // Display the helper text up the top right
show_linkback: true, // true, false
show_info: 'auto', // auto - automaticly handle, true - force
show_extended_info: 'auto', // auto - automaticly handle, true - force
// names of the options that can be modified
options: ['show_helper_text', 'auto_scroll', 'auto_resize', 'download_link', 'show_info', 'show_extended_info', 'ie6_support', 'ie6_upgrade', 'colorBlend', 'baseurl', 'files', 'text', 'show_linkback', 'keys', 'opacity', 'padding', 'speed', 'rel', 'auto_relify'],
// -----------------
// Functions
construct: function ( options )
{ // Construct our Lightbox
// -------------------
// Prepare
// Initial construct
var initial = typeof this.constructed === 'undefined' || this.constructed === false;
this.constructed = true;
// Perform domReady
var domReady = initial;
// Prepare options
options = options || {};
// -------------------
// Handle files
// Prepend function to use later
var prepend = function(item, value) {
if ( typeof item === 'object' ) {
for (var i in item) {
item[i] = prepend(item[i], value);
}
} else if ( typeof value === 'array' ) {
for (var i=0,n=item.length; i<n; ++i) {
item[i] = prepend(item[i], value);
}
} else {
item = value+item;
}
return item;
}
// Add baseurl
if ( initial && (typeof options.files === 'undefined') )
{ // Load the files like default
// Reset compressed
this.compressed = null;
// Get the src of the first script tag that includes our js file (with or without an appendix)
var $script = $('script[src*='+this.files.compressed.js.lightbox+']:first');
if ( $script.length !== 0 ) {
// Compressed
$.extend(true, this.files, this.files.compressed);
this.compressed = true;
} else {
// Uncompressed
$script = $('script[src*='+this.files.uncompressed.js.lightbox+']:first');
if ( $script.length !== 0 ) {
// Uncompressed
$.extend(true, this.files, this.files.uncompressed);
this.compressed = false;
} else {
// Nothing
}
}
// Make sure we found ourselves
if ( this.compressed === null )
{ // We didn't
$.console.error('Lightbox was not able to find it\'s javascript script tag necessary for auto-inclusion.');
// We don't work with files anymore, so don't care for domReady
domReady = false;
}
else
{ // We found ourself
// Grab the script src
this.src = $script.attr('src');
// The baseurl is the src up until the start of our js file
this.baseurl = this.src.substring(0, this.src.indexOf(this.files.js.lightbox));
// Prepend baseurl to files
this.files = prepend(this.files, this.baseurl);
// Now as we have source, we may have more params
options = $.extend(options, $.params_to_json(this.src));
}
// Create
this.images.image = {
src: '',
title: 'Untitled',
description: '',
name: '',
color: null,
width: null,
height: null,
id: null,
image: true
};
this.images.prepare = function(obj){
var image = $.extend({}, this.image);
if ( obj.tagName ) {
// We are an element
obj = $(obj);
if ( obj.attr('src') || obj.attr('href') ) {
image.src = obj.attr('src') || obj.attr('href');
image.title = obj.attr('title') || obj.attr('alt') || image.title;
image.name = obj.attr('name') || '';
image.color = obj.css('backgroundColor');
// Extract description from title
var s = image.title.indexOf(': ');
if ( s > 0 )
{ // Description exists
image.description = image.title.substring(s+2) || image.description;
image.title = image.title.substring(0,s) || image.title;
}
} else {
image = null;
}
} else if ( obj.src ) {
// We are a image object
image = $.extend(this.image,obj);
} else {
image = null;
}
if ( image ) {
image.id = image.id || image.src+image.title+image.description;
}
return image;
}
this.images.create = function(obj){
var images = this;
if ( obj.each ) {
obj.each(function(index,item){
images.create(item);
});
return;
}
var image = images.prepare(obj);
if ( !image ) {
$.console.error('We dont know what we have:', obj, image);
} else {
images.push(image);
}
return images;
};
}
else
if ( typeof options.files === 'object' )
{ // We have custom files
// Prepend baseurl to files
options.files = prepend(options.files, this.baseurl);
}
else
{ // Don't have any files, so no need to perform domReady
domReady = false;
}
// -------------------
// Apply options
for ( var i in this.options )
{ // Cycle through the options
var name = this.options[i];
if ( (typeof options[name] === 'object') && (typeof this[name] === 'object') )
{ // We have a group like text or files
this[name] = $.extend(true, this[name], options[name]);
}
else if ( typeof options[name] !== 'undefined' )
{ // We have that option, so apply it
this[name] = options[name];
}
} delete i;
// -------------------
// Figure out what to do
// Handle IE6
if ( initial && navigator.userAgent.indexOf('MSIE 6') >= 0 )
{ // Is IE6
this.ie6 = true;
}
else
{ // We are not IE6
this.ie6 = false;
}
// -------------------
// Handle our DOM
if ( domReady || typeof options.download_link !== 'undefined' || typeof options.colorBlend !== 'undefined' || typeof options.files === 'object' || typeof options.text === 'object' || typeof options.show_linkback !== 'undefined' || typeof options.scroll_with !== 'undefined' )
{ // We have reason to handle the dom
$(function() {
// DOM is ready, so fire our DOM handler
$.Lightbox.domReady();
});
}
// -------------------
// Finish Up
// All good
return true;
},
domReady: function ( )
{
// -------------------
// Include resources
// Grab resources
var bodyEl = document.getElementsByTagName($.browser.safari ? 'head' : 'body')[0];
var stylesheets = this.files.css;
var scripts = this.files.js;
// Handle IE6 appropriatly
if ( this.ie6 && this.ie6_upgrade )
{ // Add the upgrade message
scripts.ie6 = 'http://www.savethedevelopers.org/say.no.to.ie.6.js';
}
// colorBlend
if ( this.colorBlend === true && typeof $.colorBlend === 'undefined' )
{ // Force colorBlend
this.colorBlend = true;
// Leave file in place to be loaded
}
else
{ // We either have colorBlend or we don't
this.colorBlend = typeof $.colorBlend !== 'undefined';
// Remove colorBlend file
delete scripts.colorBlend;
}
// Include stylesheets
for ( stylesheet in stylesheets )
{
var linkEl = document.createElement('link');
linkEl.type = 'text/css';
linkEl.rel = 'stylesheet';
linkEl.media = 'screen';
linkEl.href = stylesheets[stylesheet];
linkEl.id = 'lightbox-stylesheet-'+stylesheet.replace(/[^a-zA-Z0-9]/g, '');
$('#'+linkEl.id).remove();
bodyEl.appendChild(linkEl);
}
// Include javascripts
for ( script in scripts )
{
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = scripts[script];
scriptEl.id = 'lightbox-script-'+script.replace(/[^a-zA-Z0-9]/g, '');
$('#'+scriptEl.id).remove();
bodyEl.appendChild(scriptEl);
}
// Cleanup
delete scripts;
delete stylesheets;
delete bodyEl;
// -------------------
// Append display
// Append markup
$('#lightbox,#lightbox-overlay').remove();
$('body').append('<div id="lightbox-overlay"><div id="lightbox-overlay-text">'+(this.show_linkback?'<p><span id="lightbox-overlay-text-about"><a href="#" title="'+this.text.about.title+'">'+this.text.about.text+'</a></span></p><p> </p>':'')+(this.show_helper_text?'<p><span id="lightbox-overlay-text-close">'+this.text.help.close+'</span><br/> <span id="lightbox-overlay-text-interact">'+this.text.help.interact+'</span></p>':'')+'</div></div><div id="lightbox"><div id="lightbox-imageBox"><div id="lightbox-imageContainer"><img id="lightbox-image" /><div id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + this.files.images.loading + '" /></a></div></div></div><div id="lightbox-infoBox"><div id="lightbox-infoContainer"><div id="lightbox-infoHeader"><span id="lightbox-caption">'+(this.download_link ? '<a href="#" title="' + this.text.download + '" id="lightbox-caption-title"></a>' : '<span id="lightbox-caption-title"></span>')+'<span id="lightbox-caption-seperator"></span><span id="lightbox-caption-description"></span></span></div><div id="lightbox-infoFooter"><span id="lightbox-currentNumber"></span><span id="lightbox-close"><a href="#" id="lightbox-close-button" title="'+this.text.closeInfo+'">' + this.text.close + '</a></span></div><div id="lightbox-infoContainer-clear"></div></div></div></div>');
// Update Boxes - for some crazy reason this has to be before the hide in safari and konqueror
this.resizeBoxes();
this.repositionBoxes();
// Hide
$('#lightbox,#lightbox-overlay,#lightbox-overlay-text-interact').hide();
// -------------------
// Browser specifics
// Handle IE6
if ( this.ie6 && this.ie6_support )
{ // Support IE6
// IE6 does not support fixed positioning so absolute it
// ^ This is okay as we disable scrolling
$('#lightbox-overlay').css({
position: 'absolute',
top: '0px',
left: '0px'
});
}
// -------------------
// Preload Images
// Cycle and preload
$.each(this.files.images, function()
{ // Proload the image
var preloader = new Image();
preloader.onload = function() {
preloader.onload = null;
preloader = null;
}; preloader.src = this;
});
// -------------------
// Apply events
// If the window resizes, act appropriatly
$(window).unbind('resize').resize(function ()
{ // The window has been resized
$.Lightbox.resizeBoxes('resized');
});
// If the window scrolls, act appropriatly
if ( this.scroll === 'follow' )
{ // We want to
$(window).scroll(function ()
{ // The window has scrolled
$.Lightbox.repositionBoxes();
});
}
// Prev
$('#lightbox-nav-btnPrev').unbind().hover(function() { // over
$(this).css({ 'background' : 'url(' + $.Lightbox.files.images.prev + ') left 45% no-repeat' });
},function() { // out
$(this).css({ 'background' : 'transparent url(' + $.Lightbox.files.images.blank + ') no-repeat' });
}).click(function() {
$.Lightbox.images.prev();
$.Lightbox.showImage();
return false;
});
// Next
$('#lightbox-nav-btnNext').unbind().hover(function() { // over
$(this).css({ 'background' : 'url(' + $.Lightbox.files.images.next + ') right 45% no-repeat' });
},function() { // out
$(this).css({ 'background' : 'transparent url(' + $.Lightbox.files.images.blank + ') no-repeat' });
}).click(function() {
$.Lightbox.images.next();
$.Lightbox.showImage();
return false;
});
// Help
if ( this.show_linkback )
{ // Linkback exists so add handler
$('#lightbox-overlay-text-about a').click(function(){window.open($.Lightbox.text.about.link); return false;});
}
$('#lightbox-overlay-text-close').unbind().hover(
function(){
$('#lightbox-overlay-text-interact').fadeIn();
},
function(){
$('#lightbox-overlay-text-interact').fadeOut();
}
);
// Image link
$('#lightbox-caption-title').click(function(){window.open($(this).attr('href')); return false;});
// Assign close clicks
$('#lightbox-overlay, #lightbox, #lightbox-loading-link, #lightbox-btnClose').unbind().click(function() {
$.Lightbox.finish();
return false;
});
// -------------------
// Finish Up
// Relify
if ( this.auto_relify )
{ // We want to relify, no the user
this.relify();
}
// All good
return true;
},
relify: function ( )
{ // Create event
//
var groups = {};
var groups_n = 0;
var orig_rel = this.rel;
// Create the groups
$.each($('[rel*='+orig_rel+']'), function(index, obj){
// Get the group
var rel = $(obj).attr('rel');
// Are we really a group
if ( rel === orig_rel )
{ // We aren't
rel = groups_n; // we are individual
}
// Does the group exist
if ( typeof groups[rel] === 'undefined' )
{ // Make the group
groups[rel] = [];
groups_n++;
}
// Append the image
groups[rel].push(obj);
});
// Lightbox groups
$.each(groups, function(index, group){
$(group).lightbox();
});
// Done
return true;
},
init: function ( image, images )
{ // Init a batch of lightboxes
// Establish images
if ( typeof images === 'undefined' ) {
images = image;
image = 0;
}
// Clear
this.images.clear();
// Add images
this.images.create(images);
// Do we need to bother
if ( this.images.isEmpty() ) {
// No images
$.console.warn('WARNING', 'Lightbox started, but no images: ', image, images);
return false;
}
// Set current
if ( !this.images.current(image) ) {
// No images
$.console.warn('WARNING', 'Could not find current image: ', image, this.images);
return false;
}
// Done
return true;
},
start: function ( )
{ // Display the lightbox
// We are alive
this.visible = true;
// Adjust scrolling
if ( this.scroll === 'disable' )
{ //
$(document.body).css('overflow', 'hidden');
}
// Fix attention seekers
$('embed, object, select').css('visibility', 'hidden');//.hide(); - don't use this, give it a go, find out why!
// Resize the boxes appropriatly
this.resizeBoxes('general');
// Reposition the Boxes
this.repositionBoxes({'speed':0});
// Hide things
$('#lightbox-infoFooter').hide(); // we hide this here because it makes the display smoother
$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-infoBox').hide();
// Display the boxes
$('#lightbox-overlay').css('opacity',this.opacity).fadeIn(400, function(){
// Show the lightbox
$('#lightbox').fadeIn(300);
// Display first image
if ( !$.Lightbox.showImage() ) {
$.Lightbox.finish();
return false;
}
});
// All done
return true;
},
finish: function ( )
{ // Get rid of lightbox
// Hide lightbox
$('#lightbox').hide();
$('#lightbox-overlay').fadeOut(function() { $('#lightbox-overlay').hide(); });
// Fix attention seekers
$('embed, object, select').css({ 'visibility' : 'visible' });//.show();
// Kill current image
this.images.reset();
// Adjust scrolling
if ( this.scroll === 'disable' )
{ //
$(document.body).css('overflow', 'visible');
}
// We are dead
this.visible = false;
},
resizeBoxes: function ( type )
{ // Resize the boxes
// Used on transition or window resize
// Resize Overlay
if ( type !== 'transition' )
{ // We don't care for transition
var $body = $(this.ie6 ? document.body : document);
$('#lightbox-overlay').css({
width: $body.width(),
height: $body.height()
});
delete $body;
}
// Handle cases
switch ( type )
{
case 'general': // general resize (start of lightbox)
return true;
break;
case 'resized': // window was resized
if ( this.auto_resize === false )
{ // Stop
// Reposition
this.repositionBoxes({'nHeight':nHeight, 'speed':this.speed});
return true;
}
case 'transition': // transition between images
default: // unknown
break;
}
// Get image
var image = this.images.current();
if ( !image || !image.width || !this.visible )
{ // No image or no visible lightbox, so we don't care
//$.console.warn('A resize occured while no image or no lightbox...');
return false;
}
// Resize image box
// i:image, w:window, b:box, c:current, n:new, d:difference
// Get image dimensions
var iWidth = image.width;
var iHeight = image.height;
// Get window dimensions
var wWidth = $(window).width();
var wHeight = $(window).height();
// Check if we are in size
// Lightbox can take up 4/5 of size
if ( this.auto_resize !== false )
{ // We want to auto resize
var maxWidth = Math.floor(wWidth*(4/5));
var maxHeight = Math.floor(wHeight*(4/5));
var resizeRatio;
while ( iWidth > maxWidth || iHeight > maxHeight )
{ // We need to resize
if ( iWidth > maxWidth )
{ // Resize width, then height proportionally
resizeRatio = maxWidth/iWidth;
iWidth = maxWidth;
iHeight = Math.floor(iHeight*resizeRatio);
}
if ( iHeight > maxHeight )
{ // Resize height, then width proportionally
resizeRatio = maxHeight/iHeight;
iHeight = maxHeight;
iWidth = Math.floor(iWidth*resizeRatio);
}
}
}
// Get current width and height
var cWidth = $('#lightbox-imageBox').width();
var cHeight = $('#lightbox-imageBox').height();
// Get the width and height of the selected image plus the padding
// padding*2 for both sides (left+right || top+bottom)
var nWidth = (iWidth + (this.padding * 2));
var nHeight = (iHeight + (this.padding * 2));
// Diferences
var dWidth = cWidth - nWidth;
var dHeight = cHeight - nHeight;
// Set the overlay buttons height and the infobox width
// Other dimensions specified by CSS
$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css('height', nHeight);
$('#lightbox-infoBox').css('width', nWidth);
// Handle final action
if ( type === 'transition' )
{ // We are transition
// Do we need to wait? (just a nice effect to counter the other
if ( dWidth === 0 && dHeight === 0 )
{ // We are the same size
this.pause(this.speed/3);
this.showImage(null, 3);
}
else
{ // We are not the same size
// Animate
$('#lightbox-image').width(iWidth).height(iHeight);
$('#lightbox-imageBox').animate({width: nWidth, height: nHeight}, this.speed, function ( ) { $.Lightbox.showImage(null, 3); } );
}
}
else
{ // We are a resize
// Animate Lightbox
$('#lightbox-image').animate({width:iWidth, height:iHeight}, this.speed);
$('#lightbox-imageBox').animate({width: nWidth, height: nHeight}, this.speed);
}
// Reposition
this.repositionBoxes({'nHeight':nHeight, 'speed':this.speed});
// Done
return true;
},
repositioning: false, // are we currently repositioning
reposition_failsafe: false, // failsafe
repositionBoxes: function ( options )
{
// Prepare
if ( this.repositioning )
{ // Already here
this.reposition_failsafe = true;
return null;
}
this.repositioning = true;
// Options
options = $.extend({}, options);
options.callback = options.callback || null;
options.speed = options.speed || 'slow';
// Get page scroll
var pageScroll = this.getPageScroll();
// Figure it out
// alert($(window).height()+"\n"+$(document.body).height()+"\n"+$(document).height());
// var nHeight = options.nHeight || parseInt($('#lightbox').height(),10) || $(document).height()/3;
var nHeight = options.nHeight || parseInt($('#lightbox').height(),10);
// Display lightbox in center
// var nTop = pageScroll.yScroll + ($(document.body).height() /*frame height*/ - nHeight) / 2.5;
var nTop = pageScroll.yScroll + ($(window).height() /*frame height*/ - nHeight) / 2.5;
var nLeft = pageScroll.xScroll;
// Animate
var css = {
left: nLeft,
top: nTop
};
if (options.speed) {
$('#lightbox').animate(css, 'slow', function(){
if ( $.Lightbox.reposition_failsafe )
{ // Fire again
$.Lightbox.repositioning = $.Lightbox.reposition_failsafe = false;
$.Lightbox.repositionBoxes(options);
}
else
{ // Done
$.Lightbox.repositioning = false;
if ( options.callback )
{ // Call the user callback
options.callback();
}
}
});
}
else
{
$('#lightbox').css(css);
if ( this.reposition_failsafe )
{ // Fire again
this.repositioning = this.reposition_failsafe = false;
this.repositionBoxes(options);
}
else
{ // Done
this.repositioning = false;
}
}
// Done
return true;
},
visible: false,
showImage: function ( image, step ){
// Default step
step = step || 1;
// Make the image the current image, or get the current
image = this.images.current(image) || this.images.get('first',true);
if ( !image ) {
return;
}
// What do we need to do
switch ( step )
{
// ---------------------------------
// We need to preload
case 1:
// Disable keyboard nav
this.KeyboardNav_Disable();
// Show the loading image
$('#lightbox-loading').show();
// Hide things
$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-infoBox').hide();
// Remove show info events
$('#lightbox-imageBox').unbind();
// ^ Why? Because otherwise when the image is changing, the info pops out, not good!
// Check if we need to preload
if ( image.width && image.height )
{ // We don't
// Continue to next step
this.showImage(null, 2);
}
else
{ // We do
// Create preloader
var preloader = new Image();
// Set callback
preloader.onload = function()
{ // We have preloaded the image
// Update image with our new info
image.width = preloader.width;
image.height = preloader.height;
// Continue to next step
$.Lightbox.showImage(null, 2);
// Kill preloader
preloader.onload = null;
preloader = null;
};
// Start preload
preloader.src = image.src;
}
// Done
break;
// ---------------------------------
// Resize the container
case 2:
// Apply image changes
$('#lightbox-image').attr('src', image.src);
// Set container border (Moved here for Konqueror fix - Credits to Blueyed)
if ( typeof this.padding === 'undefined' || this.padding === null || isNaN(this.padding) )
{ // Autodetect
this.padding = parseInt($('#lightbox-imageContainer').css('padding-left'), 10) || parseInt($('#lightbox-imageContainer').css('padding'), 10) || 0;
}
// Use colorBlend?
if ( this.colorBlend )
{ // We have colorBlend
// Background
$('#lightbox-overlay').animate({'backgroundColor':image.color}, this.speed*2);
// Border
$('#lightbox-imageBox').css('borderColor', image.color);
}
// Resize boxes
this.resizeBoxes('transition');
// ^ contains callback to next step
// Done
break;
// ---------------------------------
// Display the image
case 3:
// Hide loading
$('#lightbox-loading').hide();
// Animate image
$('#lightbox-image').fadeIn(this.speed*1.5, function() {
$.Lightbox.showImage(null, 4);
});
// Start the proloading of other images
this.preloadNeighbours();
// Fire custom handler show
if ( this.handlers.show !== null )
{ // Fire it
this.handlers.show(image);
}
// Done
break;
// ---------------------------------
// Set image info / Set navigation
case 4:
// ---------------------------------
// Set image info
// Hide and set image info
var $title = $('#lightbox-caption-title').html(image.title || 'Untitled');
if ( this.download_link )
{ $title.attr('href', this.download_link ? image.src : ''); }
delete $title;
$('#lightbox-caption-seperator').html(image.description ? ': ' : '');
$('#lightbox-caption-description').html(image.description || ' ');
// If we have a set, display image position
if ( this.images.length > 1 )
{ // Display
$('#lightbox-currentNumber').html(this.text.image + ' ' + ( image.index + 1 ) + ' ' + this.text.of + ' ' + this.images.length);
} else
{ // Empty
$('#lightbox-currentNumber').html(' ');
}
// ---------------------------------
// Info events
// Apply event
$('#lightbox-imageBox').unbind('mouseover').mouseover(function(){
$('#lightbox-infoBox:not(:visible)').stop().slideDown('fast');
});
// Apply event
$('#lightbox-infoBox').unbind('mouseover').mouseover(function(){
$('#lightbox-infoFooter:not(:visible)').stop().slideDown('fast');
});
// Forced show?
if ( this.show_extended_info === true )
{ // Force show
$('#lightbox-imageBox').trigger('mouseover');
$('#lightbox-infoBox').trigger('mouseover');
}
else if ( this.show_info === true )
{ // Force show
$('#lightbox-imageBox').trigger('mouseover');
}
// ---------------------------------
// Set navigation
// Instead to define this configuration in CSS file, we define here. And it's need to IE. Just.
$('#lightbox-nav-btnPrev, #lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + this.files.images.blank + ') no-repeat' });
// If not first, show previous button
if ( !this.images.isFirst() ) {
// Not first, show button
$('#lightbox-nav-btnPrev').show();
}
// If not last, show next button
if ( !this.images.isLast() ) {
// Not first, show button
$('#lightbox-nav-btnNext').show();
}
// Make navigation current / show it
$('#lightbox-nav').show();
// Enable keyboard navigation
this.KeyboardNav_Enable();
// Done
break;
// ---------------------------------
// Error handling
default:
$.console.error('Don\'t know what to do: ', image, step);
return this.showImage(image, 1);
// break;
}
// All done
return true;
},
preloadNeighbours: function ( )
{ // Preload all neighbour images
// Do we need to do this?
if ( this.images.isSingle() || this.images.isEmpty() )
{ return true; }
// Get current image
var image = this.images.current();
var index = this.images.index;
if ( !image ) { return image; }
var objNext;
// Load previous
var prev = this.images.prev();
if ( prev ) {
objNext = new Image();
objNext.src = prev.src;
}
this.images.setIndex(index); // reset
// Load next
var next = this.images.next();
if ( next ) {
objNext = new Image();
objNext.src = next.src;
}
this.images.setIndex(index); // reset
},
// --------------------------------------------------
// Things we don't really care about
KeyboardNav_Enable: function ( ) {
$(document).keydown(function(objEvent) {
$.Lightbox.KeyboardNav_Action(objEvent);
});
},
KeyboardNav_Disable: function ( ) {
$(document).unbind('keydown');
},
KeyboardNav_Action: function ( objEvent ) {
// Prepare
objEvent = objEvent || window.event;
// Get the keycode
var keycode = objEvent.keyCode;
var escapeKey = objEvent.DOM_VK_ESCAPE /* moz */ || 27;
// Get key
var key = String.fromCharCode(keycode).toLowerCase();
// Close?
if ( key === this.keys.close || keycode === escapeKey )
{ return $.Lightbox.finish(); }
// Prev?
if ( key === this.keys.prev || keycode === 37 )
{ // We want previous
return $.Lightbox.showImage($.Lightbox.images.prev());
}
// Next?
if ( key === this.keys.next || keycode === 39 )
{ // We want next
return $.Lightbox.showImage($.Lightbox.images.next());
}
// Unknown
return true;
},
getPageScroll: function ( ) {
var xScroll, yScroll;
if (self.pageYOffset)
{ // Some browser
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop)
{ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body)
{ // All other browsers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
var arrayPageScroll = {'xScroll':xScroll,'yScroll':yScroll};
return arrayPageScroll;
},
pause: function ( ms ) {
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while ( curDate - date < ms);
}
}); // We have finished extending/defining our LightboxClass
// --------------------------------------------------
// Finish up
// Instantiate
if ( typeof $.Lightbox === 'undefined' )
{ //
$.Lightbox = new $.LightboxClass();
}
// Finished definition
})(jQuery); // We are done with our plugin, so lets call it with jQuery as the argument
| JavaScript |
(function($){
var initLayout = function() {
var hash = window.location.hash.replace('#', '');
var currentTab = $('ul.navigationTabs a')
.bind('click', showTab)
.filter('a[rel=' + hash + ']');
if (currentTab.size() == 0) {
currentTab = $('ul.navigationTabs a:first');
}
showTab.apply(currentTab.get(0));
$('#colorpickerHolder').ColorPicker({flat: true});
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
}
});
$('#colorpickerHolder2>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorpickerField1').ColorPicker({
onSubmit: function(hsb, hex, rgb) {
$('#colorpickerField1').val(hex);
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
})
.bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
$('#colorSelector').ColorPicker({
color: '#0000ff',
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(500);
return false;
},
onChange: function (hsb, hex, rgb) {
$('#colorSelector div').css('backgroundColor', '#' + hex);
}
});
};
var showTab = function(e) {
var tabIndex = $('ul.navigationTabs a')
.removeClass('active')
.index(this);
$(this)
.addClass('active')
.blur();
$('div.tab')
.hide()
.eq(tabIndex)
.show();
};
EYE.register(initLayout, 'init');
})(jQuery) | JavaScript |
/**
*
* Zoomimage
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($){
var EYE = window.EYE = function() {
var _registered = {
init: []
};
return {
init: function() {
$.each(_registered.init, function(nr, fn){
fn.call();
});
},
extend: function(prop) {
for (var i in prop) {
if (prop[i] != undefined) {
this[i] = prop[i];
}
}
},
register: function(fn, type) {
if (!_registered[type]) {
_registered[type] = [];
}
_registered[type].push(fn);
}
};
}();
$(EYE.init);
})(jQuery);
| JavaScript |
/**
*
* Utilities
* Author: Stefan Petre www.eyecon.ro
*
*/
(function($) {
EYE.extend({
getPosition : function(e, forceIt)
{
var x = 0;
var y = 0;
var es = e.style;
var restoreStyles = false;
if (forceIt && jQuery.curCSS(e,'display') == 'none') {
var oldVisibility = es.visibility;
var oldPosition = es.position;
restoreStyles = true;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
}
var el = e;
if (el.getBoundingClientRect) { // IE
var box = el.getBoundingClientRect();
x = box.left + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - 2;
y = box.top + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - 2;
} else {
x = el.offsetLeft;
y = el.offsetTop;
el = el.offsetParent;
if (e != el) {
while (el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
}
if (jQuery.browser.safari && jQuery.curCSS(e, 'position') == 'absolute' ) {
x -= document.body.offsetLeft;
y -= document.body.offsetTop;
}
el = e.parentNode;
while (el && el.tagName.toUpperCase() != 'BODY' && el.tagName.toUpperCase() != 'HTML')
{
if (jQuery.curCSS(el, 'display') != 'inline') {
x -= el.scrollLeft;
y -= el.scrollTop;
}
el = el.parentNode;
}
}
if (restoreStyles == true) {
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {x:x, y:y};
},
getSize : function(e)
{
var w = parseInt(jQuery.curCSS(e,'width'), 10);
var h = parseInt(jQuery.curCSS(e,'height'), 10);
var wb = 0;
var hb = 0;
if (jQuery.curCSS(e, 'display') != 'none') {
wb = e.offsetWidth;
hb = e.offsetHeight;
} else {
var es = e.style;
var oldVisibility = es.visibility;
var oldPosition = es.position;
es.visibility = 'hidden';
es.display = 'block';
es.position = 'absolute';
wb = e.offsetWidth;
hb = e.offsetHeight;
es.display = 'none';
es.position = oldPosition;
es.visibility = oldVisibility;
}
return {w:w, h:h, wb:wb, hb:hb};
},
getClient : function(e)
{
var h, w;
if (e) {
w = e.clientWidth;
h = e.clientHeight;
} else {
var de = document.documentElement;
w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
}
return {w:w,h:h};
},
getScroll : function (e)
{
var t=0, l=0, w=0, h=0, iw=0, ih=0;
if (e && e.nodeName.toLowerCase() != 'body') {
t = e.scrollTop;
l = e.scrollLeft;
w = e.scrollWidth;
h = e.scrollHeight;
} else {
if (document.documentElement) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
if (typeof pageYOffset != 'undefined') {
t = pageYOffset;
l = pageXOffset;
}
iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0;
ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0;
}
return { t: t, l: l, w: w, h: h, iw: iw, ih: ih };
},
getMargins : function(e, toInteger)
{
var t = jQuery.curCSS(e,'marginTop') || '';
var r = jQuery.curCSS(e,'marginRight') || '';
var b = jQuery.curCSS(e,'marginBottom') || '';
var l = jQuery.curCSS(e,'marginLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getPadding : function(e, toInteger)
{
var t = jQuery.curCSS(e,'paddingTop') || '';
var r = jQuery.curCSS(e,'paddingRight') || '';
var b = jQuery.curCSS(e,'paddingBottom') || '';
var l = jQuery.curCSS(e,'paddingLeft') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)
};
else
return {t: t, r: r, b: b, l: l};
},
getBorder : function(e, toInteger)
{
var t = jQuery.curCSS(e,'borderTopWidth') || '';
var r = jQuery.curCSS(e,'borderRightWidth') || '';
var b = jQuery.curCSS(e,'borderBottomWidth') || '';
var l = jQuery.curCSS(e,'borderLeftWidth') || '';
if (toInteger)
return {
t: parseInt(t, 10)||0,
r: parseInt(r, 10)||0,
b: parseInt(b, 10)||0,
l: parseInt(l, 10)||0
};
else
return {t: t, r: r, b: b, l: l};
},
traverseDOM : function(nodeEl, func)
{
func(nodeEl);
nodeEl = nodeEl.firstChild;
while(nodeEl){
EYE.traverseDOM(nodeEl, func);
nodeEl = nodeEl.nextSibling;
}
},
getInnerWidth : function(el, scroll) {
var offsetW = el.offsetWidth;
return scroll ? Math.max(el.scrollWidth,offsetW) - offsetW + el.clientWidth:el.clientWidth;
},
getInnerHeight : function(el, scroll) {
var offsetH = el.offsetHeight;
return scroll ? Math.max(el.scrollHeight,offsetH) - offsetH + el.clientHeight:el.clientHeight;
},
getExtraWidth : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingLeft'))||0)
+ (parseInt($.curCSS(el, 'paddingRight'))||0)
+ (parseInt($.curCSS(el, 'borderLeftWidth'))||0)
+ (parseInt($.curCSS(el, 'borderRightWidth'))||0);
return 0;
},
getExtraHeight : function(el) {
if($.boxModel)
return (parseInt($.curCSS(el, 'paddingTop'))||0)
+ (parseInt($.curCSS(el, 'paddingBottom'))||0)
+ (parseInt($.curCSS(el, 'borderTopWidth'))||0)
+ (parseInt($.curCSS(el, 'borderBottomWidth'))||0);
return 0;
},
isChildOf: function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (!el || !el.nodeType || el.nodeType != 1) {
return false;
}
if (parentEl.contains && !$.browser.safari) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
centerEl : function(el, axis)
{
var clientScroll = EYE.getScroll();
var size = EYE.getSize(el);
if (!axis || axis == 'vertically')
$(el).css(
{
top: clientScroll.t + ((Math.min(clientScroll.h,clientScroll.ih) - size.hb)/2) + 'px'
}
);
if (!axis || axis == 'horizontally')
$(el).css(
{
left: clientScroll.l + ((Math.min(clientScroll.w,clientScroll.iw) - size.wb)/2) + 'px'
}
);
}
});
if (!$.easing.easeout) {
$.easing.easeout = function(p, n, firstNum, delta, duration) {
return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum;
};
}
})(jQuery); | JavaScript |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus')
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col));
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {};
hsb.b = Math.max(Math.max(rgb.r,rgb.g),rgb.b);
hsb.s = (hsb.b <= 0) ? 0 : Math.round(100*(hsb.b - Math.min(Math.min(rgb.r,rgb.g),rgb.b))/hsb.b);
hsb.b = Math.round((hsb.b /255)*100);
if((rgb.r==rgb.g) && (rgb.g==rgb.b)) hsb.h = 0;
else if(rgb.r>=rgb.g && rgb.g>=rgb.b) hsb.h = 60*(rgb.g-rgb.b)/(rgb.r-rgb.b);
else if(rgb.g>=rgb.r && rgb.r>=rgb.b) hsb.h = 60 + 60*(rgb.g-rgb.r)/(rgb.g-rgb.b);
else if(rgb.g>=rgb.b && rgb.b>=rgb.r) hsb.h = 120 + 60*(rgb.b-rgb.r)/(rgb.g-rgb.r);
else if(rgb.b>=rgb.g && rgb.g>=rgb.r) hsb.h = 180 + 60*(rgb.b-rgb.g)/(rgb.b-rgb.r);
else if(rgb.b>=rgb.r && rgb.r>=rgb.g) hsb.h = 240 + 60*(rgb.r-rgb.g)/(rgb.b-rgb.g);
else if(rgb.r>=rgb.b && rgb.b>=rgb.g) hsb.h = 300 + 60*(rgb.r-rgb.b)/(rgb.r-rgb.g);
else hsb.h = 0;
hsb.h = Math.round(hsb.h);
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
};
return {
init: function (options) {
options = $.extend({}, defaults, options||{});
if (typeof options.color == 'string') {
options.color = HexToHSB(options.color);
} else if (options.color.r != undefined && options.color.g != undefined && options.color.b != undefined) {
options.color = RGBToHSB(options.color);
} else if (options.color.h != undefined && options.color.s != undefined && options.color.b != undefined) {
options.color = fixHSB(options.color);
} else {
return this;
}
options.origColor = options.color;
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keydown', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal.find('span').bind('mousedown', downIncrement);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hide,
ColorPickerShow: ColorPicker.show,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery) | JavaScript |
/*
* Easy Slider 1.5 - jQuery plugin
* written by Alen Grakalic
* http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
*
* Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* Built for jQuery library
* http://jquery.com
*
*/
/*
* markup example for $("#slider").easySlider();
*
* <div id="slider">
* <ul>
* <li><img src="images/01.jpg" alt="" /></li>
* <li><img src="images/02.jpg" alt="" /></li>
* <li><img src="images/03.jpg" alt="" /></li>
* <li><img src="images/04.jpg" alt="" /></li>
* <li><img src="images/05.jpg" alt="" /></li>
* </ul>
* </div>
*
*/
(function($) {
$.fn.easySlider = function(options){
// default configuration properties
var defaults = {
prevId: 'prevBtn',
prevText: '',
nextId: 'nextBtn',
nextText: '',
controlsShow: true,
controlsBefore: '',
controlsAfter: '',
controlsFade: true,
firstId: 'firstBtn',
firstText: 'First',
firstShow: false,
lastId: 'lastBtn',
lastText: 'Last',
lastShow: false,
vertical: false,
speed: 800,
auto: false,
pause: 2000,
continuous: false
};
var options = $.extend(defaults, options);
this.each(function() {
var obj = $(this);
var s = $("li", obj).length;
var w = $("li", obj).width();
var h = $("li", obj).height();
obj.width(w);
obj.height(h);
obj.css("overflow","hidden");
var ts = s-1;
var t = 0;
$("ul", obj).css('width',s*w);
if(!options.vertical) $("li", obj).css('float','left');
if(options.controlsShow){
var html = options.controlsBefore;
if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>';
html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';
html += options.controlsAfter;
$(obj).after(html);
};
$("a","#"+options.nextId).click(function(){
animate("next",true);
});
$("a","#"+options.prevId).click(function(){
animate("prev",true);
});
$("a","#"+options.firstId).click(function(){
animate("first",true);
});
$("a","#"+options.lastId).click(function(){
animate("last",true);
});
function animate(dir,clicked){
var ot = t;
switch(dir){
case "next":
t = (ot>=ts) ? (options.continuous ? 0 : ts) : t+1;
break;
case "prev":
t = (t<=0) ? (options.continuous ? ts : 0) : t-1;
break;
case "first":
t = 0;
break;
case "last":
t = ts;
break;
default:
break;
};
var diff = Math.abs(ot-t);
var speed = diff*options.speed;
if(!options.vertical) {
p = (t*w*-1);
$("ul",obj).animate(
{ marginLeft: p },
speed
);
} else {
p = (t*h*-1);
$("ul",obj).animate(
{ marginTop: p },
speed
);
};
if(!options.continuous && options.controlsFade){
if(t==ts){
$("a","#"+options.nextId).hide();
$("a","#"+options.lastId).hide();
} else {
$("a","#"+options.nextId).show();
$("a","#"+options.lastId).show();
};
if(t==0){
$("a","#"+options.prevId).hide();
$("a","#"+options.firstId).hide();
} else {
$("a","#"+options.prevId).show();
$("a","#"+options.firstId).show();
};
};
if(clicked) clearTimeout(timeout);
if(options.auto && dir=="next" && !clicked){;
timeout = setTimeout(function(){
animate("next",false);
},diff*options.speed+options.pause);
};
};
// init
var timeout;
if(options.auto){;
timeout = setTimeout(function(){
animate("next",false);
},options.pause);
};
if(!options.continuous && options.controlsFade){
$("a","#"+options.prevId).hide();
$("a","#"+options.firstId).hide();
};
});
};
})(jQuery);
| JavaScript |
/*
* Facebox (for jQuery)
* version: 1.2 (05/05/2008)
* @requires jQuery v1.2 or later
*
* Examples at http://famspam.com/facebox/
*
* Licensed under the MIT:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
*
* Usage:
*
* jQuery(document).ready(function() {
* jQuery('a[rel*=facebox]').facebox()
* })
*
* <a href="#terms" rel="facebox">Terms</a>
* Loads the #terms div in the box
*
* <a href="terms.html" rel="facebox">Terms</a>
* Loads the terms.html page in the box
*
* <a href="terms.png" rel="facebox">Terms</a>
* Loads the terms.png image in the box
*
*
* You can also use it programmatically:
*
* jQuery.facebox('some html')
*
* The above will open a facebox with "some html" as the content.
*
* jQuery.facebox(function($) {
* $.get('blah.html', function(data) { $.facebox(data) })
* })
*
* The above will show a loading screen before the passed function is called,
* allowing for a better ajaxy experience.
*
* The facebox function can also display an ajax page or image:
*
* jQuery.facebox({ ajax: 'remote.html' })
* jQuery.facebox({ image: 'dude.jpg' })
*
* Want to close the facebox? Trigger the 'close.facebox' document event:
*
* jQuery(document).trigger('close.facebox')
*
* Facebox also has a bunch of other hooks:
*
* loading.facebox
* beforeReveal.facebox
* reveal.facebox (aliased as 'afterReveal.facebox')
* init.facebox
*
* Simply bind a function to any of these hooks:
*
* $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
*
*/
(function($) {
$.facebox = function(data, klass) {
$.facebox.loading()
if (data.ajax) fillFaceboxFromAjax(data.ajax)
else if (data.image) fillFaceboxFromImage(data.image)
else if (data.div) fillFaceboxFromHref(data.div)
else if ($.isFunction(data)) data.call($)
else $.facebox.reveal(data, klass)
}
/*
* Public, $.facebox methods
*/
$.extend($.facebox, {
settings: {
opacity : 0,
overlay : true,
loadingImage : '/public/skins/icons/loading.gif',
closeImage : '/public/skins/icons/closelabel.gif',
imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ],
faceboxHtml : '\
<div id="facebox" style="display:none;"> \
<div class="popup"> \
<table> \
<tbody> \
<tr> \
<td class="tl"/><td class="b"/><td class="tr"/> \
</tr> \
<tr> \
<td class="b"/> \
<td class="body"> \
<div class="content"> \
</div> \
<div class="footer"> \
<a href="#" class="close"> \
<img src="closelabel.gif" title="close" class="close_image" /> \
</a> \
</div> \
</td> \
<td class="b"/> \
</tr> \
<tr> \
<td class="bl"/><td class="b"/><td class="br"/> \
</tr> \
</tbody> \
</table> \
</div> \
</div>'
},
loading: function() {
init()
if ($('#facebox .loading').length == 1) return true
showOverlay()
$('#facebox .content').empty()
$('#facebox .body').children().hide().end().
append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')
$('#facebox').css({
top: getPageScroll()[1] + (getPageHeight() / 10),
left: 385.5
}).show()
$(document).bind('keydown.facebox', function(e) {
if (e.keyCode == 27) $.facebox.close()
return true
})
$(document).trigger('loading.facebox')
},
reveal: function(data, klass) {
$(document).trigger('beforeReveal.facebox')
if (klass) $('#facebox .content').addClass(klass)
$('#facebox .content').append(data)
$('#facebox .loading').remove()
$('#facebox .body').children().fadeIn('normal')
$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
},
close: function() {
$(document).trigger('close.facebox')
return false
}
})
/*
* Public, $.fn methods
*/
$.fn.facebox = function(settings) {
init(settings)
function clickHandler() {
$.facebox.loading(true)
// support for rel="facebox.inline_popup" syntax, to add a class
// also supports deprecated "facebox[.inline_popup]" syntax
var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
if (klass) klass = klass[1]
fillFaceboxFromHref(this.href, klass)
return false
}
return this.click(clickHandler)
}
/*
* Private methods
*/
// called one time to setup facebox on this page
function init(settings) {
if ($.facebox.settings.inited) return true
else $.facebox.settings.inited = true
$(document).trigger('init.facebox')
makeCompatible()
var imageTypes = $.facebox.settings.imageTypes.join('|')
$.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')
if (settings) $.extend($.facebox.settings, settings)
$('body').append($.facebox.settings.faceboxHtml)
var preload = [ new Image(), new Image() ]
preload[0].src = $.facebox.settings.closeImage
preload[1].src = $.facebox.settings.loadingImage
$('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
preload.push(new Image())
preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
})
$('#facebox .close').click($.facebox.close)
$('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
}
// getPageScroll() by quirksmode.com
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
// Backwards compatibility
function makeCompatible() {
var $s = $.facebox.settings
$s.loadingImage = $s.loading_image || $s.loadingImage
$s.closeImage = $s.close_image || $s.closeImage
$s.imageTypes = $s.image_types || $s.imageTypes
$s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
}
// Figures out what you want to display and displays it
// formats are:
// div: #id
// image: blah.extension
// ajax: anything else
function fillFaceboxFromHref(href, klass) {
// div
if (href.match(/#/)) {
var url = window.location.href.split('#')[0]
var target = href.replace(url,'')
$.facebox.reveal($(target).clone().show(), klass)
// image
} else if (href.match($.facebox.settings.imageTypesRegexp)) {
fillFaceboxFromImage(href, klass)
// ajax
} else {
fillFaceboxFromAjax(href, klass)
}
}
function fillFaceboxFromImage(href, klass) {
var image = new Image()
image.onload = function() {
$.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
}
image.src = href
}
function fillFaceboxFromAjax(href, klass) {
$.get(href, function(data) { $.facebox.reveal(data, klass) })
}
function skipOverlay() {
return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
}
function showOverlay() {
if (skipOverlay()) return
if ($('facebox_overlay').length == 0)
$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
$('#facebox_overlay').hide().addClass("facebox_overlayBG")
.css('opacity', $.facebox.settings.opacity)
.click(function() { $(document).trigger('close.facebox') })
.fadeIn(200)
return false
}
function hideOverlay() {
if (skipOverlay()) return
$('#facebox_overlay').fadeOut(200, function(){
$("#facebox_overlay").removeClass("facebox_overlayBG")
$("#facebox_overlay").addClass("facebox_hide")
$("#facebox_overlay").remove()
})
return false
}
/*
* Bindings
*/
$(document).bind('close.facebox', function() {
$(document).unbind('keydown.facebox')
$('#facebox').fadeOut(function() {
$('#facebox .content').removeClass().addClass('content')
hideOverlay()
$('#facebox .loading').remove()
})
})
})(jQuery);
| JavaScript |
/******************************************************************************
Name: Highslide JS
Version: 4.1.7 (September 28 2009)
Config: default +slideshow +positioning +transitions +viewport +thumbstrip
Author: Torstein Hønsi
Support: http://highslide.com/support
Licence:
Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5
License (http://creativecommons.org/licenses/by-nc/2.5/).
You are free:
* to copy, distribute, display, and perform the work
* to make derivative works
Under the following conditions:
* Attribution. You must attribute the work in the manner specified by the
author or licensor.
* Noncommercial. You may not use this work for commercial purposes.
* For any reuse or distribution, you must make clear to others the license
terms of this work.
* Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
******************************************************************************/
if (!hs) { var hs = {
// Language strings
lang : {
cssDirection: 'ltr',
loadingText : 'Loading...',
loadingTitle : 'Click to cancel',
focusTitle : 'Click to bring to front',
fullExpandTitle : 'Expand to actual size (f)',
creditsText : 'Powered by <i>Highslide JS</i>',
creditsTitle : 'Go to the Highslide JS homepage',
previousText : 'Previous',
nextText : 'Next',
moveText : 'Move',
closeText : 'Close',
closeTitle : 'Close (esc)',
resizeTitle : 'Resize',
playText : 'Play',
playTitle : 'Play slideshow (spacebar)',
pauseText : 'Pause',
pauseTitle : 'Pause slideshow (spacebar)',
previousTitle : 'Previous (arrow left)',
nextTitle : 'Next (arrow right)',
moveTitle : 'Move',
fullExpandText : '1:1',
number: 'Image %1 of %2',
restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.'
},
// See http://highslide.com/ref for examples of settings
graphicsDir : 'highslide/graphics/',
expandCursor : 'zoomin.cur', // null disables
restoreCursor : 'zoomout.cur', // null disables
expandDuration : 250, // milliseconds
restoreDuration : 250,
marginLeft : 15,
marginRight : 15,
marginTop : 15,
marginBottom : 15,
zIndexCounter : 1001, // adjust to other absolutely positioned elements
loadingOpacity : 0.75,
allowMultipleInstances: true,
numberOfImagesToPreload : 5,
outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only
outlineStartOffset : 3, // ends at 10
padToMinWidth : false, // pad the popup width to make room for wide caption
fullExpandPosition : 'bottom right',
fullExpandOpacity : 1,
showCredits : true, // you can set this to false if you want
creditsHref : 'http://21w.pl/',
creditsTarget : '_self',
enableKeyListener : true,
openerTagNames : ['a'], // Add more to allow slideshow indexing
transitions : [],
transitionDuration: 250,
dimmingOpacity: 0, // Lightbox style dimming background
dimmingDuration: 50, // 0 for instant dimming
anchor : 'auto', // where the image expands from
align : 'auto', // position in the client (overrides anchor)
targetX: null, // the id of a target element
targetY: null,
dragByHeading: true,
minWidth: 200,
minHeight: 200,
allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight
outlineType : 'drop-shadow', // set null to disable outlines
skin : {
controls:
'<div class="highslide-controls"><ul>'+
'<li class="highslide-previous">'+
'<a href="#" title="{hs.lang.previousTitle}">'+
'<span>{hs.lang.previousText}</span></a>'+
'</li>'+
'<li class="highslide-play">'+
'<a href="#" title="{hs.lang.playTitle}">'+
'<span>{hs.lang.playText}</span></a>'+
'</li>'+
'<li class="highslide-pause">'+
'<a href="#" title="{hs.lang.pauseTitle}">'+
'<span>{hs.lang.pauseText}</span></a>'+
'</li>'+
'<li class="highslide-next">'+
'<a href="#" title="{hs.lang.nextTitle}">'+
'<span>{hs.lang.nextText}</span></a>'+
'</li>'+
'<li class="highslide-move">'+
'<a href="#" title="{hs.lang.moveTitle}">'+
'<span>{hs.lang.moveText}</span></a>'+
'</li>'+
'<li class="highslide-full-expand">'+
'<a href="#" title="{hs.lang.fullExpandTitle}">'+
'<span>{hs.lang.fullExpandText}</span></a>'+
'</li>'+
'<li class="highslide-close">'+
'<a href="#" title="{hs.lang.closeTitle}" >'+
'<span>{hs.lang.closeText}</span></a>'+
'</li>'+
'</ul></div>'
},
// END OF YOUR SETTINGS
// declare internal properties
preloadTheseImages : [],
continuePreloading: true,
expanders : [],
overrides : [
'allowSizeReduction',
'useBox',
'anchor',
'align',
'targetX',
'targetY',
'outlineType',
'outlineWhileAnimating',
'captionId',
'captionText',
'captionEval',
'captionOverlay',
'headingId',
'headingText',
'headingEval',
'headingOverlay',
'creditsPosition',
'dragByHeading',
'autoplay',
'numberPosition',
'transitions',
'dimmingOpacity',
'width',
'height',
'wrapperClassName',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'slideshowGroup',
'easing',
'easingClose',
'fadeInOut',
'src'
],
overlays : [],
idCounter : 0,
oPos : {
x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'],
y: ['above', 'top', 'middle', 'bottom', 'below']
},
mouse: {},
headingOverlay: {},
captionOverlay: {},
timers : [],
slideshows : [],
pendingOutlines : {},
clones : {},
onReady: [],
uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 :
parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]),
ie : (document.all && !window.opera),
safari : /Safari/.test(navigator.userAgent),
geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent),
$ : function (id) {
if (id) return document.getElementById(id);
},
push : function (arr, val) {
arr[arr.length] = val;
},
createElement : function (tag, attribs, styles, parent, nopad) {
var el = document.createElement(tag);
if (attribs) hs.extend(el, attribs);
if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0});
if (styles) hs.setStyles(el, styles);
if (parent) parent.appendChild(el);
return el;
},
extend : function (el, attribs) {
for (var x in attribs) el[x] = attribs[x];
return el;
},
setStyles : function (el, styles) {
for (var x in styles) {
if (hs.ie && x == 'opacity') {
if (styles[x] > 0.99) el.style.removeAttribute('filter');
else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')';
}
else el.style[x] = styles[x];
}
},
animate: function(el, prop, opt) {
var start,
end,
unit;
if (typeof opt != 'object' || opt === null) {
var args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (typeof opt.duration != 'number') opt.duration = 250;
opt.easing = Math[opt.easing] || Math.easeInQuad;
opt.curAnim = hs.extend({}, prop);
for (var name in prop) {
var e = new hs.fx(el, opt , name );
start = parseFloat(hs.css(el, name)) || 0;
end = parseFloat(prop[name]);
unit = name != 'opacity' ? 'px' : '';
e.custom( start, end, unit );
}
},
css: function(el, prop) {
if (document.defaultView) {
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
} else {
if (prop == 'opacity') prop = 'filter';
var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })];
if (prop == 'filter')
val = val.replace(/alpha\(opacity=([0-9]+)\)/,
function (a, b) { return b / 100 });
return val === '' ? 1 : val;
}
},
getPageSize : function () {
var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat'
? d.documentElement : d.body;
var width = hs.ie ? iebody.clientWidth :
(d.documentElement.clientWidth || self.innerWidth),
height = hs.ie ? iebody.clientHeight : self.innerHeight;
hs.page = {
width: width,
height: height,
scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset,
scrollTop: hs.ie ? iebody.scrollTop : pageYOffset
}
},
getPosition : function(el) {
var p = { x: el.offsetLeft, y: el.offsetTop };
while (el.offsetParent) {
el = el.offsetParent;
p.x += el.offsetLeft;
p.y += el.offsetTop;
if (el != document.body && el != document.documentElement) {
p.x -= el.scrollLeft;
p.y -= el.scrollTop;
}
}
return p;
},
expand : function(a, params, custom, type) {
if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container);
if (typeof a.getParams == 'function') return params;
try {
new hs.Expander(a, params, custom);
return false;
} catch (e) { return true; }
},
getElementByClass : function (el, tagName, className) {
var els = el.getElementsByTagName(tagName);
for (var i = 0; i < els.length; i++) {
if ((new RegExp(className)).test(els[i].className)) {
return els[i];
}
}
return null;
},
replaceLang : function(s) {
s = s.replace(/\s/g, ' ');
var re = /{hs\.lang\.([^}]+)\}/g,
matches = s.match(re),
lang;
if (matches) for (var i = 0; i < matches.length; i++) {
lang = matches[i].replace(re, "$1");
if (typeof hs.lang[lang] != 'undefined') s = s.replace(matches[i], hs.lang[lang]);
}
return s;
},
focusTopmost : function() {
var topZ = 0,
topmostKey = -1,
expanders = hs.expanders,
exp,
zIndex;
for (var i = 0; i < expanders.length; i++) {
exp = expanders[i];
if (exp) {
zIndex = exp.wrapper.style.zIndex;
if (zIndex && zIndex > topZ) {
topZ = zIndex;
topmostKey = i;
}
}
}
if (topmostKey == -1) hs.focusKey = -1;
else expanders[topmostKey].focus();
},
getParam : function (a, param) {
a.getParams = a.onclick;
var p = a.getParams ? a.getParams() : null;
a.getParams = null;
return (p && typeof p[param] != 'undefined') ? p[param] :
(typeof hs[param] != 'undefined' ? hs[param] : null);
},
getSrc : function (a) {
var src = hs.getParam(a, 'src');
if (src) return src;
return a.href;
},
getNode : function (id) {
var node = hs.$(id), clone = hs.clones[id], a = {};
if (!node && !clone) return null;
if (!clone) {
clone = node.cloneNode(true);
clone.id = '';
hs.clones[id] = clone;
return node;
} else {
return clone.cloneNode(true);
}
},
discardElement : function(d) {
if (d) hs.garbageBin.appendChild(d);
hs.garbageBin.innerHTML = '';
},
dim : function(exp) {
function fix(prop) {
return 'expression( ( ( ignoreMe = document.documentElement.'+ prop +
' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );';
}
if (!hs.dimmer) {
hs.dimmer = hs.createElement ('div', {
className: 'highslide-dimming highslide-viewport-size',
owner: '',
onclick: function() {
hs.close();
}
}, {
visibility: 'visible',
opacity: 0
}, hs.container, true);
}
hs.dimmer.style.display = '';
hs.dimmer.owner += '|'+ exp.key;
if (hs.geckoMac && hs.dimmingGeckoFix)
hs.setStyles(hs.dimmer, {
background: 'url('+ hs.graphicsDir + 'geckodimmer.png)',
opacity: 1
});
else
hs.animate(hs.dimmer, { opacity: exp.dimmingOpacity }, hs.dimmingDuration);
},
undim : function(key) {
if (!hs.dimmer) return;
if (typeof key != 'undefined') hs.dimmer.owner = hs.dimmer.owner.replace('|'+ key, '');
if (
(typeof key != 'undefined' && hs.dimmer.owner != '')
|| (hs.upcoming && hs.getParam(hs.upcoming, 'dimmingOpacity'))
) return;
if (hs.geckoMac && hs.dimmingGeckoFix) hs.dimmer.style.display = 'none';
else hs.animate(hs.dimmer, { opacity: 0 }, hs.dimmingDuration, null, function() {
hs.dimmer.style.display = 'none';
});
},
transit : function (adj, exp) {
var last = exp = exp || hs.getExpander();
if (hs.upcoming) return false;
else hs.last = last;
try {
hs.upcoming = adj;
adj.onclick();
} catch (e){
hs.last = hs.upcoming = null;
}
try {
if (!adj || exp.transitions[1] != 'crossfade')
exp.close();
} catch (e) {}
return false;
},
previousOrNext : function (el, op) {
var exp = hs.getExpander(el);
if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp);
else return false;
},
previous : function (el) {
return hs.previousOrNext(el, -1);
},
next : function (el) {
return hs.previousOrNext(el, 1);
},
keyHandler : function(e) {
if (!e) e = window.event;
if (!e.target) e.target = e.srcElement; // ie
if (typeof e.target.form != 'undefined') return true; // form element has focus
var exp = hs.getExpander();
var op = null;
switch (e.keyCode) {
case 70: // f
if (exp) exp.doFullExpand();
return true;
case 32: // Space
op = 2;
break;
case 34: // Page Down
case 39: // Arrow right
case 40: // Arrow down
op = 1;
break;
case 8: // Backspace
case 33: // Page Up
case 37: // Arrow left
case 38: // Arrow up
op = -1;
break;
case 27: // Escape
case 13: // Enter
op = 0;
}
if (op !== null) {if (op != 2)hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
if (!hs.enableKeyListener) return true;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (exp) {
if (op == 0) {
exp.close();
} else if (op == 2) {
if (exp.slideshow) exp.slideshow.hitSpace();
} else {
if (exp.slideshow) exp.slideshow.pause();
hs.previousOrNext(exp.key, op);
}
return false;
}
}
return true;
},
registerOverlay : function (overlay) {
hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } ));
},
addSlideshow : function (options) {
var sg = options.slideshowGroup;
if (typeof sg == 'object') {
for (var i = 0; i < sg.length; i++) {
var o = {};
for (var x in options) o[x] = options[x];
o.slideshowGroup = sg[i];
hs.push(hs.slideshows, o);
}
} else {
hs.push(hs.slideshows, options);
}
},
getWrapperKey : function (element, expOnly) {
var el, re = /^highslide-wrapper-([0-9]+)$/;
// 1. look in open expanders
el = element;
while (el.parentNode) {
if (el.hsKey !== undefined) return el.hsKey;
if (el.id && re.test(el.id)) return el.id.replace(re, "$1");
el = el.parentNode;
}
// 2. look in thumbnail
if (!expOnly) {
el = element;
while (el.parentNode) {
if (el.tagName && hs.isHsAnchor(el)) {
for (var key = 0; key < hs.expanders.length; key++) {
var exp = hs.expanders[key];
if (exp && exp.a == el) return key;
}
}
el = el.parentNode;
}
}
return null;
},
getExpander : function (el, expOnly) {
if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null;
if (typeof el == 'number') return hs.expanders[el] || null;
if (typeof el == 'string') el = hs.$(el);
return hs.expanders[hs.getWrapperKey(el, expOnly)] || null;
},
isHsAnchor : function (a) {
return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/));
},
reOrder : function () {
for (var i = 0; i < hs.expanders.length; i++)
if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost();
},
mouseClickHandler : function(e)
{
if (!e) e = window.event;
if (e.button > 1) return true;
if (!e.target) e.target = e.srcElement;
var el = e.target;
while (el.parentNode
&& !(/highslide-(image|move|html|resize)/.test(el.className)))
{
el = el.parentNode;
}
var exp = hs.getExpander(el);
if (exp && (exp.isClosing || !exp.isExpanded)) return true;
if (exp && e.type == 'mousedown') {
if (e.target.form) return true;
var match = el.className.match(/highslide-(image|move|resize)/);
if (match) {
hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos,
height: exp.y.size, clickX: e.clientX, clickY: e.clientY };
hs.addEventListener(document, 'mousemove', hs.dragHandler);
if (e.preventDefault) e.preventDefault(); // FF
if (/highslide-(image|html)-blur/.test(exp.content.className)) {
exp.focus();
hs.hasFocused = true;
}
return false;
}
} else if (e.type == 'mouseup') {
hs.removeEventListener(document, 'mousemove', hs.dragHandler);
if (hs.dragArgs) {
if (hs.styleRestoreCursor && hs.dragArgs.type == 'image')
hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor;
var hasDragged = hs.dragArgs.hasDragged;
if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) {
exp.close();
}
else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) {
hs.dragArgs.exp.doShowHide('hidden');
}
hs.hasFocused = false;
hs.dragArgs = null;
} else if (/highslide-image-blur/.test(el.className)) {
el.style.cursor = hs.styleRestoreCursor;
}
}
return false;
},
dragHandler : function(e)
{
if (!hs.dragArgs) return true;
if (!e) e = window.event;
var a = hs.dragArgs, exp = a.exp;
a.dX = e.clientX - a.clickX;
a.dY = e.clientY - a.clickY;
var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2));
if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0)
|| (distance > (hs.dragSensitivity || 5));
if (a.hasDragged && e.clientX > 5 && e.clientY > 5) {
if (a.type == 'resize') exp.resize(a);
else {
exp.moveTo(a.left + a.dX, a.top + a.dY);
if (a.type == 'image') exp.content.style.cursor = 'move';
}
}
return false;
},
wrapperMouseHandler : function (e) {
try {
if (!e) e = window.event;
var over = /mouseover/i.test(e.type);
if (!e.target) e.target = e.srcElement; // ie
if (hs.ie) e.relatedTarget =
over ? e.fromElement : e.toElement; // ie
var exp = hs.getExpander(e.target);
if (!exp.isExpanded) return;
if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp
|| hs.dragArgs) return;
for (var i = 0; i < exp.overlays.length; i++) (function() {
var o = hs.$('hsId'+ exp.overlays[i]);
if (o && o.hideOnMouseOut) {
if (over) hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur);
}
})();
} catch (e) {}
},
addEventListener : function (el, event, func) {
if (el == document && event == 'ready') hs.push(hs.onReady, func);
try {
el.addEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
el.attachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = func;
}
}
},
removeEventListener : function (el, event, func) {
try {
el.removeEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = null;
}
}
},
preloadFullImage : function (i) {
if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') {
var img = document.createElement('img');
img.onload = function() {
img = null;
hs.preloadFullImage(i + 1);
};
img.src = hs.preloadTheseImages[i];
}
},
preloadImages : function (number) {
if (number && typeof number != 'object') hs.numberOfImagesToPreload = number;
var arr = hs.getAnchors();
for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) {
hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i]));
}
// preload outlines
if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} );
else
hs.preloadFullImage(0);
// preload cursor
if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor });
},
init : function () {
if (!hs.container) {
hs.getPageSize();
hs.ieLt7 = hs.ie && hs.uaVersion < 7;
for (var x in hs.langDefaults) {
if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x];
else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined')
hs.lang[x] = hs.langDefaults[x];
}
hs.container = hs.createElement('div', {
className: 'highslide-container'
}, {
position: 'absolute',
left: 0,
top: 0,
width: '100%',
zIndex: hs.zIndexCounter,
direction: 'ltr'
},
document.body,
true
);
hs.loading = hs.createElement('a', {
className: 'highslide-loading',
title: hs.lang.loadingTitle,
innerHTML: hs.lang.loadingText,
href: 'javascript:;'
}, {
position: 'absolute',
top: '-9999px',
opacity: hs.loadingOpacity,
zIndex: 1
}, hs.container
);
hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container);
hs.viewport = hs.createElement('div', {
className: 'highslide-viewport highslide-viewport-size'
}, {
visibility: (hs.safari && hs.uaVersion < 525) ? 'visible' : 'hidden'
}, hs.container, 1
);
// http://www.robertpenner.com/easing/
Math.linearTween = function (t, b, c, d) {
return c*t/d + b;
};
Math.easeInQuad = function (t, b, c, d) {
return c*(t/=d)*t + b;
};
Math.easeOutQuad = function (t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
};
hs.hideSelects = hs.ieLt7;
hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE'
|| (hs.ie && hs.uaVersion < 5.5));
}
},
ready : function() {
if (hs.isReady) return;
hs.isReady = true;
for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i]();
},
updateAnchors : function() {
var el, els, all = [], images = [],groups = {}, re;
for (var i = 0; i < hs.openerTagNames.length; i++) {
els = document.getElementsByTagName(hs.openerTagNames[i]);
for (var j = 0; j < els.length; j++) {
el = els[j];
re = hs.isHsAnchor(el);
if (re) {
hs.push(all, el);
if (re[0] == 'hs.expand') hs.push(images, el);
var g = hs.getParam(el, 'slideshowGroup') || 'none';
if (!groups[g]) groups[g] = [];
hs.push(groups[g], el);
}
}
}
hs.anchors = { all: all, groups: groups, images: images };
return hs.anchors;
},
getAnchors : function() {
return hs.anchors || hs.updateAnchors();
},
close : function(el) {
var exp = hs.getExpander(el);
if (exp) exp.close();
return false;
}
}; // end hs object
hs.fx = function( elem, options, prop ){
this.options = options;
this.elem = elem;
this.prop = prop;
if (!options.orig) options.orig = {};
};
hs.fx.prototype = {
update: function(){
(hs.fx.step[this.prop] || hs.fx.step._default)(this);
if (this.options.step)
this.options.step.call(this.elem, this.now, this);
},
custom: function(from, to, unit){
this.startTime = (new Date()).getTime();
this.start = from;
this.end = to;
this.unit = unit;// || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t(gotoEnd){
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && hs.timers.push(t) == 1 ) {
hs.timerId = setInterval(function(){
var timers = hs.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval(hs.timerId);
}
}, 13);
}
},
step: function(gotoEnd){
var t = (new Date()).getTime();
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
var done = true;
for ( var i in this.options.curAnim )
if ( this.options.curAnim[i] !== true )
done = false;
if ( done ) {
if (this.options.complete) this.options.complete.call(this.elem);
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
this.pos = this.options.easing(n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
}
return true;
}
};
hs.extend( hs.fx, {
step: {
opacity: function(fx){
hs.setStyles(fx.elem, { opacity: fx.now });
},
_default: function(fx){
try {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
else
fx.elem[ fx.prop ] = fx.now;
} catch (e) {}
}
}
});
hs.Outline = function (outlineType, onLoad) {
this.onLoad = onLoad;
this.outlineType = outlineType;
var v = hs.uaVersion, tr;
this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7;
if (!outlineType) {
if (onLoad) onLoad();
return;
}
hs.init();
this.table = hs.createElement(
'table', {
cellSpacing: 0
}, {
visibility: 'hidden',
position: 'absolute',
borderCollapse: 'collapse',
width: 0
},
hs.container,
true
);
var tbody = hs.createElement('tbody', null, null, this.table, 1);
this.td = [];
for (var i = 0; i <= 8; i++) {
if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true);
this.td[i] = hs.createElement('td', null, null, tr, true);
var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' };
hs.setStyles(this.td[i], style);
}
this.td[4].className = outlineType +' highslide-outline';
this.preloadGraphic();
};
hs.Outline.prototype = {
preloadGraphic : function () {
var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png";
var appendTo = hs.safari ? hs.container : null;
this.graphic = hs.createElement('img', null, { position: 'absolute',
top: '-9999px' }, appendTo, true); // for onload trigger
var pThis = this;
this.graphic.onload = function() { pThis.onGraphicLoad(); };
this.graphic.src = src;
},
onGraphicLoad : function () {
var o = this.offset = this.graphic.width / 4,
pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]],
dim = { height: (2*o) +'px', width: (2*o) +'px' };
for (var i = 0; i <= 8; i++) {
if (pos[i]) {
if (this.hasAlphaImageLoader) {
var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px';
var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true);
hs.createElement ('div', null, {
filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')",
position: 'absolute',
width: w,
height: this.graphic.height +'px',
left: (pos[i][0]*o)+'px',
top: (pos[i][1]*o)+'px'
},
div,
true);
} else {
hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'});
}
if (window.opera && (i == 3 || i ==5))
hs.createElement('div', null, dim, this.td[i], true);
hs.setStyles (this.td[i], dim);
}
}
this.graphic = null;
if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy();
hs.pendingOutlines[this.outlineType] = this;
if (this.onLoad) this.onLoad();
},
setPosition : function (pos, offset, vis, dur, easing) {
var exp = this.exp,
stl = exp.wrapper.style,
offset = offset || 0,
pos = pos || {
x: exp.x.pos + offset,
y: exp.y.pos + offset,
w: exp.x.get('wsize') - 2 * offset,
h: exp.y.get('wsize') - 2 * offset
};
if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset)
? 'visible' : 'hidden';
hs.setStyles(this.table, {
left: (pos.x - this.offset) +'px',
top: (pos.y - this.offset) +'px',
width: (pos.w + 2 * this.offset) +'px'
});
pos.w -= 2 * this.offset;
pos.h -= 2 * this.offset;
hs.setStyles (this.td[4], {
width: pos.w >= 0 ? pos.w +'px' : 0,
height: pos.h >= 0 ? pos.h +'px' : 0
});
if (this.hasAlphaImageLoader) this.td[3].style.height
= this.td[5].style.height = this.td[4].style.height;
},
destroy : function(hide) {
if (hide) this.table.style.visibility = 'hidden';
else hs.discardElement(this.table);
}
};
hs.Dimension = function(exp, dim) {
this.exp = exp;
this.dim = dim;
this.ucwh = dim == 'x' ? 'Width' : 'Height';
this.wh = this.ucwh.toLowerCase();
this.uclt = dim == 'x' ? 'Left' : 'Top';
this.lt = this.uclt.toLowerCase();
this.ucrb = dim == 'x' ? 'Right' : 'Bottom';
this.rb = this.ucrb.toLowerCase();
this.p1 = this.p2 = 0;
};
hs.Dimension.prototype = {
get : function(key) {
switch (key) {
case 'loadingPos':
return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2;
case 'loadingPosXfade':
return this.pos + this.cb+ this.p1 + (this.size - hs.loading['offset'+ this.ucwh]) / 2;
case 'wsize':
return this.size + 2 * this.cb + this.p1 + this.p2;
case 'fitsize':
return this.clientSize - this.marginMin - this.marginMax;
case 'maxsize':
return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ;
case 'opos':
return this.pos - (this.exp.outline ? this.exp.outline.offset : 0);
case 'osize':
return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0);
case 'imgPad':
return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0;
}
},
calcBorders: function() {
// correct for borders
this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2;
this.marginMax = hs['margin'+ this.ucrb];
},
calcThumb: function() {
this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) :
this.exp.el['offset'+ this.ucwh];
this.tpos = this.exp.tpos[this.dim];
this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2;
if (this.tpos == 0 || this.tpos == -1) {
this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt];
};
},
calcExpanded: function() {
var exp = this.exp;
this.justify = 'auto';
// get alignment
if (exp.align == 'center') this.justify = 'center';
else if (new RegExp(this.lt).test(exp.anchor)) this.justify = null;
else if (new RegExp(this.rb).test(exp.anchor)) this.justify = 'max';
// size and position
this.pos = this.tpos - this.cb + this.tb;
if (this.dim == 'x')
exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full);
this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full);
this.minSize = exp.allowSizeReduction ?
Math.min(exp['min'+ this.ucwh], this.full) :this.full;
if (exp.isImage && exp.useBox) {
this.size = exp[this.wh];
this.imgSize = this.full;
}
if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth;
this.target = exp['target'+ this.dim.toUpperCase()];
this.marginMin = hs['margin'+ this.uclt];
this.scroll = hs.page['scroll'+ this.uclt];
this.clientSize = hs.page[this.wh];
},
setSize: function(i) {
var exp = this.exp;
if (exp.isImage && (exp.useBox || hs.padToMinWidth)) {
this.imgSize = i;
this.size = Math.max(this.size, this.imgSize);
exp.content.style[this.lt] = this.get('imgPad')+'px';
} else
this.size = i;
exp.content.style[this.wh] = i +'px';
exp.wrapper.style[this.wh] = this.get('wsize') +'px';
if (exp.outline) exp.outline.setPosition();
if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true);
if (this.dim == 'x' && exp.slideshow && exp.isImage) {
if (i == this.full) exp.slideshow.disable('full-expand');
else exp.slideshow.enable('full-expand');
}
},
setPos: function(i) {
this.pos = i;
this.exp.wrapper.style[this.lt] = i +'px';
if (this.exp.outline) this.exp.outline.setPosition();
}
};
hs.Expander = function(a, params, custom, contentType) {
if (document.readyState && hs.ie && !hs.isReady) {
hs.addEventListener(document, 'ready', function() {
new hs.Expander(a, params, custom, contentType);
});
return;
}
this.a = a;
this.custom = custom;
this.contentType = contentType || 'image';
this.isImage = !this.isHtml;
hs.continuePreloading = false;
this.overlays = [];
this.last = hs.last;
hs.last = null;
hs.init();
var key = this.key = hs.expanders.length;
// override inline parameters
for (var i = 0; i < hs.overrides.length; i++) {
var name = hs.overrides[i];
this[name] = params && typeof params[name] != 'undefined' ?
params[name] : hs[name];
}
if (!this.src) this.src = a.href;
// get thumb
var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a;
el = this.thumb = el.getElementsByTagName('img')[0] || el;
this.thumbsUserSetId = el.id || a.id;
// check if already open
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].a == a
&& !(this.last && this.transitions[1] == 'crossfade')) {
hs.expanders[i].focus();
return false;
}
}
// cancel other
if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) {
hs.expanders[i].cancelLoading();
}
}
hs.expanders[key] = this;
if (!hs.allowMultipleInstances && !hs.upcoming) {
if (hs.expanders[key-1]) hs.expanders[key-1].close();
if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey])
hs.expanders[hs.focusKey].close();
}
// initiate metrics
this.el = el;
this.tpos = hs.getPosition(el);
hs.getPageSize();
var x = this.x = new hs.Dimension(this, 'x');
x.calcThumb();
var y = this.y = new hs.Dimension(this, 'y');
y.calcThumb();
this.wrapper = hs.createElement(
'div', {
id: 'highslide-wrapper-'+ this.key,
className: 'highslide-wrapper '+ this.wrapperClassName
}, {
visibility: 'hidden',
position: 'absolute',
zIndex: hs.zIndexCounter += 2
}, null, true );
this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler;
if (this.contentType == 'image' && this.outlineWhileAnimating == 2)
this.outlineWhileAnimating = 0;
// get the outline
if (!this.outlineType
|| (this.last && this.isImage && this.transitions[1] == 'crossfade')) {
this[this.contentType +'Create']();
} else if (hs.pendingOutlines[this.outlineType]) {
this.connectOutline();
this[this.contentType +'Create']();
} else {
this.showLoading();
var exp = this;
new hs.Outline(this.outlineType,
function () {
exp.connectOutline();
exp[exp.contentType +'Create']();
}
);
}
return true;
};
hs.Expander.prototype = {
error : function(e) {
// alert ('Line '+ e.lineNumber +': '+ e.message);
window.location.href = this.src;
},
connectOutline : function() {
var outline = this.outline = hs.pendingOutlines[this.outlineType];
outline.exp = this;
outline.table.style.zIndex = this.wrapper.style.zIndex - 1;
hs.pendingOutlines[this.outlineType] = null;
},
showLoading : function() {
if (this.onLoadStarted || this.loading) return;
this.loading = hs.loading;
var exp = this;
this.loading.onclick = function() {
exp.cancelLoading();
};
var exp = this,
l = this.x.get('loadingPos') +'px',
t = this.y.get('loadingPos') +'px';
if (!tgt && this.last && this.transitions[1] == 'crossfade')
var tgt = this.last;
if (tgt) {
l = tgt.x.get('loadingPosXfade') +'px';
t = tgt.y.get('loadingPosXfade') +'px';
this.loading.style.zIndex = hs.zIndexCounter++;
}
setTimeout(function () {
if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })}
, 100);
},
imageCreate : function() {
var exp = this;
var img = document.createElement('img');
this.content = img;
img.onload = function () {
if (hs.expanders[exp.key]) exp.contentLoaded();
};
if (hs.blockRightClick) img.oncontextmenu = function() { return false; };
img.className = 'highslide-image';
hs.setStyles(img, {
visibility: 'hidden',
display: 'block',
position: 'absolute',
maxWidth: '9999px',
zIndex: 3
});
img.title = hs.lang.restoreTitle;
if (hs.safari) hs.container.appendChild(img);
if (hs.ie && hs.flushImgSize) img.src = null;
img.src = this.src;
this.showLoading();
},
contentLoaded : function() {
try {
if (!this.content) return;
this.content.onload = null;
if (this.onLoadStarted) return;
else this.onLoadStarted = true;
var x = this.x, y = this.y;
if (this.loading) {
hs.setStyles(this.loading, { top: '-9999px' });
this.loading = null;
}
x.full = this.content.width;
y.full = this.content.height;
hs.setStyles(this.content, {
width: x.t +'px',
height: y.t +'px'
});
this.wrapper.appendChild(this.content);
hs.container.appendChild(this.wrapper);
x.calcBorders();
y.calcBorders();
hs.setStyles (this.wrapper, {
left: (x.tpos + x.tb - x.cb) +'px',
top: (y.tpos + x.tb - y.cb) +'px'
});
this.initSlideshow();
this.getOverlays();
var ratio = x.full / y.full;
x.calcExpanded();
this.justify(x);
y.calcExpanded();
this.justify(y);
if (this.overlayBox) this.sizeOverlayBox(0, 1);
if (this.allowSizeReduction) {
this.correctRatio(ratio);
var ss = this.slideshow;
if (ss && this.last && ss.controls && ss.fixedControls) {
var pos = ss.overlayOptions.position || '', p;
for (var dim in hs.oPos) for (var i = 0; i < 5; i++) {
p = this[dim];
if (pos.match(hs.oPos[dim][i])) {
p.pos = this.last[dim].pos
+ (this.last[dim].p1 - p.p1)
+ (this.last[dim].size - p.size) * [0, 0, .5, 1, 1][i];
if (ss.fixedControls == 'fit') {
if (p.pos + p.size + p.p1 + p.p2 > p.scroll + p.clientSize - p.marginMax)
p.pos = p.scroll + p.clientSize - p.size - p.marginMin - p.marginMax - p.p1 - p.p2;
if (p.pos < p.scroll + p.marginMin) p.pos = p.scroll + p.marginMin;
}
}
}
}
if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) {
this.createFullExpand();
if (this.overlays.length == 1) this.sizeOverlayBox();
}
}
this.show();
} catch (e) {
this.error(e);
}
},
justify : function (p, moveOnly) {
var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y';
if (tgt && tgt.match(/ /)) {
tgtArr = tgt.split(' ');
tgt = tgtArr[0];
}
if (tgt && hs.$(tgt)) {
p.pos = hs.getPosition(hs.$(tgt))[dim];
if (tgtArr && tgtArr[1] && tgtArr[1].match(/^[-]?[0-9]+px$/))
p.pos += parseInt(tgtArr[1]);
if (p.size < p.minSize) p.size = p.minSize;
} else if (p.justify == 'auto' || p.justify == 'center') {
var hasMovedMin = false;
var allowReduce = p.exp.allowSizeReduction;
if (p.justify == 'center')
p.pos = Math.round(p.scroll + (p.clientSize + p.marginMin - p.marginMax - p.get('wsize')) / 2);
else
p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2));
if (p.pos < p.scroll + p.marginMin) {
p.pos = p.scroll + p.marginMin;
hasMovedMin = true;
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) {
if (!moveOnly && hasMovedMin && allowReduce) {
p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize'));
} else if (p.get('wsize') < p.get('fitsize')) {
p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize');
} else { // image larger than viewport
p.pos = p.scroll + p.marginMin;
if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize');
}
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
} else if (p.justify == 'max') {
p.pos = Math.floor(p.pos - p.size + p.t);
}
if (p.pos < p.marginMin) {
var tmpMin = p.pos;
p.pos = p.marginMin;
if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin);
}
},
correctRatio : function(ratio) {
var x = this.x,
y = this.y,
changed = false,
xSize = Math.min(x.full, x.size),
ySize = Math.min(y.full, y.size),
useBox = (this.useBox || hs.padToMinWidth);
if (xSize / ySize > ratio) { // width greater
xSize = ySize * ratio;
if (xSize < x.minSize) { // below minWidth
xSize = x.minSize;
ySize = xSize / ratio;
}
changed = true;
} else if (xSize / ySize < ratio) { // height greater
ySize = xSize / ratio;
changed = true;
}
if (hs.padToMinWidth && x.full < x.minSize) {
x.imgSize = x.full;
y.size = y.imgSize = y.full;
} else if (this.useBox) {
x.imgSize = xSize;
y.imgSize = ySize;
} else {
x.size = xSize;
y.size = ySize;
}
changed = this.fitOverlayBox(useBox ? null : ratio, changed);
if (useBox && y.size < y.imgSize) {
y.imgSize = y.size;
x.imgSize = y.size * ratio;
}
if (changed || useBox) {
x.pos = x.tpos - x.cb + x.tb;
x.minSize = x.size;
this.justify(x, true);
y.pos = y.tpos - y.cb + y.tb;
y.minSize = y.size;
this.justify(y, true);
if (this.overlayBox) this.sizeOverlayBox();
}
},
fitOverlayBox : function(ratio, changed) {
var x = this.x, y = this.y;
if (this.overlayBox) {
while (y.size > this.minHeight && x.size > this.minWidth
&& y.get('wsize') > y.get('fitsize')) {
y.size -= 10;
if (ratio) x.size = y.size * ratio;
this.sizeOverlayBox(0, 1);
changed = true;
}
}
return changed;
},
show : function () {
var x = this.x, y = this.y;
this.doShowHide('hidden');
if (this.slideshow && this.slideshow.thumbstrip) this.slideshow.thumbstrip.selectThumb();
// Apply size change
this.changeSize(
1, {
wrapper: {
width : x.get('wsize'),
height : y.get('wsize'),
left: x.pos,
top: y.pos
},
content: {
left: x.p1 + x.get('imgPad'),
top: y.p1 + y.get('imgPad'),
width:x.imgSize ||x.size,
height:y.imgSize ||y.size
}
},
hs.expandDuration
);
},
changeSize : function(up, to, dur) {
// transition
var trans = this.transitions,
other = up ? (this.last ? this.last.a : null) : hs.upcoming,
t = (trans[1] && other
&& hs.getParam(other, 'transitions')[1] == trans[1]) ?
trans[1] : trans[0];
if (this[t] && t != 'expand') {
this[t](up, to);
return;
}
if (this.outline && !this.outlineWhileAnimating) {
if (up) this.outline.setPosition();
else this.outline.destroy();
}
if (!up) this.destroyOverlays();
var exp = this,
x = exp.x,
y = exp.y,
easing = this.easing;
if (!up) easing = this.easingClose || easing;
var after = up ?
function() {
if (exp.outline) exp.outline.table.style.visibility = "visible";
setTimeout(function() {
exp.afterExpand();
}, 50);
} :
function() {
exp.afterClose();
};
if (up) hs.setStyles( this.wrapper, {
width: x.t +'px',
height: y.t +'px'
});
if (this.fadeInOut) {
hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 });
hs.extend(to.wrapper, { opacity: up });
}
hs.animate( this.wrapper, to.wrapper, {
duration: dur,
easing: easing,
step: function(val, args) {
if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') {
var fac = up ? args.pos : 1 - args.pos;
var pos = {
w: x.t + (x.get('wsize') - x.t) * fac,
h: y.t + (y.get('wsize') - y.t) * fac,
x: x.tpos + (x.pos - x.tpos) * fac,
y: y.tpos + (y.pos - y.tpos) * fac
};
exp.outline.setPosition(pos, 0, 1);
}
}
});
hs.animate( this.content, to.content, dur, easing, after);
if (up) {
this.wrapper.style.visibility = 'visible';
this.content.style.visibility = 'visible';
this.a.className += ' highslide-active-anchor';
}
},
fade : function(up, to) {
this.outlineWhileAnimating = false;
var exp = this, t = up ? hs.expandDuration : 0;
if (up) {
hs.animate(this.wrapper, to.wrapper, 0);
hs.setStyles(this.wrapper, { opacity: 0, visibility: 'visible' });
hs.animate(this.content, to.content, 0);
this.content.style.visibility = 'visible';
hs.animate(this.wrapper, { opacity: 1 }, t, null,
function() { exp.afterExpand(); });
}
if (this.outline) {
this.outline.table.style.zIndex = this.wrapper.style.zIndex;
var dir = up || -1,
offset = this.outline.offset,
startOff = up ? 3 : offset,
endOff = up? offset : 3;
for (var i = startOff; dir * i <= dir * endOff; i += dir, t += 25) {
(function() {
var o = up ? endOff - i : startOff - i;
setTimeout(function() {
exp.outline.setPosition(0, o, 1);
}, t);
})();
}
}
if (up) {}//setTimeout(function() { exp.afterExpand(); }, t+50);
else {
setTimeout( function() {
if (exp.outline) exp.outline.destroy(exp.preserveContent);
exp.destroyOverlays();
hs.animate( exp.wrapper, { opacity: 0 }, hs.restoreDuration, null, function(){
exp.afterClose();
});
}, t);
}
},
crossfade : function (up, to, from) {
if (!up) return;
var exp = this,
last = this.last,
x = this.x,
y = this.y,
lastX = last.x,
lastY = last.y,
wrapper = this.wrapper,
content = this.content,
overlayBox = this.overlayBox;
hs.removeEventListener(document, 'mousemove', hs.dragHandler);
hs.setStyles(content, {
width: (x.imgSize || x.size) +'px',
height: (y.imgSize || y.size) +'px'
});
if (overlayBox) overlayBox.style.overflow = 'visible';
this.outline = last.outline;
if (this.outline) this.outline.exp = exp;
last.outline = null;
var fadeBox = hs.createElement('div', {
className: 'highslide-image'
}, {
position: 'absolute',
zIndex: 4,
overflow: 'hidden',
display: 'none'
}
);
var names = { oldImg: last, newImg: this };
for (var n in names) {
this[n] = names[n].content.cloneNode(1);
hs.setStyles(this[n], {
position: 'absolute',
border: 0,
visibility: 'visible'
});
fadeBox.appendChild(this[n]);
}
wrapper.appendChild(fadeBox);
if (overlayBox) {
overlayBox.className = '';
wrapper.appendChild(overlayBox);
}
fadeBox.style.display = '';
last.content.style.display = 'none';
if (hs.safari) {
var match = navigator.userAgent.match(/Safari\/([0-9]{3})/);
if (match && parseInt(match[1]) < 525) this.wrapper.style.visibility = 'visible';
}
hs.animate(wrapper, {
width: x.size
}, {
duration: hs.transitionDuration,
step: function(val, args) {
var pos = args.pos,
invPos = 1 - pos;
var prop,
size = {},
props = ['pos', 'size', 'p1', 'p2'];
for (var n in props) {
prop = props[n];
size['x'+ prop] = invPos * lastX[prop] + pos * x[prop];
size['y'+ prop] = invPos * lastY[prop] + pos * y[prop];
size.ximgSize = invPos * (lastX.imgSize || lastX.size) + pos * (x.imgSize || x.size);
size.ximgPad = invPos * lastX.get('imgPad') + pos * x.get('imgPad');
size.yimgSize = invPos * (lastY.imgSize || lastY.size) + pos * (y.imgSize || y.size);
size.yimgPad = invPos * lastY.get('imgPad') + pos * y.get('imgPad');
}
if (exp.outline) exp.outline.setPosition({
x: size.xpos,
y: size.ypos,
w: size.xsize + size.xp1 + size.xp2 + 2 * x.cb,
h: size.ysize + size.yp1 + size.yp2 + 2 * y.cb
});
last.wrapper.style.clip = 'rect('
+ (size.ypos - lastY.pos)+'px, '
+ (size.xsize + size.xp1 + size.xp2 + size.xpos + 2 * lastX.cb - lastX.pos) +'px, '
+ (size.ysize + size.yp1 + size.yp2 + size.ypos + 2 * lastY.cb - lastY.pos) +'px, '
+ (size.xpos - lastX.pos)+'px)';
hs.setStyles(content, {
top: (size.yp1 + y.get('imgPad')) +'px',
left: (size.xp1 + x.get('imgPad')) +'px',
marginTop: (y.pos - size.ypos) +'px',
marginLeft: (x.pos - size.xpos) +'px'
});
hs.setStyles(wrapper, {
top: size.ypos +'px',
left: size.xpos +'px',
width: (size.xp1 + size.xp2 + size.xsize + 2 * x.cb)+ 'px',
height: (size.yp1 + size.yp2 + size.ysize + 2 * y.cb) + 'px'
});
hs.setStyles(fadeBox, {
width: (size.ximgSize || size.xsize) + 'px',
height: (size.yimgSize || size.ysize) +'px',
left: (size.xp1 + size.ximgPad) +'px',
top: (size.yp1 + size.yimgPad) +'px',
visibility: 'visible'
});
hs.setStyles(exp.oldImg, {
top: (lastY.pos - size.ypos + lastY.p1 - size.yp1 + lastY.get('imgPad') - size.yimgPad)+'px',
left: (lastX.pos - size.xpos + lastX.p1 - size.xp1 + lastX.get('imgPad') - size.ximgPad)+'px'
});
hs.setStyles(exp.newImg, {
opacity: pos,
top: (y.pos - size.ypos + y.p1 - size.yp1 + y.get('imgPad') - size.yimgPad) +'px',
left: (x.pos - size.xpos + x.p1 - size.xp1 + x.get('imgPad') - size.ximgPad) +'px'
});
if (overlayBox) hs.setStyles(overlayBox, {
width: size.xsize + 'px',
height: size.ysize +'px',
left: (size.xp1 + x.cb) +'px',
top: (size.yp1 + y.cb) +'px'
});
},
complete: function () {
wrapper.style.visibility = content.style.visibility = 'visible';
content.style.display = 'block';
fadeBox.style.display = 'none';
exp.a.className += ' highslide-active-anchor';
exp.afterExpand();
last.afterClose();
exp.last = null;
}
});
},
reuseOverlay : function(o, el) {
if (!this.last) return false;
for (var i = 0; i < this.last.overlays.length; i++) {
var oDiv = hs.$('hsId'+ this.last.overlays[i]);
if (oDiv && oDiv.hsId == o.hsId) {
this.genOverlayBox();
oDiv.reuse = this.key;
hs.push(this.overlays, this.last.overlays[i]);
return true;
}
}
return false;
},
afterExpand : function() {
this.isExpanded = true;
this.focus();
if (this.dimmingOpacity) hs.dim(this);
if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null;
this.prepareNextOutline();
var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop;
this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize')
&& this.y.pos < mY && mY < this.y.pos + this.y.get('wsize');
if (this.overlayBox) this.showOverlays();
},
prepareNextOutline : function() {
var key = this.key;
var outlineType = this.outlineType;
new hs.Outline(outlineType,
function () { try { hs.expanders[key].preloadNext(); } catch (e) {} });
},
preloadNext : function() {
var next = this.getAdjacentAnchor(1);
if (next && next.onclick.toString().match(/hs\.expand/))
var img = hs.createElement('img', { src: hs.getSrc(next) });
},
getAdjacentAnchor : function(op) {
var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none'];
/*< ? if ($cfg->slideshow) : ?>s*/
if (!as[current + op] && this.slideshow && this.slideshow.repeat) {
if (op == 1) return as[0];
else if (op == -1) return as[as.length-1];
}
/*< ? endif ?>s*/
return as[current + op] || null;
},
getAnchorIndex : function() {
var arr = hs.getAnchors().groups[this.slideshowGroup || 'none'];
if (arr) for (var i = 0; i < arr.length; i++) {
if (arr[i] == this.a) return i;
}
return null;
},
getNumber : function() {
if (this[this.numberPosition]) {
var arr = hs.anchors.groups[this.slideshowGroup || 'none'];
if (arr) {
var s = hs.lang.number.replace('%1', this.getAnchorIndex() + 1).replace('%2', arr.length);
this[this.numberPosition].innerHTML =
'<div class="highslide-number">'+ s +'</div>'+ this[this.numberPosition].innerHTML;
}
}
},
initSlideshow : function() {
if (!this.last) {
for (var i = 0; i < hs.slideshows.length; i++) {
var ss = hs.slideshows[i], sg = ss.slideshowGroup;
if (typeof sg == 'undefined' || sg === null || sg === this.slideshowGroup)
this.slideshow = new hs.Slideshow(this.key, ss);
}
} else {
this.slideshow = this.last.slideshow;
}
var ss = this.slideshow;
if (!ss) return;
var key = ss.expKey = this.key;
ss.checkFirstAndLast();
ss.disable('full-expand');
if (ss.controls) {
var o = ss.overlayOptions || {};
o.overlayId = ss.controls;
o.hsId = 'controls';
this.createOverlay(o);
}
if (ss.thumbstrip) ss.thumbstrip.add(this);
if (!this.last && this.autoplay) ss.play(true);
if (ss.autoplay) {
ss.autoplay = setTimeout(function() {
hs.next(key);
}, (ss.interval || 500));
}
},
cancelLoading : function() {
hs.discardElement (this.wrapper);
hs.expanders[this.key] = null;
if (hs.upcoming == this.a) hs.upcoming = null;
hs.undim(this.key);
if (this.loading) hs.loading.style.left = '-9999px';
},
writeCredits : function () {
if (this.credits) return;
this.credits = hs.createElement('a', {
href: hs.creditsHref,
target: hs.creditsTarget,
className: 'highslide-credits',
innerHTML: hs.lang.creditsText,
title: hs.lang.creditsTitle
});
this.createOverlay({
overlayId: this.credits,
position: this.creditsPosition || 'top left',
hsId: 'credits'
});
},
getInline : function(types, addOverlay) {
for (var i = 0; i < types.length; i++) {
var type = types[i], s = null;
if (!this[type +'Id'] && this.thumbsUserSetId)
this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId;
if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']);
if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try {
s = eval(this[type +'Eval']);
} catch (e) {}
if (!this[type] && this[type +'Text']) {
s = this[type +'Text'];
}
if (!this[type] && !s) {
this[type] = hs.getNode(this.a['_'+ type + 'Id']);
if (!this[type]) {
var next = this.a.nextSibling;
while (next && !hs.isHsAnchor(next)) {
if ((new RegExp('highslide-'+ type)).test(next.className || null)) {
if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++;
this[type] = hs.getNode(next.id);
break;
}
next = next.nextSibling;
}
}
}
if (!this[type] && !s && this.numberPosition == type) s = '\n';
if (!this[type] && s) this[type] = hs.createElement('div',
{ className: 'highslide-'+ type, innerHTML: s } );
if (addOverlay && this[type]) {
var o = { position: (type == 'heading') ? 'above' : 'below' };
for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x];
o.overlayId = this[type];
this.createOverlay(o);
}
}
},
// on end move and resize
doShowHide : function(visibility) {
if (hs.hideSelects) this.showHideElements('SELECT', visibility);
if (hs.hideIframes) this.showHideElements('IFRAME', visibility);
if (hs.geckoMac) this.showHideElements('*', visibility);
},
showHideElements : function (tagName, visibility) {
var els = document.getElementsByTagName(tagName);
var prop = tagName == '*' ? 'overflow' : 'visibility';
for (var i = 0; i < els.length; i++) {
if (prop == 'visibility' || (document.defaultView.getComputedStyle(
els[i], "").getPropertyValue('overflow') == 'auto'
|| els[i].getAttribute('hidden-by') != null)) {
var hiddenBy = els[i].getAttribute('hidden-by');
if (visibility == 'visible' && hiddenBy) {
hiddenBy = hiddenBy.replace('['+ this.key +']', '');
els[i].setAttribute('hidden-by', hiddenBy);
if (!hiddenBy) els[i].style[prop] = els[i].origProp;
} else if (visibility == 'hidden') { // hide if behind
var elPos = hs.getPosition(els[i]);
elPos.w = els[i].offsetWidth;
elPos.h = els[i].offsetHeight;
if (!this.dimmingOpacity) { // hide all if dimming
var clearsX = (elPos.x + elPos.w < this.x.get('opos')
|| elPos.x > this.x.get('opos') + this.x.get('osize'));
var clearsY = (elPos.y + elPos.h < this.y.get('opos')
|| elPos.y > this.y.get('opos') + this.y.get('osize'));
}
var wrapperKey = hs.getWrapperKey(els[i]);
if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image
if (!hiddenBy) {
els[i].setAttribute('hidden-by', '['+ this.key +']');
els[i].origProp = els[i].style[prop];
els[i].style[prop] = 'hidden';
} else if (hiddenBy.indexOf('['+ this.key +']') == -1) {
els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']');
}
} else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey)
&& wrapperKey != this.key) { // on move
els[i].setAttribute('hidden-by', '');
els[i].style[prop] = els[i].origProp || '';
} else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) {
els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', ''));
}
}
}
}
},
focus : function() {
this.wrapper.style.zIndex = hs.zIndexCounter += 2;
// blur others
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && i == hs.focusKey) {
var blurExp = hs.expanders[i];
blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur';
blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer';
blurExp.content.title = hs.lang.focusTitle;
}
}
// focus this
if (this.outline) this.outline.table.style.zIndex
= this.wrapper.style.zIndex - 1;
this.content.className = 'highslide-'+ this.contentType;
this.content.title = hs.lang.restoreTitle;
if (hs.restoreCursor) {
hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer';
if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand';
this.content.style.cursor = hs.styleRestoreCursor;
}
hs.focusKey = this.key;
hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
},
moveTo: function(x, y) {
this.x.setPos(x);
this.y.setPos(y);
},
resize : function (e) {
var w, h, r = e.width / e.height;
w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full));
if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full;
h = w / r;
if (h < Math.min(this.minHeight, this.y.full)) {
h = Math.min(this.minHeight, this.y.full);
if (this.isImage) w = h * r;
}
this.resizeTo(w, h);
},
resizeTo: function(w, h) {
this.y.setSize(h);
this.x.setSize(w);
this.wrapper.style.height = this.y.get('wsize') +'px';
},
close : function() {
if (this.isClosing || !this.isExpanded) return;
if (this.transitions[1] == 'crossfade' && hs.upcoming) {
hs.getExpander(hs.upcoming).cancelLoading();
hs.upcoming = null;
}
this.isClosing = true;
if (this.slideshow && !hs.upcoming) this.slideshow.pause();
hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
try {
this.content.style.cursor = 'default';
this.changeSize(
0, {
wrapper: {
width : this.x.t,
height : this.y.t,
left: this.x.tpos - this.x.cb + this.x.tb,
top: this.y.tpos - this.y.cb + this.y.tb
},
content: {
left: 0,
top: 0,
width: this.x.t,
height: this.y.t
}
}, hs.restoreDuration
);
} catch (e) { this.afterClose(); }
},
createOverlay : function (o) {
var el = o.overlayId,
relToVP = (o.relativeTo == 'viewport' && !/panel$/.test(o.position));
if (typeof el == 'string') el = hs.getNode(el);
if (o.html) el = hs.createElement('div', { innerHTML: o.html });
if (!el || typeof el == 'string') return;
el.style.display = 'block';
o.hsId = o.hsId || o.overlayId;
if (this.transitions[1] == 'crossfade' && this.reuseOverlay(o, el)) return;
this.genOverlayBox();
var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto';
if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px';
var overlay = hs.createElement(
'div', {
id: 'hsId'+ hs.idCounter++,
hsId: o.hsId
}, {
position: 'absolute',
visibility: 'hidden',
width: width,
direction: hs.lang.cssDirection || '',
opacity: 0
},
relToVP ? hs.viewport :this.overlayBox,
true
);
if (relToVP) overlay.hsKey = this.key;
overlay.appendChild(el);
hs.extend(overlay, {
opacity: 1,
offsetX: 0,
offsetY: 0,
dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250
});
hs.extend(overlay, o);
if (this.gotOverlays) {
this.positionOverlay(overlay);
if (!overlay.hideOnMouseOut || this.mouseIsOver)
hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur);
}
hs.push(this.overlays, hs.idCounter - 1);
},
positionOverlay : function(overlay) {
var p = overlay.position || 'middle center',
relToVP = (overlay.relativeTo == 'viewport'),
offX = overlay.offsetX,
offY = overlay.offsetY;
if (relToVP) {
hs.viewport.style.display = 'block';
overlay.hsKey = this.key;
if (overlay.offsetWidth > overlay.parentNode.offsetWidth)
overlay.style.width = '100%';
} else
if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay);
if (/left$/.test(p)) overlay.style.left = offX +'px';
if (/center$/.test(p)) hs.setStyles (overlay, {
left: '50%',
marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px'
});
if (/right$/.test(p)) overlay.style.right = - offX +'px';
if (/^leftpanel$/.test(p)) {
hs.setStyles(overlay, {
right: '100%',
marginRight: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p1 = overlay.offsetWidth;
} else if (/^rightpanel$/.test(p)) {
hs.setStyles(overlay, {
left: '100%',
marginLeft: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p2 = overlay.offsetWidth;
}
var parOff = overlay.parentNode.offsetHeight;
overlay.style.height = 'auto';
if (relToVP && overlay.offsetHeight > parOff)
overlay.style.height = hs.ieLt7 ? parOff +'px' : '100%';
if (/^top/.test(p)) overlay.style.top = offY +'px';
if (/^middle/.test(p)) hs.setStyles (overlay, {
top: '50%',
marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px'
});
if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px';
if (/^above$/.test(p)) {
hs.setStyles(overlay, {
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
bottom: '100%',
marginBottom: this.y.cb +'px',
width: 'auto'
});
this.y.p1 = overlay.offsetHeight;
} else if (/^below$/.test(p)) {
hs.setStyles(overlay, {
position: 'relative',
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
top: '100%',
marginTop: this.y.cb +'px',
width: 'auto'
});
this.y.p2 = overlay.offsetHeight;
overlay.style.position = 'absolute';
}
},
getOverlays : function() {
this.getInline(['heading', 'caption'], true);
this.getNumber();
if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move';
if (hs.showCredits) this.writeCredits();
for (var i = 0; i < hs.overlays.length; i++) {
var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup;
if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId)
|| (sg && sg === this.slideshowGroup)) {
this.createOverlay(o);
}
}
var os = [];
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
if (/panel$/.test(o.position)) this.positionOverlay(o);
else hs.push(os, o);
}
for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]);
this.gotOverlays = true;
},
genOverlayBox : function() {
if (!this.overlayBox) this.overlayBox = hs.createElement (
'div', {
className: this.wrapperClassName
}, {
position : 'absolute',
width: (this.x.size || (this.useBox ? this.width : null)
|| this.x.full) +'px',
height: (this.y.size || this.y.full) +'px',
visibility : 'hidden',
overflow : 'hidden',
zIndex : hs.ie ? 4 : 'auto'
},
hs.container,
true
);
},
sizeOverlayBox : function(doWrapper, doPanels) {
var overlayBox = this.overlayBox,
x = this.x,
y = this.y;
hs.setStyles( overlayBox, {
width: x.size +'px',
height: y.size +'px'
});
if (doWrapper || doPanels) {
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat');
if (o && /^(above|below)$/.test(o.position)) {
if (ie6) {
o.style.width = (overlayBox.offsetWidth + 2 * x.cb
+ x.p1 + x.p2) +'px';
}
y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight;
}
if (o && ie6 && /^(left|right)panel$/.test(o.position)) {
o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px';
}
}
}
if (doWrapper) {
hs.setStyles(this.content, {
top: y.p1 +'px'
});
hs.setStyles(overlayBox, {
top: (y.p1 + y.cb) +'px'
});
}
},
showOverlays : function() {
var b = this.overlayBox;
b.className = '';
hs.setStyles(b, {
top: (this.y.p1 + this.y.cb) +'px',
left: (this.x.p1 + this.x.cb) +'px',
overflow : 'visible'
});
if (hs.safari) b.style.visibility = 'visible';
this.wrapper.appendChild (b);
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
o.style.zIndex = o.hsId == 'controls' ? 5 : 4;
if (!o.hideOnMouseOut || this.mouseIsOver) {
o.style.visibility = 'visible';
hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: o.opacity }, o.dur);
}
}
},
destroyOverlays : function() {
if (!this.overlays.length) return;
if (this.slideshow) {
var c = this.slideshow.controls;
if (c && hs.getExpander(c) == this) c.parentNode.removeChild(c);
}
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
if (o && o.parentNode == hs.viewport && hs.getExpander(o) == this) hs.discardElement(o);
}
hs.discardElement(this.overlayBox);
},
createFullExpand : function () {
if (this.slideshow && this.slideshow.controls) {
this.slideshow.enable('full-expand');
return;
}
this.fullExpandLabel = hs.createElement(
'a', {
href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();',
title: hs.lang.fullExpandTitle,
className: 'highslide-full-expand'
}
);
this.createOverlay({
overlayId: this.fullExpandLabel,
position: hs.fullExpandPosition,
hideOnMouseOut: true,
opacity: hs.fullExpandOpacity
});
},
doFullExpand : function () {
try {
if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel);
this.focus();
var xSize = this.x.size;
this.resizeTo(this.x.full, this.y.full);
var xpos = this.x.pos - (this.x.size - xSize) / 2;
if (xpos < hs.marginLeft) xpos = hs.marginLeft;
this.moveTo(xpos, this.y.pos);
this.doShowHide('hidden');
} catch (e) {
this.error(e);
}
},
afterClose : function () {
this.a.className = this.a.className.replace('highslide-active-anchor', '');
this.doShowHide('visible');
if (this.outline && this.outlineWhileAnimating) this.outline.destroy();
hs.discardElement(this.wrapper);
this.destroyOverlays();
if (!hs.viewport.childNodes.length) hs.viewport.style.display = 'none';
if (this.dimmingOpacity) hs.undim(this.key);
hs.expanders[this.key] = null;
hs.reOrder();
}
};
hs.Slideshow = function (expKey, options) {
if (hs.dynamicallyUpdateAnchors !== false) hs.updateAnchors();
this.expKey = expKey;
for (var x in options) this[x] = options[x];
if (this.useControls) this.getControls();
if (this.thumbstrip) this.thumbstrip = hs.Thumbstrip(this);
};
hs.Slideshow.prototype = {
getControls: function() {
this.controls = hs.createElement('div', { innerHTML: hs.replaceLang(hs.skin.controls) },
null, hs.container);
var buttons = ['play', 'pause', 'previous', 'next', 'move', 'full-expand', 'close'];
this.btn = {};
var pThis = this;
for (var i = 0; i < buttons.length; i++) {
this.btn[buttons[i]] = hs.getElementByClass(this.controls, 'li', 'highslide-'+ buttons[i]);
this.enable(buttons[i]);
}
this.btn.pause.style.display = 'none';
//this.disable('full-expand');
},
checkFirstAndLast: function() {
if (this.repeat || !this.controls) return;
var exp = hs.expanders[this.expKey],
cur = exp.getAnchorIndex(),
re = /disabled$/;
if (cur == 0)
this.disable('previous');
else if (re.test(this.btn.previous.getElementsByTagName('a')[0].className))
this.enable('previous');
if (cur + 1 == hs.anchors.groups[exp.slideshowGroup || 'none'].length) {
this.disable('next');
this.disable('play');
} else if (re.test(this.btn.next.getElementsByTagName('a')[0].className)) {
this.enable('next');
this.enable('play');
}
},
enable: function(btn) {
if (!this.btn) return;
var sls = this, a = this.btn[btn].getElementsByTagName('a')[0], re = /disabled$/;
a.onclick = function() {
sls[btn]();
return false;
};
if (re.test(a.className)) a.className = a.className.replace(re, '');
},
disable: function(btn) {
if (!this.btn) return;
var a = this.btn[btn].getElementsByTagName('a')[0];
a.onclick = function() { return false; };
if (!/disabled$/.test(a.className)) a.className += ' disabled';
},
hitSpace: function() {
if (this.autoplay) this.pause();
else this.play();
},
play: function(wait) {
if (this.btn) {
this.btn.play.style.display = 'none';
this.btn.pause.style.display = '';
}
this.autoplay = true;
if (!wait) hs.next(this.expKey);
},
pause: function() {
if (this.btn) {
this.btn.pause.style.display = 'none';
this.btn.play.style.display = '';
}
clearTimeout(this.autoplay);
this.autoplay = null;
},
previous: function() {
this.pause();
hs.previous(this.btn.previous);
},
next: function() {
this.pause();
hs.next(this.btn.next);
},
move: function() {},
'full-expand': function() {
hs.getExpander().doFullExpand();
},
close: function() {
hs.close(this.btn.close);
}
};
hs.Thumbstrip = function(slideshow) {
function add (exp) {
hs.extend(options || {}, {
overlayId: dom,
hsId: 'thumbstrip',
className: 'highslide-thumbstrip-'+ mode +'-overlay ' + (options.className || '')
});
if (hs.ieLt7) options.fade = 0;
exp.createOverlay(options);
hs.setStyles(dom.parentNode, { overflow: 'hidden' });
};
function scroll (delta) {
selectThumb(undefined, Math.round(delta * dom[isX ? 'offsetWidth' : 'offsetHeight'] * 0.7));
};
function selectThumb (i, scrollBy) {
if (i === undefined) for (var j = 0; j < group.length; j++) {
if (group[j] == hs.expanders[slideshow.expKey].a) {
i = j;
break;
}
}
if (i === undefined) return;
var as = dom.getElementsByTagName('a'),
active = as[i],
cell = active.parentNode,
left = isX ? 'Left' : 'Top',
right = isX ? 'Right' : 'Bottom',
width = isX ? 'Width' : 'Height',
offsetLeft = 'offset' + left,
offsetWidth = 'offset' + width,
overlayWidth = div.parentNode.parentNode[offsetWidth],
minTblPos = overlayWidth - table[offsetWidth],
curTblPos = parseInt(table.style[isX ? 'left' : 'top']) || 0,
tblPos = curTblPos,
mgnRight = 20;
if (scrollBy !== undefined) {
tblPos = curTblPos - scrollBy;
if (tblPos > 0) tblPos = 0;
if (tblPos < minTblPos) tblPos = minTblPos;
} else {
for (var j = 0; j < as.length; j++) as[j].className = '';
active.className = 'highslide-active-anchor';
var activeLeft = i > 0 ? as[i - 1].parentNode[offsetLeft] : cell[offsetLeft],
activeRight = cell[offsetLeft] + cell[offsetWidth] +
(as[i + 1] ? as[i + 1].parentNode[offsetWidth] : 0);
if (activeRight > overlayWidth - curTblPos) tblPos = overlayWidth - activeRight;
else if (activeLeft < -curTblPos) tblPos = -activeLeft;
}
var markerPos = cell[offsetLeft] + (cell[offsetWidth] - marker[offsetWidth]) / 2 + tblPos;
hs.animate(table, isX ? { left: tblPos } : { top: tblPos }, null, 'easeOutQuad');
hs.animate(marker, isX ? { left: markerPos } : { top: markerPos }, null, 'easeOutQuad');
scrollUp.style.display = tblPos < 0 ? 'block' : 'none';
scrollDown.style.display = (tblPos > minTblPos) ? 'block' : 'none';
};
// initialize
var group = hs.anchors.groups[hs.expanders[slideshow.expKey].slideshowGroup || 'none'],
options = slideshow.thumbstrip,
mode = options.mode || 'horizontal',
floatMode = (mode == 'float'),
tree = floatMode ? ['div', 'ul', 'li', 'span'] : ['table', 'tbody', 'tr', 'td'],
isX = (mode == 'horizontal'),
dom = hs.createElement('div', {
className: 'highslide-thumbstrip highslide-thumbstrip-'+ mode,
innerHTML:
'<div class="highslide-thumbstrip-inner">'+
'<'+ tree[0] +'><'+ tree[1] +'></'+ tree[1] +'></'+ tree[0] +'></div>'+
'<div class="highslide-scroll-up"><div></div></div>'+
'<div class="highslide-scroll-down"><div></div></div>'+
'<div class="highslide-marker"><div></div></div>'
}, {
display: 'none'
}, hs.container),
domCh = dom.childNodes,
div = domCh[0],
scrollUp = domCh[1],
scrollDown = domCh[2],
marker = domCh[3],
table = div.firstChild,
tbody = dom.getElementsByTagName(tree[1])[0],
tr;
for (var i = 0; i < group.length; i++) {
if (i == 0 || !isX) tr = hs.createElement(tree[2], null, null, tbody);
(function(){
var a = group[i],
cell = hs.createElement(tree[3], null, null, tr),
pI = i;
hs.createElement('a', {
href: a.href,
onclick: function() {
hs.getExpander(this).focus();
return hs.transit(a);
},
innerHTML: hs.stripItemFormatter ? hs.stripItemFormatter(a) : a.innerHTML
}, null, cell);
})();
}
if (!floatMode) {
scrollUp.onclick = function () { scroll(-1); };
scrollDown.onclick = function() { scroll(1); };
hs.addEventListener(tbody, document.onmousewheel !== undefined ?
'mousewheel' : 'DOMMouseScroll', function(e) {
var delta = 0;
e = e || window.event;
if (e.wheelDelta) {
delta = e.wheelDelta/120;
if (hs.opera) delta = -delta;
} else if (e.detail) {
delta = -e.detail/3;
}
if (delta) scroll(-delta * 0.2);
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
});
}
return {
add: add,
selectThumb: selectThumb
}
};
hs.langDefaults = hs.lang;
// history
var HsExpander = hs.Expander;
if (hs.ie) {
(function () {
try {
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
hs.ready();
})();
}
hs.addEventListener(document, 'DOMContentLoaded', hs.ready);
hs.addEventListener(window, 'load', hs.ready);
// set handlers
hs.addEventListener(document, 'ready', function() {
if (hs.expandCursor || hs.dimmingOpacity) {
var style = hs.createElement('style', { type: 'text/css' }, null,
document.getElementsByTagName('HEAD')[0]);
function addRule(sel, dec) {
if (!hs.ie) {
style.appendChild(document.createTextNode(sel + " {" + dec + "}"));
} else {
var last = document.styleSheets[document.styleSheets.length - 1];
if (typeof(last.addRule) == "object") last.addRule(sel, dec);
}
}
function fix(prop) {
return 'expression( ( ( ignoreMe = document.documentElement.'+ prop +
' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );';
}
if (hs.expandCursor) addRule ('.highslide img',
'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;');
addRule ('.highslide-viewport-size',
(hs.ieLt7 || (hs.ie && document.compatMode == 'BackCompat')) ?
'position: absolute; '+
'left:'+ fix('scrollLeft') +
'top:'+ fix('scrollTop') +
'width:'+ fix('clientWidth') +
'height:'+ fix('clientHeight') :
'position: fixed; width: 100%; height: 100%; left: 0; top: 0');
}
});
hs.addEventListener(window, 'resize', function() {
hs.getPageSize();
if (hs.viewport) for (var i = 0; i < hs.viewport.childNodes.length; i++) {
var node = hs.viewport.childNodes[i],
exp = hs.getExpander(node);
exp.positionOverlay(node);
if (node.hsId == 'thumbstrip') exp.slideshow.thumbstrip.selectThumb();
}
});
hs.addEventListener(document, 'mousemove', function(e) {
hs.mouse = { x: e.clientX, y: e.clientY };
});
hs.addEventListener(document, 'mousedown', hs.mouseClickHandler);
hs.addEventListener(document, 'mouseup', hs.mouseClickHandler);
hs.addEventListener(document, 'ready', hs.getAnchors);
hs.addEventListener(window, 'load', hs.preloadImages);
} | JavaScript |
/******************************************************************************
Name: Highslide JS
Version: 4.1.7 (September 28 2009)
Config: default +inline +ajax +iframe +flash
Author: Torstein Hønsi
Support: http://highslide.com/support
Licence:
Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5
License (http://creativecommons.org/licenses/by-nc/2.5/).
You are free:
* to copy, distribute, display, and perform the work
* to make derivative works
Under the following conditions:
* Attribution. You must attribute the work in the manner specified by the
author or licensor.
* Noncommercial. You may not use this work for commercial purposes.
* For any reuse or distribution, you must make clear to others the license
terms of this work.
* Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
******************************************************************************/
if (!hs) { var hs = {
// Language strings
lang : {
cssDirection: 'ltr',
loadingText : 'Loading...',
loadingTitle : 'Click to cancel',
focusTitle : 'Click to bring to front',
fullExpandTitle : 'Expand to actual size (f)',
creditsText : 'Powered by <i>Highslide JS</i>',
creditsTitle : 'Go to the Highslide JS homepage',
previousText : 'Previous',
nextText : 'Next',
moveText : 'Move',
closeText : 'Close',
closeTitle : 'Close (esc)',
resizeTitle : 'Resize',
playText : 'Play',
playTitle : 'Play slideshow (spacebar)',
pauseText : 'Pause',
pauseTitle : 'Pause slideshow (spacebar)',
previousTitle : 'Previous (arrow left)',
nextTitle : 'Next (arrow right)',
moveTitle : 'Move',
fullExpandText : '1:1',
restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.'
},
// See http://highslide.com/ref for examples of settings
graphicsDir : 'highslide/graphics/',
expandCursor : 'zoomin.cur', // null disables
restoreCursor : 'zoomout.cur', // null disables
expandDuration : 250, // milliseconds
restoreDuration : 250,
marginLeft : 15,
marginRight : 15,
marginTop : 15,
marginBottom : 15,
zIndexCounter : 1001, // adjust to other absolutely positioned elements
loadingOpacity : 0.75,
allowMultipleInstances: true,
numberOfImagesToPreload : 5,
outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only
outlineStartOffset : 3, // ends at 10
padToMinWidth : false, // pad the popup width to make room for wide caption
fullExpandPosition : 'bottom right',
fullExpandOpacity : 1,
showCredits : true, // you can set this to false if you want
creditsHref : 'http://highslide.com/',
creditsTarget : '_self',
enableKeyListener : true,
openerTagNames : ['a'], // Add more to allow slideshow indexing
allowWidthReduction : false,
allowHeightReduction : true,
preserveContent : true, // Preserve changes made to the content and position of HTML popups.
objectLoadTime : 'before', // Load iframes 'before' or 'after' expansion.
cacheAjax : true, // Cache ajax popups for instant display. Can be overridden for each popup.
dragByHeading: true,
minWidth: 200,
minHeight: 200,
allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight
outlineType : 'drop-shadow', // set null to disable outlines
skin : {
contentWrapper:
'<div class="highslide-header"><ul>'+
'<li class="highslide-previous">'+
'<a href="#" title="{hs.lang.previousTitle}" onclick="return hs.previous(this)">'+
'<span>{hs.lang.previousText}</span></a>'+
'</li>'+
'<li class="highslide-next">'+
'<a href="#" title="{hs.lang.nextTitle}" onclick="return hs.next(this)">'+
'<span>{hs.lang.nextText}</span></a>'+
'</li>'+
'<li class="highslide-move">'+
'<a href="#" title="{hs.lang.moveTitle}" onclick="return false">'+
'<span>{hs.lang.moveText}</span></a>'+
'</li>'+
'<li class="highslide-close">'+
'<a href="#" title="{hs.lang.closeTitle}" onclick="return hs.close(this)">'+
'<span>{hs.lang.closeText}</span></a>'+
'</li>'+
'</ul></div>'+
'<div class="highslide-body"></div>'+
'<div class="highslide-footer"><div>'+
'<span class="highslide-resize" title="{hs.lang.resizeTitle}"><span></span></span>'+
'</div></div>'
},
// END OF YOUR SETTINGS
// declare internal properties
preloadTheseImages : [],
continuePreloading: true,
expanders : [],
overrides : [
'allowSizeReduction',
'useBox',
'outlineType',
'outlineWhileAnimating',
'captionId',
'captionText',
'captionEval',
'captionOverlay',
'headingId',
'headingText',
'headingEval',
'headingOverlay',
'creditsPosition',
'dragByHeading',
'width',
'height',
'contentId',
'allowWidthReduction',
'allowHeightReduction',
'preserveContent',
'maincontentId',
'maincontentText',
'maincontentEval',
'objectType',
'cacheAjax',
'objectWidth',
'objectHeight',
'objectLoadTime',
'swfOptions',
'wrapperClassName',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'slideshowGroup',
'easing',
'easingClose',
'fadeInOut',
'src'
],
overlays : [],
idCounter : 0,
oPos : {
x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'],
y: ['above', 'top', 'middle', 'bottom', 'below']
},
mouse: {},
headingOverlay: {},
captionOverlay: {},
swfOptions: { flashvars: {}, params: {}, attributes: {} },
timers : [],
pendingOutlines : {},
sleeping : [],
preloadTheseAjax : [],
cacheBindings : [],
cachedGets : {},
clones : {},
onReady: [],
uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 :
parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]),
ie : (document.all && !window.opera),
safari : /Safari/.test(navigator.userAgent),
geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent),
$ : function (id) {
if (id) return document.getElementById(id);
},
push : function (arr, val) {
arr[arr.length] = val;
},
createElement : function (tag, attribs, styles, parent, nopad) {
var el = document.createElement(tag);
if (attribs) hs.extend(el, attribs);
if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0});
if (styles) hs.setStyles(el, styles);
if (parent) parent.appendChild(el);
return el;
},
extend : function (el, attribs) {
for (var x in attribs) el[x] = attribs[x];
return el;
},
setStyles : function (el, styles) {
for (var x in styles) {
if (hs.ie && x == 'opacity') {
if (styles[x] > 0.99) el.style.removeAttribute('filter');
else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')';
}
else el.style[x] = styles[x];
}
},
animate: function(el, prop, opt) {
var start,
end,
unit;
if (typeof opt != 'object' || opt === null) {
var args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (typeof opt.duration != 'number') opt.duration = 250;
opt.easing = Math[opt.easing] || Math.easeInQuad;
opt.curAnim = hs.extend({}, prop);
for (var name in prop) {
var e = new hs.fx(el, opt , name );
start = parseFloat(hs.css(el, name)) || 0;
end = parseFloat(prop[name]);
unit = name != 'opacity' ? 'px' : '';
e.custom( start, end, unit );
}
},
css: function(el, prop) {
if (document.defaultView) {
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
} else {
if (prop == 'opacity') prop = 'filter';
var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })];
if (prop == 'filter')
val = val.replace(/alpha\(opacity=([0-9]+)\)/,
function (a, b) { return b / 100 });
return val === '' ? 1 : val;
}
},
getPageSize : function () {
var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat'
? d.documentElement : d.body;
var width = hs.ie ? iebody.clientWidth :
(d.documentElement.clientWidth || self.innerWidth),
height = hs.ie ? iebody.clientHeight : self.innerHeight;
hs.page = {
width: width,
height: height,
scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset,
scrollTop: hs.ie ? iebody.scrollTop : pageYOffset
}
},
getPosition : function(el) {
var p = { x: el.offsetLeft, y: el.offsetTop };
while (el.offsetParent) {
el = el.offsetParent;
p.x += el.offsetLeft;
p.y += el.offsetTop;
if (el != document.body && el != document.documentElement) {
p.x -= el.scrollLeft;
p.y -= el.scrollTop;
}
}
return p;
},
expand : function(a, params, custom, type) {
if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container);
if (typeof a.getParams == 'function') return params;
if (type == 'html') {
for (var i = 0; i < hs.sleeping.length; i++) {
if (hs.sleeping[i] && hs.sleeping[i].a == a) {
hs.sleeping[i].awake();
hs.sleeping[i] = null;
return false;
}
}
hs.hasHtmlExpanders = true;
}
try {
new hs.Expander(a, params, custom, type);
return false;
} catch (e) { return true; }
},
htmlExpand : function(a, params, custom) {
return hs.expand(a, params, custom, 'html');
},
getSelfRendered : function() {
return hs.createElement('div', {
className: 'highslide-html-content',
innerHTML: hs.replaceLang(hs.skin.contentWrapper)
});
},
getElementByClass : function (el, tagName, className) {
var els = el.getElementsByTagName(tagName);
for (var i = 0; i < els.length; i++) {
if ((new RegExp(className)).test(els[i].className)) {
return els[i];
}
}
return null;
},
replaceLang : function(s) {
s = s.replace(/\s/g, ' ');
var re = /{hs\.lang\.([^}]+)\}/g,
matches = s.match(re),
lang;
if (matches) for (var i = 0; i < matches.length; i++) {
lang = matches[i].replace(re, "$1");
if (typeof hs.lang[lang] != 'undefined') s = s.replace(matches[i], hs.lang[lang]);
}
return s;
},
getCacheBinding : function (a) {
for (var i = 0; i < hs.cacheBindings.length; i++) {
if (hs.cacheBindings[i][0] == a) {
var c = hs.cacheBindings[i][1];
hs.cacheBindings[i][1] = c.cloneNode(1);
return c;
}
}
return null;
},
preloadAjax : function (e) {
var arr = hs.getAnchors();
for (var i = 0; i < arr.htmls.length; i++) {
var a = arr.htmls[i];
if (hs.getParam(a, 'objectType') == 'ajax' && hs.getParam(a, 'cacheAjax'))
hs.push(hs.preloadTheseAjax, a);
}
hs.preloadAjaxElement(0);
},
preloadAjaxElement : function (i) {
if (!hs.preloadTheseAjax[i]) return;
var a = hs.preloadTheseAjax[i];
var cache = hs.getNode(hs.getParam(a, 'contentId'));
if (!cache) cache = hs.getSelfRendered();
var ajax = new hs.Ajax(a, cache, 1);
ajax.onError = function () { };
ajax.onLoad = function () {
hs.push(hs.cacheBindings, [a, cache]);
hs.preloadAjaxElement(i + 1);
};
ajax.run();
},
focusTopmost : function() {
var topZ = 0,
topmostKey = -1,
expanders = hs.expanders,
exp,
zIndex;
for (var i = 0; i < expanders.length; i++) {
exp = expanders[i];
if (exp) {
zIndex = exp.wrapper.style.zIndex;
if (zIndex && zIndex > topZ) {
topZ = zIndex;
topmostKey = i;
}
}
}
if (topmostKey == -1) hs.focusKey = -1;
else expanders[topmostKey].focus();
},
getParam : function (a, param) {
a.getParams = a.onclick;
var p = a.getParams ? a.getParams() : null;
a.getParams = null;
return (p && typeof p[param] != 'undefined') ? p[param] :
(typeof hs[param] != 'undefined' ? hs[param] : null);
},
getSrc : function (a) {
var src = hs.getParam(a, 'src');
if (src) return src;
return a.href;
},
getNode : function (id) {
var node = hs.$(id), clone = hs.clones[id], a = {};
if (!node && !clone) return null;
if (!clone) {
clone = node.cloneNode(true);
clone.id = '';
hs.clones[id] = clone;
return node;
} else {
return clone.cloneNode(true);
}
},
discardElement : function(d) {
if (d) hs.garbageBin.appendChild(d);
hs.garbageBin.innerHTML = '';
},
transit : function (adj, exp) {
var last = exp = exp || hs.getExpander();
if (hs.upcoming) return false;
else hs.last = last;
try {
hs.upcoming = adj;
adj.onclick();
} catch (e){
hs.last = hs.upcoming = null;
}
try {
exp.close();
} catch (e) {}
return false;
},
previousOrNext : function (el, op) {
var exp = hs.getExpander(el);
if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp);
else return false;
},
previous : function (el) {
return hs.previousOrNext(el, -1);
},
next : function (el) {
return hs.previousOrNext(el, 1);
},
keyHandler : function(e) {
if (!e) e = window.event;
if (!e.target) e.target = e.srcElement; // ie
if (typeof e.target.form != 'undefined') return true; // form element has focus
var exp = hs.getExpander();
var op = null;
switch (e.keyCode) {
case 70: // f
if (exp) exp.doFullExpand();
return true;
case 32: // Space
case 34: // Page Down
case 39: // Arrow right
case 40: // Arrow down
op = 1;
break;
case 8: // Backspace
case 33: // Page Up
case 37: // Arrow left
case 38: // Arrow up
op = -1;
break;
case 27: // Escape
case 13: // Enter
op = 0;
}
if (op !== null) {hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
if (!hs.enableKeyListener) return true;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (exp) {
if (op == 0) {
exp.close();
} else {
hs.previousOrNext(exp.key, op);
}
return false;
}
}
return true;
},
registerOverlay : function (overlay) {
hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } ));
},
getWrapperKey : function (element, expOnly) {
var el, re = /^highslide-wrapper-([0-9]+)$/;
// 1. look in open expanders
el = element;
while (el.parentNode) {
if (el.id && re.test(el.id)) return el.id.replace(re, "$1");
el = el.parentNode;
}
// 2. look in thumbnail
if (!expOnly) {
el = element;
while (el.parentNode) {
if (el.tagName && hs.isHsAnchor(el)) {
for (var key = 0; key < hs.expanders.length; key++) {
var exp = hs.expanders[key];
if (exp && exp.a == el) return key;
}
}
el = el.parentNode;
}
}
return null;
},
getExpander : function (el, expOnly) {
if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null;
if (typeof el == 'number') return hs.expanders[el] || null;
if (typeof el == 'string') el = hs.$(el);
return hs.expanders[hs.getWrapperKey(el, expOnly)] || null;
},
isHsAnchor : function (a) {
return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/));
},
reOrder : function () {
for (var i = 0; i < hs.expanders.length; i++)
if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost();
},
mouseClickHandler : function(e)
{
if (!e) e = window.event;
if (e.button > 1) return true;
if (!e.target) e.target = e.srcElement;
var el = e.target;
while (el.parentNode
&& !(/highslide-(image|move|html|resize)/.test(el.className)))
{
el = el.parentNode;
}
var exp = hs.getExpander(el);
if (exp && (exp.isClosing || !exp.isExpanded)) return true;
if (exp && e.type == 'mousedown') {
if (e.target.form) return true;
var match = el.className.match(/highslide-(image|move|resize)/);
if (match) {
hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos,
height: exp.y.size, clickX: e.clientX, clickY: e.clientY };
hs.addEventListener(document, 'mousemove', hs.dragHandler);
if (e.preventDefault) e.preventDefault(); // FF
if (/highslide-(image|html)-blur/.test(exp.content.className)) {
exp.focus();
hs.hasFocused = true;
}
return false;
}
else if (/highslide-html/.test(el.className) && hs.focusKey != exp.key) {
exp.focus();
exp.doShowHide('hidden');
}
} else if (e.type == 'mouseup') {
hs.removeEventListener(document, 'mousemove', hs.dragHandler);
if (hs.dragArgs) {
if (hs.styleRestoreCursor && hs.dragArgs.type == 'image')
hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor;
var hasDragged = hs.dragArgs.hasDragged;
if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) {
exp.close();
}
else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) {
hs.dragArgs.exp.doShowHide('hidden');
}
if (hs.dragArgs.exp.releaseMask)
hs.dragArgs.exp.releaseMask.style.display = 'none';
hs.hasFocused = false;
hs.dragArgs = null;
} else if (/highslide-image-blur/.test(el.className)) {
el.style.cursor = hs.styleRestoreCursor;
}
}
return false;
},
dragHandler : function(e)
{
if (!hs.dragArgs) return true;
if (!e) e = window.event;
var a = hs.dragArgs, exp = a.exp;
if (exp.iframe) {
if (!exp.releaseMask) exp.releaseMask = hs.createElement('div', null,
{ position: 'absolute', width: exp.x.size+'px', height: exp.y.size+'px',
left: exp.x.cb+'px', top: exp.y.cb+'px', zIndex: 4, background: (hs.ie ? 'white' : 'none'),
opacity: .01 },
exp.wrapper, true);
if (exp.releaseMask.style.display == 'none')
exp.releaseMask.style.display = '';
}
a.dX = e.clientX - a.clickX;
a.dY = e.clientY - a.clickY;
var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2));
if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0)
|| (distance > (hs.dragSensitivity || 5));
if (a.hasDragged && e.clientX > 5 && e.clientY > 5) {
if (a.type == 'resize') exp.resize(a);
else {
exp.moveTo(a.left + a.dX, a.top + a.dY);
if (a.type == 'image') exp.content.style.cursor = 'move';
}
}
return false;
},
wrapperMouseHandler : function (e) {
try {
if (!e) e = window.event;
var over = /mouseover/i.test(e.type);
if (!e.target) e.target = e.srcElement; // ie
if (hs.ie) e.relatedTarget =
over ? e.fromElement : e.toElement; // ie
var exp = hs.getExpander(e.target);
if (!exp.isExpanded) return;
if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp
|| hs.dragArgs) return;
for (var i = 0; i < exp.overlays.length; i++) (function() {
var o = hs.$('hsId'+ exp.overlays[i]);
if (o && o.hideOnMouseOut) {
if (over) hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur);
}
})();
} catch (e) {}
},
addEventListener : function (el, event, func) {
if (el == document && event == 'ready') hs.push(hs.onReady, func);
try {
el.addEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
el.attachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = func;
}
}
},
removeEventListener : function (el, event, func) {
try {
el.removeEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = null;
}
}
},
preloadFullImage : function (i) {
if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') {
var img = document.createElement('img');
img.onload = function() {
img = null;
hs.preloadFullImage(i + 1);
};
img.src = hs.preloadTheseImages[i];
}
},
preloadImages : function (number) {
if (number && typeof number != 'object') hs.numberOfImagesToPreload = number;
var arr = hs.getAnchors();
for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) {
hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i]));
}
// preload outlines
if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} );
else
hs.preloadFullImage(0);
// preload cursor
if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor });
},
init : function () {
if (!hs.container) {
hs.getPageSize();
hs.ieLt7 = hs.ie && hs.uaVersion < 7;
hs.ie6SSL = hs.ieLt7 && location.protocol == 'https:';
for (var x in hs.langDefaults) {
if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x];
else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined')
hs.lang[x] = hs.langDefaults[x];
}
hs.container = hs.createElement('div', {
className: 'highslide-container'
}, {
position: 'absolute',
left: 0,
top: 0,
width: '100%',
zIndex: hs.zIndexCounter,
direction: 'ltr'
},
document.body,
true
);
hs.loading = hs.createElement('a', {
className: 'highslide-loading',
title: hs.lang.loadingTitle,
innerHTML: hs.lang.loadingText,
href: 'javascript:;'
}, {
position: 'absolute',
top: '-9999px',
opacity: hs.loadingOpacity,
zIndex: 1
}, hs.container
);
hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container);
hs.clearing = hs.createElement('div', null,
{ clear: 'both', paddingTop: '1px' }, null, true);
// http://www.robertpenner.com/easing/
Math.linearTween = function (t, b, c, d) {
return c*t/d + b;
};
Math.easeInQuad = function (t, b, c, d) {
return c*(t/=d)*t + b;
};
hs.hideSelects = hs.ieLt7;
hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE'
|| (hs.ie && hs.uaVersion < 5.5));
}
},
ready : function() {
if (hs.isReady) return;
hs.isReady = true;
for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i]();
},
updateAnchors : function() {
var el, els, all = [], images = [], htmls = [],groups = {}, re;
for (var i = 0; i < hs.openerTagNames.length; i++) {
els = document.getElementsByTagName(hs.openerTagNames[i]);
for (var j = 0; j < els.length; j++) {
el = els[j];
re = hs.isHsAnchor(el);
if (re) {
hs.push(all, el);
if (re[0] == 'hs.expand') hs.push(images, el);
else if (re[0] == 'hs.htmlExpand') hs.push(htmls, el);
var g = hs.getParam(el, 'slideshowGroup') || 'none';
if (!groups[g]) groups[g] = [];
hs.push(groups[g], el);
}
}
}
hs.anchors = { all: all, groups: groups, images: images, htmls: htmls };
return hs.anchors;
},
getAnchors : function() {
return hs.anchors || hs.updateAnchors();
},
close : function(el) {
var exp = hs.getExpander(el);
if (exp) exp.close();
return false;
}
}; // end hs object
hs.fx = function( elem, options, prop ){
this.options = options;
this.elem = elem;
this.prop = prop;
if (!options.orig) options.orig = {};
};
hs.fx.prototype = {
update: function(){
(hs.fx.step[this.prop] || hs.fx.step._default)(this);
if (this.options.step)
this.options.step.call(this.elem, this.now, this);
},
custom: function(from, to, unit){
this.startTime = (new Date()).getTime();
this.start = from;
this.end = to;
this.unit = unit;// || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t(gotoEnd){
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && hs.timers.push(t) == 1 ) {
hs.timerId = setInterval(function(){
var timers = hs.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval(hs.timerId);
}
}, 13);
}
},
step: function(gotoEnd){
var t = (new Date()).getTime();
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
var done = true;
for ( var i in this.options.curAnim )
if ( this.options.curAnim[i] !== true )
done = false;
if ( done ) {
if (this.options.complete) this.options.complete.call(this.elem);
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
this.pos = this.options.easing(n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
}
return true;
}
};
hs.extend( hs.fx, {
step: {
opacity: function(fx){
hs.setStyles(fx.elem, { opacity: fx.now });
},
_default: function(fx){
try {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
else
fx.elem[ fx.prop ] = fx.now;
} catch (e) {}
}
}
});
hs.Outline = function (outlineType, onLoad) {
this.onLoad = onLoad;
this.outlineType = outlineType;
var v = hs.uaVersion, tr;
this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7;
if (!outlineType) {
if (onLoad) onLoad();
return;
}
hs.init();
this.table = hs.createElement(
'table', {
cellSpacing: 0
}, {
visibility: 'hidden',
position: 'absolute',
borderCollapse: 'collapse',
width: 0
},
hs.container,
true
);
var tbody = hs.createElement('tbody', null, null, this.table, 1);
this.td = [];
for (var i = 0; i <= 8; i++) {
if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true);
this.td[i] = hs.createElement('td', null, null, tr, true);
var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' };
hs.setStyles(this.td[i], style);
}
this.td[4].className = outlineType +' highslide-outline';
this.preloadGraphic();
};
hs.Outline.prototype = {
preloadGraphic : function () {
var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png";
var appendTo = hs.safari ? hs.container : null;
this.graphic = hs.createElement('img', null, { position: 'absolute',
top: '-9999px' }, appendTo, true); // for onload trigger
var pThis = this;
this.graphic.onload = function() { pThis.onGraphicLoad(); };
this.graphic.src = src;
},
onGraphicLoad : function () {
var o = this.offset = this.graphic.width / 4,
pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]],
dim = { height: (2*o) +'px', width: (2*o) +'px' };
for (var i = 0; i <= 8; i++) {
if (pos[i]) {
if (this.hasAlphaImageLoader) {
var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px';
var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true);
hs.createElement ('div', null, {
filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')",
position: 'absolute',
width: w,
height: this.graphic.height +'px',
left: (pos[i][0]*o)+'px',
top: (pos[i][1]*o)+'px'
},
div,
true);
} else {
hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'});
}
if (window.opera && (i == 3 || i ==5))
hs.createElement('div', null, dim, this.td[i], true);
hs.setStyles (this.td[i], dim);
}
}
this.graphic = null;
if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy();
hs.pendingOutlines[this.outlineType] = this;
if (this.onLoad) this.onLoad();
},
setPosition : function (pos, offset, vis, dur, easing) {
var exp = this.exp,
stl = exp.wrapper.style,
offset = offset || 0,
pos = pos || {
x: exp.x.pos + offset,
y: exp.y.pos + offset,
w: exp.x.get('wsize') - 2 * offset,
h: exp.y.get('wsize') - 2 * offset
};
if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset)
? 'visible' : 'hidden';
hs.setStyles(this.table, {
left: (pos.x - this.offset) +'px',
top: (pos.y - this.offset) +'px',
width: (pos.w + 2 * this.offset) +'px'
});
pos.w -= 2 * this.offset;
pos.h -= 2 * this.offset;
hs.setStyles (this.td[4], {
width: pos.w >= 0 ? pos.w +'px' : 0,
height: pos.h >= 0 ? pos.h +'px' : 0
});
if (this.hasAlphaImageLoader) this.td[3].style.height
= this.td[5].style.height = this.td[4].style.height;
},
destroy : function(hide) {
if (hide) this.table.style.visibility = 'hidden';
else hs.discardElement(this.table);
}
};
hs.Dimension = function(exp, dim) {
this.exp = exp;
this.dim = dim;
this.ucwh = dim == 'x' ? 'Width' : 'Height';
this.wh = this.ucwh.toLowerCase();
this.uclt = dim == 'x' ? 'Left' : 'Top';
this.lt = this.uclt.toLowerCase();
this.ucrb = dim == 'x' ? 'Right' : 'Bottom';
this.rb = this.ucrb.toLowerCase();
this.p1 = this.p2 = 0;
};
hs.Dimension.prototype = {
get : function(key) {
switch (key) {
case 'loadingPos':
return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2;
case 'wsize':
return this.size + 2 * this.cb + this.p1 + this.p2;
case 'fitsize':
return this.clientSize - this.marginMin - this.marginMax;
case 'maxsize':
return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ;
case 'opos':
return this.pos - (this.exp.outline ? this.exp.outline.offset : 0);
case 'osize':
return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0);
case 'imgPad':
return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0;
}
},
calcBorders: function() {
// correct for borders
this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2;
this.marginMax = hs['margin'+ this.ucrb];
},
calcThumb: function() {
this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) :
this.exp.el['offset'+ this.ucwh];
this.tpos = this.exp.tpos[this.dim];
this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2;
if (this.tpos == 0 || this.tpos == -1) {
this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt];
};
},
calcExpanded: function() {
var exp = this.exp;
this.justify = 'auto';
// size and position
this.pos = this.tpos - this.cb + this.tb;
if (this.dim == 'x')
exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full);
this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full);
this.minSize = exp.allowSizeReduction ?
Math.min(exp['min'+ this.ucwh], this.full) :this.full;
if (exp.isImage && exp.useBox) {
this.size = exp[this.wh];
this.imgSize = this.full;
}
if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth;
this.marginMin = hs['margin'+ this.uclt];
this.scroll = hs.page['scroll'+ this.uclt];
this.clientSize = hs.page[this.wh];
},
setSize: function(i) {
var exp = this.exp;
if (exp.isImage && (exp.useBox || hs.padToMinWidth)) {
this.imgSize = i;
this.size = Math.max(this.size, this.imgSize);
exp.content.style[this.lt] = this.get('imgPad')+'px';
} else
this.size = i;
exp.content.style[this.wh] = i +'px';
exp.wrapper.style[this.wh] = this.get('wsize') +'px';
if (exp.outline) exp.outline.setPosition();
if (exp.releaseMask) exp.releaseMask.style[this.wh] = i +'px';
if (this.dim == 'y' && exp.iDoc && exp.body.style.height != 'auto')
exp.iDoc.body.style.overflow = 'auto';
if (exp.isHtml) {
var d = exp.scrollerDiv;
if (this.sizeDiff === undefined)
this.sizeDiff = exp.innerContent['offset'+ this.ucwh] - d['offset'+ this.ucwh];
d.style[this.wh] = (this.size - this.sizeDiff) +'px';
if (this.dim == 'x') exp.mediumContent.style.width = 'auto';
if (exp.body) exp.body.style[this.wh] = 'auto';
}
if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true);
},
setPos: function(i) {
this.pos = i;
this.exp.wrapper.style[this.lt] = i +'px';
if (this.exp.outline) this.exp.outline.setPosition();
}
};
hs.Expander = function(a, params, custom, contentType) {
if (document.readyState && hs.ie && !hs.isReady) {
hs.addEventListener(document, 'ready', function() {
new hs.Expander(a, params, custom, contentType);
});
return;
}
this.a = a;
this.custom = custom;
this.contentType = contentType || 'image';
this.isHtml = (contentType == 'html');
this.isImage = !this.isHtml;
hs.continuePreloading = false;
this.overlays = [];
hs.init();
var key = this.key = hs.expanders.length;
// override inline parameters
for (var i = 0; i < hs.overrides.length; i++) {
var name = hs.overrides[i];
this[name] = params && typeof params[name] != 'undefined' ?
params[name] : hs[name];
}
if (!this.src) this.src = a.href;
// get thumb
var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a;
el = this.thumb = el.getElementsByTagName('img')[0] || el;
this.thumbsUserSetId = el.id || a.id;
// check if already open
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].a == a) {
hs.expanders[i].focus();
return false;
}
}
// cancel other
if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) {
hs.expanders[i].cancelLoading();
}
}
hs.expanders[key] = this;
if (!hs.allowMultipleInstances && !hs.upcoming) {
if (hs.expanders[key-1]) hs.expanders[key-1].close();
if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey])
hs.expanders[hs.focusKey].close();
}
// initiate metrics
this.el = el;
this.tpos = hs.getPosition(el);
hs.getPageSize();
var x = this.x = new hs.Dimension(this, 'x');
x.calcThumb();
var y = this.y = new hs.Dimension(this, 'y');
y.calcThumb();
this.wrapper = hs.createElement(
'div', {
id: 'highslide-wrapper-'+ this.key,
className: 'highslide-wrapper '+ this.wrapperClassName
}, {
visibility: 'hidden',
position: 'absolute',
zIndex: hs.zIndexCounter += 2
}, null, true );
this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler;
if (this.contentType == 'image' && this.outlineWhileAnimating == 2)
this.outlineWhileAnimating = 0;
// get the outline
if (!this.outlineType) {
this[this.contentType +'Create']();
} else if (hs.pendingOutlines[this.outlineType]) {
this.connectOutline();
this[this.contentType +'Create']();
} else {
this.showLoading();
var exp = this;
new hs.Outline(this.outlineType,
function () {
exp.connectOutline();
exp[exp.contentType +'Create']();
}
);
}
return true;
};
hs.Expander.prototype = {
error : function(e) {
// alert ('Line '+ e.lineNumber +': '+ e.message);
window.location.href = this.src;
},
connectOutline : function() {
var outline = this.outline = hs.pendingOutlines[this.outlineType];
outline.exp = this;
outline.table.style.zIndex = this.wrapper.style.zIndex - 1;
hs.pendingOutlines[this.outlineType] = null;
},
showLoading : function() {
if (this.onLoadStarted || this.loading) return;
this.loading = hs.loading;
var exp = this;
this.loading.onclick = function() {
exp.cancelLoading();
};
var exp = this,
l = this.x.get('loadingPos') +'px',
t = this.y.get('loadingPos') +'px';
setTimeout(function () {
if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })}
, 100);
},
imageCreate : function() {
var exp = this;
var img = document.createElement('img');
this.content = img;
img.onload = function () {
if (hs.expanders[exp.key]) exp.contentLoaded();
};
if (hs.blockRightClick) img.oncontextmenu = function() { return false; };
img.className = 'highslide-image';
hs.setStyles(img, {
visibility: 'hidden',
display: 'block',
position: 'absolute',
maxWidth: '9999px',
zIndex: 3
});
img.title = hs.lang.restoreTitle;
if (hs.safari) hs.container.appendChild(img);
if (hs.ie && hs.flushImgSize) img.src = null;
img.src = this.src;
this.showLoading();
},
htmlCreate : function () {
this.content = hs.getCacheBinding(this.a);
if (!this.content)
this.content = hs.getNode(this.contentId);
if (!this.content)
this.content = hs.getSelfRendered();
this.getInline(['maincontent']);
if (this.maincontent) {
var body = hs.getElementByClass(this.content, 'div', 'highslide-body');
if (body) body.appendChild(this.maincontent);
this.maincontent.style.display = 'block';
}
var innerContent = this.innerContent = this.content;
if (/(swf|iframe)/.test(this.objectType)) this.setObjContainerSize(innerContent);
// the content tree
hs.container.appendChild(this.wrapper);
hs.setStyles( this.wrapper, {
position: 'static',
padding: '0 '+ hs.marginRight +'px 0 '+ hs.marginLeft +'px'
});
this.content = hs.createElement(
'div', {
className: 'highslide-html'
}, {
position: 'relative',
zIndex: 3,
overflow: 'hidden'
},
this.wrapper
);
this.mediumContent = hs.createElement('div', null, null, this.content, 1);
this.mediumContent.appendChild(innerContent);
hs.setStyles (innerContent, {
position: 'relative',
display: 'block',
direction: hs.lang.cssDirection || ''
});
if (this.width) innerContent.style.width = this.width +'px';
if (this.height) hs.setStyles(innerContent, {
height: this.height +'px',
overflow: 'hidden'
});
if (innerContent.offsetWidth < this.minWidth)
innerContent.style.width = this.minWidth +'px';
if (this.objectType == 'ajax' && !hs.getCacheBinding(this.a)) {
this.showLoading();
var exp = this;
var ajax = new hs.Ajax(this.a, innerContent);
ajax.src = this.src;
ajax.onLoad = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); };
ajax.onError = function () { location.href = exp.src; };
ajax.run();
}
else
if (this.objectType == 'iframe' && this.objectLoadTime == 'before') {
this.writeExtendedContent();
}
else
this.contentLoaded();
},
contentLoaded : function() {
try {
if (!this.content) return;
this.content.onload = null;
if (this.onLoadStarted) return;
else this.onLoadStarted = true;
var x = this.x, y = this.y;
if (this.loading) {
hs.setStyles(this.loading, { top: '-9999px' });
this.loading = null;
}
if (this.isImage) {
x.full = this.content.width;
y.full = this.content.height;
hs.setStyles(this.content, {
width: x.t +'px',
height: y.t +'px'
});
this.wrapper.appendChild(this.content);
hs.container.appendChild(this.wrapper);
} else if (this.htmlGetSize) this.htmlGetSize();
x.calcBorders();
y.calcBorders();
hs.setStyles (this.wrapper, {
left: (x.tpos + x.tb - x.cb) +'px',
top: (y.tpos + x.tb - y.cb) +'px'
});
this.getOverlays();
var ratio = x.full / y.full;
x.calcExpanded();
this.justify(x);
y.calcExpanded();
this.justify(y);
if (this.isHtml) this.htmlSizeOperations();
if (this.overlayBox) this.sizeOverlayBox(0, 1);
if (this.allowSizeReduction) {
if (this.isImage)
this.correctRatio(ratio);
else this.fitOverlayBox();
if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) {
this.createFullExpand();
if (this.overlays.length == 1) this.sizeOverlayBox();
}
}
this.show();
} catch (e) {
this.error(e);
}
},
setObjContainerSize : function(parent, auto) {
var c = hs.getElementByClass(parent, 'DIV', 'highslide-body');
if (/(iframe|swf)/.test(this.objectType)) {
if (this.objectWidth) c.style.width = this.objectWidth +'px';
if (this.objectHeight) c.style.height = this.objectHeight +'px';
}
},
writeExtendedContent : function () {
if (this.hasExtendedContent) return;
var exp = this;
this.body = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body');
if (this.objectType == 'iframe') {
this.showLoading();
var ruler = hs.clearing.cloneNode(1);
this.body.appendChild(ruler);
this.newWidth = this.innerContent.offsetWidth;
if (!this.objectWidth) this.objectWidth = ruler.offsetWidth;
var hDiff = this.innerContent.offsetHeight - this.body.offsetHeight,
h = this.objectHeight || hs.page.height - hDiff - hs.marginTop - hs.marginBottom,
onload = this.objectLoadTime == 'before' ?
' onload="if (hs.expanders['+ this.key +']) hs.expanders['+ this.key +'].contentLoaded()" ' : '';
this.body.innerHTML += '<iframe name="hs'+ (new Date()).getTime() +'" frameborder="0" key="'+ this.key +'" '
+' style="width:'+ this.objectWidth +'px; height:'+ h +'px" '
+ onload +' src="'+ this.src +'" ></iframe>';
this.ruler = this.body.getElementsByTagName('div')[0];
this.iframe = this.body.getElementsByTagName('iframe')[0];
if (this.objectLoadTime == 'after') this.correctIframeSize();
}
if (this.objectType == 'swf') {
this.body.id = this.body.id || 'hs-flash-id-' + this.key;
var a = this.swfOptions;
if (!a.params) a.params = {};
if (typeof a.params.wmode == 'undefined') a.params.wmode = 'transparent';
if (swfobject) swfobject.embedSWF(this.src, this.body.id, this.objectWidth, this.objectHeight,
a.version || '7', a.expressInstallSwfurl, a.flashvars, a.params, a.attributes);
}
this.hasExtendedContent = true;
},
htmlGetSize : function() {
if (this.iframe && !this.objectHeight) { // loadtime before
this.iframe.style.height = this.body.style.height = this.getIframePageHeight() +'px';
}
this.innerContent.appendChild(hs.clearing);
if (!this.x.full) this.x.full = this.innerContent.offsetWidth;
this.y.full = this.innerContent.offsetHeight;
this.innerContent.removeChild(hs.clearing);
if (hs.ie && this.newHeight > parseInt(this.innerContent.currentStyle.height)) { // ie css bug
this.newHeight = parseInt(this.innerContent.currentStyle.height);
}
hs.setStyles( this.wrapper, { position: 'absolute', padding: '0'});
hs.setStyles( this.content, { width: this.x.t +'px', height: this.y.t +'px'});
},
getIframePageHeight : function() {
var h;
try {
var doc = this.iDoc = this.iframe.contentDocument || this.iframe.contentWindow.document;
var clearing = doc.createElement('div');
clearing.style.clear = 'both';
doc.body.appendChild(clearing);
h = clearing.offsetTop;
if (hs.ie) h += parseInt(doc.body.currentStyle.marginTop)
+ parseInt(doc.body.currentStyle.marginBottom) - 1;
} catch (e) { // other domain
h = 300;
}
return h;
},
correctIframeSize : function () {
var wDiff = this.innerContent.offsetWidth - this.ruler.offsetWidth;
hs.discardElement(this.ruler);
if (wDiff < 0) wDiff = 0;
var hDiff = this.innerContent.offsetHeight - this.iframe.offsetHeight;
if (this.iDoc && !this.objectHeight && this.y.size == this.y.full)
this.iDoc.body.style.overflow = 'hidden';
hs.setStyles(this.iframe, {
width: Math.abs(this.x.size - wDiff) +'px',
height: Math.abs(this.y.size - hDiff) +'px'
});
hs.setStyles(this.body, {
width: this.iframe.style.width,
height: this.iframe.style.height
});
this.scrollingContent = this.iframe;
this.scrollerDiv = this.scrollingContent;
},
htmlSizeOperations : function () {
this.setObjContainerSize(this.innerContent);
if (this.objectType == 'swf' && this.objectLoadTime == 'before') this.writeExtendedContent();
// handle minimum size
if (this.x.size < this.x.full && !this.allowWidthReduction) this.x.size = this.x.full;
if (this.y.size < this.y.full && !this.allowHeightReduction) this.y.size = this.y.full;
this.scrollerDiv = this.innerContent;
hs.setStyles(this.mediumContent, {
position: 'relative',
width: this.x.size +'px'
});
hs.setStyles(this.innerContent, {
border: 'none',
width: 'auto',
height: 'auto'
});
var node = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body');
if (node && !/(iframe|swf)/.test(this.objectType)) {
var cNode = node; // wrap to get true size
node = hs.createElement(cNode.nodeName, null, {overflow: 'hidden'}, null, true);
cNode.parentNode.insertBefore(node, cNode);
node.appendChild(hs.clearing); // IE6
node.appendChild(cNode);
var wDiff = this.innerContent.offsetWidth - node.offsetWidth;
var hDiff = this.innerContent.offsetHeight - node.offsetHeight;
node.removeChild(hs.clearing);
var kdeBugCorr = hs.safari || navigator.vendor == 'KDE' ? 1 : 0; // KDE repainting bug
hs.setStyles(node, {
width: (this.x.size - wDiff - kdeBugCorr) +'px',
height: (this.y.size - hDiff) +'px',
overflow: 'auto',
position: 'relative'
}
);
if (kdeBugCorr && cNode.offsetHeight > node.offsetHeight) {
node.style.width = (parseInt(node.style.width) + kdeBugCorr) + 'px';
}
this.scrollingContent = node;
this.scrollerDiv = this.scrollingContent;
}
if (this.iframe && this.objectLoadTime == 'before') this.correctIframeSize();
if (!this.scrollingContent && this.y.size < this.mediumContent.offsetHeight) this.scrollerDiv = this.content;
if (this.scrollerDiv == this.content && !this.allowWidthReduction && !/(iframe|swf)/.test(this.objectType)) {
this.x.size += 17; // room for scrollbars
}
if (this.scrollerDiv && this.scrollerDiv.offsetHeight > this.scrollerDiv.parentNode.offsetHeight) {
setTimeout("try { hs.expanders["+ this.key +"].scrollerDiv.style.overflow = 'auto'; } catch(e) {}",
hs.expandDuration);
}
},
justify : function (p, moveOnly) {
var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y';
var hasMovedMin = false;
var allowReduce = p.exp.allowSizeReduction;
p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2));
if (p.pos < p.scroll + p.marginMin) {
p.pos = p.scroll + p.marginMin;
hasMovedMin = true;
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) {
if (!moveOnly && hasMovedMin && allowReduce) {
p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize'));
} else if (p.get('wsize') < p.get('fitsize')) {
p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize');
} else { // image larger than viewport
p.pos = p.scroll + p.marginMin;
if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize');
}
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos < p.marginMin) {
var tmpMin = p.pos;
p.pos = p.marginMin;
if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin);
}
},
correctRatio : function(ratio) {
var x = this.x,
y = this.y,
changed = false,
xSize = Math.min(x.full, x.size),
ySize = Math.min(y.full, y.size),
useBox = (this.useBox || hs.padToMinWidth);
if (xSize / ySize > ratio) { // width greater
xSize = ySize * ratio;
if (xSize < x.minSize) { // below minWidth
xSize = x.minSize;
ySize = xSize / ratio;
}
changed = true;
} else if (xSize / ySize < ratio) { // height greater
ySize = xSize / ratio;
changed = true;
}
if (hs.padToMinWidth && x.full < x.minSize) {
x.imgSize = x.full;
y.size = y.imgSize = y.full;
} else if (this.useBox) {
x.imgSize = xSize;
y.imgSize = ySize;
} else {
x.size = xSize;
y.size = ySize;
}
changed = this.fitOverlayBox(useBox ? null : ratio, changed);
if (useBox && y.size < y.imgSize) {
y.imgSize = y.size;
x.imgSize = y.size * ratio;
}
if (changed || useBox) {
x.pos = x.tpos - x.cb + x.tb;
x.minSize = x.size;
this.justify(x, true);
y.pos = y.tpos - y.cb + y.tb;
y.minSize = y.size;
this.justify(y, true);
if (this.overlayBox) this.sizeOverlayBox();
}
},
fitOverlayBox : function(ratio, changed) {
var x = this.x, y = this.y;
if (this.overlayBox) {
while (y.size > this.minHeight && x.size > this.minWidth
&& y.get('wsize') > y.get('fitsize')) {
y.size -= 10;
if (ratio) x.size = y.size * ratio;
this.sizeOverlayBox(0, 1);
changed = true;
}
}
return changed;
},
show : function () {
var x = this.x, y = this.y;
this.doShowHide('hidden');
// Apply size change
this.changeSize(
1, {
wrapper: {
width : x.get('wsize'),
height : y.get('wsize'),
left: x.pos,
top: y.pos
},
content: {
left: x.p1 + x.get('imgPad'),
top: y.p1 + y.get('imgPad'),
width:x.imgSize ||x.size,
height:y.imgSize ||y.size
}
},
hs.expandDuration
);
},
changeSize : function(up, to, dur) {
if (this.outline && !this.outlineWhileAnimating) {
if (up) this.outline.setPosition();
else this.outline.destroy(
(this.isHtml && this.preserveContent));
}
if (!up) this.destroyOverlays();
var exp = this,
x = exp.x,
y = exp.y,
easing = this.easing;
if (!up) easing = this.easingClose || easing;
var after = up ?
function() {
if (exp.outline) exp.outline.table.style.visibility = "visible";
setTimeout(function() {
exp.afterExpand();
}, 50);
} :
function() {
exp.afterClose();
};
if (up) hs.setStyles( this.wrapper, {
width: x.t +'px',
height: y.t +'px'
});
if (up && this.isHtml) {
hs.setStyles(this.wrapper, {
left: (x.tpos - x.cb + x.tb) +'px',
top: (y.tpos - y.cb + y.tb) +'px'
});
}
if (this.fadeInOut) {
hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 });
hs.extend(to.wrapper, { opacity: up });
}
hs.animate( this.wrapper, to.wrapper, {
duration: dur,
easing: easing,
step: function(val, args) {
if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') {
var fac = up ? args.pos : 1 - args.pos;
var pos = {
w: x.t + (x.get('wsize') - x.t) * fac,
h: y.t + (y.get('wsize') - y.t) * fac,
x: x.tpos + (x.pos - x.tpos) * fac,
y: y.tpos + (y.pos - y.tpos) * fac
};
exp.outline.setPosition(pos, 0, 1);
}
if (exp.isHtml) {
if (args.prop == 'left')
exp.mediumContent.style.left = (x.pos - val) +'px';
if (args.prop == 'top')
exp.mediumContent.style.top = (y.pos - val) +'px';
}
}
});
hs.animate( this.content, to.content, dur, easing, after);
if (up) {
this.wrapper.style.visibility = 'visible';
this.content.style.visibility = 'visible';
if (this.isHtml) this.innerContent.style.visibility = 'visible';
this.a.className += ' highslide-active-anchor';
}
},
afterExpand : function() {
this.isExpanded = true;
this.focus();
if (this.isHtml && this.objectLoadTime == 'after') this.writeExtendedContent();
if (this.iframe) {
try {
var exp = this,
doc = this.iframe.contentDocument || this.iframe.contentWindow.document;
hs.addEventListener(doc, 'mousedown', function () {
if (hs.focusKey != exp.key) exp.focus();
});
} catch(e) {}
if (hs.ie && typeof this.isClosing != 'boolean') // first open
this.iframe.style.width = (this.objectWidth - 1) +'px'; // hasLayout
}
if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null;
this.prepareNextOutline();
var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop;
this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize')
&& this.y.pos < mY && mY < this.y.pos + this.y.get('wsize');
if (this.overlayBox) this.showOverlays();
},
prepareNextOutline : function() {
var key = this.key;
var outlineType = this.outlineType;
new hs.Outline(outlineType,
function () { try { hs.expanders[key].preloadNext(); } catch (e) {} });
},
preloadNext : function() {
var next = this.getAdjacentAnchor(1);
if (next && next.onclick.toString().match(/hs\.expand/))
var img = hs.createElement('img', { src: hs.getSrc(next) });
},
getAdjacentAnchor : function(op) {
var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none'];
/*< ? if ($cfg->slideshow) : ?>s*/
if (!as[current + op] && this.slideshow && this.slideshow.repeat) {
if (op == 1) return as[0];
else if (op == -1) return as[as.length-1];
}
/*< ? endif ?>s*/
return as[current + op] || null;
},
getAnchorIndex : function() {
var arr = hs.getAnchors().groups[this.slideshowGroup || 'none'];
if (arr) for (var i = 0; i < arr.length; i++) {
if (arr[i] == this.a) return i;
}
return null;
},
cancelLoading : function() {
hs.discardElement (this.wrapper);
hs.expanders[this.key] = null;
if (this.loading) hs.loading.style.left = '-9999px';
},
writeCredits : function () {
this.credits = hs.createElement('a', {
href: hs.creditsHref,
target: hs.creditsTarget,
className: 'highslide-credits',
innerHTML: hs.lang.creditsText,
title: hs.lang.creditsTitle
});
this.createOverlay({
overlayId: this.credits,
position: this.creditsPosition || 'top left'
});
},
getInline : function(types, addOverlay) {
for (var i = 0; i < types.length; i++) {
var type = types[i], s = null;
if (!this[type +'Id'] && this.thumbsUserSetId)
this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId;
if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']);
if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try {
s = eval(this[type +'Eval']);
} catch (e) {}
if (!this[type] && this[type +'Text']) {
s = this[type +'Text'];
}
if (!this[type] && !s) {
this[type] = hs.getNode(this.a['_'+ type + 'Id']);
if (!this[type]) {
var next = this.a.nextSibling;
while (next && !hs.isHsAnchor(next)) {
if ((new RegExp('highslide-'+ type)).test(next.className || null)) {
if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++;
this[type] = hs.getNode(next.id);
break;
}
next = next.nextSibling;
}
}
}
if (!this[type] && s) this[type] = hs.createElement('div',
{ className: 'highslide-'+ type, innerHTML: s } );
if (addOverlay && this[type]) {
var o = { position: (type == 'heading') ? 'above' : 'below' };
for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x];
o.overlayId = this[type];
this.createOverlay(o);
}
}
},
// on end move and resize
doShowHide : function(visibility) {
if (hs.hideSelects) this.showHideElements('SELECT', visibility);
if (hs.hideIframes) this.showHideElements('IFRAME', visibility);
if (hs.geckoMac) this.showHideElements('*', visibility);
},
showHideElements : function (tagName, visibility) {
var els = document.getElementsByTagName(tagName);
var prop = tagName == '*' ? 'overflow' : 'visibility';
for (var i = 0; i < els.length; i++) {
if (prop == 'visibility' || (document.defaultView.getComputedStyle(
els[i], "").getPropertyValue('overflow') == 'auto'
|| els[i].getAttribute('hidden-by') != null)) {
var hiddenBy = els[i].getAttribute('hidden-by');
if (visibility == 'visible' && hiddenBy) {
hiddenBy = hiddenBy.replace('['+ this.key +']', '');
els[i].setAttribute('hidden-by', hiddenBy);
if (!hiddenBy) els[i].style[prop] = els[i].origProp;
} else if (visibility == 'hidden') { // hide if behind
var elPos = hs.getPosition(els[i]);
elPos.w = els[i].offsetWidth;
elPos.h = els[i].offsetHeight;
var clearsX = (elPos.x + elPos.w < this.x.get('opos')
|| elPos.x > this.x.get('opos') + this.x.get('osize'));
var clearsY = (elPos.y + elPos.h < this.y.get('opos')
|| elPos.y > this.y.get('opos') + this.y.get('osize'));
var wrapperKey = hs.getWrapperKey(els[i]);
if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image
if (!hiddenBy) {
els[i].setAttribute('hidden-by', '['+ this.key +']');
els[i].origProp = els[i].style[prop];
els[i].style[prop] = 'hidden';
} else if (hiddenBy.indexOf('['+ this.key +']') == -1) {
els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']');
}
} else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey)
&& wrapperKey != this.key) { // on move
els[i].setAttribute('hidden-by', '');
els[i].style[prop] = els[i].origProp || '';
} else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) {
els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', ''));
}
}
}
}
},
focus : function() {
this.wrapper.style.zIndex = hs.zIndexCounter += 2;
// blur others
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && i == hs.focusKey) {
var blurExp = hs.expanders[i];
blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur';
if (blurExp.isImage) {
blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer';
blurExp.content.title = hs.lang.focusTitle;
}
}
}
// focus this
if (this.outline) this.outline.table.style.zIndex
= this.wrapper.style.zIndex - 1;
this.content.className = 'highslide-'+ this.contentType;
if (this.isImage) {
this.content.title = hs.lang.restoreTitle;
if (hs.restoreCursor) {
hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer';
if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand';
this.content.style.cursor = hs.styleRestoreCursor;
}
}
hs.focusKey = this.key;
hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
},
moveTo: function(x, y) {
this.x.setPos(x);
this.y.setPos(y);
},
resize : function (e) {
var w, h, r = e.width / e.height;
w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full));
if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full;
h = this.isHtml ? e.height + e.dY : w / r;
if (h < Math.min(this.minHeight, this.y.full)) {
h = Math.min(this.minHeight, this.y.full);
if (this.isImage) w = h * r;
}
this.resizeTo(w, h);
},
resizeTo: function(w, h) {
this.y.setSize(h);
this.x.setSize(w);
this.wrapper.style.height = this.y.get('wsize') +'px';
},
close : function() {
if (this.isClosing || !this.isExpanded) return;
this.isClosing = true;
hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
try {
if (this.isHtml) this.htmlPrepareClose();
this.content.style.cursor = 'default';
this.changeSize(
0, {
wrapper: {
width : this.x.t,
height : this.y.t,
left: this.x.tpos - this.x.cb + this.x.tb,
top: this.y.tpos - this.y.cb + this.y.tb
},
content: {
left: 0,
top: 0,
width: this.x.t,
height: this.y.t
}
}, hs.restoreDuration
);
} catch (e) { this.afterClose(); }
},
htmlPrepareClose : function() {
if (hs.geckoMac) { // bad redraws
if (!hs.mask) hs.mask = hs.createElement('div', null,
{ position: 'absolute' }, hs.container);
hs.setStyles(hs.mask, { width: this.x.size +'px', height: this.y.size +'px',
left: this.x.pos +'px', top: this.y.pos +'px', display: 'block' });
}
if (this.objectType == 'swf') try { hs.$(this.body.id).StopPlay(); } catch (e) {}
if (this.objectLoadTime == 'after' && !this.preserveContent) this.destroyObject();
if (this.scrollerDiv && this.scrollerDiv != this.scrollingContent)
this.scrollerDiv.style.overflow = 'hidden';
},
destroyObject : function () {
if (hs.ie && this.iframe)
try { this.iframe.contentWindow.document.body.innerHTML = ''; } catch (e) {}
if (this.objectType == 'swf') swfobject.removeSWF(this.body.id);
this.body.innerHTML = '';
},
sleep : function() {
if (this.outline) this.outline.table.style.display = 'none';
this.releaseMask = null;
this.wrapper.style.display = 'none';
hs.push(hs.sleeping, this);
},
awake : function() {try {
hs.expanders[this.key] = this;
if (!hs.allowMultipleInstances &&hs.focusKey != this.key) {
try { hs.expanders[hs.focusKey].close(); } catch (e){}
}
var z = hs.zIndexCounter++, stl = { display: '', zIndex: z };
hs.setStyles (this.wrapper, stl);
this.isClosing = false;
var o = this.outline || 0;
if (o) {
if (!this.outlineWhileAnimating) stl.visibility = 'hidden';
hs.setStyles (o.table, stl);
}
this.show();
} catch (e) {}
},
createOverlay : function (o) {
var el = o.overlayId;
if (typeof el == 'string') el = hs.getNode(el);
if (o.html) el = hs.createElement('div', { innerHTML: o.html });
if (!el || typeof el == 'string') return;
el.style.display = 'block';
this.genOverlayBox();
var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto';
if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px';
var overlay = hs.createElement(
'div', {
id: 'hsId'+ hs.idCounter++,
hsId: o.hsId
}, {
position: 'absolute',
visibility: 'hidden',
width: width,
direction: hs.lang.cssDirection || '',
opacity: 0
},this.overlayBox,
true
);
overlay.appendChild(el);
hs.extend(overlay, {
opacity: 1,
offsetX: 0,
offsetY: 0,
dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250
});
hs.extend(overlay, o);
if (this.gotOverlays) {
this.positionOverlay(overlay);
if (!overlay.hideOnMouseOut || this.mouseIsOver)
hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur);
}
hs.push(this.overlays, hs.idCounter - 1);
},
positionOverlay : function(overlay) {
var p = overlay.position || 'middle center',
offX = overlay.offsetX,
offY = overlay.offsetY;
if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay);
if (/left$/.test(p)) overlay.style.left = offX +'px';
if (/center$/.test(p)) hs.setStyles (overlay, {
left: '50%',
marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px'
});
if (/right$/.test(p)) overlay.style.right = - offX +'px';
if (/^leftpanel$/.test(p)) {
hs.setStyles(overlay, {
right: '100%',
marginRight: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p1 = overlay.offsetWidth;
} else if (/^rightpanel$/.test(p)) {
hs.setStyles(overlay, {
left: '100%',
marginLeft: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p2 = overlay.offsetWidth;
}
if (/^top/.test(p)) overlay.style.top = offY +'px';
if (/^middle/.test(p)) hs.setStyles (overlay, {
top: '50%',
marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px'
});
if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px';
if (/^above$/.test(p)) {
hs.setStyles(overlay, {
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
bottom: '100%',
marginBottom: this.y.cb +'px',
width: 'auto'
});
this.y.p1 = overlay.offsetHeight;
} else if (/^below$/.test(p)) {
hs.setStyles(overlay, {
position: 'relative',
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
top: '100%',
marginTop: this.y.cb +'px',
width: 'auto'
});
this.y.p2 = overlay.offsetHeight;
overlay.style.position = 'absolute';
}
},
getOverlays : function() {
this.getInline(['heading', 'caption'], true);
if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move';
if (hs.showCredits) this.writeCredits();
for (var i = 0; i < hs.overlays.length; i++) {
var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup;
if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId)
|| (sg && sg === this.slideshowGroup)) {
if (this.isImage || (this.isHtml && o.useOnHtml))
this.createOverlay(o);
}
}
var os = [];
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
if (/panel$/.test(o.position)) this.positionOverlay(o);
else hs.push(os, o);
}
for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]);
this.gotOverlays = true;
},
genOverlayBox : function() {
if (!this.overlayBox) this.overlayBox = hs.createElement (
'div', {
className: this.wrapperClassName
}, {
position : 'absolute',
width: (this.x.size || (this.useBox ? this.width : null)
|| this.x.full) +'px',
height: (this.y.size || this.y.full) +'px',
visibility : 'hidden',
overflow : 'hidden',
zIndex : hs.ie ? 4 : 'auto'
},
hs.container,
true
);
},
sizeOverlayBox : function(doWrapper, doPanels) {
var overlayBox = this.overlayBox,
x = this.x,
y = this.y;
hs.setStyles( overlayBox, {
width: x.size +'px',
height: y.size +'px'
});
if (doWrapper || doPanels) {
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat');
if (o && /^(above|below)$/.test(o.position)) {
if (ie6) {
o.style.width = (overlayBox.offsetWidth + 2 * x.cb
+ x.p1 + x.p2) +'px';
}
y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight;
}
if (o && ie6 && /^(left|right)panel$/.test(o.position)) {
o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px';
}
}
}
if (doWrapper) {
hs.setStyles(this.content, {
top: y.p1 +'px'
});
hs.setStyles(overlayBox, {
top: (y.p1 + y.cb) +'px'
});
}
},
showOverlays : function() {
var b = this.overlayBox;
b.className = '';
hs.setStyles(b, {
top: (this.y.p1 + this.y.cb) +'px',
left: (this.x.p1 + this.x.cb) +'px',
overflow : 'visible'
});
if (hs.safari) b.style.visibility = 'visible';
this.wrapper.appendChild (b);
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
o.style.zIndex = 4;
if (!o.hideOnMouseOut || this.mouseIsOver) {
o.style.visibility = 'visible';
hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: o.opacity }, o.dur);
}
}
},
destroyOverlays : function() {
if (!this.overlays.length) return;
if (this.isHtml && this.preserveContent) {
this.overlayBox.style.top = '-9999px';
hs.container.appendChild(this.overlayBox);
} else
hs.discardElement(this.overlayBox);
},
createFullExpand : function () {
this.fullExpandLabel = hs.createElement(
'a', {
href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();',
title: hs.lang.fullExpandTitle,
className: 'highslide-full-expand'
}
);
this.createOverlay({
overlayId: this.fullExpandLabel,
position: hs.fullExpandPosition,
hideOnMouseOut: true,
opacity: hs.fullExpandOpacity
});
},
doFullExpand : function () {
try {
if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel);
this.focus();
var xSize = this.x.size;
this.resizeTo(this.x.full, this.y.full);
var xpos = this.x.pos - (this.x.size - xSize) / 2;
if (xpos < hs.marginLeft) xpos = hs.marginLeft;
this.moveTo(xpos, this.y.pos);
this.doShowHide('hidden');
} catch (e) {
this.error(e);
}
},
afterClose : function () {
this.a.className = this.a.className.replace('highslide-active-anchor', '');
this.doShowHide('visible');
if (this.isHtml && this.preserveContent) {
this.sleep();
} else {
if (this.outline && this.outlineWhileAnimating) this.outline.destroy();
hs.discardElement(this.wrapper);
}
if (hs.mask) hs.mask.style.display = 'none';
hs.expanders[this.key] = null;
hs.reOrder();
}
};
// hs.Ajax object prototype
hs.Ajax = function (a, content, pre) {
this.a = a;
this.content = content;
this.pre = pre;
};
hs.Ajax.prototype = {
run : function () {
var xhr;
if (!this.src) this.src = hs.getSrc(this.a);
if (this.src.match('#')) {
var arr = this.src.split('#');
this.src = arr[0];
this.id = arr[1];
}
if (hs.cachedGets[this.src]) {
this.cachedGet = hs.cachedGets[this.src];
if (this.id) this.getElementContent();
else this.loadHTML();
return;
}
try { xhr = new XMLHttpRequest(); }
catch (e) {
try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {
try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { this.onError(); }
}
}
var pThis = this;
xhr.onreadystatechange = function() {
if(pThis.xhr.readyState == 4) {
if (pThis.id) pThis.getElementContent();
else pThis.loadHTML();
}
};
var src = this.src;
this.xhr = xhr;
if (hs.forceAjaxReload)
src = src.replace(/$/, (/\?/.test(src) ? '&' : '?') +'dummy='+ (new Date()).getTime());
xhr.open('GET', src, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(null);
},
getElementContent : function() {
hs.init();
var attribs = window.opera || hs.ie6SSL ? { src: 'about:blank' } : null;
this.iframe = hs.createElement('iframe', attribs,
{ position: 'absolute', top: '-9999px' }, hs.container);
this.loadHTML();
},
loadHTML : function() {
var s = this.cachedGet || this.xhr.responseText,
regBody;
if (this.pre) hs.cachedGets[this.src] = s;
if (!hs.ie || hs.uaVersion >= 5.5) {
s = s.replace(new RegExp('<link[^>]*>', 'gi'), '')
.replace(new RegExp('<script[^>]*>.*?</script>', 'gi'), '');
if (this.iframe) {
var doc = this.iframe.contentDocument;
if (!doc && this.iframe.contentWindow) doc = this.iframe.contentWindow.document;
if (!doc) { // Opera
var pThis = this;
setTimeout(function() { pThis.loadHTML(); }, 25);
return;
}
doc.open();
doc.write(s);
doc.close();
try { s = doc.getElementById(this.id).innerHTML; } catch (e) {
try { s = this.iframe.document.getElementById(this.id).innerHTML; } catch (e) {} // opera
}
hs.discardElement(this.iframe);
} else {
regBody = /(<body[^>]*>|<\/body>)/ig;
if (regBody.test(s)) s = s.split(regBody)[hs.ie ? 1 : 2];
}
}
hs.getElementByClass(this.content, 'DIV', 'highslide-body').innerHTML = s;
this.onLoad();
for (var x in this) this[x] = null;
}
};
hs.langDefaults = hs.lang;
// history
var HsExpander = hs.Expander;
if (hs.ie) {
(function () {
try {
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
hs.ready();
})();
}
hs.addEventListener(document, 'DOMContentLoaded', hs.ready);
hs.addEventListener(window, 'load', hs.ready);
// set handlers
hs.addEventListener(document, 'ready', function() {
if (hs.expandCursor) {
var style = hs.createElement('style', { type: 'text/css' }, null,
document.getElementsByTagName('HEAD')[0]);
function addRule(sel, dec) {
if (!hs.ie) {
style.appendChild(document.createTextNode(sel + " {" + dec + "}"));
} else {
var last = document.styleSheets[document.styleSheets.length - 1];
if (typeof(last.addRule) == "object") last.addRule(sel, dec);
}
}
function fix(prop) {
return 'expression( ( ( ignoreMe = document.documentElement.'+ prop +
' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );';
}
if (hs.expandCursor) addRule ('.highslide img',
'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;');
}
});
hs.addEventListener(window, 'resize', function() {
hs.getPageSize();
});
hs.addEventListener(document, 'mousemove', function(e) {
hs.mouse = { x: e.clientX, y: e.clientY };
});
hs.addEventListener(document, 'mousedown', hs.mouseClickHandler);
hs.addEventListener(document, 'mouseup', hs.mouseClickHandler);
hs.addEventListener(document, 'ready', hs.getAnchors);
hs.addEventListener(window, 'load', hs.preloadImages);
hs.addEventListener(window, 'load', hs.preloadAjax);
} | JavaScript |
/******************************************************************************
Name: Highslide JS
Version: 4.1.7 (September 28 2009)
Config: default +events +unobtrusive +imagemap +slideshow +positioning +transitions +viewport +thumbstrip +inline +ajax +iframe +flash
Author: Torstein Hønsi
Support: http://highslide.com/support
Licence:
Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5
License (http://creativecommons.org/licenses/by-nc/2.5/).
You are free:
* to copy, distribute, display, and perform the work
* to make derivative works
Under the following conditions:
* Attribution. You must attribute the work in the manner specified by the
author or licensor.
* Noncommercial. You may not use this work for commercial purposes.
* For any reuse or distribution, you must make clear to others the license
terms of this work.
* Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
******************************************************************************/
if (!hs) { var hs = {
// Language strings
lang : {
cssDirection: 'ltr',
loadingText : 'Loading...',
loadingTitle : 'Click to cancel',
focusTitle : 'Click to bring to front',
fullExpandTitle : 'Expand to actual size (f)',
creditsText : 'Powered by <i>Highslide JS</i>',
creditsTitle : 'Go to the Highslide JS homepage',
previousText : 'Previous',
nextText : 'Next',
moveText : 'Move',
closeText : 'Close',
closeTitle : 'Close (esc)',
resizeTitle : 'Resize',
playText : 'Play',
playTitle : 'Play slideshow (spacebar)',
pauseText : 'Pause',
pauseTitle : 'Pause slideshow (spacebar)',
previousTitle : 'Previous (arrow left)',
nextTitle : 'Next (arrow right)',
moveTitle : 'Move',
fullExpandText : '1:1',
number: 'Image %1 of %2',
restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.'
},
// See http://highslide.com/ref for examples of settings
graphicsDir : 'highslide/graphics/',
expandCursor : 'zoomin.cur', // null disables
restoreCursor : 'zoomout.cur', // null disables
expandDuration : 250, // milliseconds
restoreDuration : 250,
marginLeft : 15,
marginRight : 15,
marginTop : 15,
marginBottom : 15,
zIndexCounter : 1001, // adjust to other absolutely positioned elements
loadingOpacity : 0.75,
allowMultipleInstances: true,
numberOfImagesToPreload : 5,
outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only
outlineStartOffset : 3, // ends at 10
padToMinWidth : false, // pad the popup width to make room for wide caption
fullExpandPosition : 'bottom right',
fullExpandOpacity : 1,
showCredits : true, // you can set this to false if you want
creditsHref : 'http://highslide.com/',
creditsTarget : '_self',
enableKeyListener : true,
openerTagNames : ['a', 'area'], // Add more to allow slideshow indexing
transitions : [],
transitionDuration: 250,
dimmingOpacity: 0, // Lightbox style dimming background
dimmingDuration: 50, // 0 for instant dimming
allowWidthReduction : false,
allowHeightReduction : true,
preserveContent : true, // Preserve changes made to the content and position of HTML popups.
objectLoadTime : 'before', // Load iframes 'before' or 'after' expansion.
cacheAjax : true, // Cache ajax popups for instant display. Can be overridden for each popup.
anchor : 'auto', // where the image expands from
align : 'auto', // position in the client (overrides anchor)
targetX: null, // the id of a target element
targetY: null,
dragByHeading: true,
minWidth: 200,
minHeight: 200,
allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight
outlineType : 'drop-shadow', // set null to disable outlines
skin : {
controls:
'<div class="highslide-controls"><ul>'+
'<li class="highslide-previous">'+
'<a href="#" title="{hs.lang.previousTitle}">'+
'<span>{hs.lang.previousText}</span></a>'+
'</li>'+
'<li class="highslide-play">'+
'<a href="#" title="{hs.lang.playTitle}">'+
'<span>{hs.lang.playText}</span></a>'+
'</li>'+
'<li class="highslide-pause">'+
'<a href="#" title="{hs.lang.pauseTitle}">'+
'<span>{hs.lang.pauseText}</span></a>'+
'</li>'+
'<li class="highslide-next">'+
'<a href="#" title="{hs.lang.nextTitle}">'+
'<span>{hs.lang.nextText}</span></a>'+
'</li>'+
'<li class="highslide-move">'+
'<a href="#" title="{hs.lang.moveTitle}">'+
'<span>{hs.lang.moveText}</span></a>'+
'</li>'+
'<li class="highslide-full-expand">'+
'<a href="#" title="{hs.lang.fullExpandTitle}">'+
'<span>{hs.lang.fullExpandText}</span></a>'+
'</li>'+
'<li class="highslide-close">'+
'<a href="#" title="{hs.lang.closeTitle}" >'+
'<span>{hs.lang.closeText}</span></a>'+
'</li>'+
'</ul></div>'
,
contentWrapper:
'<div class="highslide-header"><ul>'+
'<li class="highslide-previous">'+
'<a href="#" title="{hs.lang.previousTitle}" onclick="return hs.previous(this)">'+
'<span>{hs.lang.previousText}</span></a>'+
'</li>'+
'<li class="highslide-next">'+
'<a href="#" title="{hs.lang.nextTitle}" onclick="return hs.next(this)">'+
'<span>{hs.lang.nextText}</span></a>'+
'</li>'+
'<li class="highslide-move">'+
'<a href="#" title="{hs.lang.moveTitle}" onclick="return false">'+
'<span>{hs.lang.moveText}</span></a>'+
'</li>'+
'<li class="highslide-close">'+
'<a href="#" title="{hs.lang.closeTitle}" onclick="return hs.close(this)">'+
'<span>{hs.lang.closeText}</span></a>'+
'</li>'+
'</ul></div>'+
'<div class="highslide-body"></div>'+
'<div class="highslide-footer"><div>'+
'<span class="highslide-resize" title="{hs.lang.resizeTitle}"><span></span></span>'+
'</div></div>'
},
// END OF YOUR SETTINGS
// declare internal properties
preloadTheseImages : [],
continuePreloading: true,
expanders : [],
overrides : [
'allowSizeReduction',
'useBox',
'anchor',
'align',
'targetX',
'targetY',
'outlineType',
'outlineWhileAnimating',
'captionId',
'captionText',
'captionEval',
'captionOverlay',
'headingId',
'headingText',
'headingEval',
'headingOverlay',
'creditsPosition',
'dragByHeading',
'autoplay',
'numberPosition',
'transitions',
'dimmingOpacity',
'width',
'height',
'contentId',
'allowWidthReduction',
'allowHeightReduction',
'preserveContent',
'maincontentId',
'maincontentText',
'maincontentEval',
'objectType',
'cacheAjax',
'objectWidth',
'objectHeight',
'objectLoadTime',
'swfOptions',
'wrapperClassName',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'slideshowGroup',
'easing',
'easingClose',
'fadeInOut',
'src'
],
overlays : [],
idCounter : 0,
oPos : {
x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'],
y: ['above', 'top', 'middle', 'bottom', 'below']
},
mouse: {},
headingOverlay: {},
captionOverlay: {},
swfOptions: { flashvars: {}, params: {}, attributes: {} },
timers : [],
slideshows : [],
pendingOutlines : {},
sleeping : [],
preloadTheseAjax : [],
cacheBindings : [],
cachedGets : {},
clones : {},
onReady: [],
uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 :
parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]),
ie : (document.all && !window.opera),
safari : /Safari/.test(navigator.userAgent),
geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent),
$ : function (id) {
if (id) return document.getElementById(id);
},
push : function (arr, val) {
arr[arr.length] = val;
},
createElement : function (tag, attribs, styles, parent, nopad) {
var el = document.createElement(tag);
if (attribs) hs.extend(el, attribs);
if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0});
if (styles) hs.setStyles(el, styles);
if (parent) parent.appendChild(el);
return el;
},
extend : function (el, attribs) {
for (var x in attribs) el[x] = attribs[x];
return el;
},
setStyles : function (el, styles) {
for (var x in styles) {
if (hs.ie && x == 'opacity') {
if (styles[x] > 0.99) el.style.removeAttribute('filter');
else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')';
}
else el.style[x] = styles[x];
}
},
animate: function(el, prop, opt) {
var start,
end,
unit;
if (typeof opt != 'object' || opt === null) {
var args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (typeof opt.duration != 'number') opt.duration = 250;
opt.easing = Math[opt.easing] || Math.easeInQuad;
opt.curAnim = hs.extend({}, prop);
for (var name in prop) {
var e = new hs.fx(el, opt , name );
start = parseFloat(hs.css(el, name)) || 0;
end = parseFloat(prop[name]);
unit = name != 'opacity' ? 'px' : '';
e.custom( start, end, unit );
}
},
css: function(el, prop) {
if (document.defaultView) {
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
} else {
if (prop == 'opacity') prop = 'filter';
var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })];
if (prop == 'filter')
val = val.replace(/alpha\(opacity=([0-9]+)\)/,
function (a, b) { return b / 100 });
return val === '' ? 1 : val;
}
},
getPageSize : function () {
var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat'
? d.documentElement : d.body;
var width = hs.ie ? iebody.clientWidth :
(d.documentElement.clientWidth || self.innerWidth),
height = hs.ie ? iebody.clientHeight : self.innerHeight;
hs.page = {
width: width,
height: height,
scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset,
scrollTop: hs.ie ? iebody.scrollTop : pageYOffset
}
},
getPosition : function(el) {
if (/area/i.test(el.tagName)) {
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var u = imgs[i].useMap;
if (u && u.replace(/^.*?#/, '') == el.parentNode.name) {
el = imgs[i];
break;
}
}
}
var p = { x: el.offsetLeft, y: el.offsetTop };
while (el.offsetParent) {
el = el.offsetParent;
p.x += el.offsetLeft;
p.y += el.offsetTop;
if (el != document.body && el != document.documentElement) {
p.x -= el.scrollLeft;
p.y -= el.scrollTop;
}
}
return p;
},
expand : function(a, params, custom, type) {
if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container);
if (typeof a.getParams == 'function') return params;
if (type == 'html') {
for (var i = 0; i < hs.sleeping.length; i++) {
if (hs.sleeping[i] && hs.sleeping[i].a == a) {
hs.sleeping[i].awake();
hs.sleeping[i] = null;
return false;
}
}
hs.hasHtmlExpanders = true;
}
try {
new hs.Expander(a, params, custom, type);
return false;
} catch (e) { return true; }
},
htmlExpand : function(a, params, custom) {
return hs.expand(a, params, custom, 'html');
},
getSelfRendered : function() {
return hs.createElement('div', {
className: 'highslide-html-content',
innerHTML: hs.replaceLang(hs.skin.contentWrapper)
});
},
getElementByClass : function (el, tagName, className) {
var els = el.getElementsByTagName(tagName);
for (var i = 0; i < els.length; i++) {
if ((new RegExp(className)).test(els[i].className)) {
return els[i];
}
}
return null;
},
replaceLang : function(s) {
s = s.replace(/\s/g, ' ');
var re = /{hs\.lang\.([^}]+)\}/g,
matches = s.match(re),
lang;
if (matches) for (var i = 0; i < matches.length; i++) {
lang = matches[i].replace(re, "$1");
if (typeof hs.lang[lang] != 'undefined') s = s.replace(matches[i], hs.lang[lang]);
}
return s;
},
setClickEvents : function () {
var els = document.getElementsByTagName('a');
for (var i = 0; i < els.length; i++) {
var type = hs.isUnobtrusiveAnchor(els[i]);
if (type && !els[i].hsHasSetClick) {
(function(){
var t = type;
if (hs.fireEvent(hs, 'onSetClickEvent', { element: els[i], type: t })) {
els[i].onclick =(type == 'image') ?function() { return hs.expand(this) }:
function() { return hs.htmlExpand(this, { objectType: t } );};
}
})();
els[i].hsHasSetClick = true;
}
}
hs.getAnchors();
},
isUnobtrusiveAnchor: function(el) {
if (el.rel == 'highslide') return 'image';
else if (el.rel == 'highslide-ajax') return 'ajax';
else if (el.rel == 'highslide-iframe') return 'iframe';
else if (el.rel == 'highslide-swf') return 'swf';
},
getCacheBinding : function (a) {
for (var i = 0; i < hs.cacheBindings.length; i++) {
if (hs.cacheBindings[i][0] == a) {
var c = hs.cacheBindings[i][1];
hs.cacheBindings[i][1] = c.cloneNode(1);
return c;
}
}
return null;
},
preloadAjax : function (e) {
var arr = hs.getAnchors();
for (var i = 0; i < arr.htmls.length; i++) {
var a = arr.htmls[i];
if (hs.getParam(a, 'objectType') == 'ajax' && hs.getParam(a, 'cacheAjax'))
hs.push(hs.preloadTheseAjax, a);
}
hs.preloadAjaxElement(0);
},
preloadAjaxElement : function (i) {
if (!hs.preloadTheseAjax[i]) return;
var a = hs.preloadTheseAjax[i];
var cache = hs.getNode(hs.getParam(a, 'contentId'));
if (!cache) cache = hs.getSelfRendered();
var ajax = new hs.Ajax(a, cache, 1);
ajax.onError = function () { };
ajax.onLoad = function () {
hs.push(hs.cacheBindings, [a, cache]);
hs.preloadAjaxElement(i + 1);
};
ajax.run();
},
focusTopmost : function() {
var topZ = 0,
topmostKey = -1,
expanders = hs.expanders,
exp,
zIndex;
for (var i = 0; i < expanders.length; i++) {
exp = expanders[i];
if (exp) {
zIndex = exp.wrapper.style.zIndex;
if (zIndex && zIndex > topZ) {
topZ = zIndex;
topmostKey = i;
}
}
}
if (topmostKey == -1) hs.focusKey = -1;
else expanders[topmostKey].focus();
},
getParam : function (a, param) {
a.getParams = a.onclick;
var p = a.getParams ? a.getParams() : null;
a.getParams = null;
return (p && typeof p[param] != 'undefined') ? p[param] :
(typeof hs[param] != 'undefined' ? hs[param] : null);
},
getSrc : function (a) {
var src = hs.getParam(a, 'src');
if (src) return src;
return a.href;
},
getNode : function (id) {
var node = hs.$(id), clone = hs.clones[id], a = {};
if (!node && !clone) return null;
if (!clone) {
clone = node.cloneNode(true);
clone.id = '';
hs.clones[id] = clone;
return node;
} else {
return clone.cloneNode(true);
}
},
discardElement : function(d) {
if (d) hs.garbageBin.appendChild(d);
hs.garbageBin.innerHTML = '';
},
dim : function(exp) {
function fix(prop) {
return 'expression( ( ( ignoreMe = document.documentElement.'+ prop +
' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );';
}
if (!hs.dimmer) {
hs.dimmer = hs.createElement ('div', {
className: 'highslide-dimming highslide-viewport-size',
owner: '',
onclick: function() {
if (hs.fireEvent(hs, 'onDimmerClick'))
hs.close();
}
}, {
visibility: 'visible',
opacity: 0
}, hs.container, true);
}
hs.dimmer.style.display = '';
hs.dimmer.owner += '|'+ exp.key;
if (hs.geckoMac && hs.dimmingGeckoFix)
hs.setStyles(hs.dimmer, {
background: 'url('+ hs.graphicsDir + 'geckodimmer.png)',
opacity: 1
});
else
hs.animate(hs.dimmer, { opacity: exp.dimmingOpacity }, hs.dimmingDuration);
},
undim : function(key) {
if (!hs.dimmer) return;
if (typeof key != 'undefined') hs.dimmer.owner = hs.dimmer.owner.replace('|'+ key, '');
if (
(typeof key != 'undefined' && hs.dimmer.owner != '')
|| (hs.upcoming && hs.getParam(hs.upcoming, 'dimmingOpacity'))
) return;
if (hs.geckoMac && hs.dimmingGeckoFix) hs.dimmer.style.display = 'none';
else hs.animate(hs.dimmer, { opacity: 0 }, hs.dimmingDuration, null, function() {
hs.dimmer.style.display = 'none';
});
},
transit : function (adj, exp) {
var last = exp = exp || hs.getExpander();
if (hs.upcoming) return false;
else hs.last = last;
try {
hs.upcoming = adj;
adj.onclick();
} catch (e){
hs.last = hs.upcoming = null;
}
try {
if (!adj || exp.transitions[1] != 'crossfade')
exp.close();
} catch (e) {}
return false;
},
previousOrNext : function (el, op) {
var exp = hs.getExpander(el);
if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp);
else return false;
},
previous : function (el) {
return hs.previousOrNext(el, -1);
},
next : function (el) {
return hs.previousOrNext(el, 1);
},
keyHandler : function(e) {
if (!e) e = window.event;
if (!e.target) e.target = e.srcElement; // ie
if (typeof e.target.form != 'undefined') return true; // form element has focus
if (!hs.fireEvent(hs, 'onKeyDown', e)) return true;
var exp = hs.getExpander();
var op = null;
switch (e.keyCode) {
case 70: // f
if (exp) exp.doFullExpand();
return true;
case 32: // Space
op = 2;
break;
case 34: // Page Down
case 39: // Arrow right
case 40: // Arrow down
op = 1;
break;
case 8: // Backspace
case 33: // Page Up
case 37: // Arrow left
case 38: // Arrow up
op = -1;
break;
case 27: // Escape
case 13: // Enter
op = 0;
}
if (op !== null) {if (op != 2)hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
if (!hs.enableKeyListener) return true;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (exp) {
if (op == 0) {
exp.close();
} else if (op == 2) {
if (exp.slideshow) exp.slideshow.hitSpace();
} else {
if (exp.slideshow) exp.slideshow.pause();
hs.previousOrNext(exp.key, op);
}
return false;
}
}
return true;
},
registerOverlay : function (overlay) {
hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } ));
},
addSlideshow : function (options) {
var sg = options.slideshowGroup;
if (typeof sg == 'object') {
for (var i = 0; i < sg.length; i++) {
var o = {};
for (var x in options) o[x] = options[x];
o.slideshowGroup = sg[i];
hs.push(hs.slideshows, o);
}
} else {
hs.push(hs.slideshows, options);
}
},
getWrapperKey : function (element, expOnly) {
var el, re = /^highslide-wrapper-([0-9]+)$/;
// 1. look in open expanders
el = element;
while (el.parentNode) {
if (el.hsKey !== undefined) return el.hsKey;
if (el.id && re.test(el.id)) return el.id.replace(re, "$1");
el = el.parentNode;
}
// 2. look in thumbnail
if (!expOnly) {
el = element;
while (el.parentNode) {
if (el.tagName && hs.isHsAnchor(el)) {
for (var key = 0; key < hs.expanders.length; key++) {
var exp = hs.expanders[key];
if (exp && exp.a == el) return key;
}
}
el = el.parentNode;
}
}
return null;
},
getExpander : function (el, expOnly) {
if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null;
if (typeof el == 'number') return hs.expanders[el] || null;
if (typeof el == 'string') el = hs.$(el);
return hs.expanders[hs.getWrapperKey(el, expOnly)] || null;
},
isHsAnchor : function (a) {
return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/));
},
reOrder : function () {
for (var i = 0; i < hs.expanders.length; i++)
if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost();
},
fireEvent : function (obj, evt, args) {
return obj && obj[evt] ? (obj[evt](obj, args) !== false) : true;
},
mouseClickHandler : function(e)
{
if (!e) e = window.event;
if (e.button > 1) return true;
if (!e.target) e.target = e.srcElement;
var el = e.target;
while (el.parentNode
&& !(/highslide-(image|move|html|resize)/.test(el.className)))
{
el = el.parentNode;
}
var exp = hs.getExpander(el);
if (exp && (exp.isClosing || !exp.isExpanded)) return true;
if (exp && e.type == 'mousedown') {
if (e.target.form) return true;
var match = el.className.match(/highslide-(image|move|resize)/);
if (match) {
hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos,
height: exp.y.size, clickX: e.clientX, clickY: e.clientY };
hs.addEventListener(document, 'mousemove', hs.dragHandler);
if (e.preventDefault) e.preventDefault(); // FF
if (/highslide-(image|html)-blur/.test(exp.content.className)) {
exp.focus();
hs.hasFocused = true;
}
return false;
}
else if (/highslide-html/.test(el.className) && hs.focusKey != exp.key) {
exp.focus();
exp.doShowHide('hidden');
}
} else if (e.type == 'mouseup') {
hs.removeEventListener(document, 'mousemove', hs.dragHandler);
if (hs.dragArgs) {
if (hs.styleRestoreCursor && hs.dragArgs.type == 'image')
hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor;
var hasDragged = hs.dragArgs.hasDragged;
if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) {
if (hs.fireEvent(exp, 'onImageClick'))
exp.close();
}
else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) {
hs.dragArgs.exp.doShowHide('hidden');
}
if (hs.dragArgs.exp.releaseMask)
hs.dragArgs.exp.releaseMask.style.display = 'none';
if (hasDragged) hs.fireEvent(hs.dragArgs.exp, 'onDrop', hs.dragArgs);
hs.hasFocused = false;
hs.dragArgs = null;
} else if (/highslide-image-blur/.test(el.className)) {
el.style.cursor = hs.styleRestoreCursor;
}
}
return false;
},
dragHandler : function(e)
{
if (!hs.dragArgs) return true;
if (!e) e = window.event;
var a = hs.dragArgs, exp = a.exp;
if (exp.iframe) {
if (!exp.releaseMask) exp.releaseMask = hs.createElement('div', null,
{ position: 'absolute', width: exp.x.size+'px', height: exp.y.size+'px',
left: exp.x.cb+'px', top: exp.y.cb+'px', zIndex: 4, background: (hs.ie ? 'white' : 'none'),
opacity: .01 },
exp.wrapper, true);
if (exp.releaseMask.style.display == 'none')
exp.releaseMask.style.display = '';
}
a.dX = e.clientX - a.clickX;
a.dY = e.clientY - a.clickY;
var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2));
if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0)
|| (distance > (hs.dragSensitivity || 5));
if (a.hasDragged && e.clientX > 5 && e.clientY > 5) {
if (!hs.fireEvent(exp, 'onDrag', a)) return false;
if (a.type == 'resize') exp.resize(a);
else {
exp.moveTo(a.left + a.dX, a.top + a.dY);
if (a.type == 'image') exp.content.style.cursor = 'move';
}
}
return false;
},
wrapperMouseHandler : function (e) {
try {
if (!e) e = window.event;
var over = /mouseover/i.test(e.type);
if (!e.target) e.target = e.srcElement; // ie
if (hs.ie) e.relatedTarget =
over ? e.fromElement : e.toElement; // ie
var exp = hs.getExpander(e.target);
if (!exp.isExpanded) return;
if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp
|| hs.dragArgs) return;
hs.fireEvent(exp, over ? 'onMouseOver' : 'onMouseOut', e);
for (var i = 0; i < exp.overlays.length; i++) (function() {
var o = hs.$('hsId'+ exp.overlays[i]);
if (o && o.hideOnMouseOut) {
if (over) hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur);
}
})();
} catch (e) {}
},
addEventListener : function (el, event, func) {
if (el == document && event == 'ready') hs.push(hs.onReady, func);
try {
el.addEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
el.attachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = func;
}
}
},
removeEventListener : function (el, event, func) {
try {
el.removeEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = null;
}
}
},
preloadFullImage : function (i) {
if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') {
var img = document.createElement('img');
img.onload = function() {
img = null;
hs.preloadFullImage(i + 1);
};
img.src = hs.preloadTheseImages[i];
}
},
preloadImages : function (number) {
if (number && typeof number != 'object') hs.numberOfImagesToPreload = number;
var arr = hs.getAnchors();
for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) {
hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i]));
}
// preload outlines
if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} );
else
hs.preloadFullImage(0);
// preload cursor
if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor });
},
init : function () {
if (!hs.container) {
hs.getPageSize();
hs.ieLt7 = hs.ie && hs.uaVersion < 7;
hs.ie6SSL = hs.ieLt7 && location.protocol == 'https:';
for (var x in hs.langDefaults) {
if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x];
else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined')
hs.lang[x] = hs.langDefaults[x];
}
hs.container = hs.createElement('div', {
className: 'highslide-container'
}, {
position: 'absolute',
left: 0,
top: 0,
width: '100%',
zIndex: hs.zIndexCounter,
direction: 'ltr'
},
document.body,
true
);
hs.loading = hs.createElement('a', {
className: 'highslide-loading',
title: hs.lang.loadingTitle,
innerHTML: hs.lang.loadingText,
href: 'javascript:;'
}, {
position: 'absolute',
top: '-9999px',
opacity: hs.loadingOpacity,
zIndex: 1
}, hs.container
);
hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container);
hs.viewport = hs.createElement('div', {
className: 'highslide-viewport highslide-viewport-size'
}, {
visibility: (hs.safari && hs.uaVersion < 525) ? 'visible' : 'hidden'
}, hs.container, 1
);
hs.clearing = hs.createElement('div', null,
{ clear: 'both', paddingTop: '1px' }, null, true);
// http://www.robertpenner.com/easing/
Math.linearTween = function (t, b, c, d) {
return c*t/d + b;
};
Math.easeInQuad = function (t, b, c, d) {
return c*(t/=d)*t + b;
};
Math.easeOutQuad = function (t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
};
hs.hideSelects = hs.ieLt7;
hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE'
|| (hs.ie && hs.uaVersion < 5.5));
hs.fireEvent(this, 'onActivate');
}
},
ready : function() {
if (hs.isReady) return;
hs.isReady = true;
for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i]();
},
updateAnchors : function() {
var el, els, all = [], images = [], htmls = [],groups = {}, re;
for (var i = 0; i < hs.openerTagNames.length; i++) {
els = document.getElementsByTagName(hs.openerTagNames[i]);
for (var j = 0; j < els.length; j++) {
el = els[j];
re = hs.isHsAnchor(el);
if (re) {
hs.push(all, el);
if (re[0] == 'hs.expand') hs.push(images, el);
else if (re[0] == 'hs.htmlExpand') hs.push(htmls, el);
var g = hs.getParam(el, 'slideshowGroup') || 'none';
if (!groups[g]) groups[g] = [];
hs.push(groups[g], el);
}
}
}
hs.anchors = { all: all, groups: groups, images: images, htmls: htmls };
return hs.anchors;
},
getAnchors : function() {
return hs.anchors || hs.updateAnchors();
},
close : function(el) {
var exp = hs.getExpander(el);
if (exp) exp.close();
return false;
}
}; // end hs object
hs.fx = function( elem, options, prop ){
this.options = options;
this.elem = elem;
this.prop = prop;
if (!options.orig) options.orig = {};
};
hs.fx.prototype = {
update: function(){
(hs.fx.step[this.prop] || hs.fx.step._default)(this);
if (this.options.step)
this.options.step.call(this.elem, this.now, this);
},
custom: function(from, to, unit){
this.startTime = (new Date()).getTime();
this.start = from;
this.end = to;
this.unit = unit;// || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t(gotoEnd){
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && hs.timers.push(t) == 1 ) {
hs.timerId = setInterval(function(){
var timers = hs.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval(hs.timerId);
}
}, 13);
}
},
step: function(gotoEnd){
var t = (new Date()).getTime();
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
var done = true;
for ( var i in this.options.curAnim )
if ( this.options.curAnim[i] !== true )
done = false;
if ( done ) {
if (this.options.complete) this.options.complete.call(this.elem);
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
this.pos = this.options.easing(n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
}
return true;
}
};
hs.extend( hs.fx, {
step: {
opacity: function(fx){
hs.setStyles(fx.elem, { opacity: fx.now });
},
_default: function(fx){
try {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
else
fx.elem[ fx.prop ] = fx.now;
} catch (e) {}
}
}
});
hs.Outline = function (outlineType, onLoad) {
this.onLoad = onLoad;
this.outlineType = outlineType;
var v = hs.uaVersion, tr;
this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7;
if (!outlineType) {
if (onLoad) onLoad();
return;
}
hs.init();
this.table = hs.createElement(
'table', {
cellSpacing: 0
}, {
visibility: 'hidden',
position: 'absolute',
borderCollapse: 'collapse',
width: 0
},
hs.container,
true
);
var tbody = hs.createElement('tbody', null, null, this.table, 1);
this.td = [];
for (var i = 0; i <= 8; i++) {
if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true);
this.td[i] = hs.createElement('td', null, null, tr, true);
var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' };
hs.setStyles(this.td[i], style);
}
this.td[4].className = outlineType +' highslide-outline';
this.preloadGraphic();
};
hs.Outline.prototype = {
preloadGraphic : function () {
var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png";
var appendTo = hs.safari ? hs.container : null;
this.graphic = hs.createElement('img', null, { position: 'absolute',
top: '-9999px' }, appendTo, true); // for onload trigger
var pThis = this;
this.graphic.onload = function() { pThis.onGraphicLoad(); };
this.graphic.src = src;
},
onGraphicLoad : function () {
var o = this.offset = this.graphic.width / 4,
pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]],
dim = { height: (2*o) +'px', width: (2*o) +'px' };
for (var i = 0; i <= 8; i++) {
if (pos[i]) {
if (this.hasAlphaImageLoader) {
var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px';
var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true);
hs.createElement ('div', null, {
filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')",
position: 'absolute',
width: w,
height: this.graphic.height +'px',
left: (pos[i][0]*o)+'px',
top: (pos[i][1]*o)+'px'
},
div,
true);
} else {
hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'});
}
if (window.opera && (i == 3 || i ==5))
hs.createElement('div', null, dim, this.td[i], true);
hs.setStyles (this.td[i], dim);
}
}
this.graphic = null;
if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy();
hs.pendingOutlines[this.outlineType] = this;
if (this.onLoad) this.onLoad();
},
setPosition : function (pos, offset, vis, dur, easing) {
var exp = this.exp,
stl = exp.wrapper.style,
offset = offset || 0,
pos = pos || {
x: exp.x.pos + offset,
y: exp.y.pos + offset,
w: exp.x.get('wsize') - 2 * offset,
h: exp.y.get('wsize') - 2 * offset
};
if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset)
? 'visible' : 'hidden';
hs.setStyles(this.table, {
left: (pos.x - this.offset) +'px',
top: (pos.y - this.offset) +'px',
width: (pos.w + 2 * this.offset) +'px'
});
pos.w -= 2 * this.offset;
pos.h -= 2 * this.offset;
hs.setStyles (this.td[4], {
width: pos.w >= 0 ? pos.w +'px' : 0,
height: pos.h >= 0 ? pos.h +'px' : 0
});
if (this.hasAlphaImageLoader) this.td[3].style.height
= this.td[5].style.height = this.td[4].style.height;
},
destroy : function(hide) {
if (hide) this.table.style.visibility = 'hidden';
else hs.discardElement(this.table);
}
};
hs.Dimension = function(exp, dim) {
this.exp = exp;
this.dim = dim;
this.ucwh = dim == 'x' ? 'Width' : 'Height';
this.wh = this.ucwh.toLowerCase();
this.uclt = dim == 'x' ? 'Left' : 'Top';
this.lt = this.uclt.toLowerCase();
this.ucrb = dim == 'x' ? 'Right' : 'Bottom';
this.rb = this.ucrb.toLowerCase();
this.p1 = this.p2 = 0;
};
hs.Dimension.prototype = {
get : function(key) {
switch (key) {
case 'loadingPos':
return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2;
case 'loadingPosXfade':
return this.pos + this.cb+ this.p1 + (this.size - hs.loading['offset'+ this.ucwh]) / 2;
case 'wsize':
return this.size + 2 * this.cb + this.p1 + this.p2;
case 'fitsize':
return this.clientSize - this.marginMin - this.marginMax;
case 'maxsize':
return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ;
case 'opos':
return this.pos - (this.exp.outline ? this.exp.outline.offset : 0);
case 'osize':
return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0);
case 'imgPad':
return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0;
}
},
calcBorders: function() {
// correct for borders
this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2;
this.marginMax = hs['margin'+ this.ucrb];
},
calcThumb: function() {
this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) :
this.exp.el['offset'+ this.ucwh];
this.tpos = this.exp.tpos[this.dim];
this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2;
if (this.tpos == 0 || this.tpos == -1) {
this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt];
};
},
calcExpanded: function() {
var exp = this.exp;
this.justify = 'auto';
// get alignment
if (exp.align == 'center') this.justify = 'center';
else if (new RegExp(this.lt).test(exp.anchor)) this.justify = null;
else if (new RegExp(this.rb).test(exp.anchor)) this.justify = 'max';
// size and position
this.pos = this.tpos - this.cb + this.tb;
if (this.dim == 'x')
exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full);
this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full);
this.minSize = exp.allowSizeReduction ?
Math.min(exp['min'+ this.ucwh], this.full) :this.full;
if (exp.isImage && exp.useBox) {
this.size = exp[this.wh];
this.imgSize = this.full;
}
if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth;
this.target = exp['target'+ this.dim.toUpperCase()];
this.marginMin = hs['margin'+ this.uclt];
this.scroll = hs.page['scroll'+ this.uclt];
this.clientSize = hs.page[this.wh];
},
setSize: function(i) {
var exp = this.exp;
if (exp.isImage && (exp.useBox || hs.padToMinWidth)) {
this.imgSize = i;
this.size = Math.max(this.size, this.imgSize);
exp.content.style[this.lt] = this.get('imgPad')+'px';
} else
this.size = i;
exp.content.style[this.wh] = i +'px';
exp.wrapper.style[this.wh] = this.get('wsize') +'px';
if (exp.outline) exp.outline.setPosition();
if (exp.releaseMask) exp.releaseMask.style[this.wh] = i +'px';
if (this.dim == 'y' && exp.iDoc && exp.body.style.height != 'auto')
exp.iDoc.body.style.overflow = 'auto';
if (exp.isHtml) {
var d = exp.scrollerDiv;
if (this.sizeDiff === undefined)
this.sizeDiff = exp.innerContent['offset'+ this.ucwh] - d['offset'+ this.ucwh];
d.style[this.wh] = (this.size - this.sizeDiff) +'px';
if (this.dim == 'x') exp.mediumContent.style.width = 'auto';
if (exp.body) exp.body.style[this.wh] = 'auto';
}
if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true);
if (this.dim == 'x' && exp.slideshow && exp.isImage) {
if (i == this.full) exp.slideshow.disable('full-expand');
else exp.slideshow.enable('full-expand');
}
},
setPos: function(i) {
this.pos = i;
this.exp.wrapper.style[this.lt] = i +'px';
if (this.exp.outline) this.exp.outline.setPosition();
}
};
hs.Expander = function(a, params, custom, contentType) {
if (document.readyState && hs.ie && !hs.isReady) {
hs.addEventListener(document, 'ready', function() {
new hs.Expander(a, params, custom, contentType);
});
return;
}
this.a = a;
this.custom = custom;
this.contentType = contentType || 'image';
this.isHtml = (contentType == 'html');
this.isImage = !this.isHtml;
hs.continuePreloading = false;
this.overlays = [];
this.last = hs.last;
hs.last = null;
hs.init();
var key = this.key = hs.expanders.length;
// override inline parameters
for (var i = 0; i < hs.overrides.length; i++) {
var name = hs.overrides[i];
this[name] = params && typeof params[name] != 'undefined' ?
params[name] : hs[name];
}
if (!this.src) this.src = a.href;
// get thumb
var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a;
el = this.thumb = el.getElementsByTagName('img')[0] || el;
this.thumbsUserSetId = el.id || a.id;
if (!hs.fireEvent(this, 'onInit')) return true;
// check if already open
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].a == a
&& !(this.last && this.transitions[1] == 'crossfade')) {
hs.expanders[i].focus();
return false;
}
}
// cancel other
if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) {
hs.expanders[i].cancelLoading();
}
}
hs.expanders[key] = this;
if (!hs.allowMultipleInstances && !hs.upcoming) {
if (hs.expanders[key-1]) hs.expanders[key-1].close();
if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey])
hs.expanders[hs.focusKey].close();
}
// initiate metrics
this.el = el;
this.tpos = hs.getPosition(el);
hs.getPageSize();
var x = this.x = new hs.Dimension(this, 'x');
x.calcThumb();
var y = this.y = new hs.Dimension(this, 'y');
y.calcThumb();
if (/area/i.test(el.tagName)) this.getImageMapAreaCorrection(el);
this.wrapper = hs.createElement(
'div', {
id: 'highslide-wrapper-'+ this.key,
className: 'highslide-wrapper '+ this.wrapperClassName
}, {
visibility: 'hidden',
position: 'absolute',
zIndex: hs.zIndexCounter += 2
}, null, true );
this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler;
if (this.contentType == 'image' && this.outlineWhileAnimating == 2)
this.outlineWhileAnimating = 0;
// get the outline
if (!this.outlineType
|| (this.last && this.isImage && this.transitions[1] == 'crossfade')) {
this[this.contentType +'Create']();
} else if (hs.pendingOutlines[this.outlineType]) {
this.connectOutline();
this[this.contentType +'Create']();
} else {
this.showLoading();
var exp = this;
new hs.Outline(this.outlineType,
function () {
exp.connectOutline();
exp[exp.contentType +'Create']();
}
);
}
return true;
};
hs.Expander.prototype = {
error : function(e) {
// alert ('Line '+ e.lineNumber +': '+ e.message);
window.location.href = this.src;
},
connectOutline : function() {
var outline = this.outline = hs.pendingOutlines[this.outlineType];
outline.exp = this;
outline.table.style.zIndex = this.wrapper.style.zIndex - 1;
hs.pendingOutlines[this.outlineType] = null;
},
showLoading : function() {
if (this.onLoadStarted || this.loading) return;
this.loading = hs.loading;
var exp = this;
this.loading.onclick = function() {
exp.cancelLoading();
};
if (!hs.fireEvent(this, 'onShowLoading')) return;
var exp = this,
l = this.x.get('loadingPos') +'px',
t = this.y.get('loadingPos') +'px';
if (!tgt && this.last && this.transitions[1] == 'crossfade')
var tgt = this.last;
if (tgt) {
l = tgt.x.get('loadingPosXfade') +'px';
t = tgt.y.get('loadingPosXfade') +'px';
this.loading.style.zIndex = hs.zIndexCounter++;
}
setTimeout(function () {
if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })}
, 100);
},
imageCreate : function() {
var exp = this;
var img = document.createElement('img');
this.content = img;
img.onload = function () {
if (hs.expanders[exp.key]) exp.contentLoaded();
};
if (hs.blockRightClick) img.oncontextmenu = function() { return false; };
img.className = 'highslide-image';
hs.setStyles(img, {
visibility: 'hidden',
display: 'block',
position: 'absolute',
maxWidth: '9999px',
zIndex: 3
});
img.title = hs.lang.restoreTitle;
if (hs.safari) hs.container.appendChild(img);
if (hs.ie && hs.flushImgSize) img.src = null;
img.src = this.src;
this.showLoading();
},
htmlCreate : function () {
if (!hs.fireEvent(this, 'onBeforeGetContent')) return;
this.content = hs.getCacheBinding(this.a);
if (!this.content)
this.content = hs.getNode(this.contentId);
if (!this.content)
this.content = hs.getSelfRendered();
this.getInline(['maincontent']);
if (this.maincontent) {
var body = hs.getElementByClass(this.content, 'div', 'highslide-body');
if (body) body.appendChild(this.maincontent);
this.maincontent.style.display = 'block';
}
hs.fireEvent(this, 'onAfterGetContent');
var innerContent = this.innerContent = this.content;
if (/(swf|iframe)/.test(this.objectType)) this.setObjContainerSize(innerContent);
// the content tree
hs.container.appendChild(this.wrapper);
hs.setStyles( this.wrapper, {
position: 'static',
padding: '0 '+ hs.marginRight +'px 0 '+ hs.marginLeft +'px'
});
this.content = hs.createElement(
'div', {
className: 'highslide-html'
}, {
position: 'relative',
zIndex: 3,
overflow: 'hidden'
},
this.wrapper
);
this.mediumContent = hs.createElement('div', null, null, this.content, 1);
this.mediumContent.appendChild(innerContent);
hs.setStyles (innerContent, {
position: 'relative',
display: 'block',
direction: hs.lang.cssDirection || ''
});
if (this.width) innerContent.style.width = this.width +'px';
if (this.height) hs.setStyles(innerContent, {
height: this.height +'px',
overflow: 'hidden'
});
if (innerContent.offsetWidth < this.minWidth)
innerContent.style.width = this.minWidth +'px';
if (this.objectType == 'ajax' && !hs.getCacheBinding(this.a)) {
this.showLoading();
var exp = this;
var ajax = new hs.Ajax(this.a, innerContent);
ajax.src = this.src;
ajax.onLoad = function () { if (hs.expanders[exp.key]) exp.contentLoaded(); };
ajax.onError = function () { location.href = exp.src; };
ajax.run();
}
else
if (this.objectType == 'iframe' && this.objectLoadTime == 'before') {
this.writeExtendedContent();
}
else
this.contentLoaded();
},
contentLoaded : function() {
try {
if (!this.content) return;
this.content.onload = null;
if (this.onLoadStarted) return;
else this.onLoadStarted = true;
var x = this.x, y = this.y;
if (this.loading) {
hs.setStyles(this.loading, { top: '-9999px' });
this.loading = null;
hs.fireEvent(this, 'onHideLoading');
}
if (this.isImage) {
x.full = this.content.width;
y.full = this.content.height;
hs.setStyles(this.content, {
width: x.t +'px',
height: y.t +'px'
});
this.wrapper.appendChild(this.content);
hs.container.appendChild(this.wrapper);
} else if (this.htmlGetSize) this.htmlGetSize();
x.calcBorders();
y.calcBorders();
hs.setStyles (this.wrapper, {
left: (x.tpos + x.tb - x.cb) +'px',
top: (y.tpos + x.tb - y.cb) +'px'
});
this.initSlideshow();
this.getOverlays();
var ratio = x.full / y.full;
x.calcExpanded();
this.justify(x);
y.calcExpanded();
this.justify(y);
if (this.isHtml) this.htmlSizeOperations();
if (this.overlayBox) this.sizeOverlayBox(0, 1);
if (this.allowSizeReduction) {
if (this.isImage)
this.correctRatio(ratio);
else this.fitOverlayBox();
var ss = this.slideshow;
if (ss && this.last && ss.controls && ss.fixedControls) {
var pos = ss.overlayOptions.position || '', p;
for (var dim in hs.oPos) for (var i = 0; i < 5; i++) {
p = this[dim];
if (pos.match(hs.oPos[dim][i])) {
p.pos = this.last[dim].pos
+ (this.last[dim].p1 - p.p1)
+ (this.last[dim].size - p.size) * [0, 0, .5, 1, 1][i];
if (ss.fixedControls == 'fit') {
if (p.pos + p.size + p.p1 + p.p2 > p.scroll + p.clientSize - p.marginMax)
p.pos = p.scroll + p.clientSize - p.size - p.marginMin - p.marginMax - p.p1 - p.p2;
if (p.pos < p.scroll + p.marginMin) p.pos = p.scroll + p.marginMin;
}
}
}
}
if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) {
this.createFullExpand();
if (this.overlays.length == 1) this.sizeOverlayBox();
}
}
this.show();
} catch (e) {
this.error(e);
}
},
setObjContainerSize : function(parent, auto) {
var c = hs.getElementByClass(parent, 'DIV', 'highslide-body');
if (/(iframe|swf)/.test(this.objectType)) {
if (this.objectWidth) c.style.width = this.objectWidth +'px';
if (this.objectHeight) c.style.height = this.objectHeight +'px';
}
},
writeExtendedContent : function () {
if (this.hasExtendedContent) return;
var exp = this;
this.body = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body');
if (this.objectType == 'iframe') {
this.showLoading();
var ruler = hs.clearing.cloneNode(1);
this.body.appendChild(ruler);
this.newWidth = this.innerContent.offsetWidth;
if (!this.objectWidth) this.objectWidth = ruler.offsetWidth;
var hDiff = this.innerContent.offsetHeight - this.body.offsetHeight,
h = this.objectHeight || hs.page.height - hDiff - hs.marginTop - hs.marginBottom,
onload = this.objectLoadTime == 'before' ?
' onload="if (hs.expanders['+ this.key +']) hs.expanders['+ this.key +'].contentLoaded()" ' : '';
this.body.innerHTML += '<iframe name="hs'+ (new Date()).getTime() +'" frameborder="0" key="'+ this.key +'" '
+' style="width:'+ this.objectWidth +'px; height:'+ h +'px" '
+ onload +' src="'+ this.src +'" ></iframe>';
this.ruler = this.body.getElementsByTagName('div')[0];
this.iframe = this.body.getElementsByTagName('iframe')[0];
if (this.objectLoadTime == 'after') this.correctIframeSize();
}
if (this.objectType == 'swf') {
this.body.id = this.body.id || 'hs-flash-id-' + this.key;
var a = this.swfOptions;
if (!a.params) a.params = {};
if (typeof a.params.wmode == 'undefined') a.params.wmode = 'transparent';
if (swfobject) swfobject.embedSWF(this.src, this.body.id, this.objectWidth, this.objectHeight,
a.version || '7', a.expressInstallSwfurl, a.flashvars, a.params, a.attributes);
}
this.hasExtendedContent = true;
},
htmlGetSize : function() {
if (this.iframe && !this.objectHeight) { // loadtime before
this.iframe.style.height = this.body.style.height = this.getIframePageHeight() +'px';
}
this.innerContent.appendChild(hs.clearing);
if (!this.x.full) this.x.full = this.innerContent.offsetWidth;
this.y.full = this.innerContent.offsetHeight;
this.innerContent.removeChild(hs.clearing);
if (hs.ie && this.newHeight > parseInt(this.innerContent.currentStyle.height)) { // ie css bug
this.newHeight = parseInt(this.innerContent.currentStyle.height);
}
hs.setStyles( this.wrapper, { position: 'absolute', padding: '0'});
hs.setStyles( this.content, { width: this.x.t +'px', height: this.y.t +'px'});
},
getIframePageHeight : function() {
var h;
try {
var doc = this.iDoc = this.iframe.contentDocument || this.iframe.contentWindow.document;
var clearing = doc.createElement('div');
clearing.style.clear = 'both';
doc.body.appendChild(clearing);
h = clearing.offsetTop;
if (hs.ie) h += parseInt(doc.body.currentStyle.marginTop)
+ parseInt(doc.body.currentStyle.marginBottom) - 1;
} catch (e) { // other domain
h = 300;
}
return h;
},
correctIframeSize : function () {
var wDiff = this.innerContent.offsetWidth - this.ruler.offsetWidth;
hs.discardElement(this.ruler);
if (wDiff < 0) wDiff = 0;
var hDiff = this.innerContent.offsetHeight - this.iframe.offsetHeight;
if (this.iDoc && !this.objectHeight && this.y.size == this.y.full)
this.iDoc.body.style.overflow = 'hidden';
hs.setStyles(this.iframe, {
width: Math.abs(this.x.size - wDiff) +'px',
height: Math.abs(this.y.size - hDiff) +'px'
});
hs.setStyles(this.body, {
width: this.iframe.style.width,
height: this.iframe.style.height
});
this.scrollingContent = this.iframe;
this.scrollerDiv = this.scrollingContent;
},
htmlSizeOperations : function () {
this.setObjContainerSize(this.innerContent);
if (this.objectType == 'swf' && this.objectLoadTime == 'before') this.writeExtendedContent();
// handle minimum size
if (this.x.size < this.x.full && !this.allowWidthReduction) this.x.size = this.x.full;
if (this.y.size < this.y.full && !this.allowHeightReduction) this.y.size = this.y.full;
this.scrollerDiv = this.innerContent;
hs.setStyles(this.mediumContent, {
position: 'relative',
width: this.x.size +'px'
});
hs.setStyles(this.innerContent, {
border: 'none',
width: 'auto',
height: 'auto'
});
var node = hs.getElementByClass(this.innerContent, 'DIV', 'highslide-body');
if (node && !/(iframe|swf)/.test(this.objectType)) {
var cNode = node; // wrap to get true size
node = hs.createElement(cNode.nodeName, null, {overflow: 'hidden'}, null, true);
cNode.parentNode.insertBefore(node, cNode);
node.appendChild(hs.clearing); // IE6
node.appendChild(cNode);
var wDiff = this.innerContent.offsetWidth - node.offsetWidth;
var hDiff = this.innerContent.offsetHeight - node.offsetHeight;
node.removeChild(hs.clearing);
var kdeBugCorr = hs.safari || navigator.vendor == 'KDE' ? 1 : 0; // KDE repainting bug
hs.setStyles(node, {
width: (this.x.size - wDiff - kdeBugCorr) +'px',
height: (this.y.size - hDiff) +'px',
overflow: 'auto',
position: 'relative'
}
);
if (kdeBugCorr && cNode.offsetHeight > node.offsetHeight) {
node.style.width = (parseInt(node.style.width) + kdeBugCorr) + 'px';
}
this.scrollingContent = node;
this.scrollerDiv = this.scrollingContent;
}
if (this.iframe && this.objectLoadTime == 'before') this.correctIframeSize();
if (!this.scrollingContent && this.y.size < this.mediumContent.offsetHeight) this.scrollerDiv = this.content;
if (this.scrollerDiv == this.content && !this.allowWidthReduction && !/(iframe|swf)/.test(this.objectType)) {
this.x.size += 17; // room for scrollbars
}
if (this.scrollerDiv && this.scrollerDiv.offsetHeight > this.scrollerDiv.parentNode.offsetHeight) {
setTimeout("try { hs.expanders["+ this.key +"].scrollerDiv.style.overflow = 'auto'; } catch(e) {}",
hs.expandDuration);
}
},
getImageMapAreaCorrection : function(area) {
var c = area.coords.split(',');
for (var i = 0; i < c.length; i++) c[i] = parseInt(c[i]);
if (area.shape.toLowerCase() == 'circle') {
this.x.tpos += c[0] - c[2];
this.y.tpos += c[1] - c[2];
this.x.t = this.y.t = 2 * c[2];
} else {
var maxX, maxY, minX = maxX = c[0], minY = maxY = c[1];
for (var i = 0; i < c.length; i++) {
if (i % 2 == 0) {
minX = Math.min(minX, c[i]);
maxX = Math.max(maxX, c[i]);
} else {
minY = Math.min(minY, c[i]);
maxY = Math.max(maxY, c[i]);
}
}
this.x.tpos += minX;
this.x.t = maxX - minX;
this.y.tpos += minY;
this.y.t = maxY - minY;
}
},
justify : function (p, moveOnly) {
var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y';
if (tgt && tgt.match(/ /)) {
tgtArr = tgt.split(' ');
tgt = tgtArr[0];
}
if (tgt && hs.$(tgt)) {
p.pos = hs.getPosition(hs.$(tgt))[dim];
if (tgtArr && tgtArr[1] && tgtArr[1].match(/^[-]?[0-9]+px$/))
p.pos += parseInt(tgtArr[1]);
if (p.size < p.minSize) p.size = p.minSize;
} else if (p.justify == 'auto' || p.justify == 'center') {
var hasMovedMin = false;
var allowReduce = p.exp.allowSizeReduction;
if (p.justify == 'center')
p.pos = Math.round(p.scroll + (p.clientSize + p.marginMin - p.marginMax - p.get('wsize')) / 2);
else
p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2));
if (p.pos < p.scroll + p.marginMin) {
p.pos = p.scroll + p.marginMin;
hasMovedMin = true;
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) {
if (!moveOnly && hasMovedMin && allowReduce) {
p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize'));
} else if (p.get('wsize') < p.get('fitsize')) {
p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize');
} else { // image larger than viewport
p.pos = p.scroll + p.marginMin;
if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize');
}
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
} else if (p.justify == 'max') {
p.pos = Math.floor(p.pos - p.size + p.t);
}
if (p.pos < p.marginMin) {
var tmpMin = p.pos;
p.pos = p.marginMin;
if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin);
}
},
correctRatio : function(ratio) {
var x = this.x,
y = this.y,
changed = false,
xSize = Math.min(x.full, x.size),
ySize = Math.min(y.full, y.size),
useBox = (this.useBox || hs.padToMinWidth);
if (xSize / ySize > ratio) { // width greater
xSize = ySize * ratio;
if (xSize < x.minSize) { // below minWidth
xSize = x.minSize;
ySize = xSize / ratio;
}
changed = true;
} else if (xSize / ySize < ratio) { // height greater
ySize = xSize / ratio;
changed = true;
}
if (hs.padToMinWidth && x.full < x.minSize) {
x.imgSize = x.full;
y.size = y.imgSize = y.full;
} else if (this.useBox) {
x.imgSize = xSize;
y.imgSize = ySize;
} else {
x.size = xSize;
y.size = ySize;
}
changed = this.fitOverlayBox(useBox ? null : ratio, changed);
if (useBox && y.size < y.imgSize) {
y.imgSize = y.size;
x.imgSize = y.size * ratio;
}
if (changed || useBox) {
x.pos = x.tpos - x.cb + x.tb;
x.minSize = x.size;
this.justify(x, true);
y.pos = y.tpos - y.cb + y.tb;
y.minSize = y.size;
this.justify(y, true);
if (this.overlayBox) this.sizeOverlayBox();
}
},
fitOverlayBox : function(ratio, changed) {
var x = this.x, y = this.y;
if (this.overlayBox) {
while (y.size > this.minHeight && x.size > this.minWidth
&& y.get('wsize') > y.get('fitsize')) {
y.size -= 10;
if (ratio) x.size = y.size * ratio;
this.sizeOverlayBox(0, 1);
changed = true;
}
}
return changed;
},
reflow : function () {
if (this.scrollerDiv) {
var h = /iframe/i.test(this.scrollerDiv.tagName) ? (this.getIframePageHeight() + 1) +'px' : 'auto';
if (this.body) this.body.style.height = h;
this.scrollerDiv.style.height = h;
this.y.setSize(this.innerContent.offsetHeight);
}
},
show : function () {
var x = this.x, y = this.y;
this.doShowHide('hidden');
hs.fireEvent(this, 'onBeforeExpand');
if (this.slideshow && this.slideshow.thumbstrip) this.slideshow.thumbstrip.selectThumb();
// Apply size change
this.changeSize(
1, {
wrapper: {
width : x.get('wsize'),
height : y.get('wsize'),
left: x.pos,
top: y.pos
},
content: {
left: x.p1 + x.get('imgPad'),
top: y.p1 + y.get('imgPad'),
width:x.imgSize ||x.size,
height:y.imgSize ||y.size
}
},
hs.expandDuration
);
},
changeSize : function(up, to, dur) {
// transition
var trans = this.transitions,
other = up ? (this.last ? this.last.a : null) : hs.upcoming,
t = (trans[1] && other
&& hs.getParam(other, 'transitions')[1] == trans[1]) ?
trans[1] : trans[0];
if (this[t] && t != 'expand') {
this[t](up, to);
return;
}
if (this.outline && !this.outlineWhileAnimating) {
if (up) this.outline.setPosition();
else this.outline.destroy(
(this.isHtml && this.preserveContent));
}
if (!up) this.destroyOverlays();
var exp = this,
x = exp.x,
y = exp.y,
easing = this.easing;
if (!up) easing = this.easingClose || easing;
var after = up ?
function() {
if (exp.outline) exp.outline.table.style.visibility = "visible";
setTimeout(function() {
exp.afterExpand();
}, 50);
} :
function() {
exp.afterClose();
};
if (up) hs.setStyles( this.wrapper, {
width: x.t +'px',
height: y.t +'px'
});
if (up && this.isHtml) {
hs.setStyles(this.wrapper, {
left: (x.tpos - x.cb + x.tb) +'px',
top: (y.tpos - y.cb + y.tb) +'px'
});
}
if (this.fadeInOut) {
hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 });
hs.extend(to.wrapper, { opacity: up });
}
hs.animate( this.wrapper, to.wrapper, {
duration: dur,
easing: easing,
step: function(val, args) {
if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') {
var fac = up ? args.pos : 1 - args.pos;
var pos = {
w: x.t + (x.get('wsize') - x.t) * fac,
h: y.t + (y.get('wsize') - y.t) * fac,
x: x.tpos + (x.pos - x.tpos) * fac,
y: y.tpos + (y.pos - y.tpos) * fac
};
exp.outline.setPosition(pos, 0, 1);
}
if (exp.isHtml) {
if (args.prop == 'left')
exp.mediumContent.style.left = (x.pos - val) +'px';
if (args.prop == 'top')
exp.mediumContent.style.top = (y.pos - val) +'px';
}
}
});
hs.animate( this.content, to.content, dur, easing, after);
if (up) {
this.wrapper.style.visibility = 'visible';
this.content.style.visibility = 'visible';
if (this.isHtml) this.innerContent.style.visibility = 'visible';
this.a.className += ' highslide-active-anchor';
}
},
fade : function(up, to) {
this.outlineWhileAnimating = false;
var exp = this, t = up ? hs.expandDuration : 0;
if (up) {
hs.animate(this.wrapper, to.wrapper, 0);
hs.setStyles(this.wrapper, { opacity: 0, visibility: 'visible' });
hs.animate(this.content, to.content, 0);
this.content.style.visibility = 'visible';
hs.animate(this.wrapper, { opacity: 1 }, t, null,
function() { exp.afterExpand(); });
}
if (this.outline) {
this.outline.table.style.zIndex = this.wrapper.style.zIndex;
var dir = up || -1,
offset = this.outline.offset,
startOff = up ? 3 : offset,
endOff = up? offset : 3;
for (var i = startOff; dir * i <= dir * endOff; i += dir, t += 25) {
(function() {
var o = up ? endOff - i : startOff - i;
setTimeout(function() {
exp.outline.setPosition(0, o, 1);
}, t);
})();
}
}
if (up) {}//setTimeout(function() { exp.afterExpand(); }, t+50);
else {
setTimeout( function() {
if (exp.outline) exp.outline.destroy(exp.preserveContent);
exp.destroyOverlays();
hs.animate( exp.wrapper, { opacity: 0 }, hs.restoreDuration, null, function(){
exp.afterClose();
});
}, t);
}
},
crossfade : function (up, to, from) {
if (!up) return;
var exp = this,
last = this.last,
x = this.x,
y = this.y,
lastX = last.x,
lastY = last.y,
wrapper = this.wrapper,
content = this.content,
overlayBox = this.overlayBox;
hs.removeEventListener(document, 'mousemove', hs.dragHandler);
hs.setStyles(content, {
width: (x.imgSize || x.size) +'px',
height: (y.imgSize || y.size) +'px'
});
if (overlayBox) overlayBox.style.overflow = 'visible';
this.outline = last.outline;
if (this.outline) this.outline.exp = exp;
last.outline = null;
var fadeBox = hs.createElement('div', {
className: 'highslide-image'
}, {
position: 'absolute',
zIndex: 4,
overflow: 'hidden',
display: 'none'
}
);
var names = { oldImg: last, newImg: this };
for (var n in names) {
this[n] = names[n].content.cloneNode(1);
hs.setStyles(this[n], {
position: 'absolute',
border: 0,
visibility: 'visible'
});
fadeBox.appendChild(this[n]);
}
wrapper.appendChild(fadeBox);
if (this.isHtml) hs.setStyles(this.mediumContent, {
left: 0,
top: 0
});
if (overlayBox) {
overlayBox.className = '';
wrapper.appendChild(overlayBox);
}
fadeBox.style.display = '';
last.content.style.display = 'none';
if (hs.safari) {
var match = navigator.userAgent.match(/Safari\/([0-9]{3})/);
if (match && parseInt(match[1]) < 525) this.wrapper.style.visibility = 'visible';
}
hs.animate(wrapper, {
width: x.size
}, {
duration: hs.transitionDuration,
step: function(val, args) {
var pos = args.pos,
invPos = 1 - pos;
var prop,
size = {},
props = ['pos', 'size', 'p1', 'p2'];
for (var n in props) {
prop = props[n];
size['x'+ prop] = invPos * lastX[prop] + pos * x[prop];
size['y'+ prop] = invPos * lastY[prop] + pos * y[prop];
size.ximgSize = invPos * (lastX.imgSize || lastX.size) + pos * (x.imgSize || x.size);
size.ximgPad = invPos * lastX.get('imgPad') + pos * x.get('imgPad');
size.yimgSize = invPos * (lastY.imgSize || lastY.size) + pos * (y.imgSize || y.size);
size.yimgPad = invPos * lastY.get('imgPad') + pos * y.get('imgPad');
}
if (exp.outline) exp.outline.setPosition({
x: size.xpos,
y: size.ypos,
w: size.xsize + size.xp1 + size.xp2 + 2 * x.cb,
h: size.ysize + size.yp1 + size.yp2 + 2 * y.cb
});
last.wrapper.style.clip = 'rect('
+ (size.ypos - lastY.pos)+'px, '
+ (size.xsize + size.xp1 + size.xp2 + size.xpos + 2 * lastX.cb - lastX.pos) +'px, '
+ (size.ysize + size.yp1 + size.yp2 + size.ypos + 2 * lastY.cb - lastY.pos) +'px, '
+ (size.xpos - lastX.pos)+'px)';
hs.setStyles(content, {
top: (size.yp1 + y.get('imgPad')) +'px',
left: (size.xp1 + x.get('imgPad')) +'px',
marginTop: (y.pos - size.ypos) +'px',
marginLeft: (x.pos - size.xpos) +'px'
});
hs.setStyles(wrapper, {
top: size.ypos +'px',
left: size.xpos +'px',
width: (size.xp1 + size.xp2 + size.xsize + 2 * x.cb)+ 'px',
height: (size.yp1 + size.yp2 + size.ysize + 2 * y.cb) + 'px'
});
hs.setStyles(fadeBox, {
width: (size.ximgSize || size.xsize) + 'px',
height: (size.yimgSize || size.ysize) +'px',
left: (size.xp1 + size.ximgPad) +'px',
top: (size.yp1 + size.yimgPad) +'px',
visibility: 'visible'
});
hs.setStyles(exp.oldImg, {
top: (lastY.pos - size.ypos + lastY.p1 - size.yp1 + lastY.get('imgPad') - size.yimgPad)+'px',
left: (lastX.pos - size.xpos + lastX.p1 - size.xp1 + lastX.get('imgPad') - size.ximgPad)+'px'
});
hs.setStyles(exp.newImg, {
opacity: pos,
top: (y.pos - size.ypos + y.p1 - size.yp1 + y.get('imgPad') - size.yimgPad) +'px',
left: (x.pos - size.xpos + x.p1 - size.xp1 + x.get('imgPad') - size.ximgPad) +'px'
});
if (overlayBox) hs.setStyles(overlayBox, {
width: size.xsize + 'px',
height: size.ysize +'px',
left: (size.xp1 + x.cb) +'px',
top: (size.yp1 + y.cb) +'px'
});
},
complete: function () {
wrapper.style.visibility = content.style.visibility = 'visible';
content.style.display = 'block';
fadeBox.style.display = 'none';
exp.a.className += ' highslide-active-anchor';
exp.afterExpand();
last.afterClose();
exp.last = null;
}
});
},
reuseOverlay : function(o, el) {
if (!this.last) return false;
for (var i = 0; i < this.last.overlays.length; i++) {
var oDiv = hs.$('hsId'+ this.last.overlays[i]);
if (oDiv && oDiv.hsId == o.hsId) {
this.genOverlayBox();
oDiv.reuse = this.key;
hs.push(this.overlays, this.last.overlays[i]);
return true;
}
}
return false;
},
afterExpand : function() {
this.isExpanded = true;
this.focus();
if (this.isHtml && this.objectLoadTime == 'after') this.writeExtendedContent();
if (this.iframe) {
try {
var exp = this,
doc = this.iframe.contentDocument || this.iframe.contentWindow.document;
hs.addEventListener(doc, 'mousedown', function () {
if (hs.focusKey != exp.key) exp.focus();
});
} catch(e) {}
if (hs.ie && typeof this.isClosing != 'boolean') // first open
this.iframe.style.width = (this.objectWidth - 1) +'px'; // hasLayout
}
if (this.dimmingOpacity) hs.dim(this);
if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null;
this.prepareNextOutline();
var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop;
this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize')
&& this.y.pos < mY && mY < this.y.pos + this.y.get('wsize');
if (this.overlayBox) this.showOverlays();
hs.fireEvent(this, 'onAfterExpand');
},
prepareNextOutline : function() {
var key = this.key;
var outlineType = this.outlineType;
new hs.Outline(outlineType,
function () { try { hs.expanders[key].preloadNext(); } catch (e) {} });
},
preloadNext : function() {
var next = this.getAdjacentAnchor(1);
if (next && next.onclick.toString().match(/hs\.expand/))
var img = hs.createElement('img', { src: hs.getSrc(next) });
},
getAdjacentAnchor : function(op) {
var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none'];
/*< ? if ($cfg->slideshow) : ?>s*/
if (!as[current + op] && this.slideshow && this.slideshow.repeat) {
if (op == 1) return as[0];
else if (op == -1) return as[as.length-1];
}
/*< ? endif ?>s*/
return as[current + op] || null;
},
getAnchorIndex : function() {
var arr = hs.getAnchors().groups[this.slideshowGroup || 'none'];
if (arr) for (var i = 0; i < arr.length; i++) {
if (arr[i] == this.a) return i;
}
return null;
},
getNumber : function() {
if (this[this.numberPosition]) {
var arr = hs.anchors.groups[this.slideshowGroup || 'none'];
if (arr) {
var s = hs.lang.number.replace('%1', this.getAnchorIndex() + 1).replace('%2', arr.length);
this[this.numberPosition].innerHTML =
'<div class="highslide-number">'+ s +'</div>'+ this[this.numberPosition].innerHTML;
}
}
},
initSlideshow : function() {
if (!this.last) {
for (var i = 0; i < hs.slideshows.length; i++) {
var ss = hs.slideshows[i], sg = ss.slideshowGroup;
if (typeof sg == 'undefined' || sg === null || sg === this.slideshowGroup)
this.slideshow = new hs.Slideshow(this.key, ss);
}
} else {
this.slideshow = this.last.slideshow;
}
var ss = this.slideshow;
if (!ss) return;
var key = ss.expKey = this.key;
ss.checkFirstAndLast();
ss.disable('full-expand');
if (ss.controls) {
var o = ss.overlayOptions || {};
o.overlayId = ss.controls;
o.hsId = 'controls';
this.createOverlay(o);
}
if (ss.thumbstrip) ss.thumbstrip.add(this);
if (!this.last && this.autoplay) ss.play(true);
if (ss.autoplay) {
ss.autoplay = setTimeout(function() {
hs.next(key);
}, (ss.interval || 500));
}
},
cancelLoading : function() {
hs.discardElement (this.wrapper);
hs.expanders[this.key] = null;
if (hs.upcoming == this.a) hs.upcoming = null;
hs.undim(this.key);
if (this.loading) hs.loading.style.left = '-9999px';
hs.fireEvent(this, 'onHideLoading');
},
writeCredits : function () {
if (this.credits) return;
this.credits = hs.createElement('a', {
href: hs.creditsHref,
target: hs.creditsTarget,
className: 'highslide-credits',
innerHTML: hs.lang.creditsText,
title: hs.lang.creditsTitle
});
this.createOverlay({
overlayId: this.credits,
position: this.creditsPosition || 'top left',
hsId: 'credits'
});
},
getInline : function(types, addOverlay) {
for (var i = 0; i < types.length; i++) {
var type = types[i], s = null;
if (type == 'caption' && !hs.fireEvent(this, 'onBeforeGetCaption')) return;
else if (type == 'heading' && !hs.fireEvent(this, 'onBeforeGetHeading')) return;
if (!this[type +'Id'] && this.thumbsUserSetId)
this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId;
if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']);
if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try {
s = eval(this[type +'Eval']);
} catch (e) {}
if (!this[type] && this[type +'Text']) {
s = this[type +'Text'];
}
if (!this[type] && !s) {
this[type] = hs.getNode(this.a['_'+ type + 'Id']);
if (!this[type]) {
var next = this.a.nextSibling;
while (next && !hs.isHsAnchor(next)) {
if ((new RegExp('highslide-'+ type)).test(next.className || null)) {
if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++;
this[type] = hs.getNode(next.id);
break;
}
next = next.nextSibling;
}
}
}
if (!this[type] && !s && this.numberPosition == type) s = '\n';
if (!this[type] && s) this[type] = hs.createElement('div',
{ className: 'highslide-'+ type, innerHTML: s } );
if (addOverlay && this[type]) {
var o = { position: (type == 'heading') ? 'above' : 'below' };
for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x];
o.overlayId = this[type];
this.createOverlay(o);
}
}
},
// on end move and resize
doShowHide : function(visibility) {
if (hs.hideSelects) this.showHideElements('SELECT', visibility);
if (hs.hideIframes) this.showHideElements('IFRAME', visibility);
if (hs.geckoMac) this.showHideElements('*', visibility);
},
showHideElements : function (tagName, visibility) {
var els = document.getElementsByTagName(tagName);
var prop = tagName == '*' ? 'overflow' : 'visibility';
for (var i = 0; i < els.length; i++) {
if (prop == 'visibility' || (document.defaultView.getComputedStyle(
els[i], "").getPropertyValue('overflow') == 'auto'
|| els[i].getAttribute('hidden-by') != null)) {
var hiddenBy = els[i].getAttribute('hidden-by');
if (visibility == 'visible' && hiddenBy) {
hiddenBy = hiddenBy.replace('['+ this.key +']', '');
els[i].setAttribute('hidden-by', hiddenBy);
if (!hiddenBy) els[i].style[prop] = els[i].origProp;
} else if (visibility == 'hidden') { // hide if behind
var elPos = hs.getPosition(els[i]);
elPos.w = els[i].offsetWidth;
elPos.h = els[i].offsetHeight;
if (!this.dimmingOpacity) { // hide all if dimming
var clearsX = (elPos.x + elPos.w < this.x.get('opos')
|| elPos.x > this.x.get('opos') + this.x.get('osize'));
var clearsY = (elPos.y + elPos.h < this.y.get('opos')
|| elPos.y > this.y.get('opos') + this.y.get('osize'));
}
var wrapperKey = hs.getWrapperKey(els[i]);
if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image
if (!hiddenBy) {
els[i].setAttribute('hidden-by', '['+ this.key +']');
els[i].origProp = els[i].style[prop];
els[i].style[prop] = 'hidden';
} else if (hiddenBy.indexOf('['+ this.key +']') == -1) {
els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']');
}
} else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey)
&& wrapperKey != this.key) { // on move
els[i].setAttribute('hidden-by', '');
els[i].style[prop] = els[i].origProp || '';
} else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) {
els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', ''));
}
}
}
}
},
focus : function() {
this.wrapper.style.zIndex = hs.zIndexCounter += 2;
// blur others
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && i == hs.focusKey) {
var blurExp = hs.expanders[i];
blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur';
if (blurExp.isImage) {
blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer';
blurExp.content.title = hs.lang.focusTitle;
}
hs.fireEvent(blurExp, 'onBlur');
}
}
// focus this
if (this.outline) this.outline.table.style.zIndex
= this.wrapper.style.zIndex - 1;
this.content.className = 'highslide-'+ this.contentType;
if (this.isImage) {
this.content.title = hs.lang.restoreTitle;
if (hs.restoreCursor) {
hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer';
if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand';
this.content.style.cursor = hs.styleRestoreCursor;
}
}
hs.focusKey = this.key;
hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
hs.fireEvent(this, 'onFocus');
},
moveTo: function(x, y) {
this.x.setPos(x);
this.y.setPos(y);
},
resize : function (e) {
var w, h, r = e.width / e.height;
w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full));
if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full;
h = this.isHtml ? e.height + e.dY : w / r;
if (h < Math.min(this.minHeight, this.y.full)) {
h = Math.min(this.minHeight, this.y.full);
if (this.isImage) w = h * r;
}
this.resizeTo(w, h);
},
resizeTo: function(w, h) {
this.y.setSize(h);
this.x.setSize(w);
this.wrapper.style.height = this.y.get('wsize') +'px';
},
close : function() {
if (this.isClosing || !this.isExpanded) return;
if (this.transitions[1] == 'crossfade' && hs.upcoming) {
hs.getExpander(hs.upcoming).cancelLoading();
hs.upcoming = null;
}
if (!hs.fireEvent(this, 'onBeforeClose')) return;
this.isClosing = true;
if (this.slideshow && !hs.upcoming) this.slideshow.pause();
hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
try {
if (this.isHtml) this.htmlPrepareClose();
this.content.style.cursor = 'default';
this.changeSize(
0, {
wrapper: {
width : this.x.t,
height : this.y.t,
left: this.x.tpos - this.x.cb + this.x.tb,
top: this.y.tpos - this.y.cb + this.y.tb
},
content: {
left: 0,
top: 0,
width: this.x.t,
height: this.y.t
}
}, hs.restoreDuration
);
} catch (e) { this.afterClose(); }
},
htmlPrepareClose : function() {
if (hs.geckoMac) { // bad redraws
if (!hs.mask) hs.mask = hs.createElement('div', null,
{ position: 'absolute' }, hs.container);
hs.setStyles(hs.mask, { width: this.x.size +'px', height: this.y.size +'px',
left: this.x.pos +'px', top: this.y.pos +'px', display: 'block' });
}
if (this.objectType == 'swf') try { hs.$(this.body.id).StopPlay(); } catch (e) {}
if (this.objectLoadTime == 'after' && !this.preserveContent) this.destroyObject();
if (this.scrollerDiv && this.scrollerDiv != this.scrollingContent)
this.scrollerDiv.style.overflow = 'hidden';
},
destroyObject : function () {
if (hs.ie && this.iframe)
try { this.iframe.contentWindow.document.body.innerHTML = ''; } catch (e) {}
if (this.objectType == 'swf') swfobject.removeSWF(this.body.id);
this.body.innerHTML = '';
},
sleep : function() {
if (this.outline) this.outline.table.style.display = 'none';
this.releaseMask = null;
this.wrapper.style.display = 'none';
hs.push(hs.sleeping, this);
},
awake : function() {try {
hs.expanders[this.key] = this;
if (!hs.allowMultipleInstances &&hs.focusKey != this.key) {
try { hs.expanders[hs.focusKey].close(); } catch (e){}
}
var z = hs.zIndexCounter++, stl = { display: '', zIndex: z };
hs.setStyles (this.wrapper, stl);
this.isClosing = false;
var o = this.outline || 0;
if (o) {
if (!this.outlineWhileAnimating) stl.visibility = 'hidden';
hs.setStyles (o.table, stl);
}
if (this.slideshow) {
this.initSlideshow();
}
this.show();
} catch (e) {}
},
createOverlay : function (o) {
var el = o.overlayId,
relToVP = (o.relativeTo == 'viewport' && !/panel$/.test(o.position));
if (typeof el == 'string') el = hs.getNode(el);
if (o.html) el = hs.createElement('div', { innerHTML: o.html });
if (!el || typeof el == 'string') return;
if (!hs.fireEvent(this, 'onCreateOverlay', { overlay: el })) return;
el.style.display = 'block';
o.hsId = o.hsId || o.overlayId;
if (this.transitions[1] == 'crossfade' && this.reuseOverlay(o, el)) return;
this.genOverlayBox();
var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto';
if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px';
var overlay = hs.createElement(
'div', {
id: 'hsId'+ hs.idCounter++,
hsId: o.hsId
}, {
position: 'absolute',
visibility: 'hidden',
width: width,
direction: hs.lang.cssDirection || '',
opacity: 0
},
relToVP ? hs.viewport :this.overlayBox,
true
);
if (relToVP) overlay.hsKey = this.key;
overlay.appendChild(el);
hs.extend(overlay, {
opacity: 1,
offsetX: 0,
offsetY: 0,
dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250
});
hs.extend(overlay, o);
if (this.gotOverlays) {
this.positionOverlay(overlay);
if (!overlay.hideOnMouseOut || this.mouseIsOver)
hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur);
}
hs.push(this.overlays, hs.idCounter - 1);
},
positionOverlay : function(overlay) {
var p = overlay.position || 'middle center',
relToVP = (overlay.relativeTo == 'viewport'),
offX = overlay.offsetX,
offY = overlay.offsetY;
if (relToVP) {
hs.viewport.style.display = 'block';
overlay.hsKey = this.key;
if (overlay.offsetWidth > overlay.parentNode.offsetWidth)
overlay.style.width = '100%';
} else
if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay);
if (/left$/.test(p)) overlay.style.left = offX +'px';
if (/center$/.test(p)) hs.setStyles (overlay, {
left: '50%',
marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px'
});
if (/right$/.test(p)) overlay.style.right = - offX +'px';
if (/^leftpanel$/.test(p)) {
hs.setStyles(overlay, {
right: '100%',
marginRight: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p1 = overlay.offsetWidth;
} else if (/^rightpanel$/.test(p)) {
hs.setStyles(overlay, {
left: '100%',
marginLeft: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p2 = overlay.offsetWidth;
}
var parOff = overlay.parentNode.offsetHeight;
overlay.style.height = 'auto';
if (relToVP && overlay.offsetHeight > parOff)
overlay.style.height = hs.ieLt7 ? parOff +'px' : '100%';
if (/^top/.test(p)) overlay.style.top = offY +'px';
if (/^middle/.test(p)) hs.setStyles (overlay, {
top: '50%',
marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px'
});
if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px';
if (/^above$/.test(p)) {
hs.setStyles(overlay, {
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
bottom: '100%',
marginBottom: this.y.cb +'px',
width: 'auto'
});
this.y.p1 = overlay.offsetHeight;
} else if (/^below$/.test(p)) {
hs.setStyles(overlay, {
position: 'relative',
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
top: '100%',
marginTop: this.y.cb +'px',
width: 'auto'
});
this.y.p2 = overlay.offsetHeight;
overlay.style.position = 'absolute';
}
},
getOverlays : function() {
this.getInline(['heading', 'caption'], true);
this.getNumber();
if (this.caption) hs.fireEvent(this, 'onAfterGetCaption');
if (this.heading) hs.fireEvent(this, 'onAfterGetHeading');
if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move';
if (hs.showCredits) this.writeCredits();
for (var i = 0; i < hs.overlays.length; i++) {
var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup;
if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId)
|| (sg && sg === this.slideshowGroup)) {
if (this.isImage || (this.isHtml && o.useOnHtml))
this.createOverlay(o);
}
}
var os = [];
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
if (/panel$/.test(o.position)) this.positionOverlay(o);
else hs.push(os, o);
}
for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]);
this.gotOverlays = true;
},
genOverlayBox : function() {
if (!this.overlayBox) this.overlayBox = hs.createElement (
'div', {
className: this.wrapperClassName
}, {
position : 'absolute',
width: (this.x.size || (this.useBox ? this.width : null)
|| this.x.full) +'px',
height: (this.y.size || this.y.full) +'px',
visibility : 'hidden',
overflow : 'hidden',
zIndex : hs.ie ? 4 : 'auto'
},
hs.container,
true
);
},
sizeOverlayBox : function(doWrapper, doPanels) {
var overlayBox = this.overlayBox,
x = this.x,
y = this.y;
hs.setStyles( overlayBox, {
width: x.size +'px',
height: y.size +'px'
});
if (doWrapper || doPanels) {
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat');
if (o && /^(above|below)$/.test(o.position)) {
if (ie6) {
o.style.width = (overlayBox.offsetWidth + 2 * x.cb
+ x.p1 + x.p2) +'px';
}
y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight;
}
if (o && ie6 && /^(left|right)panel$/.test(o.position)) {
o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px';
}
}
}
if (doWrapper) {
hs.setStyles(this.content, {
top: y.p1 +'px'
});
hs.setStyles(overlayBox, {
top: (y.p1 + y.cb) +'px'
});
}
},
showOverlays : function() {
var b = this.overlayBox;
b.className = '';
hs.setStyles(b, {
top: (this.y.p1 + this.y.cb) +'px',
left: (this.x.p1 + this.x.cb) +'px',
overflow : 'visible'
});
if (hs.safari) b.style.visibility = 'visible';
this.wrapper.appendChild (b);
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
o.style.zIndex = o.hsId == 'controls' ? 5 : 4;
if (!o.hideOnMouseOut || this.mouseIsOver) {
o.style.visibility = 'visible';
hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: o.opacity }, o.dur);
}
}
},
destroyOverlays : function() {
if (!this.overlays.length) return;
if (this.slideshow) {
var c = this.slideshow.controls;
if (c && hs.getExpander(c) == this) c.parentNode.removeChild(c);
}
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
if (o && o.parentNode == hs.viewport && hs.getExpander(o) == this) hs.discardElement(o);
}
if (this.isHtml && this.preserveContent) {
this.overlayBox.style.top = '-9999px';
hs.container.appendChild(this.overlayBox);
} else
hs.discardElement(this.overlayBox);
},
createFullExpand : function () {
if (this.slideshow && this.slideshow.controls) {
this.slideshow.enable('full-expand');
return;
}
this.fullExpandLabel = hs.createElement(
'a', {
href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();',
title: hs.lang.fullExpandTitle,
className: 'highslide-full-expand'
}
);
if (!hs.fireEvent(this, 'onCreateFullExpand')) return;
this.createOverlay({
overlayId: this.fullExpandLabel,
position: hs.fullExpandPosition,
hideOnMouseOut: true,
opacity: hs.fullExpandOpacity
});
},
doFullExpand : function () {
try {
if (!hs.fireEvent(this, 'onDoFullExpand')) return;
if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel);
this.focus();
var xSize = this.x.size;
this.resizeTo(this.x.full, this.y.full);
var xpos = this.x.pos - (this.x.size - xSize) / 2;
if (xpos < hs.marginLeft) xpos = hs.marginLeft;
this.moveTo(xpos, this.y.pos);
this.doShowHide('hidden');
} catch (e) {
this.error(e);
}
},
afterClose : function () {
this.a.className = this.a.className.replace('highslide-active-anchor', '');
this.doShowHide('visible');
if (this.isHtml && this.preserveContent
&& this.transitions[1] != 'crossfade') {
this.sleep();
} else {
if (this.outline && this.outlineWhileAnimating) this.outline.destroy();
hs.discardElement(this.wrapper);
}
if (hs.mask) hs.mask.style.display = 'none';
this.destroyOverlays();
if (!hs.viewport.childNodes.length) hs.viewport.style.display = 'none';
if (this.dimmingOpacity) hs.undim(this.key);
hs.fireEvent(this, 'onAfterClose');
hs.expanders[this.key] = null;
hs.reOrder();
}
};
// hs.Ajax object prototype
hs.Ajax = function (a, content, pre) {
this.a = a;
this.content = content;
this.pre = pre;
};
hs.Ajax.prototype = {
run : function () {
var xhr;
if (!this.src) this.src = hs.getSrc(this.a);
if (this.src.match('#')) {
var arr = this.src.split('#');
this.src = arr[0];
this.id = arr[1];
}
if (hs.cachedGets[this.src]) {
this.cachedGet = hs.cachedGets[this.src];
if (this.id) this.getElementContent();
else this.loadHTML();
return;
}
try { xhr = new XMLHttpRequest(); }
catch (e) {
try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {
try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { this.onError(); }
}
}
var pThis = this;
xhr.onreadystatechange = function() {
if(pThis.xhr.readyState == 4) {
if (pThis.id) pThis.getElementContent();
else pThis.loadHTML();
}
};
var src = this.src;
this.xhr = xhr;
if (hs.forceAjaxReload)
src = src.replace(/$/, (/\?/.test(src) ? '&' : '?') +'dummy='+ (new Date()).getTime());
xhr.open('GET', src, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(null);
},
getElementContent : function() {
hs.init();
var attribs = window.opera || hs.ie6SSL ? { src: 'about:blank' } : null;
this.iframe = hs.createElement('iframe', attribs,
{ position: 'absolute', top: '-9999px' }, hs.container);
this.loadHTML();
},
loadHTML : function() {
var s = this.cachedGet || this.xhr.responseText,
regBody;
if (this.pre) hs.cachedGets[this.src] = s;
if (!hs.ie || hs.uaVersion >= 5.5) {
s = s.replace(new RegExp('<link[^>]*>', 'gi'), '')
.replace(new RegExp('<script[^>]*>.*?</script>', 'gi'), '');
if (this.iframe) {
var doc = this.iframe.contentDocument;
if (!doc && this.iframe.contentWindow) doc = this.iframe.contentWindow.document;
if (!doc) { // Opera
var pThis = this;
setTimeout(function() { pThis.loadHTML(); }, 25);
return;
}
doc.open();
doc.write(s);
doc.close();
try { s = doc.getElementById(this.id).innerHTML; } catch (e) {
try { s = this.iframe.document.getElementById(this.id).innerHTML; } catch (e) {} // opera
}
hs.discardElement(this.iframe);
} else {
regBody = /(<body[^>]*>|<\/body>)/ig;
if (regBody.test(s)) s = s.split(regBody)[hs.ie ? 1 : 2];
}
}
hs.getElementByClass(this.content, 'DIV', 'highslide-body').innerHTML = s;
this.onLoad();
for (var x in this) this[x] = null;
}
};
hs.Slideshow = function (expKey, options) {
if (hs.dynamicallyUpdateAnchors !== false) hs.updateAnchors();
this.expKey = expKey;
for (var x in options) this[x] = options[x];
if (this.useControls) this.getControls();
if (this.thumbstrip) this.thumbstrip = hs.Thumbstrip(this);
};
hs.Slideshow.prototype = {
getControls: function() {
this.controls = hs.createElement('div', { innerHTML: hs.replaceLang(hs.skin.controls) },
null, hs.container);
var buttons = ['play', 'pause', 'previous', 'next', 'move', 'full-expand', 'close'];
this.btn = {};
var pThis = this;
for (var i = 0; i < buttons.length; i++) {
this.btn[buttons[i]] = hs.getElementByClass(this.controls, 'li', 'highslide-'+ buttons[i]);
this.enable(buttons[i]);
}
this.btn.pause.style.display = 'none';
//this.disable('full-expand');
},
checkFirstAndLast: function() {
if (this.repeat || !this.controls) return;
var exp = hs.expanders[this.expKey],
cur = exp.getAnchorIndex(),
re = /disabled$/;
if (cur == 0)
this.disable('previous');
else if (re.test(this.btn.previous.getElementsByTagName('a')[0].className))
this.enable('previous');
if (cur + 1 == hs.anchors.groups[exp.slideshowGroup || 'none'].length) {
this.disable('next');
this.disable('play');
} else if (re.test(this.btn.next.getElementsByTagName('a')[0].className)) {
this.enable('next');
this.enable('play');
}
},
enable: function(btn) {
if (!this.btn) return;
var sls = this, a = this.btn[btn].getElementsByTagName('a')[0], re = /disabled$/;
a.onclick = function() {
sls[btn]();
return false;
};
if (re.test(a.className)) a.className = a.className.replace(re, '');
},
disable: function(btn) {
if (!this.btn) return;
var a = this.btn[btn].getElementsByTagName('a')[0];
a.onclick = function() { return false; };
if (!/disabled$/.test(a.className)) a.className += ' disabled';
},
hitSpace: function() {
if (this.autoplay) this.pause();
else this.play();
},
play: function(wait) {
if (this.btn) {
this.btn.play.style.display = 'none';
this.btn.pause.style.display = '';
}
this.autoplay = true;
if (!wait) hs.next(this.expKey);
},
pause: function() {
if (this.btn) {
this.btn.pause.style.display = 'none';
this.btn.play.style.display = '';
}
clearTimeout(this.autoplay);
this.autoplay = null;
},
previous: function() {
this.pause();
hs.previous(this.btn.previous);
},
next: function() {
this.pause();
hs.next(this.btn.next);
},
move: function() {},
'full-expand': function() {
hs.getExpander().doFullExpand();
},
close: function() {
hs.close(this.btn.close);
}
};
hs.Thumbstrip = function(slideshow) {
function add (exp) {
hs.extend(options || {}, {
overlayId: dom,
hsId: 'thumbstrip',
className: 'highslide-thumbstrip-'+ mode +'-overlay ' + (options.className || '')
});
if (hs.ieLt7) options.fade = 0;
exp.createOverlay(options);
hs.setStyles(dom.parentNode, { overflow: 'hidden' });
};
function scroll (delta) {
selectThumb(undefined, Math.round(delta * dom[isX ? 'offsetWidth' : 'offsetHeight'] * 0.7));
};
function selectThumb (i, scrollBy) {
if (i === undefined) for (var j = 0; j < group.length; j++) {
if (group[j] == hs.expanders[slideshow.expKey].a) {
i = j;
break;
}
}
if (i === undefined) return;
var as = dom.getElementsByTagName('a'),
active = as[i],
cell = active.parentNode,
left = isX ? 'Left' : 'Top',
right = isX ? 'Right' : 'Bottom',
width = isX ? 'Width' : 'Height',
offsetLeft = 'offset' + left,
offsetWidth = 'offset' + width,
overlayWidth = div.parentNode.parentNode[offsetWidth],
minTblPos = overlayWidth - table[offsetWidth],
curTblPos = parseInt(table.style[isX ? 'left' : 'top']) || 0,
tblPos = curTblPos,
mgnRight = 20;
if (scrollBy !== undefined) {
tblPos = curTblPos - scrollBy;
if (tblPos > 0) tblPos = 0;
if (tblPos < minTblPos) tblPos = minTblPos;
} else {
for (var j = 0; j < as.length; j++) as[j].className = '';
active.className = 'highslide-active-anchor';
var activeLeft = i > 0 ? as[i - 1].parentNode[offsetLeft] : cell[offsetLeft],
activeRight = cell[offsetLeft] + cell[offsetWidth] +
(as[i + 1] ? as[i + 1].parentNode[offsetWidth] : 0);
if (activeRight > overlayWidth - curTblPos) tblPos = overlayWidth - activeRight;
else if (activeLeft < -curTblPos) tblPos = -activeLeft;
}
var markerPos = cell[offsetLeft] + (cell[offsetWidth] - marker[offsetWidth]) / 2 + tblPos;
hs.animate(table, isX ? { left: tblPos } : { top: tblPos }, null, 'easeOutQuad');
hs.animate(marker, isX ? { left: markerPos } : { top: markerPos }, null, 'easeOutQuad');
scrollUp.style.display = tblPos < 0 ? 'block' : 'none';
scrollDown.style.display = (tblPos > minTblPos) ? 'block' : 'none';
};
// initialize
var group = hs.anchors.groups[hs.expanders[slideshow.expKey].slideshowGroup || 'none'],
options = slideshow.thumbstrip,
mode = options.mode || 'horizontal',
floatMode = (mode == 'float'),
tree = floatMode ? ['div', 'ul', 'li', 'span'] : ['table', 'tbody', 'tr', 'td'],
isX = (mode == 'horizontal'),
dom = hs.createElement('div', {
className: 'highslide-thumbstrip highslide-thumbstrip-'+ mode,
innerHTML:
'<div class="highslide-thumbstrip-inner">'+
'<'+ tree[0] +'><'+ tree[1] +'></'+ tree[1] +'></'+ tree[0] +'></div>'+
'<div class="highslide-scroll-up"><div></div></div>'+
'<div class="highslide-scroll-down"><div></div></div>'+
'<div class="highslide-marker"><div></div></div>'
}, {
display: 'none'
}, hs.container),
domCh = dom.childNodes,
div = domCh[0],
scrollUp = domCh[1],
scrollDown = domCh[2],
marker = domCh[3],
table = div.firstChild,
tbody = dom.getElementsByTagName(tree[1])[0],
tr;
for (var i = 0; i < group.length; i++) {
if (i == 0 || !isX) tr = hs.createElement(tree[2], null, null, tbody);
(function(){
var a = group[i],
cell = hs.createElement(tree[3], null, null, tr),
pI = i;
hs.createElement('a', {
href: a.href,
onclick: function() {
hs.getExpander(this).focus();
return hs.transit(a);
},
innerHTML: hs.stripItemFormatter ? hs.stripItemFormatter(a) : a.innerHTML
}, null, cell);
})();
}
if (!floatMode) {
scrollUp.onclick = function () { scroll(-1); };
scrollDown.onclick = function() { scroll(1); };
hs.addEventListener(tbody, document.onmousewheel !== undefined ?
'mousewheel' : 'DOMMouseScroll', function(e) {
var delta = 0;
e = e || window.event;
if (e.wheelDelta) {
delta = e.wheelDelta/120;
if (hs.opera) delta = -delta;
} else if (e.detail) {
delta = -e.detail/3;
}
if (delta) scroll(-delta * 0.2);
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
});
}
return {
add: add,
selectThumb: selectThumb
}
};
hs.langDefaults = hs.lang;
// history
var HsExpander = hs.Expander;
if (hs.ie) {
(function () {
try {
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
hs.ready();
})();
}
hs.addEventListener(document, 'DOMContentLoaded', hs.ready);
hs.addEventListener(window, 'load', hs.ready);
// set handlers
hs.addEventListener(document, 'ready', function() {
if (hs.expandCursor || hs.dimmingOpacity) {
var style = hs.createElement('style', { type: 'text/css' }, null,
document.getElementsByTagName('HEAD')[0]);
function addRule(sel, dec) {
if (!hs.ie) {
style.appendChild(document.createTextNode(sel + " {" + dec + "}"));
} else {
var last = document.styleSheets[document.styleSheets.length - 1];
if (typeof(last.addRule) == "object") last.addRule(sel, dec);
}
}
function fix(prop) {
return 'expression( ( ( ignoreMe = document.documentElement.'+ prop +
' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );';
}
if (hs.expandCursor) addRule ('.highslide img',
'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;');
addRule ('.highslide-viewport-size',
(hs.ieLt7 || (hs.ie && document.compatMode == 'BackCompat')) ?
'position: absolute; '+
'left:'+ fix('scrollLeft') +
'top:'+ fix('scrollTop') +
'width:'+ fix('clientWidth') +
'height:'+ fix('clientHeight') :
'position: fixed; width: 100%; height: 100%; left: 0; top: 0');
}
});
hs.addEventListener(window, 'resize', function() {
hs.getPageSize();
if (hs.viewport) for (var i = 0; i < hs.viewport.childNodes.length; i++) {
var node = hs.viewport.childNodes[i],
exp = hs.getExpander(node);
exp.positionOverlay(node);
if (node.hsId == 'thumbstrip') exp.slideshow.thumbstrip.selectThumb();
}
});
hs.addEventListener(document, 'mousemove', function(e) {
hs.mouse = { x: e.clientX, y: e.clientY };
});
hs.addEventListener(document, 'mousedown', hs.mouseClickHandler);
hs.addEventListener(document, 'mouseup', hs.mouseClickHandler);
hs.addEventListener(document, 'ready', hs.setClickEvents);
hs.addEventListener(window, 'load', hs.preloadImages);
hs.addEventListener(window, 'load', hs.preloadAjax);
} | JavaScript |
/******************************************************************************
Name: Highslide JS
Version: 4.1.7 (September 28 2009)
Config: default
Author: Torstein Hønsi
Support: http://highslide.com/support
Licence:
Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5
License (http://creativecommons.org/licenses/by-nc/2.5/).
You are free:
* to copy, distribute, display, and perform the work
* to make derivative works
Under the following conditions:
* Attribution. You must attribute the work in the manner specified by the
author or licensor.
* Noncommercial. You may not use this work for commercial purposes.
* For any reuse or distribution, you must make clear to others the license
terms of this work.
* Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
******************************************************************************/
if (!hs) { var hs = {
// Language strings
lang : {
cssDirection: 'ltr',
loadingText : 'Loading...',
loadingTitle : 'Click to cancel',
focusTitle : 'Click to bring to front',
fullExpandTitle : 'Expand to actual size (f)',
creditsText : 'Powered by <i>Highslide JS</i>',
creditsTitle : 'Go to the Highslide JS homepage',
restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.'
},
// See http://highslide.com/ref for examples of settings
graphicsDir : 'highslide/graphics/',
expandCursor : 'zoomin.cur', // null disables
restoreCursor : 'zoomout.cur', // null disables
expandDuration : 250, // milliseconds
restoreDuration : 250,
marginLeft : 15,
marginRight : 15,
marginTop : 15,
marginBottom : 15,
zIndexCounter : 1001, // adjust to other absolutely positioned elements
loadingOpacity : 0.75,
allowMultipleInstances: true,
numberOfImagesToPreload : 5,
outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only
outlineStartOffset : 3, // ends at 10
padToMinWidth : false, // pad the popup width to make room for wide caption
fullExpandPosition : 'bottom right',
fullExpandOpacity : 1,
showCredits : true, // you can set this to false if you want
creditsHref : 'http://highslide.com/',
creditsTarget : '_self',
enableKeyListener : true,
openerTagNames : ['a'], // Add more to allow slideshow indexing
dragByHeading: true,
minWidth: 200,
minHeight: 200,
allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight
outlineType : 'drop-shadow', // set null to disable outlines
// END OF YOUR SETTINGS
// declare internal properties
preloadTheseImages : [],
continuePreloading: true,
expanders : [],
overrides : [
'allowSizeReduction',
'useBox',
'outlineType',
'outlineWhileAnimating',
'captionId',
'captionText',
'captionEval',
'captionOverlay',
'headingId',
'headingText',
'headingEval',
'headingOverlay',
'creditsPosition',
'dragByHeading',
'width',
'height',
'wrapperClassName',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'slideshowGroup',
'easing',
'easingClose',
'fadeInOut',
'src'
],
overlays : [],
idCounter : 0,
oPos : {
x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'],
y: ['above', 'top', 'middle', 'bottom', 'below']
},
mouse: {},
headingOverlay: {},
captionOverlay: {},
timers : [],
pendingOutlines : {},
clones : {},
onReady: [],
uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 :
parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]),
ie : (document.all && !window.opera),
safari : /Safari/.test(navigator.userAgent),
geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent),
$ : function (id) {
if (id) return document.getElementById(id);
},
push : function (arr, val) {
arr[arr.length] = val;
},
createElement : function (tag, attribs, styles, parent, nopad) {
var el = document.createElement(tag);
if (attribs) hs.extend(el, attribs);
if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0});
if (styles) hs.setStyles(el, styles);
if (parent) parent.appendChild(el);
return el;
},
extend : function (el, attribs) {
for (var x in attribs) el[x] = attribs[x];
return el;
},
setStyles : function (el, styles) {
for (var x in styles) {
if (hs.ie && x == 'opacity') {
if (styles[x] > 0.99) el.style.removeAttribute('filter');
else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')';
}
else el.style[x] = styles[x];
}
},
animate: function(el, prop, opt) {
var start,
end,
unit;
if (typeof opt != 'object' || opt === null) {
var args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (typeof opt.duration != 'number') opt.duration = 250;
opt.easing = Math[opt.easing] || Math.easeInQuad;
opt.curAnim = hs.extend({}, prop);
for (var name in prop) {
var e = new hs.fx(el, opt , name );
start = parseFloat(hs.css(el, name)) || 0;
end = parseFloat(prop[name]);
unit = name != 'opacity' ? 'px' : '';
e.custom( start, end, unit );
}
},
css: function(el, prop) {
if (document.defaultView) {
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
} else {
if (prop == 'opacity') prop = 'filter';
var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })];
if (prop == 'filter')
val = val.replace(/alpha\(opacity=([0-9]+)\)/,
function (a, b) { return b / 100 });
return val === '' ? 1 : val;
}
},
getPageSize : function () {
var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat'
? d.documentElement : d.body;
var width = hs.ie ? iebody.clientWidth :
(d.documentElement.clientWidth || self.innerWidth),
height = hs.ie ? iebody.clientHeight : self.innerHeight;
hs.page = {
width: width,
height: height,
scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset,
scrollTop: hs.ie ? iebody.scrollTop : pageYOffset
}
},
getPosition : function(el) {
var p = { x: el.offsetLeft, y: el.offsetTop };
while (el.offsetParent) {
el = el.offsetParent;
p.x += el.offsetLeft;
p.y += el.offsetTop;
if (el != document.body && el != document.documentElement) {
p.x -= el.scrollLeft;
p.y -= el.scrollTop;
}
}
return p;
},
expand : function(a, params, custom, type) {
if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container);
if (typeof a.getParams == 'function') return params;
try {
new hs.Expander(a, params, custom);
return false;
} catch (e) { return true; }
},
focusTopmost : function() {
var topZ = 0,
topmostKey = -1,
expanders = hs.expanders,
exp,
zIndex;
for (var i = 0; i < expanders.length; i++) {
exp = expanders[i];
if (exp) {
zIndex = exp.wrapper.style.zIndex;
if (zIndex && zIndex > topZ) {
topZ = zIndex;
topmostKey = i;
}
}
}
if (topmostKey == -1) hs.focusKey = -1;
else expanders[topmostKey].focus();
},
getParam : function (a, param) {
a.getParams = a.onclick;
var p = a.getParams ? a.getParams() : null;
a.getParams = null;
return (p && typeof p[param] != 'undefined') ? p[param] :
(typeof hs[param] != 'undefined' ? hs[param] : null);
},
getSrc : function (a) {
var src = hs.getParam(a, 'src');
if (src) return src;
return a.href;
},
getNode : function (id) {
var node = hs.$(id), clone = hs.clones[id], a = {};
if (!node && !clone) return null;
if (!clone) {
clone = node.cloneNode(true);
clone.id = '';
hs.clones[id] = clone;
return node;
} else {
return clone.cloneNode(true);
}
},
discardElement : function(d) {
if (d) hs.garbageBin.appendChild(d);
hs.garbageBin.innerHTML = '';
},
transit : function (adj, exp) {
var last = exp = exp || hs.getExpander();
if (hs.upcoming) return false;
else hs.last = last;
try {
hs.upcoming = adj;
adj.onclick();
} catch (e){
hs.last = hs.upcoming = null;
}
try {
exp.close();
} catch (e) {}
return false;
},
previousOrNext : function (el, op) {
var exp = hs.getExpander(el);
if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp);
else return false;
},
previous : function (el) {
return hs.previousOrNext(el, -1);
},
next : function (el) {
return hs.previousOrNext(el, 1);
},
keyHandler : function(e) {
if (!e) e = window.event;
if (!e.target) e.target = e.srcElement; // ie
if (typeof e.target.form != 'undefined') return true; // form element has focus
var exp = hs.getExpander();
var op = null;
switch (e.keyCode) {
case 70: // f
if (exp) exp.doFullExpand();
return true;
case 32: // Space
case 34: // Page Down
case 39: // Arrow right
case 40: // Arrow down
op = 1;
break;
case 8: // Backspace
case 33: // Page Up
case 37: // Arrow left
case 38: // Arrow up
op = -1;
break;
case 27: // Escape
case 13: // Enter
op = 0;
}
if (op !== null) {hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
if (!hs.enableKeyListener) return true;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (exp) {
if (op == 0) {
exp.close();
} else {
hs.previousOrNext(exp.key, op);
}
return false;
}
}
return true;
},
registerOverlay : function (overlay) {
hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } ));
},
getWrapperKey : function (element, expOnly) {
var el, re = /^highslide-wrapper-([0-9]+)$/;
// 1. look in open expanders
el = element;
while (el.parentNode) {
if (el.id && re.test(el.id)) return el.id.replace(re, "$1");
el = el.parentNode;
}
// 2. look in thumbnail
if (!expOnly) {
el = element;
while (el.parentNode) {
if (el.tagName && hs.isHsAnchor(el)) {
for (var key = 0; key < hs.expanders.length; key++) {
var exp = hs.expanders[key];
if (exp && exp.a == el) return key;
}
}
el = el.parentNode;
}
}
return null;
},
getExpander : function (el, expOnly) {
if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null;
if (typeof el == 'number') return hs.expanders[el] || null;
if (typeof el == 'string') el = hs.$(el);
return hs.expanders[hs.getWrapperKey(el, expOnly)] || null;
},
isHsAnchor : function (a) {
return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/));
},
reOrder : function () {
for (var i = 0; i < hs.expanders.length; i++)
if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost();
},
mouseClickHandler : function(e)
{
if (!e) e = window.event;
if (e.button > 1) return true;
if (!e.target) e.target = e.srcElement;
var el = e.target;
while (el.parentNode
&& !(/highslide-(image|move|html|resize)/.test(el.className)))
{
el = el.parentNode;
}
var exp = hs.getExpander(el);
if (exp && (exp.isClosing || !exp.isExpanded)) return true;
if (exp && e.type == 'mousedown') {
if (e.target.form) return true;
var match = el.className.match(/highslide-(image|move|resize)/);
if (match) {
hs.dragArgs = { exp: exp , type: match[1], left: exp.x.pos, width: exp.x.size, top: exp.y.pos,
height: exp.y.size, clickX: e.clientX, clickY: e.clientY };
hs.addEventListener(document, 'mousemove', hs.dragHandler);
if (e.preventDefault) e.preventDefault(); // FF
if (/highslide-(image|html)-blur/.test(exp.content.className)) {
exp.focus();
hs.hasFocused = true;
}
return false;
}
} else if (e.type == 'mouseup') {
hs.removeEventListener(document, 'mousemove', hs.dragHandler);
if (hs.dragArgs) {
if (hs.styleRestoreCursor && hs.dragArgs.type == 'image')
hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor;
var hasDragged = hs.dragArgs.hasDragged;
if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) {
exp.close();
}
else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) {
hs.dragArgs.exp.doShowHide('hidden');
}
hs.hasFocused = false;
hs.dragArgs = null;
} else if (/highslide-image-blur/.test(el.className)) {
el.style.cursor = hs.styleRestoreCursor;
}
}
return false;
},
dragHandler : function(e)
{
if (!hs.dragArgs) return true;
if (!e) e = window.event;
var a = hs.dragArgs, exp = a.exp;
a.dX = e.clientX - a.clickX;
a.dY = e.clientY - a.clickY;
var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2));
if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0)
|| (distance > (hs.dragSensitivity || 5));
if (a.hasDragged && e.clientX > 5 && e.clientY > 5) {
if (a.type == 'resize') exp.resize(a);
else {
exp.moveTo(a.left + a.dX, a.top + a.dY);
if (a.type == 'image') exp.content.style.cursor = 'move';
}
}
return false;
},
wrapperMouseHandler : function (e) {
try {
if (!e) e = window.event;
var over = /mouseover/i.test(e.type);
if (!e.target) e.target = e.srcElement; // ie
if (hs.ie) e.relatedTarget =
over ? e.fromElement : e.toElement; // ie
var exp = hs.getExpander(e.target);
if (!exp.isExpanded) return;
if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp
|| hs.dragArgs) return;
for (var i = 0; i < exp.overlays.length; i++) (function() {
var o = hs.$('hsId'+ exp.overlays[i]);
if (o && o.hideOnMouseOut) {
if (over) hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur);
}
})();
} catch (e) {}
},
addEventListener : function (el, event, func) {
if (el == document && event == 'ready') hs.push(hs.onReady, func);
try {
el.addEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
el.attachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = func;
}
}
},
removeEventListener : function (el, event, func) {
try {
el.removeEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = null;
}
}
},
preloadFullImage : function (i) {
if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') {
var img = document.createElement('img');
img.onload = function() {
img = null;
hs.preloadFullImage(i + 1);
};
img.src = hs.preloadTheseImages[i];
}
},
preloadImages : function (number) {
if (number && typeof number != 'object') hs.numberOfImagesToPreload = number;
var arr = hs.getAnchors();
for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) {
hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i]));
}
// preload outlines
if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} );
else
hs.preloadFullImage(0);
// preload cursor
if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor });
},
init : function () {
if (!hs.container) {
hs.getPageSize();
hs.ieLt7 = hs.ie && hs.uaVersion < 7;
for (var x in hs.langDefaults) {
if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x];
else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined')
hs.lang[x] = hs.langDefaults[x];
}
hs.container = hs.createElement('div', {
className: 'highslide-container'
}, {
position: 'absolute',
left: 0,
top: 0,
width: '100%',
zIndex: hs.zIndexCounter,
direction: 'ltr'
},
document.body,
true
);
hs.loading = hs.createElement('a', {
className: 'highslide-loading',
title: hs.lang.loadingTitle,
innerHTML: hs.lang.loadingText,
href: 'javascript:;'
}, {
position: 'absolute',
top: '-9999px',
opacity: hs.loadingOpacity,
zIndex: 1
}, hs.container
);
hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container);
// http://www.robertpenner.com/easing/
Math.linearTween = function (t, b, c, d) {
return c*t/d + b;
};
Math.easeInQuad = function (t, b, c, d) {
return c*(t/=d)*t + b;
};
hs.hideSelects = hs.ieLt7;
hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE'
|| (hs.ie && hs.uaVersion < 5.5));
}
},
ready : function() {
if (hs.isReady) return;
hs.isReady = true;
for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i]();
},
updateAnchors : function() {
var el, els, all = [], images = [],groups = {}, re;
for (var i = 0; i < hs.openerTagNames.length; i++) {
els = document.getElementsByTagName(hs.openerTagNames[i]);
for (var j = 0; j < els.length; j++) {
el = els[j];
re = hs.isHsAnchor(el);
if (re) {
hs.push(all, el);
if (re[0] == 'hs.expand') hs.push(images, el);
var g = hs.getParam(el, 'slideshowGroup') || 'none';
if (!groups[g]) groups[g] = [];
hs.push(groups[g], el);
}
}
}
hs.anchors = { all: all, groups: groups, images: images };
return hs.anchors;
},
getAnchors : function() {
return hs.anchors || hs.updateAnchors();
},
close : function(el) {
var exp = hs.getExpander(el);
if (exp) exp.close();
return false;
}
}; // end hs object
hs.fx = function( elem, options, prop ){
this.options = options;
this.elem = elem;
this.prop = prop;
if (!options.orig) options.orig = {};
};
hs.fx.prototype = {
update: function(){
(hs.fx.step[this.prop] || hs.fx.step._default)(this);
if (this.options.step)
this.options.step.call(this.elem, this.now, this);
},
custom: function(from, to, unit){
this.startTime = (new Date()).getTime();
this.start = from;
this.end = to;
this.unit = unit;// || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t(gotoEnd){
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && hs.timers.push(t) == 1 ) {
hs.timerId = setInterval(function(){
var timers = hs.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval(hs.timerId);
}
}, 13);
}
},
step: function(gotoEnd){
var t = (new Date()).getTime();
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
var done = true;
for ( var i in this.options.curAnim )
if ( this.options.curAnim[i] !== true )
done = false;
if ( done ) {
if (this.options.complete) this.options.complete.call(this.elem);
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
this.pos = this.options.easing(n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
}
return true;
}
};
hs.extend( hs.fx, {
step: {
opacity: function(fx){
hs.setStyles(fx.elem, { opacity: fx.now });
},
_default: function(fx){
try {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
else
fx.elem[ fx.prop ] = fx.now;
} catch (e) {}
}
}
});
hs.Outline = function (outlineType, onLoad) {
this.onLoad = onLoad;
this.outlineType = outlineType;
var v = hs.uaVersion, tr;
this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7;
if (!outlineType) {
if (onLoad) onLoad();
return;
}
hs.init();
this.table = hs.createElement(
'table', {
cellSpacing: 0
}, {
visibility: 'hidden',
position: 'absolute',
borderCollapse: 'collapse',
width: 0
},
hs.container,
true
);
var tbody = hs.createElement('tbody', null, null, this.table, 1);
this.td = [];
for (var i = 0; i <= 8; i++) {
if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true);
this.td[i] = hs.createElement('td', null, null, tr, true);
var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' };
hs.setStyles(this.td[i], style);
}
this.td[4].className = outlineType +' highslide-outline';
this.preloadGraphic();
};
hs.Outline.prototype = {
preloadGraphic : function () {
var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png";
var appendTo = hs.safari ? hs.container : null;
this.graphic = hs.createElement('img', null, { position: 'absolute',
top: '-9999px' }, appendTo, true); // for onload trigger
var pThis = this;
this.graphic.onload = function() { pThis.onGraphicLoad(); };
this.graphic.src = src;
},
onGraphicLoad : function () {
var o = this.offset = this.graphic.width / 4,
pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]],
dim = { height: (2*o) +'px', width: (2*o) +'px' };
for (var i = 0; i <= 8; i++) {
if (pos[i]) {
if (this.hasAlphaImageLoader) {
var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px';
var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true);
hs.createElement ('div', null, {
filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')",
position: 'absolute',
width: w,
height: this.graphic.height +'px',
left: (pos[i][0]*o)+'px',
top: (pos[i][1]*o)+'px'
},
div,
true);
} else {
hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'});
}
if (window.opera && (i == 3 || i ==5))
hs.createElement('div', null, dim, this.td[i], true);
hs.setStyles (this.td[i], dim);
}
}
this.graphic = null;
if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy();
hs.pendingOutlines[this.outlineType] = this;
if (this.onLoad) this.onLoad();
},
setPosition : function (pos, offset, vis, dur, easing) {
var exp = this.exp,
stl = exp.wrapper.style,
offset = offset || 0,
pos = pos || {
x: exp.x.pos + offset,
y: exp.y.pos + offset,
w: exp.x.get('wsize') - 2 * offset,
h: exp.y.get('wsize') - 2 * offset
};
if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset)
? 'visible' : 'hidden';
hs.setStyles(this.table, {
left: (pos.x - this.offset) +'px',
top: (pos.y - this.offset) +'px',
width: (pos.w + 2 * this.offset) +'px'
});
pos.w -= 2 * this.offset;
pos.h -= 2 * this.offset;
hs.setStyles (this.td[4], {
width: pos.w >= 0 ? pos.w +'px' : 0,
height: pos.h >= 0 ? pos.h +'px' : 0
});
if (this.hasAlphaImageLoader) this.td[3].style.height
= this.td[5].style.height = this.td[4].style.height;
},
destroy : function(hide) {
if (hide) this.table.style.visibility = 'hidden';
else hs.discardElement(this.table);
}
};
hs.Dimension = function(exp, dim) {
this.exp = exp;
this.dim = dim;
this.ucwh = dim == 'x' ? 'Width' : 'Height';
this.wh = this.ucwh.toLowerCase();
this.uclt = dim == 'x' ? 'Left' : 'Top';
this.lt = this.uclt.toLowerCase();
this.ucrb = dim == 'x' ? 'Right' : 'Bottom';
this.rb = this.ucrb.toLowerCase();
this.p1 = this.p2 = 0;
};
hs.Dimension.prototype = {
get : function(key) {
switch (key) {
case 'loadingPos':
return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2;
case 'wsize':
return this.size + 2 * this.cb + this.p1 + this.p2;
case 'fitsize':
return this.clientSize - this.marginMin - this.marginMax;
case 'maxsize':
return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ;
case 'opos':
return this.pos - (this.exp.outline ? this.exp.outline.offset : 0);
case 'osize':
return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0);
case 'imgPad':
return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0;
}
},
calcBorders: function() {
// correct for borders
this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2;
this.marginMax = hs['margin'+ this.ucrb];
},
calcThumb: function() {
this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) :
this.exp.el['offset'+ this.ucwh];
this.tpos = this.exp.tpos[this.dim];
this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2;
if (this.tpos == 0 || this.tpos == -1) {
this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt];
};
},
calcExpanded: function() {
var exp = this.exp;
this.justify = 'auto';
// size and position
this.pos = this.tpos - this.cb + this.tb;
if (this.dim == 'x')
exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full);
this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full);
this.minSize = exp.allowSizeReduction ?
Math.min(exp['min'+ this.ucwh], this.full) :this.full;
if (exp.isImage && exp.useBox) {
this.size = exp[this.wh];
this.imgSize = this.full;
}
if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth;
this.marginMin = hs['margin'+ this.uclt];
this.scroll = hs.page['scroll'+ this.uclt];
this.clientSize = hs.page[this.wh];
},
setSize: function(i) {
var exp = this.exp;
if (exp.isImage && (exp.useBox || hs.padToMinWidth)) {
this.imgSize = i;
this.size = Math.max(this.size, this.imgSize);
exp.content.style[this.lt] = this.get('imgPad')+'px';
} else
this.size = i;
exp.content.style[this.wh] = i +'px';
exp.wrapper.style[this.wh] = this.get('wsize') +'px';
if (exp.outline) exp.outline.setPosition();
if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true);
},
setPos: function(i) {
this.pos = i;
this.exp.wrapper.style[this.lt] = i +'px';
if (this.exp.outline) this.exp.outline.setPosition();
}
};
hs.Expander = function(a, params, custom, contentType) {
if (document.readyState && hs.ie && !hs.isReady) {
hs.addEventListener(document, 'ready', function() {
new hs.Expander(a, params, custom, contentType);
});
return;
}
this.a = a;
this.custom = custom;
this.contentType = contentType || 'image';
this.isImage = !this.isHtml;
hs.continuePreloading = false;
this.overlays = [];
hs.init();
var key = this.key = hs.expanders.length;
// override inline parameters
for (var i = 0; i < hs.overrides.length; i++) {
var name = hs.overrides[i];
this[name] = params && typeof params[name] != 'undefined' ?
params[name] : hs[name];
}
if (!this.src) this.src = a.href;
// get thumb
var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a;
el = this.thumb = el.getElementsByTagName('img')[0] || el;
this.thumbsUserSetId = el.id || a.id;
// check if already open
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].a == a) {
hs.expanders[i].focus();
return false;
}
}
// cancel other
if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) {
hs.expanders[i].cancelLoading();
}
}
hs.expanders[key] = this;
if (!hs.allowMultipleInstances && !hs.upcoming) {
if (hs.expanders[key-1]) hs.expanders[key-1].close();
if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey])
hs.expanders[hs.focusKey].close();
}
// initiate metrics
this.el = el;
this.tpos = hs.getPosition(el);
hs.getPageSize();
var x = this.x = new hs.Dimension(this, 'x');
x.calcThumb();
var y = this.y = new hs.Dimension(this, 'y');
y.calcThumb();
this.wrapper = hs.createElement(
'div', {
id: 'highslide-wrapper-'+ this.key,
className: 'highslide-wrapper '+ this.wrapperClassName
}, {
visibility: 'hidden',
position: 'absolute',
zIndex: hs.zIndexCounter += 2
}, null, true );
this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler;
if (this.contentType == 'image' && this.outlineWhileAnimating == 2)
this.outlineWhileAnimating = 0;
// get the outline
if (!this.outlineType) {
this[this.contentType +'Create']();
} else if (hs.pendingOutlines[this.outlineType]) {
this.connectOutline();
this[this.contentType +'Create']();
} else {
this.showLoading();
var exp = this;
new hs.Outline(this.outlineType,
function () {
exp.connectOutline();
exp[exp.contentType +'Create']();
}
);
}
return true;
};
hs.Expander.prototype = {
error : function(e) {
// alert ('Line '+ e.lineNumber +': '+ e.message);
window.location.href = this.src;
},
connectOutline : function() {
var outline = this.outline = hs.pendingOutlines[this.outlineType];
outline.exp = this;
outline.table.style.zIndex = this.wrapper.style.zIndex - 1;
hs.pendingOutlines[this.outlineType] = null;
},
showLoading : function() {
if (this.onLoadStarted || this.loading) return;
this.loading = hs.loading;
var exp = this;
this.loading.onclick = function() {
exp.cancelLoading();
};
var exp = this,
l = this.x.get('loadingPos') +'px',
t = this.y.get('loadingPos') +'px';
setTimeout(function () {
if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })}
, 100);
},
imageCreate : function() {
var exp = this;
var img = document.createElement('img');
this.content = img;
img.onload = function () {
if (hs.expanders[exp.key]) exp.contentLoaded();
};
if (hs.blockRightClick) img.oncontextmenu = function() { return false; };
img.className = 'highslide-image';
hs.setStyles(img, {
visibility: 'hidden',
display: 'block',
position: 'absolute',
maxWidth: '9999px',
zIndex: 3
});
img.title = hs.lang.restoreTitle;
if (hs.safari) hs.container.appendChild(img);
if (hs.ie && hs.flushImgSize) img.src = null;
img.src = this.src;
this.showLoading();
},
contentLoaded : function() {
try {
if (!this.content) return;
this.content.onload = null;
if (this.onLoadStarted) return;
else this.onLoadStarted = true;
var x = this.x, y = this.y;
if (this.loading) {
hs.setStyles(this.loading, { top: '-9999px' });
this.loading = null;
}
x.full = this.content.width;
y.full = this.content.height;
hs.setStyles(this.content, {
width: x.t +'px',
height: y.t +'px'
});
this.wrapper.appendChild(this.content);
hs.container.appendChild(this.wrapper);
x.calcBorders();
y.calcBorders();
hs.setStyles (this.wrapper, {
left: (x.tpos + x.tb - x.cb) +'px',
top: (y.tpos + x.tb - y.cb) +'px'
});
this.getOverlays();
var ratio = x.full / y.full;
x.calcExpanded();
this.justify(x);
y.calcExpanded();
this.justify(y);
if (this.overlayBox) this.sizeOverlayBox(0, 1);
if (this.allowSizeReduction) {
this.correctRatio(ratio);
if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) {
this.createFullExpand();
if (this.overlays.length == 1) this.sizeOverlayBox();
}
}
this.show();
} catch (e) {
this.error(e);
}
},
justify : function (p, moveOnly) {
var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y';
var hasMovedMin = false;
var allowReduce = p.exp.allowSizeReduction;
p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2));
if (p.pos < p.scroll + p.marginMin) {
p.pos = p.scroll + p.marginMin;
hasMovedMin = true;
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) {
if (!moveOnly && hasMovedMin && allowReduce) {
p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize'));
} else if (p.get('wsize') < p.get('fitsize')) {
p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize');
} else { // image larger than viewport
p.pos = p.scroll + p.marginMin;
if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize');
}
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos < p.marginMin) {
var tmpMin = p.pos;
p.pos = p.marginMin;
if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin);
}
},
correctRatio : function(ratio) {
var x = this.x,
y = this.y,
changed = false,
xSize = Math.min(x.full, x.size),
ySize = Math.min(y.full, y.size),
useBox = (this.useBox || hs.padToMinWidth);
if (xSize / ySize > ratio) { // width greater
xSize = ySize * ratio;
if (xSize < x.minSize) { // below minWidth
xSize = x.minSize;
ySize = xSize / ratio;
}
changed = true;
} else if (xSize / ySize < ratio) { // height greater
ySize = xSize / ratio;
changed = true;
}
if (hs.padToMinWidth && x.full < x.minSize) {
x.imgSize = x.full;
y.size = y.imgSize = y.full;
} else if (this.useBox) {
x.imgSize = xSize;
y.imgSize = ySize;
} else {
x.size = xSize;
y.size = ySize;
}
changed = this.fitOverlayBox(useBox ? null : ratio, changed);
if (useBox && y.size < y.imgSize) {
y.imgSize = y.size;
x.imgSize = y.size * ratio;
}
if (changed || useBox) {
x.pos = x.tpos - x.cb + x.tb;
x.minSize = x.size;
this.justify(x, true);
y.pos = y.tpos - y.cb + y.tb;
y.minSize = y.size;
this.justify(y, true);
if (this.overlayBox) this.sizeOverlayBox();
}
},
fitOverlayBox : function(ratio, changed) {
var x = this.x, y = this.y;
if (this.overlayBox) {
while (y.size > this.minHeight && x.size > this.minWidth
&& y.get('wsize') > y.get('fitsize')) {
y.size -= 10;
if (ratio) x.size = y.size * ratio;
this.sizeOverlayBox(0, 1);
changed = true;
}
}
return changed;
},
show : function () {
var x = this.x, y = this.y;
this.doShowHide('hidden');
// Apply size change
this.changeSize(
1, {
wrapper: {
width : x.get('wsize'),
height : y.get('wsize'),
left: x.pos,
top: y.pos
},
content: {
left: x.p1 + x.get('imgPad'),
top: y.p1 + y.get('imgPad'),
width:x.imgSize ||x.size,
height:y.imgSize ||y.size
}
},
hs.expandDuration
);
},
changeSize : function(up, to, dur) {
if (this.outline && !this.outlineWhileAnimating) {
if (up) this.outline.setPosition();
else this.outline.destroy();
}
if (!up) this.destroyOverlays();
var exp = this,
x = exp.x,
y = exp.y,
easing = this.easing;
if (!up) easing = this.easingClose || easing;
var after = up ?
function() {
if (exp.outline) exp.outline.table.style.visibility = "visible";
setTimeout(function() {
exp.afterExpand();
}, 50);
} :
function() {
exp.afterClose();
};
if (up) hs.setStyles( this.wrapper, {
width: x.t +'px',
height: y.t +'px'
});
if (this.fadeInOut) {
hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 });
hs.extend(to.wrapper, { opacity: up });
}
hs.animate( this.wrapper, to.wrapper, {
duration: dur,
easing: easing,
step: function(val, args) {
if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') {
var fac = up ? args.pos : 1 - args.pos;
var pos = {
w: x.t + (x.get('wsize') - x.t) * fac,
h: y.t + (y.get('wsize') - y.t) * fac,
x: x.tpos + (x.pos - x.tpos) * fac,
y: y.tpos + (y.pos - y.tpos) * fac
};
exp.outline.setPosition(pos, 0, 1);
}
}
});
hs.animate( this.content, to.content, dur, easing, after);
if (up) {
this.wrapper.style.visibility = 'visible';
this.content.style.visibility = 'visible';
this.a.className += ' highslide-active-anchor';
}
},
afterExpand : function() {
this.isExpanded = true;
this.focus();
if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null;
this.prepareNextOutline();
var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop;
this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize')
&& this.y.pos < mY && mY < this.y.pos + this.y.get('wsize');
if (this.overlayBox) this.showOverlays();
},
prepareNextOutline : function() {
var key = this.key;
var outlineType = this.outlineType;
new hs.Outline(outlineType,
function () { try { hs.expanders[key].preloadNext(); } catch (e) {} });
},
preloadNext : function() {
var next = this.getAdjacentAnchor(1);
if (next && next.onclick.toString().match(/hs\.expand/))
var img = hs.createElement('img', { src: hs.getSrc(next) });
},
getAdjacentAnchor : function(op) {
var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none'];
/*< ? if ($cfg->slideshow) : ?>s*/
if (!as[current + op] && this.slideshow && this.slideshow.repeat) {
if (op == 1) return as[0];
else if (op == -1) return as[as.length-1];
}
/*< ? endif ?>s*/
return as[current + op] || null;
},
getAnchorIndex : function() {
var arr = hs.getAnchors().groups[this.slideshowGroup || 'none'];
if (arr) for (var i = 0; i < arr.length; i++) {
if (arr[i] == this.a) return i;
}
return null;
},
cancelLoading : function() {
hs.discardElement (this.wrapper);
hs.expanders[this.key] = null;
if (this.loading) hs.loading.style.left = '-9999px';
},
writeCredits : function () {
this.credits = hs.createElement('a', {
href: hs.creditsHref,
target: hs.creditsTarget,
className: 'highslide-credits',
innerHTML: hs.lang.creditsText,
title: hs.lang.creditsTitle
});
this.createOverlay({
overlayId: this.credits,
position: this.creditsPosition || 'top left'
});
},
getInline : function(types, addOverlay) {
for (var i = 0; i < types.length; i++) {
var type = types[i], s = null;
if (!this[type +'Id'] && this.thumbsUserSetId)
this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId;
if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']);
if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try {
s = eval(this[type +'Eval']);
} catch (e) {}
if (!this[type] && this[type +'Text']) {
s = this[type +'Text'];
}
if (!this[type] && !s) {
this[type] = hs.getNode(this.a['_'+ type + 'Id']);
if (!this[type]) {
var next = this.a.nextSibling;
while (next && !hs.isHsAnchor(next)) {
if ((new RegExp('highslide-'+ type)).test(next.className || null)) {
if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++;
this[type] = hs.getNode(next.id);
break;
}
next = next.nextSibling;
}
}
}
if (!this[type] && s) this[type] = hs.createElement('div',
{ className: 'highslide-'+ type, innerHTML: s } );
if (addOverlay && this[type]) {
var o = { position: (type == 'heading') ? 'above' : 'below' };
for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x];
o.overlayId = this[type];
this.createOverlay(o);
}
}
},
// on end move and resize
doShowHide : function(visibility) {
if (hs.hideSelects) this.showHideElements('SELECT', visibility);
if (hs.hideIframes) this.showHideElements('IFRAME', visibility);
if (hs.geckoMac) this.showHideElements('*', visibility);
},
showHideElements : function (tagName, visibility) {
var els = document.getElementsByTagName(tagName);
var prop = tagName == '*' ? 'overflow' : 'visibility';
for (var i = 0; i < els.length; i++) {
if (prop == 'visibility' || (document.defaultView.getComputedStyle(
els[i], "").getPropertyValue('overflow') == 'auto'
|| els[i].getAttribute('hidden-by') != null)) {
var hiddenBy = els[i].getAttribute('hidden-by');
if (visibility == 'visible' && hiddenBy) {
hiddenBy = hiddenBy.replace('['+ this.key +']', '');
els[i].setAttribute('hidden-by', hiddenBy);
if (!hiddenBy) els[i].style[prop] = els[i].origProp;
} else if (visibility == 'hidden') { // hide if behind
var elPos = hs.getPosition(els[i]);
elPos.w = els[i].offsetWidth;
elPos.h = els[i].offsetHeight;
var clearsX = (elPos.x + elPos.w < this.x.get('opos')
|| elPos.x > this.x.get('opos') + this.x.get('osize'));
var clearsY = (elPos.y + elPos.h < this.y.get('opos')
|| elPos.y > this.y.get('opos') + this.y.get('osize'));
var wrapperKey = hs.getWrapperKey(els[i]);
if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image
if (!hiddenBy) {
els[i].setAttribute('hidden-by', '['+ this.key +']');
els[i].origProp = els[i].style[prop];
els[i].style[prop] = 'hidden';
} else if (hiddenBy.indexOf('['+ this.key +']') == -1) {
els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']');
}
} else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey)
&& wrapperKey != this.key) { // on move
els[i].setAttribute('hidden-by', '');
els[i].style[prop] = els[i].origProp || '';
} else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) {
els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', ''));
}
}
}
}
},
focus : function() {
this.wrapper.style.zIndex = hs.zIndexCounter += 2;
// blur others
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && i == hs.focusKey) {
var blurExp = hs.expanders[i];
blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur';
blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer';
blurExp.content.title = hs.lang.focusTitle;
}
}
// focus this
if (this.outline) this.outline.table.style.zIndex
= this.wrapper.style.zIndex - 1;
this.content.className = 'highslide-'+ this.contentType;
this.content.title = hs.lang.restoreTitle;
if (hs.restoreCursor) {
hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer';
if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand';
this.content.style.cursor = hs.styleRestoreCursor;
}
hs.focusKey = this.key;
hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
},
moveTo: function(x, y) {
this.x.setPos(x);
this.y.setPos(y);
},
resize : function (e) {
var w, h, r = e.width / e.height;
w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full));
if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full;
h = w / r;
if (h < Math.min(this.minHeight, this.y.full)) {
h = Math.min(this.minHeight, this.y.full);
if (this.isImage) w = h * r;
}
this.resizeTo(w, h);
},
resizeTo: function(w, h) {
this.y.setSize(h);
this.x.setSize(w);
this.wrapper.style.height = this.y.get('wsize') +'px';
},
close : function() {
if (this.isClosing || !this.isExpanded) return;
this.isClosing = true;
hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
try {
this.content.style.cursor = 'default';
this.changeSize(
0, {
wrapper: {
width : this.x.t,
height : this.y.t,
left: this.x.tpos - this.x.cb + this.x.tb,
top: this.y.tpos - this.y.cb + this.y.tb
},
content: {
left: 0,
top: 0,
width: this.x.t,
height: this.y.t
}
}, hs.restoreDuration
);
} catch (e) { this.afterClose(); }
},
createOverlay : function (o) {
var el = o.overlayId;
if (typeof el == 'string') el = hs.getNode(el);
if (o.html) el = hs.createElement('div', { innerHTML: o.html });
if (!el || typeof el == 'string') return;
el.style.display = 'block';
this.genOverlayBox();
var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto';
if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px';
var overlay = hs.createElement(
'div', {
id: 'hsId'+ hs.idCounter++,
hsId: o.hsId
}, {
position: 'absolute',
visibility: 'hidden',
width: width,
direction: hs.lang.cssDirection || '',
opacity: 0
},this.overlayBox,
true
);
overlay.appendChild(el);
hs.extend(overlay, {
opacity: 1,
offsetX: 0,
offsetY: 0,
dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250
});
hs.extend(overlay, o);
if (this.gotOverlays) {
this.positionOverlay(overlay);
if (!overlay.hideOnMouseOut || this.mouseIsOver)
hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur);
}
hs.push(this.overlays, hs.idCounter - 1);
},
positionOverlay : function(overlay) {
var p = overlay.position || 'middle center',
offX = overlay.offsetX,
offY = overlay.offsetY;
if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay);
if (/left$/.test(p)) overlay.style.left = offX +'px';
if (/center$/.test(p)) hs.setStyles (overlay, {
left: '50%',
marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px'
});
if (/right$/.test(p)) overlay.style.right = - offX +'px';
if (/^leftpanel$/.test(p)) {
hs.setStyles(overlay, {
right: '100%',
marginRight: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p1 = overlay.offsetWidth;
} else if (/^rightpanel$/.test(p)) {
hs.setStyles(overlay, {
left: '100%',
marginLeft: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p2 = overlay.offsetWidth;
}
if (/^top/.test(p)) overlay.style.top = offY +'px';
if (/^middle/.test(p)) hs.setStyles (overlay, {
top: '50%',
marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px'
});
if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px';
if (/^above$/.test(p)) {
hs.setStyles(overlay, {
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
bottom: '100%',
marginBottom: this.y.cb +'px',
width: 'auto'
});
this.y.p1 = overlay.offsetHeight;
} else if (/^below$/.test(p)) {
hs.setStyles(overlay, {
position: 'relative',
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
top: '100%',
marginTop: this.y.cb +'px',
width: 'auto'
});
this.y.p2 = overlay.offsetHeight;
overlay.style.position = 'absolute';
}
},
getOverlays : function() {
this.getInline(['heading', 'caption'], true);
if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move';
if (hs.showCredits) this.writeCredits();
for (var i = 0; i < hs.overlays.length; i++) {
var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup;
if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId)
|| (sg && sg === this.slideshowGroup)) {
this.createOverlay(o);
}
}
var os = [];
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
if (/panel$/.test(o.position)) this.positionOverlay(o);
else hs.push(os, o);
}
for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]);
this.gotOverlays = true;
},
genOverlayBox : function() {
if (!this.overlayBox) this.overlayBox = hs.createElement (
'div', {
className: this.wrapperClassName
}, {
position : 'absolute',
width: (this.x.size || (this.useBox ? this.width : null)
|| this.x.full) +'px',
height: (this.y.size || this.y.full) +'px',
visibility : 'hidden',
overflow : 'hidden',
zIndex : hs.ie ? 4 : 'auto'
},
hs.container,
true
);
},
sizeOverlayBox : function(doWrapper, doPanels) {
var overlayBox = this.overlayBox,
x = this.x,
y = this.y;
hs.setStyles( overlayBox, {
width: x.size +'px',
height: y.size +'px'
});
if (doWrapper || doPanels) {
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat');
if (o && /^(above|below)$/.test(o.position)) {
if (ie6) {
o.style.width = (overlayBox.offsetWidth + 2 * x.cb
+ x.p1 + x.p2) +'px';
}
y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight;
}
if (o && ie6 && /^(left|right)panel$/.test(o.position)) {
o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px';
}
}
}
if (doWrapper) {
hs.setStyles(this.content, {
top: y.p1 +'px'
});
hs.setStyles(overlayBox, {
top: (y.p1 + y.cb) +'px'
});
}
},
showOverlays : function() {
var b = this.overlayBox;
b.className = '';
hs.setStyles(b, {
top: (this.y.p1 + this.y.cb) +'px',
left: (this.x.p1 + this.x.cb) +'px',
overflow : 'visible'
});
if (hs.safari) b.style.visibility = 'visible';
this.wrapper.appendChild (b);
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
o.style.zIndex = 4;
if (!o.hideOnMouseOut || this.mouseIsOver) {
o.style.visibility = 'visible';
hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: o.opacity }, o.dur);
}
}
},
destroyOverlays : function() {
if (!this.overlays.length) return;
hs.discardElement(this.overlayBox);
},
createFullExpand : function () {
this.fullExpandLabel = hs.createElement(
'a', {
href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();',
title: hs.lang.fullExpandTitle,
className: 'highslide-full-expand'
}
);
this.createOverlay({
overlayId: this.fullExpandLabel,
position: hs.fullExpandPosition,
hideOnMouseOut: true,
opacity: hs.fullExpandOpacity
});
},
doFullExpand : function () {
try {
if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel);
this.focus();
var xSize = this.x.size;
this.resizeTo(this.x.full, this.y.full);
var xpos = this.x.pos - (this.x.size - xSize) / 2;
if (xpos < hs.marginLeft) xpos = hs.marginLeft;
this.moveTo(xpos, this.y.pos);
this.doShowHide('hidden');
} catch (e) {
this.error(e);
}
},
afterClose : function () {
this.a.className = this.a.className.replace('highslide-active-anchor', '');
this.doShowHide('visible');
if (this.outline && this.outlineWhileAnimating) this.outline.destroy();
hs.discardElement(this.wrapper);
hs.expanders[this.key] = null;
hs.reOrder();
}
};
hs.langDefaults = hs.lang;
// history
var HsExpander = hs.Expander;
if (hs.ie) {
(function () {
try {
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
hs.ready();
})();
}
hs.addEventListener(document, 'DOMContentLoaded', hs.ready);
hs.addEventListener(window, 'load', hs.ready);
// set handlers
hs.addEventListener(document, 'ready', function() {
if (hs.expandCursor) {
var style = hs.createElement('style', { type: 'text/css' }, null,
document.getElementsByTagName('HEAD')[0]);
function addRule(sel, dec) {
if (!hs.ie) {
style.appendChild(document.createTextNode(sel + " {" + dec + "}"));
} else {
var last = document.styleSheets[document.styleSheets.length - 1];
if (typeof(last.addRule) == "object") last.addRule(sel, dec);
}
}
function fix(prop) {
return 'expression( ( ( ignoreMe = document.documentElement.'+ prop +
' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );';
}
if (hs.expandCursor) addRule ('.highslide img',
'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;');
}
});
hs.addEventListener(window, 'resize', function() {
hs.getPageSize();
});
hs.addEventListener(document, 'mousemove', function(e) {
hs.mouse = { x: e.clientX, y: e.clientY };
});
hs.addEventListener(document, 'mousedown', hs.mouseClickHandler);
hs.addEventListener(document, 'mouseup', hs.mouseClickHandler);
hs.addEventListener(document, 'ready', hs.getAnchors);
hs.addEventListener(window, 'load', hs.preloadImages);
} | JavaScript |
/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
win = window,
doc = document,
nav = navigator,
domLoadFnArr = [],
regObjArr = [],
objIdArr = [],
listenersArr = [],
script,
timer = null,
storedAltContent = null,
storedAltContentId = null,
isDomLoaded = false,
isExpressInstallActive = false;
/* Centralized function for browser feature detection
- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
- User agent string detection is only used when no alternative is possible
- Is executed directly for optimal performance
*/
var ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
var a = null, fp6Crash = false;
try {
a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
}
catch(e) {
try {
a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
playerVersion = [6,0,21];
a.AllowScriptAccess = "always"; // Introduced in fp6.0.47
}
catch(e) {
if (playerVersion[0] == 6) {
fp6Crash = true;
}
}
if (!fp6Crash) {
try {
a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
}
catch(e) {}
}
}
if (!fp6Crash && a) { // a will return null when ActiveX is disabled
try {
d = a.GetVariable("$version"); // Will crash fp6.0.21/23/29
if (d) {
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
catch(e) {}
}
}
var u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = false,
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u);
/*@cc_on
ie = true;
@if (@_win32)
windows = true;
@elif (@_mac)
mac = true;
@end
@*/
return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
}();
/* Cross-browser onDomLoad
- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
*/
var onDomLoad = function() {
if (!ua.w3cdom) {
return;
}
addDomLoadEvent(main);
if (ua.ie && ua.win) {
try { // Avoid a possible Operation Aborted error
doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors
script = getElementById("__ie_ondomload");
if (script) {
addListener(script, "onreadystatechange", checkReadyState);
}
}
catch(e) {}
}
if (ua.webkit && typeof doc.readyState != UNDEF) {
timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
}
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
}
addLoadEvent(callDomLoadFunctions);
}();
function checkReadyState() {
if (script.readyState == "complete") {
script.parentNode.removeChild(script);
callDomLoadFunctions();
}
}
function callDomLoadFunctions() {
if (isDomLoaded) {
return;
}
if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
var s = createElement("span");
try { // Avoid a possible Operation Aborted error
var t = doc.getElementsByTagName("body")[0].appendChild(s);
t.parentNode.removeChild(t);
}
catch (e) {
return;
}
}
isDomLoaded = true;
if (timer) {
clearInterval(timer);
timer = null;
}
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() { // Static publishing only
var rl = regObjArr.length;
for (var i = 0; i < rl; i++) { // For each registered object element
var id = regObjArr[i].id;
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
fixParams(obj);
}
setVisibility(id, true);
}
else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
showExpressInstall(regObjArr[i]);
}
else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
displayAltContent(obj);
}
}
}
else { // If no fp is installed, we let the object element do its job (show alternative content)
setVisibility(id, true);
}
}
}
/* Fix nested param elements, which are ignored by older webkit engines
- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
- Fall back to the proprietary embed element
*/
function fixParams(obj) {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var e = createElement("embed"), a = nestedObj.attributes;
if (a) {
var al = a.length;
for (var i = 0; i < al; i++) {
if (a[i].nodeName == "DATA") {
e.setAttribute("src", a[i].nodeValue);
}
else {
e.setAttribute(a[i].nodeName, a[i].nodeValue);
}
}
}
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var j = 0; j < cl; j++) {
if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
}
}
}
obj.parentNode.replaceChild(e, obj);
}
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(regObj) {
isExpressInstallActive = true;
var obj = getElementById(regObj.id);
if (obj) {
if (regObj.altContentId) {
var ac = getElementById(regObj.altContentId);
if (ac) {
storedAltContent = ac;
storedAltContentId = regObj.altContentId;
}
}
else {
storedAltContent = abstractAltContent(obj);
}
if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
regObj.width = "310";
}
if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
regObj.height = "137";
}
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
dt = doc.title,
fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
replaceId = regObj.id;
// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceId += "SWFObjectNew";
newObj.setAttribute("id", replaceId);
obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
var fn = function() {
obj.parentNode.removeChild(obj);
};
addListener(win, "onload", fn);
}
createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
var fn = function() {
obj.parentNode.removeChild(obj);
};
addListener(win, "onload", fn);
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
var e = createElement("embed");
e.setAttribute("type", FLASH_MIME_TYPE);
for (var k in attObj) {
if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
if (k.toLowerCase() == "data") {
e.setAttribute("src", attObj[k]);
}
else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
e.setAttribute("class", attObj[k]);
}
else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
e.setAttribute(k, attObj[k]);
}
}
}
for (var l in parObj) {
if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
if (l.toLowerCase() != "movie") { // Filter out IE specific param element
e.setAttribute(l, parObj[l]);
}
}
}
el.parentNode.replaceChild(e, el);
r = e;
}
else { // Well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
if (ua.ie && ua.win) {
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
win.attachEvent("onload", function() {
removeObjectInIE(id);
});
}
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl) {
if (ua.ie && ua.mac) {
return;
}
var h = doc.getElementsByTagName("head")[0], s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", "screen");
if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
var ls = doc.styleSheets[doc.styleSheets.length - 1];
if (typeof ls.addRule == OBJECT) {
ls.addRule(sel, decl);
}
}
}
function setVisibility(id, isVisible) {
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
return;
}
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
},
getObjectById: function(objectIdStr) {
var r = null;
if (ua.w3cdom) {
var o = getElementById(objectIdStr);
if (o) {
var n = o.getElementsByTagName(OBJECT)[0];
if (!n || (n && typeof o.SetVariable != UNDEF)) {
r = o;
}
else if (typeof n.SetVariable != UNDEF) {
r = n;
}
}
}
return r;
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
return;
}
widthStr += ""; // Auto-convert to string
heightStr += "";
if (hasPlayerVersion(swfVersionStr)) {
setVisibility(replaceElemIdStr, false);
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
att[i] = attObj[i];
}
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
par[j] = parObj[j];
}
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) {
if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
}
addDomLoadEvent(function() {
createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
});
}
else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
isExpressInstallActive = true; // deferred execution
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
var regObj = {};
regObj.id = regObj.altContentId = replaceElemIdStr;
regObj.width = widthStr;
regObj.height = heightStr;
regObj.expressInstall = xiSwfUrlStr;
showExpressInstall(regObj);
});
}
},
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3cdom) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3cdom) {
removeSWF(objElemIdStr);
}
},
createCSS: function(sel, decl) {
if (ua.w3cdom) {
createCSS(sel, decl);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (param == null) {
return urlEncodeIfNecessary(q);
}
if (q) {
var pairs = q.substring(1).split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive && storedAltContent) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) {
storedAltContent.style.display = "block";
}
}
storedAltContent = null;
storedAltContentId = null;
isExpressInstallActive = false;
}
}
}
};
}();
| JavaScript |
var uploader = {
uploader_path:"plugins/uploader/",
uploader_vars:"", // default for this project
uploader:"", // upload.php
max_file_size: 4*1024,
extens: "*.jpg;*.jpeg;*.gif;*.png",
host: window.location.host,
init: function(_objID){
this.buttont_uploadID = _objID+"_button";
this.input_uploadID = _objID+"_input";
this.progress_uploadID = _objID+"_progress";
this.info_uploadID = _objID+"_info";
this.swf_uploadID = _objID+"_uploader";
$("#"+_objID).replaceWith('<div style="float: left;"><input readonly="readonly" id="'+this.input_uploadID+'"/></div><div style="float: left;"><div id="'+this.swf_uploadID+'"></div></div><br/><span id="'+this.progress_uploadID+'"></span><br/><span id="'+this.info_uploadID+'"></span><br/>');
this.run_flash_uploader();
$("#"+this.buttont_uploadID).click(function(){
uploader.browse();
});
},
swf_uploadID: null,
buttont_uploadID: null,
input_uploadID: null,
flash_uploader: null,
get_flash_uploader: function(){
//if(navigator.appName.indexOf("Microsoft") != -1) uploader.flash_uploader = eval("window."+this.swf_uploadID);
//else
uploader.flash_uploader = eval("window.document."+this.swf_uploadID);
},
run_flash_uploader: function (){
var flashvars = {
host: "http://"+this.host,
uploader_vars: uploader.uploader_vars,
extens: uploader.extens,
uploader: this.uploader
};
var params = {
wmode: 'transparent'
};
var attributes = {
id: this.swf_uploadID,
name: this.swf_uploadID
};
swfobject.embedSWF(this.uploader_path+"uploader.swf", this.swf_uploadID, 300, 24, "9.0.0",this.uploader_path+"expressInstall.swf", flashvars, params, attributes);
},
browse: function (){
uploader.get_flash_uploader();
uploader.flash_uploader.js_browse();
},
prepare_to_upload: function(file_name,file_size){
if (this.max_file_size >= file_size/1000 ){
$("#"+this.input_uploadID).attr("value",file_name);
$("#"+this.info_uploadID).html( file_name + " ("+Math.round(file_size/10000)/100 +" MB) ");
}else{
alert("plik jest zbyt duzy! "+this.max_file_size+">"+file_size/1000);
}
},
cancel: function(){
this.reset_form();
},
upload_file: function (){
this.flash_uploader.js_upload_file();
},
upload_progress: function(__progress){
$("#"+this.progress_uploadID).html(" upload progress: "+__progress+"%");
},
uploaded_ok: function (){
this.add_input_file_to_form($("#"+this.input_uploadID).attr("value"));
this.reset_form();
},
reset_form: function(){
$("#"+this.input_uploadID).attr("value","");
$("#"+this.info_uploadID).empty();
$("#"+this.progress_uploadID).empty();
},
add_input_file_to_form: function(__file){
$("#"+this.info_uploadID).after('<br/><input type="hidden" name="_files[]" value="'+__file+'"/><span style="border-bottom: solid 1px #eee;">'+__file+'</span>');
}
} | JavaScript |
addComment = {
moveForm : function(commId, parentId, respondId, postId) {
var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID');
if ( ! comm || ! respond || ! cancel || ! parent )
return;
t.respondId = respondId;
postId = postId || false;
if ( ! t.I('wp-temp-form-div') ) {
div = document.createElement('div');
div.id = 'wp-temp-form-div';
div.style.display = 'none';
respond.parentNode.insertBefore(div, respond);
}
comm.parentNode.insertBefore(respond, comm.nextSibling);
if ( post && postId )
post.value = postId;
parent.value = parentId;
cancel.style.display = '';
cancel.onclick = function() {
var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId);
if ( ! temp || ! respond )
return;
t.I('comment_parent').value = '0';
temp.parentNode.insertBefore(respond, temp);
temp.parentNode.removeChild(temp);
this.style.display = 'none';
this.onclick = null;
return false;
}
try { t.I('comment').focus(); }
catch(e) {}
return false;
},
I : function(e) {
return document.getElementById(e);
}
}
| JavaScript |
(function(d, w) {
var addEvent = function( obj, type, fn ) {
if (obj.addEventListener)
obj.addEventListener(type, fn, false);
else if (obj.attachEvent)
obj.attachEvent('on' + type, function() { return fn.call(obj, window.event);});
},
aB, hc = new RegExp('\\bhover\\b', 'g'), q = [],
rselected = new RegExp('\\bselected\\b', 'g'),
/**
* Get the timeout ID of the given element
*/
getTOID = function(el) {
var i = q.length;
while( i-- )
if ( q[i] && el == q[i][1] )
return q[i][0];
return false;
},
addHoverClass = function(t) {
var i, id, inA, hovering, ul, li,
ancestors = [],
ancestorLength = 0;
while ( t && t != aB && t != d ) {
if( 'LI' == t.nodeName.toUpperCase() ) {
ancestors[ ancestors.length ] = t;
id = getTOID(t);
if ( id )
clearTimeout( id );
t.className = t.className ? ( t.className.replace(hc, '') + ' hover' ) : 'hover';
hovering = t;
}
t = t.parentNode;
}
// Remove any selected classes.
if ( hovering && hovering.parentNode ) {
ul = hovering.parentNode;
if ( ul && 'UL' == ul.nodeName.toUpperCase() ) {
i = ul.childNodes.length;
while ( i-- ) {
li = ul.childNodes[i];
if ( li != hovering )
li.className = li.className ? li.className.replace( rselected, '' ) : '';
}
}
}
/* remove the hover class for any objects not in the immediate element's ancestry */
i = q.length;
while ( i-- ) {
inA = false;
ancestorLength = ancestors.length;
while( ancestorLength-- ) {
if ( ancestors[ ancestorLength ] == q[i][1] )
inA = true;
}
if ( ! inA )
q[i][1].className = q[i][1].className ? q[i][1].className.replace(hc, '') : '';
}
},
removeHoverClass = function(t) {
while ( t && t != aB && t != d ) {
if( 'LI' == t.nodeName.toUpperCase() ) {
(function(t) {
var to = setTimeout(function() {
t.className = t.className ? t.className.replace(hc, '') : '';
}, 500);
q[q.length] = [to, t];
})(t);
}
t = t.parentNode;
}
},
clickShortlink = function(e) {
var i, l, node,
t = e.target || e.srcElement;
// Make t the shortlink menu item, or return.
while ( true ) {
// Check if we've gone past the shortlink node,
// or if the user is clicking on the input.
if ( ! t || t == d || t == aB )
return;
// Check if we've found the shortlink node.
if ( t.id && t.id == 'wp-admin-bar-get-shortlink' )
break;
t = t.parentNode;
}
// IE doesn't support preventDefault, and does support returnValue
if ( e.preventDefault )
e.preventDefault();
e.returnValue = false;
if ( -1 == t.className.indexOf('selected') )
t.className += ' selected';
for ( i = 0, l = t.childNodes.length; i < l; i++ ) {
node = t.childNodes[i];
if ( node.className && -1 != node.className.indexOf('shortlink-input') ) {
node.focus();
node.select();
node.onblur = function() {
t.className = t.className ? t.className.replace( rselected, '' ) : '';
};
break;
}
}
return false;
};
addEvent(w, 'load', function() {
aB = d.getElementById('wpadminbar');
if ( d.body && aB ) {
d.body.appendChild( aB );
addEvent(aB, 'mouseover', function(e) {
addHoverClass( e.target || e.srcElement );
});
addEvent(aB, 'mouseout', function(e) {
removeHoverClass( e.target || e.srcElement );
});
addEvent(aB, 'click', clickShortlink );
}
if ( w.location.hash )
w.scrollBy(0,-32);
});
})(document, window);
| JavaScript |
/*
Cookie Plug-in
This plug in automatically gets all the cookies for this site and adds them to the post_params.
Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params.
The cookies will override any other post params with the same name.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.prototype.initSettings = function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point
};
}(SWFUpload.prototype.initSettings);
// refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True
SWFUpload.prototype.refreshCookies = function (sendToFlash) {
if (sendToFlash === undefined) {
sendToFlash = true;
}
sendToFlash = !!sendToFlash;
// Get the post_params object
var postParams = this.settings.post_params;
// Get the cookies
var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value;
for (i = 0; i < caLength; i++) {
c = cookieArray[i];
// Left Trim spaces
while (c.charAt(0) === " ") {
c = c.substring(1, c.length);
}
eqIndex = c.indexOf("=");
if (eqIndex > 0) {
name = c.substring(0, eqIndex);
value = c.substring(eqIndex + 1);
postParams[name] = value;
}
}
if (sendToFlash) {
this.setPostParams(postParams);
}
};
}
| JavaScript |
/*
Queue Plug-in
Features:
*Adds a cancelQueue() method for cancelling the entire queue.
*All queued files are uploaded when startUpload() is called.
*If false is returned from uploadComplete then the queue upload is stopped.
If false is not returned (strict comparison) then the queue upload is continued.
*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
Set the event handler with the queue_complete_handler setting.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.queue = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.queueSettings = {};
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.startUpload = function (fileID) {
this.queueSettings.queue_cancelled_flag = false;
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.cancelQueue = function () {
this.queueSettings.queue_cancelled_flag = true;
this.stopUpload();
var stats = this.getStats();
while (stats.files_queued > 0) {
this.cancelUpload();
stats = this.getStats();
}
};
SWFUpload.queue.uploadStartHandler = function (file) {
var returnValue;
if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
}
// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
returnValue = (returnValue === false) ? false : true;
this.queueSettings.queue_cancelled_flag = !returnValue;
return returnValue;
};
SWFUpload.queue.uploadCompleteHandler = function (file) {
var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
var continueUpload;
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
this.queueSettings.queue_upload_count++;
}
if (typeof(user_upload_complete_handler) === "function") {
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
// If the file was stopped and re-queued don't restart the upload
continueUpload = false;
} else {
continueUpload = true;
}
if (continueUpload) {
var stats = this.getStats();
if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
this.startUpload();
} else if (this.queueSettings.queue_cancelled_flag === false) {
this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
this.queueSettings.queue_upload_count = 0;
} else {
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
}
}
};
}
| JavaScript |
/*
SWFUpload.SWFObject Plugin
Summary:
This plugin uses SWFObject to embed SWFUpload dynamically in the page. SWFObject provides accurate Flash Player detection and DOM Ready loading.
This plugin replaces the Graceful Degradation plugin.
Features:
* swfupload_load_failed_hander event
* swfupload_pre_load_handler event
* minimum_flash_version setting (default: "9.0.28")
* SWFUpload.onload event for early loading
Usage:
Provide handlers and settings as needed. When using the SWFUpload.SWFObject plugin you should initialize SWFUploading
in SWFUpload.onload rather than in window.onload. When initialized this way SWFUpload can load earlier preventing the UI flicker
that was seen using the Graceful Degradation plugin.
<script type="text/javascript">
var swfu;
SWFUpload.onload = function () {
swfu = new SWFUpload({
minimum_flash_version: "9.0.28",
swfupload_pre_load_handler: swfuploadPreLoad,
swfupload_load_failed_handler: swfuploadLoadFailed
});
};
</script>
Notes:
You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8.
The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs
or corrupt Flash Player installations will not trigger this event.
The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can
be used to prepare the SWFUploadUI and hide alternate content.
swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser.
Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made.
*/
// SWFObject v2.1 must be loaded
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.onload = function () {};
swfobject.addDomLoadEvent(function () {
if (typeof(SWFUpload.onload) === "function") {
setTimeout(function(){SWFUpload.onload.call(window);}, 200);
}
});
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
this.ensureDefault("minimum_flash_version", "9.0.28");
this.ensureDefault("swfupload_pre_load_handler", null);
this.ensureDefault("swfupload_load_failed_handler", null);
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.loadFlash = function (oldLoadFlash) {
return function () {
var hasFlash = swfobject.hasFlashPlayerVersion(this.settings.minimum_flash_version);
if (hasFlash) {
this.queueEvent("swfupload_pre_load_handler");
if (typeof(oldLoadFlash) === "function") {
oldLoadFlash.call(this);
}
} else {
this.queueEvent("swfupload_load_failed_handler");
}
};
}(SWFUpload.prototype.loadFlash);
SWFUpload.prototype.displayDebugInfo = function (oldDisplayDebugInfo) {
return function () {
if (typeof(oldDisplayDebugInfo) === "function") {
oldDisplayDebugInfo.call(this);
}
this.debug(
[
"SWFUpload.SWFObject Plugin settings:", "\n",
"\t", "minimum_flash_version: ", this.settings.minimum_flash_version, "\n",
"\t", "swfupload_pre_load_handler assigned: ", (typeof(this.settings.swfupload_pre_load_handler) === "function").toString(), "\n",
"\t", "swfupload_load_failed_handler assigned: ", (typeof(this.settings.swfupload_load_failed_handler) === "function").toString(), "\n",
].join("")
);
};
}(SWFUpload.prototype.displayDebugInfo);
}
| JavaScript |
/*
Speed Plug-in
Features:
*Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc.
- currentSpeed -- String indicating the upload speed, bytes per second
- averageSpeed -- Overall average upload speed, bytes per second
- movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second
- timeRemaining -- Estimated remaining upload time in seconds
- timeElapsed -- Number of seconds passed for this upload
- percentUploaded -- Percentage of the file uploaded (0 to 100)
- sizeUploaded -- Formatted size uploaded so far, bytes
*Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed.
*Adds several Formatting functions for formatting that values provided on the file object.
- SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps)
- SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S)
- SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B )
- SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %)
- SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean)
- Formats a number using the division array to determine how to apply the labels in the Label Array
- factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed)
or as several numbers labeled with units (time)
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.speed = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// List used to keep the speed stats for the files we are tracking
this.fileSpeedStats = {};
this.speedSettings = {};
this.ensureDefault("moving_average_history_size", "10");
this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler;
this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler;
this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler;
this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler;
this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler;
this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler;
this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler;
this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler;
this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler;
this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler;
this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler;
this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler;
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.speed.fileQueuedHandler = function (file) {
if (typeof this.speedSettings.user_file_queued_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queued_handler.call(this, file);
}
};
SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) {
if (typeof this.speedSettings.user_file_queue_error_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadStartHandler = function (file) {
if (typeof this.speedSettings.user_upload_start_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_start_handler.call(this, file);
}
};
SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_error_handler === "function") {
return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) {
this.updateTracking(file, bytesComplete);
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_progress_handler === "function") {
return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal);
}
};
SWFUpload.speed.uploadSuccessHandler = function (file, serverData) {
if (typeof this.speedSettings.user_upload_success_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_success_handler.call(this, file, serverData);
}
};
SWFUpload.speed.uploadCompleteHandler = function (file) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_complete_handler === "function") {
return this.speedSettings.user_upload_complete_handler.call(this, file);
}
};
// Private: extends the file object with the speed plugin values
SWFUpload.speed.extendFile = function (file, trackingList) {
var tracking;
if (trackingList) {
tracking = trackingList[file.id];
}
if (tracking) {
file.currentSpeed = tracking.currentSpeed;
file.averageSpeed = tracking.averageSpeed;
file.movingAverageSpeed = tracking.movingAverageSpeed;
file.timeRemaining = tracking.timeRemaining;
file.timeElapsed = tracking.timeElapsed;
file.percentUploaded = tracking.percentUploaded;
file.sizeUploaded = tracking.bytesUploaded;
} else {
file.currentSpeed = 0;
file.averageSpeed = 0;
file.movingAverageSpeed = 0;
file.timeRemaining = 0;
file.timeElapsed = 0;
file.percentUploaded = 0;
file.sizeUploaded = 0;
}
return file;
};
// Private: Updates the speed tracking object, or creates it if necessary
SWFUpload.prototype.updateTracking = function (file, bytesUploaded) {
var tracking = this.fileSpeedStats[file.id];
if (!tracking) {
this.fileSpeedStats[file.id] = tracking = {};
}
// Sanity check inputs
bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0;
if (bytesUploaded < 0) {
bytesUploaded = 0;
}
if (bytesUploaded > file.size) {
bytesUploaded = file.size;
}
var tickTime = (new Date()).getTime();
if (!tracking.startTime) {
tracking.startTime = (new Date()).getTime();
tracking.lastTime = tracking.startTime;
tracking.currentSpeed = 0;
tracking.averageSpeed = 0;
tracking.movingAverageSpeed = 0;
tracking.movingAverageHistory = [];
tracking.timeRemaining = 0;
tracking.timeElapsed = 0;
tracking.percentUploaded = bytesUploaded / file.size;
tracking.bytesUploaded = bytesUploaded;
} else if (tracking.startTime > tickTime) {
this.debug("When backwards in time");
} else {
// Get time and deltas
var now = (new Date()).getTime();
var lastTime = tracking.lastTime;
var deltaTime = now - lastTime;
var deltaBytes = bytesUploaded - tracking.bytesUploaded;
if (deltaBytes === 0 || deltaTime === 0) {
return tracking;
}
// Update tracking object
tracking.lastTime = now;
tracking.bytesUploaded = bytesUploaded;
// Calculate speeds
tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000);
tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000);
// Calculate moving average
tracking.movingAverageHistory.push(tracking.currentSpeed);
if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) {
tracking.movingAverageHistory.shift();
}
tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory);
// Update times
tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed;
tracking.timeElapsed = (now - tracking.startTime) / 1000;
// Update percent
tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100);
}
return tracking;
};
SWFUpload.speed.removeTracking = function (file, trackingList) {
try {
trackingList[file.id] = null;
delete trackingList[file.id];
} catch (ex) {
}
};
SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) {
var i, unit, unitDivisor, unitLabel;
if (baseNumber === 0) {
return "0 " + unitLabels[unitLabels.length - 1];
}
if (singleFractional) {
unit = baseNumber;
unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : "";
for (i = 0; i < unitDivisors.length; i++) {
if (baseNumber >= unitDivisors[i]) {
unit = (baseNumber / unitDivisors[i]).toFixed(2);
unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : "";
break;
}
}
return unit + unitLabel;
} else {
var formattedStrings = [];
var remainder = baseNumber;
for (i = 0; i < unitDivisors.length; i++) {
unitDivisor = unitDivisors[i];
unitLabel = unitLabels.length > i ? " " + unitLabels[i] : "";
unit = remainder / unitDivisor;
if (i < unitDivisors.length -1) {
unit = Math.floor(unit);
} else {
unit = unit.toFixed(2);
}
if (unit > 0) {
remainder = remainder % unitDivisor;
formattedStrings.push(unit + unitLabel);
}
}
return formattedStrings.join(" ");
}
};
SWFUpload.speed.formatBPS = function (baseNumber) {
var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"];
return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true);
};
SWFUpload.speed.formatTime = function (baseNumber) {
var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"];
return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false);
};
SWFUpload.speed.formatBytes = function (baseNumber) {
var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"];
return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true);
};
SWFUpload.speed.formatPercent = function (baseNumber) {
return baseNumber.toFixed(2) + " %";
};
SWFUpload.speed.calculateMovingAverage = function (history) {
var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0;
var i;
var mSum = 0, mCount = 0;
size = history.length;
// Check for sufficient data
if (size >= 8) {
// Clone the array and Calculate sum of the values
for (i = 0; i < size; i++) {
vals[i] = history[i];
sum += vals[i];
}
mean = sum / size;
// Calculate variance for the set
for (i = 0; i < size; i++) {
varianceTemp += Math.pow((vals[i] - mean), 2);
}
variance = varianceTemp / size;
standardDev = Math.sqrt(variance);
//Standardize the Data
for (i = 0; i < size; i++) {
vals[i] = (vals[i] - mean) / standardDev;
}
// Calculate the average excluding outliers
var deviationRange = 2.0;
for (i = 0; i < size; i++) {
if (vals[i] <= deviationRange && vals[i] >= -deviationRange) {
mCount++;
mSum += history[i];
}
}
} else {
// Calculate the average (not enough data points to remove outliers)
mCount = size;
for (i = 0; i < size; i++) {
mSum += history[i];
}
}
return mSum / mCount;
};
} | JavaScript |
var topWin = window.dialogArguments || opener || parent || top;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
// Collapse a single item
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.describe-toggle-on').show();
jQuery('.describe-toggle-off').hide();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Create a progress bar containing the filename
jQuery('#media-items').append('<div id="media-item-' + fileObj.id + '" class="media-item child-of-' + post_id + '"><div class="progress"><div class="bar"></div></div><div class="filename original"><span class="percent"></span> ' + fileObj.name + '</div></div>');
// Display the progress div
jQuery('.progress', '#media-item-' + fileObj.id).show();
// Disable submit and enable cancel
jQuery('#insert-gallery').prop('disabled', true);
jQuery('#cancel-upload').prop('disabled', false);
}
function uploadStart(fileObj) {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(fileObj, bytesDone, bytesTotal) {
// Lengthen the progress bar
var w = jQuery('#media-items').width() - 2, item = jQuery('#media-item-' + fileObj.id);
jQuery('.bar', item).width( w * bytesDone / bytesTotal );
jQuery('.percent', item).html( Math.ceil(bytesDone / bytesTotal * 100) + '%' );
if ( bytesDone == bytesTotal )
jQuery('.bar', item).html('<strong class="crunching">' + swfuploadL10n.crunching + '</strong>');
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
// Move the progress bar to 100%
jQuery('.bar', item).remove();
jQuery('.progress', item).hide();
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
// Old style: Append the HTML returned by the server -- thumbnail and form inputs
if ( isNaN(serverData) || !serverData ) {
item.append(serverData);
prepareMediaItemInit(fileObj);
}
// New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
else {
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Also bind toggle to the links
jQuery('a.toggle', item).click(function(){
jQuery(this).siblings('.slidetoggle').slideToggle(350, function(){
var w = jQuery(window).height(), t = jQuery(this).offset().top, h = jQuery(this).height(), b;
if ( w && t && h ) {
b = t + h;
if ( b > w && (h + 48) < w )
window.scrollBy(0, b - w + 13);
else if ( b > w )
window.scrollTo(0, t - 36);
}
});
jQuery(this).siblings('.toggle').andSelf().toggle();
jQuery(this).siblings('a.toggle').focus();
return false;
});
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: 'admin-ajax.php',
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: 'admin-ajax.php',
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('a.describe-toggle-on, .menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').slideToggle(500).siblings('.toggle').toggle();
}
function itemAjaxError(id, html) {
var item = jQuery('#media-item-' + id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ html
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + swfuploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function updateMediaForm() {
var one = jQuery('form.type-form #media-items').children(), items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( one.length == 1 ) {
jQuery('.slidetoggle', one).slideDown(500).siblings().addClass('hidden').filter('.toggle').toggle();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
// Only show Gallery button when there are at least two files.
if ( items.length > 1 )
jQuery('.insert-gallery').show();
else
jQuery('.insert-gallery').hide();
}
function uploadSuccess(fileObj, serverData) {
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match('media-upload-error') ) {
jQuery('#media-item-' + fileObj.id).html(serverData);
return;
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function uploadComplete(fileObj) {
// If no more uploads queued, enable the submit button
if ( swfu.getStats().files_queued == 0 ) {
jQuery('#cancel-upload').prop('disabled', true);
jQuery('#insert-gallery').prop('disabled', false);
}
}
// wp-specific error handlers
// generic message
function wpQueueError(message) {
jQuery('#media-upload-error').show().text(message);
}
// file-specific message
function wpFileError(fileObj, message) {
var item = jQuery('#media-item-' + fileObj.id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ message
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function fileQueueError(fileObj, error_code, message) {
// Handle this error separately because we don't want to create a FileProgress element for it.
if ( error_code == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED ) {
wpQueueError(swfuploadL10n.queue_limit_exceeded);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.file_exceeds_size_limit);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.zero_byte_file);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.invalid_filetype);
}
else {
wpQueueError(swfuploadL10n.default_error);
}
}
function fileDialogComplete(num_files_queued) {
try {
if (num_files_queued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function switchUploader(s) {
var f = document.getElementById(swfu.customSettings.swfupload_element_id), h = document.getElementById(swfu.customSettings.degraded_element_id);
if ( s ) {
f.style.display = 'block';
h.style.display = 'none';
} else {
f.style.display = 'none';
h.style.display = 'block';
}
}
function swfuploadPreLoad() {
if ( !uploaderMode ) {
switchUploader(1);
} else {
switchUploader(0);
}
}
function swfuploadLoadFailed() {
switchUploader(0);
jQuery('.upload-html-bypass').hide();
}
function uploadError(fileObj, errorCode, message) {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
wpFileError(fileObj, swfuploadL10n.missing_upload_url);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
wpFileError(fileObj, swfuploadL10n.upload_limit_exceeded);
break;
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
wpQueueError(swfuploadL10n.http_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
wpQueueError(swfuploadL10n.upload_failed);
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
wpQueueError(swfuploadL10n.io_error);
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
wpQueueError(swfuploadL10n.security_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;
default:
wpFileError(fileObj, swfuploadL10n.default_error);
}
}
function cancelUpload() {
swfu.cancelQueue();
}
// remember the last used image size, alignment and url
jQuery(document).ready(function($){
$('input[type="radio"]', '#media-items').live('click', function(){
var tr = $(this).closest('tr');
if ( $(tr).hasClass('align') )
setUserSetting('align', $(this).val());
else if ( $(tr).hasClass('image-size') )
setUserSetting('imgsize', $(this).val());
});
$('button.button', '#media-items').live('click', function(){
var c = this.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
$(this).siblings('.urlfield').val( $(this).attr('title') );
}
});
});
| JavaScript |
/**
* Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://www.opensource.org/licenses/bsd-license.php
*
* See scriptaculous.js for full scriptaculous licence
*/
var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{});
if(this.options.minWidth>0&&this.options.minHeight>0){
this.options.ratioDim.x=this.options.minWidth;
this.options.ratioDim.y=this.options.minHeight;
}
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){return 1;
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
if(this.isIE){
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
}else{
this.overlay=Builder.node("div",{"class":_f+"overlay"});
var _12=[this.overlay];
}
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"});
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_13.length;i++){
Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
if(!this.isIE){
Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"});
Element.hide($(this.overlay));
Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"});
}else{
Element.setStyle($(this.north),{height:0});
Element.setStyle($(this.east),{width:0,height:0});
Element.setStyle($(this.south),{height:0});
Element.setStyle($(this.west),{width:0,height:0});
}
Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"});
Element.hide($(this.selArea));
var _15=Position.positionedOffset(this.imgWrap);
this.wrapOffsets={"top":_15[1],"left":_15[0]};
var _16={x1:0,y1:0,x2:0,y2:0};
this.setAreaCoords(_16);
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){
_16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_16.x2=_16.x1+this.options.ratioDim.x;
_16.y2=_16.y1+this.options.ratioDim.y;
Element.show(this.selArea);
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_17.length;i++){
Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1b){
this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true);
this.drawArea();
},cloneCoords:function(_1c){
return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2};
},setAreaCoords:function(_1d,_1e,_1f,_20,_21){
var _22=typeof _1e!="undefined"?_1e:false;
var _23=typeof _1f!="undefined"?_1f:false;
if(_1e){
var _24=_1d.x2-_1d.x1;
var _25=_1d.y2-_1d.y1;
if(_1d.x1<0){
_1d.x1=0;
_1d.x2=_24;
}
if(_1d.y1<0){
_1d.y1=0;
_1d.y2=_25;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
_1d.x1=this.imgW-_24;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
_1d.y1=this.imgH-_25;
}
}else{
if(_1d.x1<0){
_1d.x1=0;
}
if(_1d.y1<0){
_1d.y1=0;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
}
if(typeof (_20)!="undefined"){
if(this.ratioX>0){
this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21);
}else{
if(_23){
this.applyRatio(_1d,{x:1,y:1},_20,_21);
}
}
var _26={a1:_1d.x1,a2:_1d.x2};
var _27={a1:_1d.y1,a2:_1d.y2};
var _28=this.options.minWidth;
var _29=this.options.minHeight;
if((_28==0||_29==0)&&_23){
if(_28>0){
_29=_28;
}else{
if(_29>0){
_28=_29;
}
}
}
this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW});
this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH});
_1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2};
}
}
this.areaCoords=_1d;
},applyMinDimension:function(_2a,_2b,_2c,_2d){
if((_2a.a2-_2a.a1)<_2b){
if(_2c==1){
_2a.a2=_2a.a1+_2b;
}else{
_2a.a1=_2a.a2-_2b;
}
if(_2a.a1<_2d.min){
_2a.a1=_2d.min;
_2a.a2=_2b;
}else{
if(_2a.a2>_2d.max){
_2a.a1=_2d.max-_2b;
_2a.a2=_2d.max;
}
}
}
},applyRatio:function(_2e,_2f,_30,_31){
var _32;
if(_31=="N"||_31=="S"){
_32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW});
_2e.x1=_32.b1;
_2e.y1=_32.a1;
_2e.x2=_32.b2;
_2e.y2=_32.a2;
}else{
_32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH});
_2e.x1=_32.a1;
_2e.y1=_32.b1;
_2e.x2=_32.a2;
_2e.y2=_32.b2;
}
},applyRatioToAxis:function(_33,_34,_35,_36){
var _37=Object.extend(_33,{});
var _38=_37.a2-_37.a1;
var _3a=Math.floor(_38*_34.b/_34.a);
var _3b;
var _3c;
var _3d=null;
if(_35.b==1){
_3b=_37.b1+_3a;
if(_3b>_36.max){
_3b=_36.max;
_3d=_3b-_37.b1;
}
_37.b2=_3b;
}else{
_3b=_37.b2-_3a;
if(_3b<_36.min){
_3b=_36.min;
_3d=_3b+_37.b2;
}
_37.b1=_3b;
}
if(_3d!=null){
_3c=Math.floor(_3d*_34.a/_34.b);
if(_35.a==1){
_37.a2=_37.a1+_3c;
}else{
_37.a1=_37.a1=_37.a2-_3c;
}
}
return _37;
},drawArea:function(){
if(!this.isIE){
Element.show($(this.overlay));
}
var _3e=this.calcW();
var _3f=this.calcH();
var _40=this.areaCoords.x2;
var _41=this.areaCoords.y2;
var _42=this.selArea.style;
_42.left=this.areaCoords.x1+"px";
_42.top=this.areaCoords.y1+"px";
_42.width=_3e+"px";
_42.height=_3f+"px";
var _43=Math.ceil((_3e-6)/2)+"px";
var _44=Math.ceil((_3f-6)/2)+"px";
this.handleN.style.left=_43;
this.handleE.style.top=_44;
this.handleS.style.left=_43;
this.handleW.style.top=_44;
if(this.isIE){
this.north.style.height=this.areaCoords.y1+"px";
var _45=this.east.style;
_45.top=this.areaCoords.y1+"px";
_45.height=_3f+"px";
_45.left=_40+"px";
_45.width=(this.img.width-_40)+"px";
var _46=this.south.style;
_46.top=_41+"px";
_46.height=(this.img.height-_41)+"px";
var _47=this.west.style;
_47.top=this.areaCoords.y1+"px";
_47.height=_3f+"px";
_47.width=this.areaCoords.x1+"px";
}else{
_42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px";
}
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4a=["SE","S","SW"];
for(i=0;i<_4a.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
Element.show(this.selArea);
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y});
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top};
},onDrag:function(e){
var _4f=null;
if(this.dragging||this.resizing){
var _50=this.getCurPos(e);
var _51=this.cloneCoords(this.areaCoords);
var _52={x:1,y:1};
}
if(this.dragging){
if(_50.x<this.clickCoords.x){
_52.x=-1;
}
if(_50.y<this.clickCoords.y){
_52.y=-1;
}
this.transformCoords(_50.x,this.clickCoords.x,_51,"x");
this.transformCoords(_50.y,this.clickCoords.y,_51,"y");
}else{
if(this.resizing){
_4f=this.resizeHandle;
if(_4f.match(/E/)){
this.transformCoords(_50.x,this.startCoords.x1,_51,"x");
if(_50.x<this.startCoords.x1){
_52.x=-1;
}
}else{
if(_4f.match(/W/)){
this.transformCoords(_50.x,this.startCoords.x2,_51,"x");
if(_50.x<this.startCoords.x2){
_52.x=-1;
}
}
}
if(_4f.match(/N/)){
this.transformCoords(_50.y,this.startCoords.y2,_51,"y");
if(_50.y<this.startCoords.y2){
_52.y=-1;
}
}else{
if(_4f.match(/S/)){
this.transformCoords(_50.y,this.startCoords.y1,_51,"y");
if(_50.y<this.startCoords.y1){
_52.y=-1;
}
}
}
}
}
if(this.dragging||this.resizing){
this.setAreaCoords(_51,false,e.shiftKey,_52,_4f);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_53,_54,_55,_56){
var _57=new Array();
if(_53<_54){
_57[0]=_53;
_57[1]=_54;
}else{
_57[0]=_54;
_57[1]=_53;
}
if(_56=="x"){
_55.x1=_57[0];
_55.x2=_57[1];
}else{
_55.y1=_57[0];
_55.y2=_57[1];
}
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.options.displayOnInit=true;
this.hasPreviewImg=true;
Element.addClassName(this.previewWrap,"imgCrop_previewWrap");
Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _58=this.calcW();
var _59=this.calcH();
var _5a={x:this.imgW/_58,y:this.imgH/_59};
var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight};
var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"};
var _5d=this.previewImg.style;
_5d.width=_5c.w;
_5d.height=_5c.h;
_5d.left=_5c.x;
_5d.top=_5c.y;
}
}});
| JavaScript |
/**
* jquery.Jcrop.js v0.9.8
* jQuery Image Cropping Plugin
* @author Kelly Hallman <khallman@gmail.com>
* Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* }}}
*/
(function($) {
$.Jcrop = function(obj,opt)
{
// Initialization {{{
// Sanitize some options {{{
var obj = obj, opt = opt;
if (typeof(obj) !== 'object') obj = $(obj)[0];
if (typeof(opt) !== 'object') opt = { };
// Some on-the-fly fixes for MSIE...sigh
if (!('trackDocument' in opt))
{
opt.trackDocument = $.browser.msie ? false : true;
if ($.browser.msie && $.browser.version.split('.')[0] == '8')
opt.trackDocument = true;
}
if (!('keySupport' in opt))
opt.keySupport = $.browser.msie ? false : true;
// }}}
// Extend the default options {{{
var defaults = {
// Basic Settings
trackDocument: false,
baseClass: 'jcrop',
addClass: null,
// Styling Options
bgColor: 'black',
bgOpacity: .6,
borderOpacity: .4,
handleOpacity: .5,
handlePad: 5,
handleSize: 9,
handleOffset: 5,
edgeMargin: 14,
aspectRatio: 0,
keySupport: true,
cornerHandles: true,
sideHandles: true,
drawBorders: true,
dragEdges: true,
boxWidth: 0,
boxHeight: 0,
boundary: 8,
animationDelay: 20,
swingSpeed: 3,
allowSelect: true,
allowMove: true,
allowResize: true,
minSelect: [ 0, 0 ],
maxSize: [ 0, 0 ],
minSize: [ 0, 0 ],
// Callbacks / Event Handlers
onChange: function() { },
onSelect: function() { }
};
var options = defaults;
setOptions(opt);
// }}}
// Initialize some jQuery objects {{{
var $origimg = $(obj);
var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' });
$img.width($origimg.width());
$img.height($origimg.height());
$origimg.after($img).hide();
presize($img,options.boxWidth,options.boxHeight);
var boundx = $img.width(),
boundy = $img.height(),
$div = $('<div />')
.width(boundx).height(boundy)
.addClass(cssClass('holder'))
.css({
position: 'relative',
backgroundColor: options.bgColor
}).insertAfter($origimg).append($img);
;
if (options.addClass) $div.addClass(options.addClass);
//$img.wrap($div);
var $img2 = $('<img />')/*{{{*/
.attr('src',$img.attr('src'))
.css('position','absolute')
.width(boundx).height(boundy)
;/*}}}*/
var $img_holder = $('<div />')/*{{{*/
.width(pct(100)).height(pct(100))
.css({
zIndex: 310,
position: 'absolute',
overflow: 'hidden'
})
.append($img2)
;/*}}}*/
var $hdl_holder = $('<div />')/*{{{*/
.width(pct(100)).height(pct(100))
.css('zIndex',320);
/*}}}*/
var $sel = $('<div />')/*{{{*/
.css({
position: 'absolute',
zIndex: 300
})
.insertBefore($img)
.append($img_holder,$hdl_holder)
;/*}}}*/
var bound = options.boundary;
var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2))
.css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 })
.mousedown(newSelection);
/* }}} */
// Set more variables {{{
var xlimit, ylimit, xmin, ymin;
var xscale, yscale, enabled = true;
var docOffset = getPos($img),
// Internal states
btndown, lastcurs, dimmed, animating,
shift_down;
// }}}
// }}}
// Internal Modules {{{
var Coords = function()/*{{{*/
{
var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy;
function setPressed(pos)/*{{{*/
{
var pos = rebound(pos);
x2 = x1 = pos[0];
y2 = y1 = pos[1];
};
/*}}}*/
function setCurrent(pos)/*{{{*/
{
var pos = rebound(pos);
ox = pos[0] - x2;
oy = pos[1] - y2;
x2 = pos[0];
y2 = pos[1];
};
/*}}}*/
function getOffset()/*{{{*/
{
return [ ox, oy ];
};
/*}}}*/
function moveOffset(offset)/*{{{*/
{
var ox = offset[0], oy = offset[1];
if (0 > x1 + ox) ox -= ox + x1;
if (0 > y1 + oy) oy -= oy + y1;
if (boundy < y2 + oy) oy += boundy - (y2 + oy);
if (boundx < x2 + ox) ox += boundx - (x2 + ox);
x1 += ox;
x2 += ox;
y1 += oy;
y2 += oy;
};
/*}}}*/
function getCorner(ord)/*{{{*/
{
var c = getFixed();
switch(ord)
{
case 'ne': return [ c.x2, c.y ];
case 'nw': return [ c.x, c.y ];
case 'se': return [ c.x2, c.y2 ];
case 'sw': return [ c.x, c.y2 ];
}
};
/*}}}*/
function getFixed()/*{{{*/
{
if (!options.aspectRatio) return getRect();
// This function could use some optimization I think...
var aspect = options.aspectRatio,
min_x = options.minSize[0]/xscale,
min_y = options.minSize[1]/yscale,
max_x = options.maxSize[0]/xscale,
max_y = options.maxSize[1]/yscale,
rw = x2 - x1,
rh = y2 - y1,
rwa = Math.abs(rw),
rha = Math.abs(rh),
real_ratio = rwa / rha,
xx, yy
;
if (max_x == 0) { max_x = boundx * 10 }
if (max_y == 0) { max_y = boundy * 10 }
if (real_ratio < aspect)
{
yy = y2;
w = rha * aspect;
xx = rw < 0 ? x1 - w : w + x1;
if (xx < 0)
{
xx = 0;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h: h + y1;
}
else if (xx > boundx)
{
xx = boundx;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
}
}
else
{
xx = x2;
h = rwa / aspect;
yy = rh < 0 ? y1 - h : y1 + h;
if (yy < 0)
{
yy = 0;
w = Math.abs((yy - y1) * aspect);
xx = rw < 0 ? x1 - w : w + x1;
}
else if (yy > boundy)
{
yy = boundy;
w = Math.abs(yy - y1) * aspect;
xx = rw < 0 ? x1 - w : w + x1;
}
}
// Magic %-)
if(xx > x1) { // right side
if(xx - x1 < min_x) {
xx = x1 + min_x;
} else if (xx - x1 > max_x) {
xx = x1 + max_x;
}
if(yy > y1) {
yy = y1 + (xx - x1)/aspect;
} else {
yy = y1 - (xx - x1)/aspect;
}
} else if (xx < x1) { // left side
if(x1 - xx < min_x) {
xx = x1 - min_x
} else if (x1 - xx > max_x) {
xx = x1 - max_x;
}
if(yy > y1) {
yy = y1 + (x1 - xx)/aspect;
} else {
yy = y1 - (x1 - xx)/aspect;
}
}
if(xx < 0) {
x1 -= xx;
xx = 0;
} else if (xx > boundx) {
x1 -= xx - boundx;
xx = boundx;
}
if(yy < 0) {
y1 -= yy;
yy = 0;
} else if (yy > boundy) {
y1 -= yy - boundy;
yy = boundy;
}
return last = makeObj(flipCoords(x1,y1,xx,yy));
};
/*}}}*/
function rebound(p)/*{{{*/
{
if (p[0] < 0) p[0] = 0;
if (p[1] < 0) p[1] = 0;
if (p[0] > boundx) p[0] = boundx;
if (p[1] > boundy) p[1] = boundy;
return [ p[0], p[1] ];
};
/*}}}*/
function flipCoords(x1,y1,x2,y2)/*{{{*/
{
var xa = x1, xb = x2, ya = y1, yb = y2;
if (x2 < x1)
{
xa = x2;
xb = x1;
}
if (y2 < y1)
{
ya = y2;
yb = y1;
}
return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ];
};
/*}}}*/
function getRect()/*{{{*/
{
var xsize = x2 - x1;
var ysize = y2 - y1;
if (xlimit && (Math.abs(xsize) > xlimit))
x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
if (ylimit && (Math.abs(ysize) > ylimit))
y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);
if (ymin && (Math.abs(ysize) < ymin))
y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin);
if (xmin && (Math.abs(xsize) < xmin))
x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin);
if (x1 < 0) { x2 -= x1; x1 -= x1; }
if (y1 < 0) { y2 -= y1; y1 -= y1; }
if (x2 < 0) { x1 -= x2; x2 -= x2; }
if (y2 < 0) { y1 -= y2; y2 -= y2; }
if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; }
if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; }
if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; }
if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; }
return makeObj(flipCoords(x1,y1,x2,y2));
};
/*}}}*/
function makeObj(a)/*{{{*/
{
return { x: a[0], y: a[1], x2: a[2], y2: a[3],
w: a[2] - a[0], h: a[3] - a[1] };
};
/*}}}*/
return {
flipCoords: flipCoords,
setPressed: setPressed,
setCurrent: setCurrent,
getOffset: getOffset,
moveOffset: moveOffset,
getCorner: getCorner,
getFixed: getFixed
};
}();
/*}}}*/
var Selection = function()/*{{{*/
{
var start, end, dragmode, awake, hdep = 370;
var borders = { };
var handle = { };
var seehandles = false;
var hhs = options.handleOffset;
/* Insert draggable elements {{{*/
// Insert border divs for outline
if (options.drawBorders) {
borders = {
top: insertBorder('hline')
.css('top',$.browser.msie?px(-1):px(0)),
bottom: insertBorder('hline'),
left: insertBorder('vline'),
right: insertBorder('vline')
};
}
// Insert handles on edges
if (options.dragEdges) {
handle.t = insertDragbar('n');
handle.b = insertDragbar('s');
handle.r = insertDragbar('e');
handle.l = insertDragbar('w');
}
// Insert side handles
options.sideHandles &&
createHandles(['n','s','e','w']);
// Insert corner handles
options.cornerHandles &&
createHandles(['sw','nw','ne','se']);
/*}}}*/
// Private Methods
function insertBorder(type)/*{{{*/
{
var jq = $('<div />')
.css({position: 'absolute', opacity: options.borderOpacity })
.addClass(cssClass(type));
$img_holder.append(jq);
return jq;
};
/*}}}*/
function dragDiv(ord,zi)/*{{{*/
{
var jq = $('<div />')
.mousedown(createDragger(ord))
.css({
cursor: ord+'-resize',
position: 'absolute',
zIndex: zi
})
;
$hdl_holder.append(jq);
return jq;
};
/*}}}*/
function insertHandle(ord)/*{{{*/
{
return dragDiv(ord,hdep++)
.css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity })
.addClass(cssClass('handle'));
};
/*}}}*/
function insertDragbar(ord)/*{{{*/
{
var s = options.handleSize,
o = hhs,
h = s, w = s,
t = o, l = o;
switch(ord)
{
case 'n': case 's': w = pct(100); break;
case 'e': case 'w': h = pct(100); break;
}
return dragDiv(ord,hdep++).width(w).height(h)
.css({ top: px(-t+1), left: px(-l+1)});
};
/*}}}*/
function createHandles(li)/*{{{*/
{
for(i in li) handle[li[i]] = insertHandle(li[i]);
};
/*}}}*/
function moveHandles(c)/*{{{*/
{
var midvert = Math.round((c.h / 2) - hhs),
midhoriz = Math.round((c.w / 2) - hhs),
north = west = -hhs+1,
east = c.w - hhs,
south = c.h - hhs,
x, y;
'e' in handle &&
handle.e.css({ top: px(midvert), left: px(east) }) &&
handle.w.css({ top: px(midvert) }) &&
handle.s.css({ top: px(south), left: px(midhoriz) }) &&
handle.n.css({ left: px(midhoriz) });
'ne' in handle &&
handle.ne.css({ left: px(east) }) &&
handle.se.css({ top: px(south), left: px(east) }) &&
handle.sw.css({ top: px(south) });
'b' in handle &&
handle.b.css({ top: px(south) }) &&
handle.r.css({ left: px(east) });
};
/*}}}*/
function moveto(x,y)/*{{{*/
{
$img2.css({ top: px(-y), left: px(-x) });
$sel.css({ top: px(y), left: px(x) });
};
/*}}}*/
function resize(w,h)/*{{{*/
{
$sel.width(w).height(h);
};
/*}}}*/
function refresh()/*{{{*/
{
var c = Coords.getFixed();
Coords.setPressed([c.x,c.y]);
Coords.setCurrent([c.x2,c.y2]);
updateVisible();
};
/*}}}*/
// Internal Methods
function updateVisible()/*{{{*/
{ if (awake) return update(); };
/*}}}*/
function update()/*{{{*/
{
var c = Coords.getFixed();
resize(c.w,c.h);
moveto(c.x,c.y);
options.drawBorders &&
borders['right'].css({ left: px(c.w-1) }) &&
borders['bottom'].css({ top: px(c.h-1) });
seehandles && moveHandles(c);
awake || show();
options.onChange(unscale(c));
};
/*}}}*/
function show()/*{{{*/
{
$sel.show();
$img.css('opacity',options.bgOpacity);
awake = true;
};
/*}}}*/
function release()/*{{{*/
{
disableHandles();
$sel.hide();
$img.css('opacity',1);
awake = false;
};
/*}}}*/
function showHandles()//{{{
{
if (seehandles)
{
moveHandles(Coords.getFixed());
$hdl_holder.show();
}
};
//}}}
function enableHandles()/*{{{*/
{
seehandles = true;
if (options.allowResize)
{
moveHandles(Coords.getFixed());
$hdl_holder.show();
return true;
}
};
/*}}}*/
function disableHandles()/*{{{*/
{
seehandles = false;
$hdl_holder.hide();
};
/*}}}*/
function animMode(v)/*{{{*/
{
(animating = v) ? disableHandles(): enableHandles();
};
/*}}}*/
function done()/*{{{*/
{
animMode(false);
refresh();
};
/*}}}*/
var $track = newTracker().mousedown(createDragger('move'))
.css({ cursor: 'move', position: 'absolute', zIndex: 360 })
$img_holder.append($track);
disableHandles();
return {
updateVisible: updateVisible,
update: update,
release: release,
refresh: refresh,
setCursor: function (cursor) { $track.css('cursor',cursor); },
enableHandles: enableHandles,
enableOnly: function() { seehandles = true; },
showHandles: showHandles,
disableHandles: disableHandles,
animMode: animMode,
done: done
};
}();
/*}}}*/
var Tracker = function()/*{{{*/
{
var onMove = function() { },
onDone = function() { },
trackDoc = options.trackDocument;
if (!trackDoc)
{
$trk
.mousemove(trackMove)
.mouseup(trackUp)
.mouseout(trackUp)
;
}
function toFront()/*{{{*/
{
$trk.css({zIndex:450});
if (trackDoc)
{
$(document)
.mousemove(trackMove)
.mouseup(trackUp)
;
}
}
/*}}}*/
function toBack()/*{{{*/
{
$trk.css({zIndex:290});
if (trackDoc)
{
$(document)
.unbind('mousemove',trackMove)
.unbind('mouseup',trackUp)
;
}
}
/*}}}*/
function trackMove(e)/*{{{*/
{
onMove(mouseAbs(e));
};
/*}}}*/
function trackUp(e)/*{{{*/
{
e.preventDefault();
e.stopPropagation();
if (btndown)
{
btndown = false;
onDone(mouseAbs(e));
options.onSelect(unscale(Coords.getFixed()));
toBack();
onMove = function() { };
onDone = function() { };
}
return false;
};
/*}}}*/
function activateHandlers(move,done)/* {{{ */
{
btndown = true;
onMove = move;
onDone = done;
toFront();
return false;
};
/* }}} */
function setCursor(t) { $trk.css('cursor',t); };
$img.before($trk);
return {
activateHandlers: activateHandlers,
setCursor: setCursor
};
}();
/*}}}*/
var KeyManager = function()/*{{{*/
{
var $keymgr = $('<input type="radio" />')
.css({ position: 'absolute', left: '-30px' })
.keypress(parseKey)
.blur(onBlur),
$keywrap = $('<div />')
.css({
position: 'absolute',
overflow: 'hidden'
})
.append($keymgr)
;
function watchKeys()/*{{{*/
{
if (options.keySupport)
{
$keymgr.show();
$keymgr.focus();
}
};
/*}}}*/
function onBlur(e)/*{{{*/
{
$keymgr.hide();
};
/*}}}*/
function doNudge(e,x,y)/*{{{*/
{
if (options.allowMove) {
Coords.moveOffset([x,y]);
Selection.updateVisible();
};
e.preventDefault();
e.stopPropagation();
};
/*}}}*/
function parseKey(e)/*{{{*/
{
if (e.ctrlKey) return true;
shift_down = e.shiftKey ? true : false;
var nudge = shift_down ? 10 : 1;
switch(e.keyCode)
{
case 37: doNudge(e,-nudge,0); break;
case 39: doNudge(e,nudge,0); break;
case 38: doNudge(e,0,-nudge); break;
case 40: doNudge(e,0,nudge); break;
case 27: Selection.release(); break;
case 9: return true;
}
return nothing(e);
};
/*}}}*/
if (options.keySupport) $keywrap.insertBefore($img);
return {
watchKeys: watchKeys
};
}();
/*}}}*/
// }}}
// Internal Methods {{{
function px(n) { return '' + parseInt(n) + 'px'; };
function pct(n) { return '' + parseInt(n) + '%'; };
function cssClass(cl) { return options.baseClass + '-' + cl; };
function getPos(obj)/*{{{*/
{
// Updated in v0.9.4 to use built-in dimensions plugin
var pos = $(obj).offset();
return [ pos.left, pos.top ];
};
/*}}}*/
function mouseAbs(e)/*{{{*/
{
return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ];
};
/*}}}*/
function myCursor(type)/*{{{*/
{
if (type != lastcurs)
{
Tracker.setCursor(type);
//Handles.xsetCursor(type);
lastcurs = type;
}
};
/*}}}*/
function startDragMode(mode,pos)/*{{{*/
{
docOffset = getPos($img);
Tracker.setCursor(mode=='move'?mode:mode+'-resize');
if (mode == 'move')
return Tracker.activateHandlers(createMover(pos), doneSelect);
var fc = Coords.getFixed();
var opp = oppLockCorner(mode);
var opc = Coords.getCorner(oppLockCorner(opp));
Coords.setPressed(Coords.getCorner(opp));
Coords.setCurrent(opc);
Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect);
};
/*}}}*/
function dragmodeHandler(mode,f)/*{{{*/
{
return function(pos) {
if (!options.aspectRatio) switch(mode)
{
case 'e': pos[1] = f.y2; break;
case 'w': pos[1] = f.y2; break;
case 'n': pos[0] = f.x2; break;
case 's': pos[0] = f.x2; break;
}
else switch(mode)
{
case 'e': pos[1] = f.y+1; break;
case 'w': pos[1] = f.y+1; break;
case 'n': pos[0] = f.x+1; break;
case 's': pos[0] = f.x+1; break;
}
Coords.setCurrent(pos);
Selection.update();
};
};
/*}}}*/
function createMover(pos)/*{{{*/
{
var lloc = pos;
KeyManager.watchKeys();
return function(pos)
{
Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
lloc = pos;
Selection.update();
};
};
/*}}}*/
function oppLockCorner(ord)/*{{{*/
{
switch(ord)
{
case 'n': return 'sw';
case 's': return 'nw';
case 'e': return 'nw';
case 'w': return 'ne';
case 'ne': return 'sw';
case 'nw': return 'se';
case 'se': return 'nw';
case 'sw': return 'ne';
};
};
/*}}}*/
function createDragger(ord)/*{{{*/
{
return function(e) {
if (options.disabled) return false;
if ((ord == 'move') && !options.allowMove) return false;
btndown = true;
startDragMode(ord,mouseAbs(e));
e.stopPropagation();
e.preventDefault();
return false;
};
};
/*}}}*/
function presize($obj,w,h)/*{{{*/
{
var nw = $obj.width(), nh = $obj.height();
if ((nw > w) && w > 0)
{
nw = w;
nh = (w/$obj.width()) * $obj.height();
}
if ((nh > h) && h > 0)
{
nh = h;
nw = (h/$obj.height()) * $obj.width();
}
xscale = $obj.width() / nw;
yscale = $obj.height() / nh;
$obj.width(nw).height(nh);
};
/*}}}*/
function unscale(c)/*{{{*/
{
return {
x: parseInt(c.x * xscale), y: parseInt(c.y * yscale),
x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale),
w: parseInt(c.w * xscale), h: parseInt(c.h * yscale)
};
};
/*}}}*/
function doneSelect(pos)/*{{{*/
{
var c = Coords.getFixed();
if (c.w > options.minSelect[0] && c.h > options.minSelect[1])
{
Selection.enableHandles();
Selection.done();
}
else
{
Selection.release();
}
Tracker.setCursor( options.allowSelect?'crosshair':'default' );
};
/*}}}*/
function newSelection(e)/*{{{*/
{
if (options.disabled) return false;
if (!options.allowSelect) return false;
btndown = true;
docOffset = getPos($img);
Selection.disableHandles();
myCursor('crosshair');
var pos = mouseAbs(e);
Coords.setPressed(pos);
Tracker.activateHandlers(selectDrag,doneSelect);
KeyManager.watchKeys();
Selection.update();
e.stopPropagation();
e.preventDefault();
return false;
};
/*}}}*/
function selectDrag(pos)/*{{{*/
{
Coords.setCurrent(pos);
Selection.update();
};
/*}}}*/
function newTracker()
{
var trk = $('<div></div>').addClass(cssClass('tracker'));
$.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' });
return trk;
};
// }}}
// API methods {{{
function animateTo(a)/*{{{*/
{
var x1 = a[0] / xscale,
y1 = a[1] / yscale,
x2 = a[2] / xscale,
y2 = a[3] / yscale;
if (animating) return;
var animto = Coords.flipCoords(x1,y1,x2,y2);
var c = Coords.getFixed();
var animat = initcr = [ c.x, c.y, c.x2, c.y2 ];
var interv = options.animationDelay;
var x = animat[0];
var y = animat[1];
var x2 = animat[2];
var y2 = animat[3];
var ix1 = animto[0] - initcr[0];
var iy1 = animto[1] - initcr[1];
var ix2 = animto[2] - initcr[2];
var iy2 = animto[3] - initcr[3];
var pcent = 0;
var velocity = options.swingSpeed;
Selection.animMode(true);
var animator = function()
{
return function()
{
pcent += (100 - pcent) / velocity;
animat[0] = x + ((pcent / 100) * ix1);
animat[1] = y + ((pcent / 100) * iy1);
animat[2] = x2 + ((pcent / 100) * ix2);
animat[3] = y2 + ((pcent / 100) * iy2);
if (pcent < 100) animateStart();
else Selection.done();
if (pcent >= 99.8) pcent = 100;
setSelectRaw(animat);
};
}();
function animateStart()
{ window.setTimeout(animator,interv); };
animateStart();
};
/*}}}*/
function setSelect(rect)//{{{
{
setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]);
};
//}}}
function setSelectRaw(l) /*{{{*/
{
Coords.setPressed([l[0],l[1]]);
Coords.setCurrent([l[2],l[3]]);
Selection.update();
};
/*}}}*/
function setOptions(opt)/*{{{*/
{
if (typeof(opt) != 'object') opt = { };
options = $.extend(options,opt);
if (typeof(options.onChange)!=='function')
options.onChange = function() { };
if (typeof(options.onSelect)!=='function')
options.onSelect = function() { };
};
/*}}}*/
function tellSelect()/*{{{*/
{
return unscale(Coords.getFixed());
};
/*}}}*/
function tellScaled()/*{{{*/
{
return Coords.getFixed();
};
/*}}}*/
function setOptionsNew(opt)/*{{{*/
{
setOptions(opt);
interfaceUpdate();
};
/*}}}*/
function disableCrop()//{{{
{
options.disabled = true;
Selection.disableHandles();
Selection.setCursor('default');
Tracker.setCursor('default');
};
//}}}
function enableCrop()//{{{
{
options.disabled = false;
interfaceUpdate();
};
//}}}
function cancelCrop()//{{{
{
Selection.done();
Tracker.activateHandlers(null,null);
};
//}}}
function destroy()//{{{
{
$div.remove();
$origimg.show();
};
//}}}
function interfaceUpdate(alt)//{{{
// This method tweaks the interface based on options object.
// Called when options are changed and at end of initialization.
{
options.allowResize ?
alt?Selection.enableOnly():Selection.enableHandles():
Selection.disableHandles();
Tracker.setCursor( options.allowSelect? 'crosshair': 'default' );
Selection.setCursor( options.allowMove? 'move': 'default' );
$div.css('backgroundColor',options.bgColor);
if ('setSelect' in options) {
setSelect(opt.setSelect);
Selection.done();
delete(options.setSelect);
}
if ('trueSize' in options) {
xscale = options.trueSize[0] / boundx;
yscale = options.trueSize[1] / boundy;
}
xlimit = options.maxSize[0] || 0;
ylimit = options.maxSize[1] || 0;
xmin = options.minSize[0] || 0;
ymin = options.minSize[1] || 0;
if ('outerImage' in options)
{
$img.attr('src',options.outerImage);
delete(options.outerImage);
}
Selection.refresh();
};
//}}}
// }}}
$hdl_holder.hide();
interfaceUpdate(true);
var api = {
animateTo: animateTo,
setSelect: setSelect,
setOptions: setOptionsNew,
tellSelect: tellSelect,
tellScaled: tellScaled,
disable: disableCrop,
enable: enableCrop,
cancel: cancelCrop,
focus: KeyManager.watchKeys,
getBounds: function() { return [ boundx * xscale, boundy * yscale ]; },
getWidgetSize: function() { return [ boundx, boundy ]; },
release: Selection.release,
destroy: destroy
};
$origimg.data('Jcrop',api);
return api;
};
$.fn.Jcrop = function(options)/*{{{*/
{
function attachWhenDone(from)/*{{{*/
{
var loadsrc = options.useImg || from.src;
var img = new Image();
img.onload = function() { $.Jcrop(from,options); };
img.src = loadsrc;
};
/*}}}*/
if (typeof(options) !== 'object') options = { };
// Iterate over each object, attach Jcrop
this.each(function()
{
// If we've already attached to this object
if ($(this).data('Jcrop'))
{
// The API can be requested this way (undocumented)
if (options == 'api') return $(this).data('Jcrop');
// Otherwise, we just reset the options...
else $(this).data('Jcrop').setOptions(options);
}
// If we haven't been attached, preload and attach
else attachWhenDone(this);
});
// Return "this" so we're chainable a la jQuery plugin-style!
return this;
};
/*}}}*/
})(jQuery);
| JavaScript |
(function($) {
var fs = {add:'ajaxAdd',del:'ajaxDel',dim:'ajaxDim',process:'process',recolor:'recolor'}, wpList;
wpList = {
settings: {
url: ajaxurl, type: 'POST',
response: 'ajax-response',
what: '',
alt: 'alternate', altOffset: 0,
addColor: null, delColor: null, dimAddColor: null, dimDelColor: null,
confirm: null,
addBefore: null, addAfter: null,
delBefore: null, delAfter: null,
dimBefore: null, dimAfter: null
},
nonce: function(e,s) {
var url = wpAjax.unserialize(e.attr('href'));
return s.nonce || url._ajax_nonce || $('#' + s.element + ' input[name="_ajax_nonce"]').val() || url._wpnonce || $('#' + s.element + ' input[name="_wpnonce"]').val() || 0;
},
parseClass: function(e,t) {
var c = [], cl;
try {
cl = $(e).attr('class') || '';
cl = cl.match(new RegExp(t+':[\\S]+'));
if ( cl )
c = cl[0].split(':');
} catch(r) {}
return c;
},
pre: function(e,s,a) {
var bg, r;
s = $.extend( {}, this.wpList.settings, {
element: null,
nonce: 0,
target: e.get(0)
}, s || {} );
if ( $.isFunction( s.confirm ) ) {
if ( 'add' != a ) {
bg = $('#' + s.element).css('backgroundColor');
$('#' + s.element).css('backgroundColor', '#FF9966');
}
r = s.confirm.call(this, e, s, a, bg);
if ( 'add' != a )
$('#' + s.element).css('backgroundColor', bg );
if ( !r )
return false;
}
return s;
},
ajaxAdd: function( e, s ) {
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'add'), es, valid, formData, res, rres;
s = wpList.pre.call( list, e, s, 'add' );
s.element = cls[2] || e.attr( 'id' ) || s.element || null;
if ( cls[3] )
s.addColor = '#' + cls[3];
else
s.addColor = s.addColor || '#FFFF33';
if ( !s )
return false;
if ( !e.is('[class^="add:' + list.id + ':"]') )
return !wpList.add.call( list, e, s );
if ( !s.element )
return true;
s.action = 'add-' + s.what;
s.nonce = wpList.nonce(e,s);
es = $('#' + s.element + ' :input').not('[name="_ajax_nonce"], [name="_wpnonce"], [name="action"]');
valid = wpAjax.validateForm( '#' + s.element );
if ( !valid )
return false;
s.data = $.param( $.extend( { _ajax_nonce: s.nonce, action: s.action }, wpAjax.unserialize( cls[4] || '' ) ) );
formData = $.isFunction(es.fieldSerialize) ? es.fieldSerialize() : es.serialize();
if ( formData )
s.data += '&' + formData;
if ( $.isFunction(s.addBefore) ) {
s = s.addBefore( s );
if ( !s )
return true;
}
if ( !s.data.match(/_ajax_nonce=[a-f0-9]+/) )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors )
return false;
if ( true === res )
return true;
jQuery.each( res.responses, function() {
wpList.add.call( list, this.data, $.extend( {}, s, { // this.firstChild.nodevalue
pos: this.position || 0,
id: this.id || 0,
oldId: this.oldId || null
} ) );
} );
list.wpList.recolor();
$(list).trigger( 'wpListAddEnd', [ s, list.wpList ] );
wpList.clear.call(list,'#' + s.element);
};
s.complete = function(x, st) {
if ( $.isFunction(s.addAfter) ) {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.addAfter( rres, _s );
}
};
$.ajax( s );
return false;
},
ajaxDel: function( e, s ) {
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'delete'), element, res, rres;
s = wpList.pre.call( list, e, s, 'delete' );
s.element = cls[2] || s.element || null;
if ( cls[3] )
s.delColor = '#' + cls[3];
else
s.delColor = s.delColor || '#faa';
if ( !s || !s.element )
return false;
s.action = 'delete-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), _ajax_nonce: s.nonce },
wpAjax.unserialize( cls[4] || '' )
);
if ( $.isFunction(s.delBefore) ) {
s = s.delBefore( s, list );
if ( !s )
return true;
}
if ( !s.data._ajax_nonce )
return true;
element = $('#' + s.element);
if ( 'none' != s.delColor ) {
element.css( 'backgroundColor', s.delColor ).fadeOut( 350, function(){
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
});
} else {
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
}
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#faa' ).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.delAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.delAfter( rres, _s );
}).dequeue();
}
}
$.ajax( s );
return false;
},
ajaxDim: function( e, s ) {
if ( $(e).parent().css('display') == 'none' ) // Prevent hidden links from being clicked by hotkeys
return false;
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'dim'), element, isClass, color, dimColor, res, rres;
s = wpList.pre.call( list, e, s, 'dim' );
s.element = cls[2] || s.element || null;
s.dimClass = cls[3] || s.dimClass || null;
if ( cls[4] )
s.dimAddColor = '#' + cls[4];
else
s.dimAddColor = s.dimAddColor || '#FFFF33';
if ( cls[5] )
s.dimDelColor = '#' + cls[5];
else
s.dimDelColor = s.dimDelColor || '#FF3333';
if ( !s || !s.element || !s.dimClass )
return true;
s.action = 'dim-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), dimClass: s.dimClass, _ajax_nonce : s.nonce },
wpAjax.unserialize( cls[6] || '' )
);
if ( $.isFunction(s.dimBefore) ) {
s = s.dimBefore( s );
if ( !s )
return true;
}
element = $('#' + s.element);
isClass = element.toggleClass(s.dimClass).is('.' + s.dimClass);
color = wpList.getColor( element );
element.toggleClass( s.dimClass );
dimColor = isClass ? s.dimAddColor : s.dimDelColor;
if ( 'none' != dimColor ) {
element
.animate( { backgroundColor: dimColor }, 'fast' )
.queue( function() { element.toggleClass(s.dimClass); $(this).dequeue(); } )
.animate( { backgroundColor: color }, { complete: function() {
$(this).css( 'backgroundColor', '' );
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
});
} else {
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
if ( !s.data._ajax_nonce )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#FF3333' )[isClass?'removeClass':'addClass'](s.dimClass).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.dimAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.dimAfter( rres, _s );
}).dequeue();
}
};
$.ajax( s );
return false;
},
getColor: function( el ) {
var color = jQuery(el).css('backgroundColor');
return color || '#ffffff';
},
add: function( e, s ) {
e = $(e);
var list = $(this), old = false, _s = { pos: 0, id: 0, oldId: null }, ba, ref, color;
if ( 'string' == typeof s )
s = { what: s };
s = $.extend(_s, this.wpList.settings, s);
if ( !e.size() || !s.what )
return false;
if ( s.oldId )
old = $('#' + s.what + '-' + s.oldId);
if ( s.id && ( s.id != s.oldId || !old || !old.size() ) )
$('#' + s.what + '-' + s.id).remove();
if ( old && old.size() ) {
old.before(e);
old.remove();
} else if ( isNaN(s.pos) ) {
ba = 'after';
if ( '-' == s.pos.substr(0,1) ) {
s.pos = s.pos.substr(1);
ba = 'before';
}
ref = list.find( '#' + s.pos );
if ( 1 === ref.size() )
ref[ba](e);
else
list.append(e);
} else if ( 'comment' != s.what || 0 === $('#' + s.element).length ) {
if ( s.pos < 0 ) {
list.prepend(e);
} else {
list.append(e);
}
}
if ( s.alt ) {
if ( ( list.children(':visible').index( e[0] ) + s.altOffset ) % 2 ) { e.removeClass( s.alt ); }
else { e.addClass( s.alt ); }
}
if ( 'none' != s.addColor ) {
color = wpList.getColor( e );
e.css( 'backgroundColor', s.addColor ).animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); } } );
}
list.each( function() { this.wpList.process( e ); } );
return e;
},
clear: function(e) {
var list = this, t, tag;
e = $(e);
if ( list.wpList && e.parents( '#' + list.id ).size() )
return;
e.find(':input').each( function() {
if ( $(this).parents('.form-no-clear').size() )
return;
t = this.type.toLowerCase();
tag = this.tagName.toLowerCase();
if ( 'text' == t || 'password' == t || 'textarea' == tag )
this.value = '';
else if ( 'checkbox' == t || 'radio' == t )
this.checked = false;
else if ( 'select' == tag )
this.selectedIndex = null;
});
},
process: function(el) {
var list = this,
$el = $(el || document);
$el.delegate( 'form[class^="add:' + list.id + ':"]', 'submit', function(){
return list.wpList.add(this);
});
$el.delegate( '[class^="add:' + list.id + ':"]:not(form)', 'click', function(){
return list.wpList.add(this);
});
$el.delegate( '[class^="delete:' + list.id + ':"]', 'click', function(){
return list.wpList.del(this);
});
$el.delegate( '[class^="dim:' + list.id + ':"]', 'click', function(){
return list.wpList.dim(this);
});
},
recolor: function() {
var list = this, items, eo;
if ( !list.wpList.settings.alt )
return;
items = $('.list-item:visible', list);
if ( !items.size() )
items = $(list).children(':visible');
eo = [':even',':odd'];
if ( list.wpList.settings.altOffset % 2 )
eo.reverse();
items.filter(eo[0]).addClass(list.wpList.settings.alt).end().filter(eo[1]).removeClass(list.wpList.settings.alt);
},
init: function() {
var lists = this;
lists.wpList.process = function(a) {
lists.each( function() {
this.wpList.process(a);
} );
};
lists.wpList.recolor = function() {
lists.each( function() {
this.wpList.recolor();
} );
};
}
};
$.fn.wpList = function( settings ) {
this.each( function() {
var _this = this;
this.wpList = { settings: $.extend( {}, wpList.settings, { what: wpList.parseClass(this,'list')[1] || '' }, settings ) };
$.each( fs, function(i,f) { _this.wpList[i] = function( e, s ) { return wpList[f].call( _this, e, s ); }; } );
} );
wpList.init.call(this);
this.wpList.process();
return this;
};
})(jQuery);
| JavaScript |
// script.aculo.us unittest.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
// (c) 2005-2009 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
var options = Object.extend({
pointerX: 0,
pointerY: 0,
buttons: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false
}, arguments[2] || {});
var oEvent = document.createEvent("MouseEvents");
oEvent.initMouseEvent(eventName, true, true, document.defaultView,
options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
if(this.mark) Element.remove(this.mark);
this.mark = document.createElement('div');
this.mark.appendChild(document.createTextNode(" "));
document.body.appendChild(this.mark);
this.mark.style.position = 'absolute';
this.mark.style.top = options.pointerY + "px";
this.mark.style.left = options.pointerX + "px";
this.mark.style.width = "5px";
this.mark.style.height = "5px;";
this.mark.style.borderTop = "1px solid red;";
this.mark.style.borderLeft = "1px solid red;";
if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
$(element).dispatchEvent(oEvent);
};
// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
var options = Object.extend({
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: 0
}, arguments[2] || {});
var oEvent = document.createEvent("KeyEvents");
oEvent.initKeyEvent(eventName, true, true, window,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
$(element).dispatchEvent(oEvent);
};
Event.simulateKeys = function(element, command) {
for(var i=0; i<command.length; i++) {
Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
}
};
var Test = {};
Test.Unit = {};
// security exception workaround
Test.Unit.inspect = Object.inspect;
Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
initialize: function(log) {
this.log = $(log);
if (this.log) {
this._createLogTable();
}
},
start: function(testName) {
if (!this.log) return;
this.testName = testName;
this.lastLogLine = document.createElement('tr');
this.statusCell = document.createElement('td');
this.nameCell = document.createElement('td');
this.nameCell.className = "nameCell";
this.nameCell.appendChild(document.createTextNode(testName));
this.messageCell = document.createElement('td');
this.lastLogLine.appendChild(this.statusCell);
this.lastLogLine.appendChild(this.nameCell);
this.lastLogLine.appendChild(this.messageCell);
this.loglines.appendChild(this.lastLogLine);
},
finish: function(status, summary) {
if (!this.log) return;
this.lastLogLine.className = status;
this.statusCell.innerHTML = status;
this.messageCell.innerHTML = this._toHTML(summary);
this.addLinksToResults();
},
message: function(message) {
if (!this.log) return;
this.messageCell.innerHTML = this._toHTML(message);
},
summary: function(summary) {
if (!this.log) return;
this.logsummary.innerHTML = this._toHTML(summary);
},
_createLogTable: function() {
this.log.innerHTML =
'<div id="logsummary"></div>' +
'<table id="logtable">' +
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
'<tbody id="loglines"></tbody>' +
'</table>';
this.logsummary = $('logsummary');
this.loglines = $('loglines');
},
_toHTML: function(txt) {
return txt.escapeHTML().replace(/\n/g,"<br/>");
},
addLinksToResults: function(){
$$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run only this test";
Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
});
$$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run all tests";
Event.observe(td, 'click', function(){ window.location.search = "";});
});
}
};
Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
initialize: function(testcases) {
this.options = Object.extend({
testLog: 'testlog'
}, arguments[1] || {});
this.options.resultsURL = this.parseResultsURLQueryParameter();
this.options.tests = this.parseTestsQueryParameter();
if (this.options.testLog) {
this.options.testLog = $(this.options.testLog) || null;
}
if(this.options.tests) {
this.tests = [];
for(var i = 0; i < this.options.tests.length; i++) {
if(/^test/.test(this.options.tests[i])) {
this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
}
}
} else {
if (this.options.test) {
this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
} else {
this.tests = [];
for(var testcase in testcases) {
if(/^test/.test(testcase)) {
this.tests.push(
new Test.Unit.Testcase(
this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
testcases[testcase], testcases["setup"], testcases["teardown"]
));
}
}
}
}
this.currentTest = 0;
this.logger = new Test.Unit.Logger(this.options.testLog);
setTimeout(this.runTests.bind(this), 1000);
},
parseResultsURLQueryParameter: function() {
return window.location.search.parseQuery()["resultsURL"];
},
parseTestsQueryParameter: function(){
if (window.location.search.parseQuery()["tests"]){
return window.location.search.parseQuery()["tests"].split(',');
};
},
// Returns:
// "ERROR" if there was an error,
// "FAILURE" if there was a failure, or
// "SUCCESS" if there was neither
getResult: function() {
var hasFailure = false;
for(var i=0;i<this.tests.length;i++) {
if (this.tests[i].errors > 0) {
return "ERROR";
}
if (this.tests[i].failures > 0) {
hasFailure = true;
}
}
if (hasFailure) {
return "FAILURE";
} else {
return "SUCCESS";
}
},
postResults: function() {
if (this.options.resultsURL) {
new Ajax.Request(this.options.resultsURL,
{ method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
}
},
runTests: function() {
var test = this.tests[this.currentTest];
if (!test) {
// finished!
this.postResults();
this.logger.summary(this.summary());
return;
}
if(!test.isWaiting) {
this.logger.start(test.name);
}
test.run();
if(test.isWaiting) {
this.logger.message("Waiting for " + test.timeToWait + "ms");
setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
} else {
this.logger.finish(test.status(), test.summary());
this.currentTest++;
// tail recursive, hopefully the browser will skip the stackframe
this.runTests();
}
},
summary: function() {
var assertions = 0;
var failures = 0;
var errors = 0;
var messages = [];
for(var i=0;i<this.tests.length;i++) {
assertions += this.tests[i].assertions;
failures += this.tests[i].failures;
errors += this.tests[i].errors;
}
return (
(this.options.context ? this.options.context + ': ': '') +
this.tests.length + " tests, " +
assertions + " assertions, " +
failures + " failures, " +
errors + " errors");
}
};
Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
initialize: function() {
this.assertions = 0;
this.failures = 0;
this.errors = 0;
this.messages = [];
},
summary: function() {
return (
this.assertions + " assertions, " +
this.failures + " failures, " +
this.errors + " errors" + "\n" +
this.messages.join("\n"));
},
pass: function() {
this.assertions++;
},
fail: function(message) {
this.failures++;
this.messages.push("Failure: " + message);
},
info: function(message) {
this.messages.push("Info: " + message);
},
error: function(error) {
this.errors++;
this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
},
status: function() {
if (this.failures > 0) return 'failed';
if (this.errors > 0) return 'error';
return 'passed';
},
assert: function(expression) {
var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
try { expression ? this.pass() :
this.fail(message); }
catch(e) { this.error(e); }
},
assertEqual: function(expected, actual) {
var message = arguments[2] || "assertEqual";
try { (expected == actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertInspect: function(expected, actual) {
var message = arguments[2] || "assertInspect";
try { (expected == actual.inspect()) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertEnumEqual: function(expected, actual) {
var message = arguments[2] || "assertEnumEqual";
try { $A(expected).length == $A(actual).length &&
expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
', actual ' + Test.Unit.inspect(actual)); }
catch(e) { this.error(e); }
},
assertNotEqual: function(expected, actual) {
var message = arguments[2] || "assertNotEqual";
try { (expected != actual) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertIdentical: function(expected, actual) {
var message = arguments[2] || "assertIdentical";
try { (expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNotIdentical: function(expected, actual) {
var message = arguments[2] || "assertNotIdentical";
try { !(expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNull: function(obj) {
var message = arguments[1] || 'assertNull';
try { (obj==null) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
catch(e) { this.error(e); }
},
assertMatch: function(expected, actual) {
var message = arguments[2] || 'assertMatch';
var regex = new RegExp(expected);
try { (regex.exec(actual)) ? this.pass() :
this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertHidden: function(element) {
var message = arguments[1] || 'assertHidden';
this.assertEqual("none", element.style.display, message);
},
assertNotNull: function(object) {
var message = arguments[1] || 'assertNotNull';
this.assert(object != null, message);
},
assertType: function(expected, actual) {
var message = arguments[2] || 'assertType';
try {
(actual.constructor == expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertNotOfType: function(expected, actual) {
var message = arguments[2] || 'assertNotOfType';
try {
(actual.constructor != expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertInstanceOf';
try {
(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was not an instance of the expected type"); }
catch(e) { this.error(e); }
},
assertNotInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertNotInstanceOf';
try {
!(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was an instance of the not expected type"); }
catch(e) { this.error(e); }
},
assertRespondsTo: function(method, obj) {
var message = arguments[2] || 'assertRespondsTo';
try {
(obj[method] && typeof obj[method] == 'function') ? this.pass() :
this.fail(message + ": object doesn't respond to [" + method + "]"); }
catch(e) { this.error(e); }
},
assertReturnsTrue: function(method, obj) {
var message = arguments[2] || 'assertReturnsTrue';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
m() ? this.pass() :
this.fail(message + ": method returned false"); }
catch(e) { this.error(e); }
},
assertReturnsFalse: function(method, obj) {
var message = arguments[2] || 'assertReturnsFalse';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
!m() ? this.pass() :
this.fail(message + ": method returned true"); }
catch(e) { this.error(e); }
},
assertRaise: function(exceptionName, method) {
var message = arguments[2] || 'assertRaise';
try {
method();
this.fail(message + ": exception expected but none was raised"); }
catch(e) {
((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
}
},
assertElementsMatch: function() {
var expressions = $A(arguments), elements = $A(expressions.shift());
if (elements.length != expressions.length) {
this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
return false;
}
elements.zip(expressions).all(function(pair, index) {
var element = $(pair.first()), expression = pair.last();
if (element.match(expression)) return true;
this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
}.bind(this)) && this.pass();
},
assertElementMatches: function(element, expression) {
this.assertElementsMatch([element], expression);
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
},
_isVisible: function(element) {
element = $(element);
if(!element.parentNode) return true;
this.assertNotNull(element);
if(element.style && Element.getStyle(element, 'display') == 'none')
return false;
return this._isVisible(element.parentNode);
},
assertNotVisible: function(element) {
this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
},
assertVisible: function(element) {
this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
}
};
Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
initialize: function(name, test, setup, teardown) {
Test.Unit.Assertions.prototype.initialize.bind(this)();
this.name = name;
if(typeof test == 'string') {
test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
this.test = function() {
eval('with(this){'+test+'}');
}
} else {
this.test = test || function() {};
}
this.setup = setup || function() {};
this.teardown = teardown || function() {};
this.isWaiting = false;
this.timeToWait = 1000;
},
wait: function(time, nextPart) {
this.isWaiting = true;
this.test = nextPart;
this.timeToWait = time;
},
run: function() {
try {
try {
if (!this.isWaiting) this.setup.bind(this)();
this.isWaiting = false;
this.test.bind(this)();
} finally {
if(!this.isWaiting) {
this.teardown.bind(this)();
}
}
}
catch(e) { this.error(e); }
}
});
// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/
Test.setupBDDExtensionMethods = function(){
var METHODMAP = {
shouldEqual: 'assertEqual',
shouldNotEqual: 'assertNotEqual',
shouldEqualEnum: 'assertEnumEqual',
shouldBeA: 'assertType',
shouldNotBeA: 'assertNotOfType',
shouldBeAn: 'assertType',
shouldNotBeAn: 'assertNotOfType',
shouldBeNull: 'assertNull',
shouldNotBeNull: 'assertNotNull',
shouldBe: 'assertReturnsTrue',
shouldNotBe: 'assertReturnsFalse',
shouldRespondTo: 'assertRespondsTo'
};
var makeAssertion = function(assertion, args, object) {
this[assertion].apply(this,(args || []).concat([object]));
};
Test.BDDMethods = {};
$H(METHODMAP).each(function(pair) {
Test.BDDMethods[pair.key] = function() {
var args = $A(arguments);
var scope = args.shift();
makeAssertion.apply(scope, [pair.value, args, this]); };
});
[Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each(
function(p){ Object.extend(p, Test.BDDMethods) }
);
};
Test.context = function(name, spec, log){
Test.setupBDDExtensionMethods();
var compiledSpec = {};
var titles = {};
for(specName in spec) {
switch(specName){
case "setup":
case "teardown":
compiledSpec[specName] = spec[specName];
break;
default:
var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
var body = spec[specName].toString().split('\n').slice(1);
if(/^\{/.test(body[0])) body = body.slice(1);
body.pop();
body = body.map(function(statement){
return statement.strip()
});
compiledSpec[testName] = body.join('\n');
titles[testName] = specName;
}
}
new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
}; | JavaScript |
// script.aculo.us slider.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Marty Haught, Thomas Fuchs
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if (!Control) var Control = { };
// options:
// axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
// onChange(value)
// onSlide(value)
Control.Slider = Class.create({
initialize: function(handle, track, options) {
var slider = this;
if (Object.isArray(handle)) {
this.handles = handle.collect( function(e) { return $(e) });
} else {
this.handles = [$(handle)];
}
this.track = $(track);
this.options = options || { };
this.axis = this.options.axis || 'horizontal';
this.increment = this.options.increment || 1;
this.step = parseInt(this.options.step || '1');
this.range = this.options.range || $R(0,1);
this.value = 0; // assure backwards compat
this.values = this.handles.map( function() { return 0 });
this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
this.options.startSpan = $(this.options.startSpan || null);
this.options.endSpan = $(this.options.endSpan || null);
this.restricted = this.options.restricted || false;
this.maximum = this.options.maximum || this.range.end;
this.minimum = this.options.minimum || this.range.start;
// Will be used to align the handle onto the track, if necessary
this.alignX = parseInt(this.options.alignX || '0');
this.alignY = parseInt(this.options.alignY || '0');
this.trackLength = this.maximumOffset() - this.minimumOffset();
this.handleLength = this.isVertical() ?
(this.handles[0].offsetHeight != 0 ?
this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
(this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
this.handles[0].style.width.replace(/px$/,""));
this.active = false;
this.dragging = false;
this.disabled = false;
if (this.options.disabled) this.setDisabled();
// Allowed values array
this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
if (this.allowedValues) {
this.minimum = this.allowedValues.min();
this.maximum = this.allowedValues.max();
}
this.eventMouseDown = this.startDrag.bindAsEventListener(this);
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.update.bindAsEventListener(this);
// Initialize handles in reverse (make sure first handle is active)
this.handles.each( function(h,i) {
i = slider.handles.length-1-i;
slider.setValue(parseFloat(
(Object.isArray(slider.options.sliderValue) ?
slider.options.sliderValue[i] : slider.options.sliderValue) ||
slider.range.start), i);
h.makePositioned().observe("mousedown", slider.eventMouseDown);
});
this.track.observe("mousedown", this.eventMouseDown);
document.observe("mouseup", this.eventMouseUp);
document.observe("mousemove", this.eventMouseMove);
this.initialized = true;
},
dispose: function() {
var slider = this;
Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
this.handles.each( function(h) {
Event.stopObserving(h, "mousedown", slider.eventMouseDown);
});
},
setDisabled: function(){
this.disabled = true;
},
setEnabled: function(){
this.disabled = false;
},
getNearestValue: function(value){
if (this.allowedValues){
if (value >= this.allowedValues.max()) return(this.allowedValues.max());
if (value <= this.allowedValues.min()) return(this.allowedValues.min());
var offset = Math.abs(this.allowedValues[0] - value);
var newValue = this.allowedValues[0];
this.allowedValues.each( function(v) {
var currentOffset = Math.abs(v - value);
if (currentOffset <= offset){
newValue = v;
offset = currentOffset;
}
});
return newValue;
}
if (value > this.range.end) return this.range.end;
if (value < this.range.start) return this.range.start;
return value;
},
setValue: function(sliderValue, handleIdx){
if (!this.active) {
this.activeHandleIdx = handleIdx || 0;
this.activeHandle = this.handles[this.activeHandleIdx];
this.updateStyles();
}
handleIdx = handleIdx || this.activeHandleIdx || 0;
if (this.initialized && this.restricted) {
if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
sliderValue = this.values[handleIdx-1];
if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
sliderValue = this.values[handleIdx+1];
}
sliderValue = this.getNearestValue(sliderValue);
this.values[handleIdx] = sliderValue;
this.value = this.values[0]; // assure backwards compat
this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
this.translateToPx(sliderValue);
this.drawSpans();
if (!this.dragging || !this.event) this.updateFinished();
},
setValueBy: function(delta, handleIdx) {
this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
handleIdx || this.activeHandleIdx || 0);
},
translateToPx: function(value) {
return Math.round(
((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
(value - this.range.start)) + "px";
},
translateToValue: function(offset) {
return ((offset/(this.trackLength-this.handleLength) *
(this.range.end-this.range.start)) + this.range.start);
},
getRange: function(range) {
var v = this.values.sortBy(Prototype.K);
range = range || 0;
return $R(v[range],v[range+1]);
},
minimumOffset: function(){
return(this.isVertical() ? this.alignY : this.alignX);
},
maximumOffset: function(){
return(this.isVertical() ?
(this.track.offsetHeight != 0 ? this.track.offsetHeight :
this.track.style.height.replace(/px$/,"")) - this.alignY :
(this.track.offsetWidth != 0 ? this.track.offsetWidth :
this.track.style.width.replace(/px$/,"")) - this.alignX);
},
isVertical: function(){
return (this.axis == 'vertical');
},
drawSpans: function() {
var slider = this;
if (this.spans)
$R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
if (this.options.startSpan)
this.setSpan(this.options.startSpan,
$R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
if (this.options.endSpan)
this.setSpan(this.options.endSpan,
$R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
},
setSpan: function(span, range) {
if (this.isVertical()) {
span.style.top = this.translateToPx(range.start);
span.style.height = this.translateToPx(range.end - range.start + this.range.start);
} else {
span.style.left = this.translateToPx(range.start);
span.style.width = this.translateToPx(range.end - range.start + this.range.start);
}
},
updateStyles: function() {
this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
Element.addClassName(this.activeHandle, 'selected');
},
startDrag: function(event) {
if (Event.isLeftClick(event)) {
if (!this.disabled){
this.active = true;
var handle = Event.element(event);
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var track = handle;
if (track==this.track) {
var offsets = this.track.cumulativeOffset();
this.event = event;
this.setValue(this.translateToValue(
(this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
));
var offsets = this.activeHandle.cumulativeOffset();
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
} else {
// find the handle (prevents issues with Safari)
while((this.handles.indexOf(handle) == -1) && handle.parentNode)
handle = handle.parentNode;
if (this.handles.indexOf(handle)!=-1) {
this.activeHandle = handle;
this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
this.updateStyles();
var offsets = this.activeHandle.cumulativeOffset();
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
}
}
Event.stop(event);
}
},
update: function(event) {
if (this.active) {
if (!this.dragging) this.dragging = true;
this.draw(event);
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
}
},
draw: function(event) {
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var offsets = this.track.cumulativeOffset();
pointer[0] -= this.offsetX + offsets[0];
pointer[1] -= this.offsetY + offsets[1];
this.event = event;
this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
if (this.initialized && this.options.onSlide)
this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
},
endDrag: function(event) {
if (this.active && this.dragging) {
this.finishDrag(event, true);
Event.stop(event);
}
this.active = false;
this.dragging = false;
},
finishDrag: function(event, success) {
this.active = false;
this.dragging = false;
this.updateFinished();
},
updateFinished: function() {
if (this.initialized && this.options.onChange)
this.options.onChange(this.values.length>1 ? this.values : this.value, this);
this.event = null;
}
}); | JavaScript |
// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Scriptaculous = {
Version: '1.8.3',
require: function(libraryName) {
try{
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
} catch(e) {
// for xhtml+xml served content, fall back to DOM methods
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = libraryName;
document.getElementsByTagName('head')[0].appendChild(script);
}
},
REQUIRED_PROTOTYPE: '1.6.0.3',
load: function() {
function convertVersionString(versionString) {
var v = versionString.replace(/_.*|\./g, '');
v = parseInt(v + '0'.times(4-v.length));
return versionString.indexOf('_') > -1 ? v-1 : v;
}
if((typeof Prototype=='undefined') ||
(typeof Element == 'undefined') ||
(typeof Element.Methods=='undefined') ||
(convertVersionString(Prototype.Version) <
convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
throw("script.aculo.us requires the Prototype JavaScript framework >= " +
Scriptaculous.REQUIRED_PROTOTYPE);
var js = /scriptaculous\.js(\?.*)?$/;
$$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*load=([a-z,]*)/);
// Modified for WordPress to work with enqueue_script
if ( includes ) {
includes[1].split(',').each( function(include) {
Scriptaculous.require(path+include+'.js')
});
}
});
}
};
Scriptaculous.load();
| JavaScript |
// script.aculo.us sound.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Based on code created by Jules Gravinese (http://www.webveteran.com/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
Sound = {
tracks: {},
_enabled: true,
template:
new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),
enable: function(){
Sound._enabled = true;
},
disable: function(){
Sound._enabled = false;
},
play: function(url){
if(!Sound._enabled) return;
var options = Object.extend({
track: 'global', url: url, replace: false
}, arguments[1] || {});
if(options.replace && this.tracks[options.track]) {
$R(0, this.tracks[options.track].id).each(function(id){
var sound = $('sound_'+options.track+'_'+id);
sound.Stop && sound.Stop();
sound.remove();
});
this.tracks[options.track] = null;
}
if(!this.tracks[options.track])
this.tracks[options.track] = { id: 0 };
else
this.tracks[options.track].id++;
options.id = this.tracks[options.track].id;
$$('body')[0].insert(
Prototype.Browser.IE ? new Element('bgsound',{
id: 'sound_'+options.track+'_'+options.id,
src: options.url, loop: 1, autostart: true
}) : Sound.template.evaluate(options));
}
};
if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){
if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 }))
Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>');
else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('Windows Media') != -1 }))
Sound.template = new Template('<object id="sound_#{track}_#{id}" type="application/x-mplayer2" data="#{url}"></object>');
else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('RealPlayer') != -1 }))
Sound.template = new Template('<embed type="audio/x-pn-realaudio-plugin" style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>');
else
Sound.play = function(){};
} | JavaScript |
// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Scriptaculous = {
Version: '1.8.3',
require: function(libraryName) {
try{
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
} catch(e) {
// for xhtml+xml served content, fall back to DOM methods
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = libraryName;
document.getElementsByTagName('head')[0].appendChild(script);
}
},
REQUIRED_PROTOTYPE: '1.6.0.3',
load: function() {
function convertVersionString(versionString) {
var v = versionString.replace(/_.*|\./g, '');
v = parseInt(v + '0'.times(4-v.length));
return versionString.indexOf('_') > -1 ? v-1 : v;
}
if((typeof Prototype=='undefined') ||
(typeof Element == 'undefined') ||
(typeof Element.Methods=='undefined') ||
(convertVersionString(Prototype.Version) <
convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
throw("script.aculo.us requires the Prototype JavaScript framework >= " +
Scriptaculous.REQUIRED_PROTOTYPE);
var js = /scriptaculous\.js(\?.*)?$/;
$$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
}
};
Scriptaculous.load(); | JavaScript |
// script.aculo.us builder.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function(elementName) {
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
} catch(e) {}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if(element && (element.tagName.toUpperCase() != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if(!element) element = document.createElement(elementName);
// abort if nothing could be created
if(!element) return;
// attributes (or text)
if(arguments[1])
if(this._isStringOrNumber(arguments[1]) ||
(arguments[1] instanceof Array) ||
arguments[1].tagName) {
this._children(element, arguments[1]);
} else {
var attrs = this._attributes(arguments[1]);
if(attrs.length) {
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" +elementName + " " +
attrs + "></" + elementName + ">";
} catch(e) {}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if(!element) {
element = document.createElement(elementName);
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if(element.tagName.toUpperCase() != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if(arguments[2])
this._children(element, arguments[2]);
return $(element);
},
_text: function(text) {
return document.createTextNode(text);
},
ATTR_MAP: {
'className': 'class',
'htmlFor': 'for'
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
'="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'"') + '"');
return attrs.join(" ");
},
_children: function(element, children) {
if(children.tagName) {
element.appendChild(children);
return;
}
if(typeof children=='object') { // array can hold nodes and text
children.flatten().each( function(e) {
if(typeof e=='object')
element.appendChild(e);
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));
});
} else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
},
build: function(html) {
var element = this.node('div');
$(element).update(html.strip());
return element.down();
},
dump: function(scope) {
if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
tags.each( function(tag){
scope[tag] = function() {
return Builder.node.apply(Builder, [tag].concat($A(arguments)));
};
});
}
}; | JavaScript |
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
*
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*
* hoverIntent is currently available for use in all personal or commercial
* projects under both MIT and GPL licenses. This means that you can choose
* the license that best suits your project, and use it accordingly.
*
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
*
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
* sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
* interval: 100, // number = milliseconds of polling interval
* over: showNav, // function = onMouseOver callback (required)
* timeout: 0, // number = milliseconds delay before onMouseOut function call
* out: hideNav // function = onMouseOut callback (required)
* });
*
* @param f onMouseOver function || An object with configuration options
* @param g onMouseOut function || Nothing (use configuration options object)
* @author Brian Cherne <brian@cherne.net>
*/
(function($) {
$.fn.hoverIntent = function(f,g) {
// default configuration options
var cfg = {
sensitivity: 7,
interval: 100,
timeout: 0
};
// override configuration options with user supplied object
cfg = $.extend(cfg, g ? { over: f, out: g } : f );
// instantiate variables
// cX, cY = current X and Y position of mouse, updated by mousemove event
// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
var cX, cY, pX, pY;
// A private function for getting mouse position
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
// A private function for comparing current and previous mouse position
var compare = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
// compare mouse positions to see if they've crossed the threshold
if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
$(ob).unbind("mousemove",track);
// set hoverIntent state to true (so mouseOut can be called)
ob.hoverIntent_s = 1;
return cfg.over.apply(ob,[ev]);
} else {
// set previous coordinates for next time
pX = cX; pY = cY;
// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
}
};
// A private function for delaying the mouseOut function
var delay = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
ob.hoverIntent_s = 0;
return cfg.out.apply(ob,[ev]);
};
// workaround for Mozilla bug: not firing mouseout/mouseleave on absolute positioned elements over textareas and input type="text"
var handleHover = function(e) {
var t = this;
// next two lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
if ( p == this ) {
if ( $.browser.mozilla ) {
if ( e.type == "mouseout" ) {
t.mtout = setTimeout( function(){doHover(e,t);}, 30 );
} else {
if (t.mtout) { t.mtout = clearTimeout(t.mtout); }
}
}
return;
} else {
if (t.mtout) { t.mtout = clearTimeout(t.mtout); }
doHover(e,t);
}
};
// A private function for handling mouse 'hovering'
var doHover = function(e,ob) {
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
// cancel hoverIntent timer if it exists
if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
// else e.type == "onmouseover"
if (e.type == "mouseover") {
// set "previous" X and Y position based on initial entry point
pX = ev.pageX; pY = ev.pageY;
// update "current" X and Y position based on mousemove
$(ob).bind("mousemove",track);
// start polling interval (self-calling timeout) to compare mouse coordinates over time
if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
// else e.type == "onmouseout"
} else {
// unbind expensive mousemove event
$(ob).unbind("mousemove",track);
// if hoverIntent state is true, then call the mouseOut function after the specified delay
if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
}
};
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
};
})(jQuery); | JavaScript |
var autosave, autosaveLast = '', autosavePeriodical, autosaveOldMessage = '', autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen;
jQuery(document).ready( function($) {
var dotabkey = true;
autosaveLast = $('#post #title').val() + $('#post #content').val();
autosavePeriodical = $.schedule({time: autosaveL10n.autosaveInterval * 1000, func: function() { autosave(); }, repeat: true, protect: true});
//Disable autosave after the form has been submitted
$("#post").submit(function() {
$.cancel(autosavePeriodical);
});
$('input[type="submit"], a.submitdelete', '#submitpost').click(function(){
blockSave = true;
window.onbeforeunload = null;
$(':button, :submit', '#submitpost').each(function(){
var t = $(this);
if ( t.hasClass('button-primary') )
t.addClass('button-primary-disabled');
else
t.addClass('button-disabled');
});
if ( $(this).attr('id') == 'publish' )
$('#ajax-loading').css('visibility', 'visible');
else
$('#draft-ajax-loading').css('visibility', 'visible');
});
window.onbeforeunload = function(){
var mce = typeof(tinyMCE) != 'undefined' ? tinyMCE.activeEditor : false, title, content;
if ( mce && !mce.isHidden() ) {
if ( mce.isDirty() )
return autosaveL10n.saveAlert;
} else {
if ( fullscreen && fullscreen.settings.visible ) {
title = $('#wp-fullscreen-title').val();
content = $("#wp_mce_fullscreen").val();
} else {
title = $('#post #title').val();
content = $('#post #content').val();
}
if ( ( title || content ) && title + content != autosaveLast )
return autosaveL10n.saveAlert;
}
};
// preview
$('#post-preview').click(function(){
if ( $('#auto_draft').val() == '1' && notSaved ) {
autosaveDelayPreview = true;
autosave();
return false;
}
doPreview();
return false;
});
doPreview = function() {
$('input#wp-preview').val('dopreview');
$('form#post').attr('target', 'wp-preview').submit().attr('target', '');
$('input#wp-preview').val('');
}
// This code is meant to allow tabbing from Title to Post if tinyMCE is defined.
if ( typeof tinyMCE != 'undefined' ) {
$('#title')[$.browser.opera ? 'keypress' : 'keydown'](function (e) {
if ( e.which == 9 && !e.shiftKey && !e.controlKey && !e.altKey ) {
if ( ($('#auto_draft').val() == '1') && ($("#title").val().length > 0) ) { autosave(); }
if ( tinyMCE.activeEditor && ! tinyMCE.activeEditor.isHidden() && dotabkey ) {
e.preventDefault();
dotabkey = false;
tinyMCE.activeEditor.focus();
return false;
}
}
});
}
// autosave new posts after a title is typed but not if Publish or Save Draft is clicked
if ( '1' == $('#auto_draft').val() ) {
$('#title').blur( function() {
if ( !this.value || $('#auto_draft').val() != '1' )
return;
delayed_autosave();
});
}
});
function autosave_parse_response(response) {
var res = wpAjax.parseAjaxResponse(response, 'autosave'), message = '', postID, sup;
if ( res && res.responses && res.responses.length ) {
message = res.responses[0].data; // The saved message or error.
// someone else is editing: disable autosave, set errors
if ( res.responses[0].supplemental ) {
sup = res.responses[0].supplemental;
if ( 'disable' == sup['disable_autosave'] ) {
autosave = function() {};
res = { errors: true };
}
if ( sup['alert'] ) {
jQuery('#autosave-alert').remove();
jQuery('#titlediv').after('<div id="autosave-alert" class="error below-h2"><p>' + sup['alert'] + '</p></div>');
}
jQuery.each(sup, function(selector, value) {
if ( selector.match(/^replace-/) ) {
jQuery('#'+selector.replace('replace-', '')).val(value);
}
});
}
// if no errors: add slug UI
if ( !res.errors ) {
postID = parseInt( res.responses[0].id, 10 );
if ( !isNaN(postID) && postID > 0 ) {
autosave_update_slug(postID);
}
}
}
if ( message ) { // update autosave message
jQuery('.autosave-message').html(message);
} else if ( autosaveOldMessage && res ) {
jQuery('.autosave-message').html( autosaveOldMessage );
}
return res;
}
// called when autosaving pre-existing post
function autosave_saved(response) {
blockSave = false;
autosave_parse_response(response); // parse the ajax response
autosave_enable_buttons(); // re-enable disabled form buttons
}
// called when autosaving new post
function autosave_saved_new(response) {
blockSave = false;
var res = autosave_parse_response(response), postID;
if ( res && res.responses.length && !res.errors ) {
// An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves
postID = parseInt( res.responses[0].id, 10 );
if ( !isNaN(postID) && postID > 0 ) {
notSaved = false;
jQuery('#auto_draft').val('0'); // No longer an auto-draft
}
autosave_enable_buttons();
if ( autosaveDelayPreview ) {
autosaveDelayPreview = false;
doPreview();
}
} else {
autosave_enable_buttons(); // re-enable disabled form buttons
}
}
function autosave_update_slug(post_id) {
// create slug area only if not already there
if ( 'undefined' != makeSlugeditClickable && jQuery.isFunction(makeSlugeditClickable) && !jQuery('#edit-slug-box > *').size() ) {
jQuery.post( ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_title: fullscreen && fullscreen.settings.visible ? jQuery('#wp-fullscreen-title').val() : jQuery('#title').val(),
samplepermalinknonce: jQuery('#samplepermalinknonce').val()
},
function(data) {
if ( data !== '-1' ) {
jQuery('#edit-slug-box').html(data);
makeSlugeditClickable();
}
}
);
}
}
function autosave_loading() {
jQuery('.autosave-message').html(autosaveL10n.savingText);
}
function autosave_enable_buttons() {
// delay that a bit to avoid some rare collisions while the DOM is being updated.
setTimeout(function(){
jQuery(':button, :submit', '#submitpost').removeAttr('disabled');
jQuery('.ajax-loading').css('visibility', 'hidden');
}, 500);
}
function autosave_disable_buttons() {
jQuery(':button, :submit', '#submitpost').prop('disabled', true);
// Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
setTimeout(autosave_enable_buttons, 5000);
}
function delayed_autosave() {
setTimeout(function(){
if ( blockSave )
return;
autosave();
}, 200);
}
autosave = function() {
// (bool) is rich editor enabled and active
blockSave = true;
var rich = (typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden(),
post_data, doAutoSave, ed, origStatus, successCallback;
autosave_disable_buttons();
post_data = {
action: "autosave",
post_ID: jQuery("#post_ID").val() || 0,
autosavenonce: jQuery('#autosavenonce').val(),
post_type: jQuery('#post_type').val() || "",
autosave: 1
};
jQuery('.tags-input').each( function() {
post_data[this.name] = this.value;
} );
// We always send the ajax request in order to keep the post lock fresh.
// This (bool) tells whether or not to write the post to the DB during the ajax request.
doAutoSave = true;
// No autosave while thickbox is open (media buttons)
if ( jQuery("#TB_window").css('display') == 'block' )
doAutoSave = false;
/* Gotta do this up here so we can check the length when tinyMCE is in use */
if ( rich && doAutoSave ) {
ed = tinyMCE.activeEditor;
// Don't run while the TinyMCE spellcheck is on. It resets all found words.
if ( ed.plugins.spellchecker && ed.plugins.spellchecker.active ) {
doAutoSave = false;
} else {
if ( 'mce_fullscreen' == ed.id || 'wp_mce_fullscreen' == ed.id )
tinyMCE.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'});
tinyMCE.triggerSave();
}
}
if ( fullscreen && fullscreen.settings.visible ) {
post_data["post_title"] = jQuery('#wp-fullscreen-title').val();
post_data["content"] = jQuery("#wp_mce_fullscreen").val();
} else {
post_data["post_title"] = jQuery("#title").val()
post_data["content"] = jQuery("#content").val();
}
if ( jQuery('#post_name').val() )
post_data["post_name"] = jQuery('#post_name').val();
// Nothing to save or no change.
if ( ( post_data["post_title"].length == 0 && post_data["content"].length == 0 ) || post_data["post_title"] + post_data["content"] == autosaveLast ) {
doAutoSave = false;
}
origStatus = jQuery('#original_post_status').val();
goodcats = ([]);
jQuery("[name='post_category[]']:checked").each( function(i) {
goodcats.push(this.value);
} );
post_data["catslist"] = goodcats.join(",");
if ( jQuery("#comment_status").prop("checked") )
post_data["comment_status"] = 'open';
if ( jQuery("#ping_status").prop("checked") )
post_data["ping_status"] = 'open';
if ( jQuery("#excerpt").size() )
post_data["excerpt"] = jQuery("#excerpt").val();
if ( jQuery("#post_author").size() )
post_data["post_author"] = jQuery("#post_author").val();
if ( jQuery("#parent_id").val() )
post_data["parent_id"] = jQuery("#parent_id").val();
post_data["user_ID"] = jQuery("#user-id").val();
if ( jQuery('#auto_draft').val() == '1' )
post_data["auto_draft"] = '1';
if ( doAutoSave ) {
autosaveLast = post_data["post_title"] + post_data["content"];
jQuery(document).triggerHandler('wpcountwords', [ post_data["content"] ]);
} else {
post_data['autosave'] = 0;
}
if ( post_data["auto_draft"] == '1' ) {
successCallback = autosave_saved_new; // new post
} else {
successCallback = autosave_saved; // pre-existing post
}
autosaveOldMessage = jQuery('#autosave').html();
jQuery.ajax({
data: post_data,
beforeSend: doAutoSave ? autosave_loading : null,
type: "POST",
url: ajaxurl,
success: successCallback
});
}
| JavaScript |
/*
http://www.JSON.org/json2.js
2011-02-23
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON;
if (!JSON) {
JSON = {};
}
(function () {
"use strict";
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
| JavaScript |
/*!
* jQuery Form Plugin
* version: 2.73 (03-MAY-2011)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are intended to be exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').bind('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function') {
options = { success: options };
}
var action = this.attr('action');
var url = (typeof action === 'string') ? $.trim(action) : '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
url = url || window.location.href || '';
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57)
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var n,v,a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n]) {
a.push( { name: n, value: options.data[n][k] } );
}
}
else {
v = options.data[n];
v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
a.push( { name: n, value: v } );
}
}
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var $form = this, callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || options; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
// are there files to upload?
var fileInputs = $('input:file', this).length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, fileUpload);
}
else {
fileUpload();
}
}
else {
$.ajax(options);
}
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
if ($(':input[name=submit],:input[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we won't be
// able to invoke the submit fn on the form (at least not x-browser)
alert('Error: Form elements must not have name or id of "submit".');
return;
}
var s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id;
var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />');
var io = $io[0];
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
s.error && s.error.call(s.context, xhr, e, e);
g && $.event.trigger("ajaxError", [xhr, s, e]);
s.complete && s.complete.call(s.context, xhr, e);
}
};
var g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
return;
}
if (xhr.aborted) {
return;
}
var timedOut = 0, timeoutHandle;
// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (form.getAttribute('method') != 'POST') {
form.setAttribute('method', 'POST');
}
if (form.getAttribute('action') != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout);
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
.appendTo(form)[0]);
}
}
// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
if (e === true && xhr) {
xhr.abort('timeout');
return;
}
var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var ok = true;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header];
};
var scr = /(json|script|text)/.test(s.dataType);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent;
}
else if (b) {
xhr.responseText = b.innerHTML;
}
}
}
else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = httpData(xhr, s.dataType, s);
}
catch(e){
log('error caught:',e);
ok = false;
xhr.error = e;
s.error && s.error.call(s.context, xhr, 'error', e);
g && $.event.trigger("ajaxError", [xhr, s, e]);
}
if (xhr.aborted) {
log('upload aborted');
ok = false;
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
s.success && s.success.call(s.context, data, 'success', xhr);
g && $.event.trigger("ajaxSuccess", [xhr, s]);
}
g && $.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error');
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function() {
$io.removeData('form-plugin-onload');
$io.remove();
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
$.error && $.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
// in jQuery 1.3+ we can fix mistakes with the ready state
if (this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}).bind('click.form-plugin', function(e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest(':submit');
if (t.length == 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el) {
a.push({name: n, value: $(el).val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: n, value: v});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $(':text').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug) {
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
};
})(jQuery);
| JavaScript |
/******************************************************************************************************************************
* @ Original idea by by Binny V A, Original version: 2.00.A
* @ http://www.openjs.com/scripts/events/keyboard_shortcuts/
* @ Original License : BSD
* @ jQuery Plugin by Tzury Bar Yochay
mail: tzury.by@gmail.com
blog: evalinux.wordpress.com
face: facebook.com/profile.php?id=513676303
(c) Copyrights 2007
* @ jQuery Plugin version Beta (0.0.2)
* @ License: jQuery-License.
TODO:
add queue support (as in gmail) e.g. 'x' then 'y', etc.
add mouse + mouse wheel events.
USAGE:
$.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');});
$.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});>
$.hotkeys.remove('Ctrl+c');
$.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'});
******************************************************************************************************************************/
(function (jQuery){
this.version = '(beta)(0.0.3)';
this.all = {};
this.special_keys = {
27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 20: 'capslock',
144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',35:'end', 33: 'pageup',
34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 112:'f1',113:'f2', 114:'f3',
115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12'};
this.shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&",
"8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<",
".":">", "/":"?", "\\":"|" };
this.add = function(combi, options, callback) {
if (jQuery.isFunction(options)){
callback = options;
options = {};
}
var opt = {},
defaults = {type: 'keydown', propagate: false, disableInInput: false, target: jQuery('html')[0]},
that = this;
opt = jQuery.extend( opt , defaults, options || {} );
combi = combi.toLowerCase();
// inspect if keystroke matches
var inspector = function(event) {
event = jQuery.event.fix(event); // jQuery event normalization.
var element = event.target;
// @ TextNode -> nodeType == 3
element = (element.nodeType==3) ? element.parentNode : element;
if(opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields
var target = jQuery(element);
if( target.is("input") || target.is("textarea")){
return;
}
}
var code = event.which,
type = event.type,
character = String.fromCharCode(code).toLowerCase(),
special = that.special_keys[code],
shift = event.shiftKey,
ctrl = event.ctrlKey,
alt= event.altKey,
meta = event.metaKey,
propagate = true, // default behaivour
mapPoint = null;
// in opera + safari, the event.target is unpredictable.
// for example: 'keydown' might be associated with HtmlBodyElement
// or the element where you last clicked with your mouse.
if (jQuery.browser.opera || jQuery.browser.safari){
while (!that.all[element] && element.parentNode){
element = element.parentNode;
}
}
var cbMap = that.all[element].events[type].callbackMap;
if(!shift && !ctrl && !alt && !meta) { // No Modifiers
mapPoint = cbMap[special] || cbMap[character]
}
// deals with combinaitons (alt|ctrl|shift+anything)
else{
var modif = '';
if(alt) modif +='alt+';
if(ctrl) modif+= 'ctrl+';
if(shift) modif += 'shift+';
if(meta) modif += 'meta+';
// modifiers + special keys or modifiers + characters or modifiers + shift characters
mapPoint = cbMap[modif+special] || cbMap[modif+character] || cbMap[modif+that.shift_nums[character]]
}
if (mapPoint){
mapPoint.cb(event);
if(!mapPoint.propagate) {
event.stopPropagation();
event.preventDefault();
return false;
}
}
};
// first hook for this element
if (!this.all[opt.target]){
this.all[opt.target] = {events:{}};
}
if (!this.all[opt.target].events[opt.type]){
this.all[opt.target].events[opt.type] = {callbackMap: {}}
jQuery.event.add(opt.target, opt.type, inspector);
}
this.all[opt.target].events[opt.type].callbackMap[combi] = {cb: callback, propagate:opt.propagate};
return jQuery;
};
this.remove = function(exp, opt) {
opt = opt || {};
target = opt.target || jQuery('html')[0];
type = opt.type || 'keydown';
exp = exp.toLowerCase();
delete this.all[target].events[type].callbackMap[exp]
return jQuery;
};
jQuery.hotkeys = this;
return jQuery;
})(jQuery); | JavaScript |
(function($){$.scheduler=function(){this.bucket={};return;};$.scheduler.prototype={schedule:function(){var ctx={"id":null,"time":1000,"repeat":false,"protect":false,"obj":null,"func":function(){},"args":[]};function _isfn(fn){return(!!fn&&typeof fn!="string"&&typeof fn[0]=="undefined"&&RegExp("function","i").test(fn+""));};var i=0;var override=false;if(typeof arguments[i]=="object"&&arguments.length>1){override=true;i++;}
if(typeof arguments[i]=="object"){for(var option in arguments[i])
if(typeof ctx[option]!="undefined")
ctx[option]=arguments[i][option];i++;}
if(typeof arguments[i]=="number"||(typeof arguments[i]=="string"&&arguments[i].match(RegExp("^[0-9]+[smhdw]$"))))
ctx["time"]=arguments[i++];if(typeof arguments[i]=="boolean")
ctx["repeat"]=arguments[i++];if(typeof arguments[i]=="boolean")
ctx["protect"]=arguments[i++];if(typeof arguments[i]=="object"&&typeof arguments[i+1]=="string"&&_isfn(arguments[i][arguments[i+1]])){ctx["obj"]=arguments[i++];ctx["func"]=arguments[i++];}
else if(typeof arguments[i]!="undefined"&&(_isfn(arguments[i])||typeof arguments[i]=="string"))
ctx["func"]=arguments[i++];while(typeof arguments[i]!="undefined")
ctx["args"].push(arguments[i++]);if(override){if(typeof arguments[1]=="object"){for(var option in arguments[0])
if(typeof ctx[option]!="undefined"&&typeof arguments[1][option]=="undefined")
ctx[option]=arguments[0][option];}
else{for(var option in arguments[0])
if(typeof ctx[option]!="undefined")
ctx[option]=arguments[0][option];}
i++;}
ctx["_scheduler"]=this;ctx["_handle"]=null;var match=String(ctx["time"]).match(RegExp("^([0-9]+)([smhdw])$"));if(match&&match[0]!="undefined"&&match[1]!="undefined")
ctx["time"]=String(parseInt(match[1])*{s:1000,m:1000*60,h:1000*60*60,d:1000*60*60*24,w:1000*60*60*24*7}[match[2]]);if(ctx["id"]==null)
ctx["id"]=(String(ctx["repeat"])+":"
+String(ctx["protect"])+":"
+String(ctx["time"])+":"
+String(ctx["obj"])+":"
+String(ctx["func"])+":"
+String(ctx["args"]));if(ctx["protect"])
if(typeof this.bucket[ctx["id"]]!="undefined")
return this.bucket[ctx["id"]];if(!_isfn(ctx["func"])){if(ctx["obj"]!=null&&typeof ctx["obj"]=="object"&&typeof ctx["func"]=="string"&&_isfn(ctx["obj"][ctx["func"]]))
ctx["func"]=ctx["obj"][ctx["func"]];else
ctx["func"]=eval("function () { "+ctx["func"]+" }");}
ctx["_handle"]=this._schedule(ctx);this.bucket[ctx["id"]]=ctx;return ctx;},reschedule:function(ctx){if(typeof ctx=="string")
ctx=this.bucket[ctx];ctx["_handle"]=this._schedule(ctx);return ctx;},_schedule:function(ctx){var trampoline=function(){var obj=(ctx["obj"]!=null?ctx["obj"]:ctx);(ctx["func"]).apply(obj,ctx["args"]);if(typeof(ctx["_scheduler"]).bucket[ctx["id"]]!="undefined"&&ctx["repeat"])
(ctx["_scheduler"])._schedule(ctx);else
delete(ctx["_scheduler"]).bucket[ctx["id"]];};return setTimeout(trampoline,ctx["time"]);},cancel:function(ctx){if(typeof ctx=="string")
ctx=this.bucket[ctx];if(typeof ctx=="object"){clearTimeout(ctx["_handle"]);delete this.bucket[ctx["id"]];}}};$.extend({scheduler$:new $.scheduler(),schedule:function(){return $.scheduler$.schedule.apply($.scheduler$,arguments)},reschedule:function(){return $.scheduler$.reschedule.apply($.scheduler$,arguments)},cancel:function(){return $.scheduler$.cancel.apply($.scheduler$,arguments)}});$.fn.extend({schedule:function(){var a=[{}];for(var i=0;i<arguments.length;i++)
a.push(arguments[i]);return this.each(function(){a[0]={"id":this,"obj":this};return $.schedule.apply($,a);});}});})(jQuery); | JavaScript |
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent']
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0],
transparent: [255,255,255]
};
})(jQuery);
| JavaScript |
/*
* jquery.suggest 1.1b - 2007-08-06
* Patched by Mark Jaquith with Alexander Dick's "multiple items" patch to allow for auto-suggesting of more than one tag before submitting
* See: http://www.vulgarisoip.com/2007/06/29/jquerysuggest-an-alternative-jquery-based-autocomplete-library/#comment-7228
*
* Uses code and techniques from following libraries:
* 1. http://www.dyve.net/jquery/?autocomplete
* 2. http://dev.jquery.com/browser/trunk/plugins/interface/iautocompleter.js
*
* All the new stuff written by Peter Vulgaris (www.vulgarisoip.com)
* Feel free to do whatever you want with this file
*
*/
(function($) {
$.suggest = function(input, options) {
var $input, $results, timeout, prevLength, cache, cacheSize;
$input = $(input).attr("autocomplete", "off");
$results = $(document.createElement("ul"));
timeout = false; // hold timeout ID for suggestion results to appear
prevLength = 0; // last recorded length of $input.val()
cache = []; // cache MRU list
cacheSize = 0; // size of cache in chars (bytes?)
$results.addClass(options.resultsClass).appendTo('body');
resetPosition();
$(window)
.load(resetPosition) // just in case user is changing size of page while loading
.resize(resetPosition);
$input.blur(function() {
setTimeout(function() { $results.hide() }, 200);
});
// help IE users if possible
if ( $.browser.msie ) {
try {
$results.bgiframe();
} catch(e) { }
}
// I really hate browser detection, but I don't see any other way
if ($.browser.mozilla)
$input.keypress(processKey); // onkeypress repeats arrow keys in Mozilla/Opera
else
$input.keydown(processKey); // onkeydown repeats arrow keys in IE/Safari
function resetPosition() {
// requires jquery.dimension plugin
var offset = $input.offset();
$results.css({
top: (offset.top + input.offsetHeight) + 'px',
left: offset.left + 'px'
});
}
function processKey(e) {
// handling up/down/escape requires results to be visible
// handling enter/tab requires that AND a result to be selected
if ((/27$|38$|40$/.test(e.keyCode) && $results.is(':visible')) ||
(/^13$|^9$/.test(e.keyCode) && getCurrentResult())) {
if (e.preventDefault)
e.preventDefault();
if (e.stopPropagation)
e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
switch(e.keyCode) {
case 38: // up
prevResult();
break;
case 40: // down
nextResult();
break;
case 9: // tab
case 13: // return
selectCurrentResult();
break;
case 27: // escape
$results.hide();
break;
}
} else if ($input.val().length != prevLength) {
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(suggest, options.delay);
prevLength = $input.val().length;
}
}
function suggest() {
var q = $.trim($input.val()), multipleSepPos, items;
if ( options.multiple ) {
multipleSepPos = q.lastIndexOf(options.multipleSep);
if ( multipleSepPos != -1 ) {
q = $.trim(q.substr(multipleSepPos + options.multipleSep.length));
}
}
if (q.length >= options.minchars) {
cached = checkCache(q);
if (cached) {
displayItems(cached['items']);
} else {
$.get(options.source, {q: q}, function(txt) {
$results.hide();
items = parseTxt(txt, q);
displayItems(items);
addToCache(q, items, txt.length);
});
}
} else {
$results.hide();
}
}
function checkCache(q) {
var i;
for (i = 0; i < cache.length; i++)
if (cache[i]['q'] == q) {
cache.unshift(cache.splice(i, 1)[0]);
return cache[0];
}
return false;
}
function addToCache(q, items, size) {
var cached;
while (cache.length && (cacheSize + size > options.maxCacheSize)) {
cached = cache.pop();
cacheSize -= cached['size'];
}
cache.push({
q: q,
size: size,
items: items
});
cacheSize += size;
}
function displayItems(items) {
var html = '', i;
if (!items)
return;
if (!items.length) {
$results.hide();
return;
}
resetPosition(); // when the form moves after the page has loaded
for (i = 0; i < items.length; i++)
html += '<li>' + items[i] + '</li>';
$results.html(html).show();
$results
.children('li')
.mouseover(function() {
$results.children('li').removeClass(options.selectClass);
$(this).addClass(options.selectClass);
})
.click(function(e) {
e.preventDefault();
e.stopPropagation();
selectCurrentResult();
});
}
function parseTxt(txt, q) {
var items = [], tokens = txt.split(options.delimiter), i, token;
// parse returned data for non-empty items
for (i = 0; i < tokens.length; i++) {
token = $.trim(tokens[i]);
if (token) {
token = token.replace(
new RegExp(q, 'ig'),
function(q) { return '<span class="' + options.matchClass + '">' + q + '</span>' }
);
items[items.length] = token;
}
}
return items;
}
function getCurrentResult() {
var $currentResult;
if (!$results.is(':visible'))
return false;
$currentResult = $results.children('li.' + options.selectClass);
if (!$currentResult.length)
$currentResult = false;
return $currentResult;
}
function selectCurrentResult() {
$currentResult = getCurrentResult();
if ($currentResult) {
if ( options.multiple ) {
if ( $input.val().indexOf(options.multipleSep) != -1 ) {
$currentVal = $input.val().substr( 0, ( $input.val().lastIndexOf(options.multipleSep) + options.multipleSep.length ) );
} else {
$currentVal = "";
}
$input.val( $currentVal + $currentResult.text() + options.multipleSep);
$input.focus();
} else {
$input.val($currentResult.text());
}
$results.hide();
if (options.onSelect)
options.onSelect.apply($input[0]);
}
}
function nextResult() {
$currentResult = getCurrentResult();
if ($currentResult)
$currentResult
.removeClass(options.selectClass)
.next()
.addClass(options.selectClass);
else
$results.children('li:first-child').addClass(options.selectClass);
}
function prevResult() {
var $currentResult = getCurrentResult();
if ($currentResult)
$currentResult
.removeClass(options.selectClass)
.prev()
.addClass(options.selectClass);
else
$results.children('li:last-child').addClass(options.selectClass);
}
}
$.fn.suggest = function(source, options) {
if (!source)
return;
options = options || {};
options.multiple = options.multiple || false;
options.multipleSep = options.multipleSep || ", ";
options.source = source;
options.delay = options.delay || 100;
options.resultsClass = options.resultsClass || 'ac_results';
options.selectClass = options.selectClass || 'ac_over';
options.matchClass = options.matchClass || 'ac_match';
options.minchars = options.minchars || 2;
options.delimiter = options.delimiter || '\n';
options.onSelect = options.onSelect || false;
options.maxCacheSize = options.maxCacheSize || 65536;
this.each(function() {
new $.suggest(this, options);
});
return this;
};
})(jQuery); | JavaScript |
(function($){
$.fn.filter_visible = function(depth) {
depth = depth || 3;
var is_visible = function() {
var p = $(this), i;
for(i=0; i<depth-1; ++i) {
if (!p.is(':visible')) return false;
p = p.parent();
}
return true;
}
return this.filter(is_visible);
};
$.table_hotkeys = function(table, keys, opts) {
opts = $.extend($.table_hotkeys.defaults, opts);
var selected_class, destructive_class, set_current_row, adjacent_row_callback, get_adjacent_row, adjacent_row, prev_row, next_row, check, get_first_row, get_last_row, make_key_callback, first_row;
selected_class = opts.class_prefix + opts.selected_suffix;
destructive_class = opts.class_prefix + opts.destructive_suffix
set_current_row = function (tr) {
if ($.table_hotkeys.current_row) $.table_hotkeys.current_row.removeClass(selected_class);
tr.addClass(selected_class);
tr[0].scrollIntoView(false);
$.table_hotkeys.current_row = tr;
};
adjacent_row_callback = function(which) {
if (!adjacent_row(which) && $.isFunction(opts[which+'_page_link_cb'])) {
opts[which+'_page_link_cb']();
}
};
get_adjacent_row = function(which) {
var first_row, method;
if (!$.table_hotkeys.current_row) {
first_row = get_first_row();
$.table_hotkeys.current_row = first_row;
return first_row[0];
}
method = 'prev' == which? $.fn.prevAll : $.fn.nextAll;
return method.call($.table_hotkeys.current_row, opts.cycle_expr).filter_visible()[0];
};
adjacent_row = function(which) {
var adj = get_adjacent_row(which);
if (!adj) return false;
set_current_row($(adj));
return true;
};
prev_row = function() { return adjacent_row('prev'); };
next_row = function() { return adjacent_row('next'); };
check = function() {
$(opts.checkbox_expr, $.table_hotkeys.current_row).each(function() {
this.checked = !this.checked;
});
};
get_first_row = function() {
return $(opts.cycle_expr, table).filter_visible().eq(opts.start_row_index);
};
get_last_row = function() {
var rows = $(opts.cycle_expr, table).filter_visible();
return rows.eq(rows.length-1);
};
make_key_callback = function(expr) {
return function() {
if ( null == $.table_hotkeys.current_row ) return false;
var clickable = $(expr, $.table_hotkeys.current_row);
if (!clickable.length) return false;
if (clickable.is('.'+destructive_class)) next_row() || prev_row();
clickable.click();
}
};
first_row = get_first_row();
if (!first_row.length) return;
if (opts.highlight_first)
set_current_row(first_row);
else if (opts.highlight_last)
set_current_row(get_last_row());
$.hotkeys.add(opts.prev_key, opts.hotkeys_opts, function() {return adjacent_row_callback('prev')});
$.hotkeys.add(opts.next_key, opts.hotkeys_opts, function() {return adjacent_row_callback('next')});
$.hotkeys.add(opts.mark_key, opts.hotkeys_opts, check);
$.each(keys, function() {
var callback, key;
if ($.isFunction(this[1])) {
callback = this[1];
key = this[0];
$.hotkeys.add(key, opts.hotkeys_opts, function(event) { return callback(event, $.table_hotkeys.current_row); });
} else {
key = this;
$.hotkeys.add(key, opts.hotkeys_opts, make_key_callback('.'+opts.class_prefix+key));
}
});
};
$.table_hotkeys.current_row = null;
$.table_hotkeys.defaults = {cycle_expr: 'tr', class_prefix: 'vim-', selected_suffix: 'current',
destructive_suffix: 'destructive', hotkeys_opts: {disableInInput: true, type: 'keypress'},
checkbox_expr: ':checkbox', next_key: 'j', prev_key: 'k', mark_key: 'x',
start_row_index: 2, highlight_first: false, highlight_last: false, next_page_link_cb: false, prev_page_link_cb: false};
})(jQuery);
| JavaScript |
/*!
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);
| JavaScript |
var wpAjax = jQuery.extend( {
unserialize: function( s ) {
var r = {}, q, pp, i, p;
if ( !s ) { return r; }
q = s.split('?'); if ( q[1] ) { s = q[1]; }
pp = s.split('&');
for ( i in pp ) {
if ( jQuery.isFunction(pp.hasOwnProperty) && !pp.hasOwnProperty(i) ) { continue; }
p = pp[i].split('=');
r[p[0]] = p[1];
}
return r;
},
parseAjaxResponse: function( x, r, e ) { // 1 = good, 0 = strange (bad data?), -1 = you lack permission
var parsed = {}, re = jQuery('#' + r).html(''), err = '';
if ( x && typeof x == 'object' && x.getElementsByTagName('wp_ajax') ) {
parsed.responses = [];
parsed.errors = false;
jQuery('response', x).each( function() {
var th = jQuery(this), child = jQuery(this.firstChild), response;
response = { action: th.attr('action'), what: child.get(0).nodeName, id: child.attr('id'), oldId: child.attr('old_id'), position: child.attr('position') };
response.data = jQuery( 'response_data', child ).text();
response.supplemental = {};
if ( !jQuery( 'supplemental', child ).children().each( function() {
response.supplemental[this.nodeName] = jQuery(this).text();
} ).size() ) { response.supplemental = false }
response.errors = [];
if ( !jQuery('wp_error', child).each( function() {
var code = jQuery(this).attr('code'), anError, errorData, formField;
anError = { code: code, message: this.firstChild.nodeValue, data: false };
errorData = jQuery('wp_error_data[code="' + code + '"]', x);
if ( errorData ) { anError.data = errorData.get(); }
formField = jQuery( 'form-field', errorData ).text();
if ( formField ) { code = formField; }
if ( e ) { wpAjax.invalidateForm( jQuery('#' + e + ' :input[name="' + code + '"]' ).parents('.form-field:first') ); }
err += '<p>' + anError.message + '</p>';
response.errors.push( anError );
parsed.errors = true;
} ).size() ) { response.errors = false; }
parsed.responses.push( response );
} );
if ( err.length ) { re.html( '<div class="error">' + err + '</div>' ); }
return parsed;
}
if ( isNaN(x) ) { return !re.html('<div class="error"><p>' + x + '</p></div>'); }
x = parseInt(x,10);
if ( -1 == x ) { return !re.html('<div class="error"><p>' + wpAjax.noPerm + '</p></div>'); }
else if ( 0 === x ) { return !re.html('<div class="error"><p>' + wpAjax.broken + '</p></div>'); }
return true;
},
invalidateForm: function ( selector ) {
return jQuery( selector ).addClass( 'form-invalid' ).find('input:visible').change( function() { jQuery(this).closest('.form-invalid').removeClass( 'form-invalid' ); } );
},
validateForm: function( selector ) {
selector = jQuery( selector );
return !wpAjax.invalidateForm( selector.find('.form-required').filter( function() { return jQuery('input:visible', this).val() == ''; } ) ).size();
}
}, wpAjax || { noPerm: 'You do not have permission to do that.', broken: 'An unidentified error has occurred.' } );
// Basic form validation
jQuery(document).ready( function($){
$('form.validate').submit( function() { return wpAjax.validateForm( $(this) ); } );
});
| JavaScript |
(function(w) {
var init = function() {
var pr = document.getElementById('post-revisions'),
inputs = pr ? pr.getElementsByTagName('input') : [];
pr.onclick = function() {
var i, checkCount = 0, side;
for ( i = 0; i < inputs.length; i++ ) {
checkCount += inputs[i].checked ? 1 : 0;
side = inputs[i].getAttribute('name');
if ( ! inputs[i].checked &&
( 'left' == side && 1 > checkCount || 'right' == side && 1 < checkCount && ( ! inputs[i-1] || ! inputs[i-1].checked ) ) &&
! ( inputs[i+1] && inputs[i+1].checked && 'right' == inputs[i+1].getAttribute('name') ) )
inputs[i].style.visibility = 'hidden';
else if ( 'left' == side || 'right' == side )
inputs[i].style.visibility = 'visible';
}
}
pr.onclick();
}
if ( w && w.addEventListener )
w.addEventListener('load', init, false);
else if ( w && w.attachEvent )
w.attachEvent('onload', init);
})(window);
| JavaScript |
/*
* imgAreaSelect jQuery plugin
* version 0.9.6
*
* Copyright (c) 2008-2011 Michal Wojciechowski (odyniec.net)
*
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://odyniec.net/projects/imgareaselect/
*
*/
(function($) {
var abs = Math.abs,
max = Math.max,
min = Math.min,
round = Math.round;
function div() {
return $('<div/>');
}
$.imgAreaSelect = function (img, options) {
var
$img = $(img),
imgLoaded,
$box = div(),
$area = div(),
$border = div().add(div()).add(div()).add(div()),
$outer = div().add(div()).add(div()).add(div()),
$handles = $([]),
$areaOpera,
left, top,
imgOfs = { left: 0, top: 0 },
imgWidth, imgHeight,
$parent,
parOfs = { left: 0, top: 0 },
zIndex = 0,
position = 'absolute',
startX, startY,
scaleX, scaleY,
resizeMargin = 10,
resize,
minWidth, minHeight, maxWidth, maxHeight,
aspectRatio,
shown,
x1, y1, x2, y2,
selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
docElem = document.documentElement,
$p, d, i, o, w, h, adjusted;
function viewX(x) {
return x + imgOfs.left - parOfs.left;
}
function viewY(y) {
return y + imgOfs.top - parOfs.top;
}
function selX(x) {
return x - imgOfs.left + parOfs.left;
}
function selY(y) {
return y - imgOfs.top + parOfs.top;
}
function evX(event) {
return event.pageX - parOfs.left;
}
function evY(event) {
return event.pageY - parOfs.top;
}
function getSelection(noScale) {
var sx = noScale || scaleX, sy = noScale || scaleY;
return { x1: round(selection.x1 * sx),
y1: round(selection.y1 * sy),
x2: round(selection.x2 * sx),
y2: round(selection.y2 * sy),
width: round(selection.x2 * sx) - round(selection.x1 * sx),
height: round(selection.y2 * sy) - round(selection.y1 * sy) };
}
function setSelection(x1, y1, x2, y2, noScale) {
var sx = noScale || scaleX, sy = noScale || scaleY;
selection = {
x1: round(x1 / sx || 0),
y1: round(y1 / sy || 0),
x2: round(x2 / sx || 0),
y2: round(y2 / sy || 0)
};
selection.width = selection.x2 - selection.x1;
selection.height = selection.y2 - selection.y1;
}
function adjust() {
if (!$img.width())
return;
imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
imgWidth = $img.innerWidth();
imgHeight = $img.innerHeight();
imgOfs.top += ($img.outerHeight() - imgHeight) >> 1;
imgOfs.left += ($img.outerWidth() - imgWidth) >> 1;
minWidth = options.minWidth || 0;
minHeight = options.minHeight || 0;
maxWidth = min(options.maxWidth || 1<<24, imgWidth);
maxHeight = min(options.maxHeight || 1<<24, imgHeight);
if ($().jquery == '1.3.2' && position == 'fixed' &&
!docElem['getBoundingClientRect'])
{
imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
}
parOfs = $.inArray($parent.css('position'), ['absolute', 'relative']) + 1 ?
{ left: round($parent.offset().left) - $parent.scrollLeft(),
top: round($parent.offset().top) - $parent.scrollTop() } :
position == 'fixed' ?
{ left: $(document).scrollLeft(), top: $(document).scrollTop() } :
{ left: 0, top: 0 };
left = viewX(0);
top = viewY(0);
if (selection.x2 > imgWidth || selection.y2 > imgHeight)
doResize();
}
function update(resetKeyPress) {
if (!shown) return;
$box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
.add($area).width(w = selection.width).height(h = selection.height);
$area.add($border).add($handles).css({ left: 0, top: 0 });
$border
.width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
.height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
$($outer[0]).css({ left: left, top: top,
width: selection.x1, height: imgHeight });
$($outer[1]).css({ left: left + selection.x1, top: top,
width: w, height: selection.y1 });
$($outer[2]).css({ left: left + selection.x2, top: top,
width: imgWidth - selection.x2, height: imgHeight });
$($outer[3]).css({ left: left + selection.x1, top: top + selection.y2,
width: w, height: imgHeight - selection.y2 });
w -= $handles.outerWidth();
h -= $handles.outerHeight();
switch ($handles.length) {
case 8:
$($handles[4]).css({ left: w >> 1 });
$($handles[5]).css({ left: w, top: h >> 1 });
$($handles[6]).css({ left: w >> 1, top: h });
$($handles[7]).css({ top: h >> 1 });
case 4:
$handles.slice(1,3).css({ left: w });
$handles.slice(2,4).css({ top: h });
}
if (resetKeyPress !== false) {
if ($.imgAreaSelect.keyPress != docKeyPress)
$(document).unbind($.imgAreaSelect.keyPress,
$.imgAreaSelect.onKeyPress);
if (options.keys)
$(document)[$.imgAreaSelect.keyPress](
$.imgAreaSelect.onKeyPress = docKeyPress);
}
if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) {
$border.css('margin', 0);
setTimeout(function () { $border.css('margin', 'auto'); }, 0);
}
}
function doUpdate(resetKeyPress) {
adjust();
update(resetKeyPress);
x1 = viewX(selection.x1); y1 = viewY(selection.y1);
x2 = viewX(selection.x2); y2 = viewY(selection.y2);
}
function hide($elem, fn) {
options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
}
function areaMouseMove(event) {
var x = selX(evX(event)) - selection.x1,
y = selY(evY(event)) - selection.y1;
if (!adjusted) {
adjust();
adjusted = true;
$box.one('mouseout', function () { adjusted = false; });
}
resize = '';
if (options.resizable) {
if (y <= options.resizeMargin)
resize = 'n';
else if (y >= selection.height - options.resizeMargin)
resize = 's';
if (x <= options.resizeMargin)
resize += 'w';
else if (x >= selection.width - options.resizeMargin)
resize += 'e';
}
$box.css('cursor', resize ? resize + '-resize' :
options.movable ? 'move' : '');
if ($areaOpera)
$areaOpera.toggle();
}
function docMouseUp(event) {
$('body').css('cursor', '');
if (options.autoHide || selection.width * selection.height == 0)
hide($box.add($outer), function () { $(this).hide(); });
$(document).unbind('mousemove', selectingMouseMove);
$box.mousemove(areaMouseMove);
options.onSelectEnd(img, getSelection());
}
function areaMouseDown(event) {
if (event.which != 1) return false;
adjust();
if (resize) {
$('body').css('cursor', resize + '-resize');
x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
$(document).mousemove(selectingMouseMove)
.one('mouseup', docMouseUp);
$box.unbind('mousemove', areaMouseMove);
}
else if (options.movable) {
startX = left + selection.x1 - evX(event);
startY = top + selection.y1 - evY(event);
$box.unbind('mousemove', areaMouseMove);
$(document).mousemove(movingMouseMove)
.one('mouseup', function () {
options.onSelectEnd(img, getSelection());
$(document).unbind('mousemove', movingMouseMove);
$box.mousemove(areaMouseMove);
});
}
else
$img.mousedown(event);
return false;
}
function fixAspectRatio(xFirst) {
if (aspectRatio)
if (xFirst) {
x2 = max(left, min(left + imgWidth,
x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
y2 = round(max(top, min(top + imgHeight,
y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
x2 = round(x2);
}
else {
y2 = max(top, min(top + imgHeight,
y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
x2 = round(max(left, min(left + imgWidth,
x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
y2 = round(y2);
}
}
function doResize() {
x1 = min(x1, left + imgWidth);
y1 = min(y1, top + imgHeight);
if (abs(x2 - x1) < minWidth) {
x2 = x1 - minWidth * (x2 < x1 || -1);
if (x2 < left)
x1 = left + minWidth;
else if (x2 > left + imgWidth)
x1 = left + imgWidth - minWidth;
}
if (abs(y2 - y1) < minHeight) {
y2 = y1 - minHeight * (y2 < y1 || -1);
if (y2 < top)
y1 = top + minHeight;
else if (y2 > top + imgHeight)
y1 = top + imgHeight - minHeight;
}
x2 = max(left, min(x2, left + imgWidth));
y2 = max(top, min(y2, top + imgHeight));
fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
if (abs(x2 - x1) > maxWidth) {
x2 = x1 - maxWidth * (x2 < x1 || -1);
fixAspectRatio();
}
if (abs(y2 - y1) > maxHeight) {
y2 = y1 - maxHeight * (y2 < y1 || -1);
fixAspectRatio(true);
}
selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
width: abs(x2 - x1), height: abs(y2 - y1) };
update();
options.onSelectChange(img, getSelection());
}
function selectingMouseMove(event) {
x2 = resize == '' || /w|e/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
y2 = resize == '' || /n|s/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
doResize();
return false;
}
function doMove(newX1, newY1) {
x2 = (x1 = newX1) + selection.width;
y2 = (y1 = newY1) + selection.height;
$.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
y2: selY(y2) });
update();
options.onSelectChange(img, getSelection());
}
function movingMouseMove(event) {
x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
doMove(x1, y1);
event.preventDefault();
return false;
}
function startSelection() {
$(document).unbind('mousemove', startSelection);
adjust();
x2 = x1;
y2 = y1;
doResize();
resize = '';
if ($outer.is(':not(:visible)'))
$box.add($outer).hide().fadeIn(options.fadeSpeed||0);
shown = true;
$(document).unbind('mouseup', cancelSelection)
.mousemove(selectingMouseMove).one('mouseup', docMouseUp);
$box.unbind('mousemove', areaMouseMove);
options.onSelectStart(img, getSelection());
}
function cancelSelection() {
$(document).unbind('mousemove', startSelection)
.unbind('mouseup', cancelSelection);
hide($box.add($outer));
setSelection(selX(x1), selY(y1), selX(x1), selY(y1));
options.onSelectChange(img, getSelection());
options.onSelectEnd(img, getSelection());
}
function imgMouseDown(event) {
if (event.which != 1 || $outer.is(':animated')) return false;
adjust();
startX = x1 = evX(event);
startY = y1 = evY(event);
$(document).mousemove(startSelection).mouseup(cancelSelection);
return false;
}
function windowResize() {
doUpdate(false);
}
function imgLoad() {
imgLoaded = true;
setOptions(options = $.extend({
classPrefix: 'imgareaselect',
movable: true,
parent: 'body',
resizable: true,
resizeMargin: 10,
onInit: function () {},
onSelectStart: function () {},
onSelectChange: function () {},
onSelectEnd: function () {}
}, options));
$box.add($outer).css({ visibility: '' });
if (options.show) {
shown = true;
adjust();
update();
$box.add($outer).hide().fadeIn(options.fadeSpeed||0);
}
setTimeout(function () { options.onInit(img, getSelection()); }, 0);
}
var docKeyPress = function(event) {
var k = options.keys, d, t, key = event.keyCode;
d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
!isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
!isNaN(k.shift) && event.shiftKey ? k.shift :
!isNaN(k.arrows) ? k.arrows : 10;
if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
(k.ctrl == 'resize' && event.ctrlKey) ||
(k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
{
switch (key) {
case 37:
d = -d;
case 39:
t = max(x1, x2);
x1 = min(x1, x2);
x2 = max(t + d, x1);
fixAspectRatio();
break;
case 38:
d = -d;
case 40:
t = max(y1, y2);
y1 = min(y1, y2);
y2 = max(t + d, y1);
fixAspectRatio(true);
break;
default:
return;
}
doResize();
}
else {
x1 = min(x1, x2);
y1 = min(y1, y2);
switch (key) {
case 37:
doMove(max(x1 - d, left), y1);
break;
case 38:
doMove(x1, max(y1 - d, top));
break;
case 39:
doMove(x1 + min(d, imgWidth - selX(x2)), y1);
break;
case 40:
doMove(x1, y1 + min(d, imgHeight - selY(y2)));
break;
default:
return;
}
}
return false;
};
function styleOptions($elem, props) {
for (option in props)
if (options[option] !== undefined)
$elem.css(props[option], options[option]);
}
function setOptions(newOptions) {
if (newOptions.parent)
($parent = $(newOptions.parent)).append($box.add($outer));
$.extend(options, newOptions);
adjust();
if (newOptions.handles != null) {
$handles.remove();
$handles = $([]);
i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
while (i--)
$handles = $handles.add(div());
$handles.addClass(options.classPrefix + '-handle').css({
position: 'absolute',
fontSize: 0,
zIndex: zIndex + 1 || 1
});
if (!parseInt($handles.css('width')) >= 0)
$handles.width(5).height(5);
if (o = options.borderWidth)
$handles.css({ borderWidth: o, borderStyle: 'solid' });
styleOptions($handles, { borderColor1: 'border-color',
borderColor2: 'background-color',
borderOpacity: 'opacity' });
}
scaleX = options.imageWidth / imgWidth || 1;
scaleY = options.imageHeight / imgHeight || 1;
if (newOptions.x1 != null) {
setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
newOptions.y2);
newOptions.show = !newOptions.hide;
}
if (newOptions.keys)
options.keys = $.extend({ shift: 1, ctrl: 'resize' },
newOptions.keys);
$outer.addClass(options.classPrefix + '-outer');
$area.addClass(options.classPrefix + '-selection');
for (i = 0; i++ < 4;)
$($border[i-1]).addClass(options.classPrefix + '-border' + i);
styleOptions($area, { selectionColor: 'background-color',
selectionOpacity: 'opacity' });
styleOptions($border, { borderOpacity: 'opacity',
borderWidth: 'border-width' });
styleOptions($outer, { outerColor: 'background-color',
outerOpacity: 'opacity' });
if (o = options.borderColor1)
$($border[0]).css({ borderStyle: 'solid', borderColor: o });
if (o = options.borderColor2)
$($border[1]).css({ borderStyle: 'dashed', borderColor: o });
$box.append($area.add($border).add($areaOpera).add($handles));
if ($.browser.msie) {
if (o = $outer.css('filter').match(/opacity=([0-9]+)/))
$outer.css('opacity', o[1]/100);
if (o = $border.css('filter').match(/opacity=([0-9]+)/))
$border.css('opacity', o[1]/100);
}
if (newOptions.hide)
hide($box.add($outer));
else if (newOptions.show && imgLoaded) {
shown = true;
$box.add($outer).fadeIn(options.fadeSpeed||0);
doUpdate();
}
aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
$img.add($outer).unbind('mousedown', imgMouseDown);
if (options.disable || options.enable === false) {
$box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
$(window).unbind('resize', windowResize);
}
else {
if (options.enable || options.disable === false) {
if (options.resizable || options.movable)
$box.mousemove(areaMouseMove).mousedown(areaMouseDown);
$(window).resize(windowResize);
}
if (!options.persistent)
$img.add($outer).mousedown(imgMouseDown);
}
options.enable = options.disable = undefined;
}
this.remove = function () {
setOptions({ disable: true });
$box.add($outer).remove();
};
this.getOptions = function () { return options; };
this.setOptions = setOptions;
this.getSelection = getSelection;
this.setSelection = setSelection;
this.update = doUpdate;
$p = $img;
while ($p.length) {
zIndex = max(zIndex,
!isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
if ($p.css('position') == 'fixed')
position = 'fixed';
$p = $p.parent(':not(body)');
}
zIndex = options.zIndex || zIndex;
if ($.browser.msie)
$img.attr('unselectable', 'on');
$.imgAreaSelect.keyPress = $.browser.msie ||
$.browser.safari ? 'keydown' : 'keypress';
if ($.browser.opera)
$areaOpera = div().css({ width: '100%', height: '100%',
position: 'absolute', zIndex: zIndex + 2 || 2 });
$box.add($outer).css({ visibility: 'hidden', position: position,
overflow: 'hidden', zIndex: zIndex || '0' });
$box.css({ zIndex: zIndex + 2 || 2 });
$area.add($border).css({ position: 'absolute', fontSize: 0 });
img.complete || img.readyState == 'complete' || !$img.is('img') ?
imgLoad() : $img.one('load', imgLoad);
if ($.browser.msie && $.browser.version >= 9)
img.src = img.src;
};
$.fn.imgAreaSelect = function (options) {
options = options || {};
this.each(function () {
if ($(this).data('imgAreaSelect')) {
if (options.remove) {
$(this).data('imgAreaSelect').remove();
$(this).removeData('imgAreaSelect');
}
else
$(this).data('imgAreaSelect').setOptions(options);
}
else if (!options.remove) {
if (options.enable === undefined && options.disable === undefined)
options.enable = true;
$(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
}
});
if (options.instance)
return $(this).data('imgAreaSelect');
return this;
};
})(jQuery);
| JavaScript |
(function() {
tinymce.create('tinymce.plugins.wpGallery', {
init : function(ed, url) {
var t = this;
t.url = url;
t._createButtons();
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...');
ed.addCommand('WP_Gallery', function() {
var el = ed.selection.getNode(), post_id, vp = tinymce.DOM.getViewPort(),
H = vp.h - 80, W = ( 640 < vp.w ) ? 640 : vp.w;
if ( el.nodeName != 'IMG' ) return;
if ( ed.dom.getAttrib(el, 'class').indexOf('wpGallery') == -1 ) return;
post_id = tinymce.DOM.get('post_ID').value;
tb_show('', tinymce.documentBaseURL + '/media-upload.php?post_id='+post_id+'&tab=gallery&TB_iframe=true&width='+W+'&height='+H);
tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' );
});
ed.onMouseDown.add(function(ed, e) {
if ( e.target.nodeName == 'IMG' && ed.dom.hasClass(e.target, 'wpGallery') )
ed.plugins.wordpress._showButtons(e.target, 'wp_gallerybtns');
});
ed.onBeforeSetContent.add(function(ed, o) {
o.content = t._do_gallery(o.content);
});
ed.onPostProcess.add(function(ed, o) {
if (o.get)
o.content = t._get_gallery(o.content);
});
},
_do_gallery : function(co) {
return co.replace(/\[gallery([^\]]*)\]/g, function(a,b){
return '<img src="'+tinymce.baseURL+'/plugins/wpgallery/img/t.gif" class="wpGallery mceItem" title="gallery'+tinymce.DOM.encode(b)+'" />';
});
},
_get_gallery : function(co) {
function getAttr(s, n) {
n = new RegExp(n + '=\"([^\"]+)\"', 'g').exec(s);
return n ? tinymce.DOM.decode(n[1]) : '';
};
return co.replace(/(?:<p[^>]*>)*(<img[^>]+>)(?:<\/p>)*/g, function(a,im) {
var cls = getAttr(im, 'class');
if ( cls.indexOf('wpGallery') != -1 )
return '<p>['+tinymce.trim(getAttr(im, 'title'))+']</p>';
return a;
});
},
_createButtons : function() {
var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, editButton, dellButton;
DOM.remove('wp_gallerybtns');
DOM.add(document.body, 'div', {
id : 'wp_gallerybtns',
style : 'display:none;'
});
editButton = DOM.add('wp_gallerybtns', 'img', {
src : t.url+'/img/edit.png',
id : 'wp_editgallery',
width : '24',
height : '24',
title : ed.getLang('wordpress.editgallery')
});
tinymce.dom.Event.add(editButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor;
ed.windowManager.bookmark = ed.selection.getBookmark('simple');
ed.execCommand("WP_Gallery");
});
dellButton = DOM.add('wp_gallerybtns', 'img', {
src : t.url+'/img/delete.png',
id : 'wp_delgallery',
width : '24',
height : '24',
title : ed.getLang('wordpress.delgallery')
});
tinymce.dom.Event.add(dellButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor, el = ed.selection.getNode();
if ( el.nodeName == 'IMG' && ed.dom.hasClass(el, 'wpGallery') ) {
ed.dom.remove(el);
ed.execCommand('mceRepaint');
return false;
}
});
},
getInfo : function() {
return {
longname : 'Gallery Settings',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : '',
version : "1.0"
};
}
});
tinymce.PluginManager.add('wpgallery', tinymce.plugins.wpGallery);
})();
| JavaScript |
(function($){
$.ui.dialog.prototype.options.closeOnEscape = false;
$.widget("wp.wpdialog", $.ui.dialog, {
options: {
closeOnEscape: false
},
open: function() {
var ed;
// Initialize tinyMCEPopup if it exists and is the editor is active.
if ( tinyMCEPopup && typeof tinyMCE != 'undefined' && ( ed = tinyMCE.activeEditor ) && !ed.isHidden() ) {
tinyMCEPopup.init();
}
// Add beforeOpen event.
if ( this._isOpen || false === this._trigger('beforeOpen') ) {
return;
}
// Open the dialog.
$.ui.dialog.prototype.open.apply( this, arguments );
// WebKit leaves focus in the TinyMCE editor unless we shift focus.
this.element.focus();
this._trigger('refresh');
}
});
})(jQuery);
| JavaScript |
/**
* popup.js
*
* An altered version of tinyMCEPopup to work in the same window as tinymce.
*
* ------------------------------------------------------------------
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
// Some global instances
/**
* TinyMCE popup/dialog helper class. This gives you easy access to the
* parent editor instance and a bunch of other things. It's higly recommended
* that you load this script into your dialogs.
*
* @static
* @class tinyMCEPopup
*/
var tinyMCEPopup = {
/**
* Initializes the popup this will be called automatically.
*
* @method init
*/
init : function() {
var t = this, w, ti;
// Find window & API
w = t.getWin();
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.params = t.editor.windowManager.params;
t.features = t.editor.windowManager.features;
t.dom = tinymce.dom;
// Setup on init listeners
t.listeners = [];
t.onInit = {
add : function(f, s) {
t.listeners.push({func : f, scope : s});
}
};
t.isWindow = false;
t.id = t.features.id;
t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window);
},
/**
* Returns the reference to the parent window that opened the dialog.
*
* @method getWin
* @return {Window} Reference to the parent window that opened the dialog.
*/
getWin : function() {
return window;
},
/**
* Returns a window argument/parameter by name.
*
* @method getWindowArg
* @param {String} n Name of the window argument to retrive.
* @param {String} dv Optional default value to return.
* @return {String} Argument value or default value if it wasn't found.
*/
getWindowArg : function(n, dv) {
var v = this.params[n];
return tinymce.is(v) ? v : dv;
},
/**
* Returns a editor parameter/config option value.
*
* @method getParam
* @param {String} n Name of the editor config option to retrive.
* @param {String} dv Optional default value to return.
* @return {String} Parameter value or default value if it wasn't found.
*/
getParam : function(n, dv) {
return this.editor.getParam(n, dv);
},
/**
* Returns a language item by key.
*
* @method getLang
* @param {String} n Language item like mydialog.something.
* @param {String} dv Optional default value to return.
* @return {String} Language value for the item like "my string" or the default value if it wasn't found.
*/
getLang : function(n, dv) {
return this.editor.getLang(n, dv);
},
/**
* Executed a command on editor that opened the dialog/popup.
*
* @method execCommand
* @param {String} cmd Command to execute.
* @param {Boolean} ui Optional boolean value if the UI for the command should be presented or not.
* @param {Object} val Optional value to pass with the comman like an URL.
* @param {Object} a Optional arguments object.
*/
execCommand : function(cmd, ui, val, a) {
a = a || {};
a.skip_focus = 1;
this.restoreSelection();
return this.editor.execCommand(cmd, ui, val, a);
},
/**
* Resizes the dialog to the inner size of the window. This is needed since various browsers
* have different border sizes on windows.
*
* @method resizeToInnerSize
*/
resizeToInnerSize : function() {
var t = this;
// Detach it to workaround a Chrome specific bug
// https://sourceforge.net/tracker/?func=detail&atid=635682&aid=2926339&group_id=103281
setTimeout(function() {
var vp = t.dom.getViewPort(window);
t.editor.windowManager.resizeBy(
t.getWindowArg('mce_width') - vp.w,
t.getWindowArg('mce_height') - vp.h,
t.id || window
);
}, 0);
},
/**
* Will executed the specified string when the page has been loaded. This function
* was added for compatibility with the 2.x branch.
*
* @method executeOnLoad
* @param {String} s String to evalutate on init.
*/
executeOnLoad : function(s) {
this.onInit.add(function() {
eval(s);
});
},
/**
* Stores the current editor selection for later restoration. This can be useful since some browsers
* looses it's selection if a control element is selected/focused inside the dialogs.
*
* @method storeSelection
*/
storeSelection : function() {
this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark(1);
},
/**
* Restores any stored selection. This can be useful since some browsers
* looses it's selection if a control element is selected/focused inside the dialogs.
*
* @method restoreSelection
*/
restoreSelection : function() {
var t = tinyMCEPopup;
if (!t.isWindow && tinymce.isIE)
t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark);
},
/**
* Loads a specific dialog language pack. If you pass in plugin_url as a arugment
* when you open the window it will load the <plugin url>/langs/<code>_dlg.js lang pack file.
*
* @method requireLangPack
*/
requireLangPack : function() {
var t = this, u = t.getWindowArg('plugin_url') || t.getWindowArg('theme_url');
if (u && t.editor.settings.language && t.features.translate_i18n !== false) {
u += '/langs/' + t.editor.settings.language + '_dlg.js';
if (!tinymce.ScriptLoader.isDone(u)) {
document.write('<script type="text/javascript" src="' + tinymce._addVer(u) + '"></script>');
tinymce.ScriptLoader.markDone(u);
}
}
},
/**
* Executes a color picker on the specified element id. When the user
* then selects a color it will be set as the value of the specified element.
*
* @method pickColor
* @param {DOMEvent} e DOM event object.
* @param {string} element_id Element id to be filled with the color value from the picker.
*/
pickColor : function(e, element_id) {
this.execCommand('mceColorPicker', true, {
color : document.getElementById(element_id).value,
func : function(c) {
document.getElementById(element_id).value = c;
try {
document.getElementById(element_id).onchange();
} catch (ex) {
// Try fire event, ignore errors
}
}
});
},
/**
* Opens a filebrowser/imagebrowser this will set the output value from
* the browser as a value on the specified element.
*
* @method openBrowser
* @param {string} element_id Id of the element to set value in.
* @param {string} type Type of browser to open image/file/flash.
* @param {string} option Option name to get the file_broswer_callback function name from.
*/
openBrowser : function(element_id, type, option) {
tinyMCEPopup.restoreSelection();
this.editor.execCallback('file_browser_callback', element_id, document.getElementById(element_id).value, type, window);
},
/**
* Creates a confirm dialog. Please don't use the blocking behavior of this
* native version use the callback method instead then it can be extended.
*
* @method confirm
* @param {String} t Title for the new confirm dialog.
* @param {function} cb Callback function to be executed after the user has selected ok or cancel.
* @param {Object} s Optional scope to execute the callback in.
*/
confirm : function(t, cb, s) {
this.editor.windowManager.confirm(t, cb, s, window);
},
/**
* Creates a alert dialog. Please don't use the blocking behavior of this
* native version use the callback method instead then it can be extended.
*
* @method alert
* @param {String} t Title for the new alert dialog.
* @param {function} cb Callback function to be executed after the user has selected ok.
* @param {Object} s Optional scope to execute the callback in.
*/
alert : function(tx, cb, s) {
this.editor.windowManager.alert(tx, cb, s, window);
},
/**
* Closes the current window.
*
* @method close
*/
close : function() {
var t = this;
// To avoid domain relaxing issue in Opera
function close() {
t.editor.windowManager.close(window);
t.editor = null;
};
if (tinymce.isOpera)
t.getWin().setTimeout(close, 0);
else
close();
},
// Internal functions
_restoreSelection : function() {
var e = window.event.srcElement;
if (e.nodeName == 'INPUT' && (e.type == 'submit' || e.type == 'button'))
tinyMCEPopup.restoreSelection();
},
/* _restoreSelection : function() {
var e = window.event.srcElement;
// If user focus a non text input or textarea
if ((e.nodeName != 'INPUT' && e.nodeName != 'TEXTAREA') || e.type != 'text')
tinyMCEPopup.restoreSelection();
},*/
_onDOMLoaded : function() {
var t = tinyMCEPopup, ti = document.title, bm, h, nv;
if (t.domLoaded)
return;
t.domLoaded = 1;
tinyMCEPopup.init();
// Translate page
if (t.features.translate_i18n !== false) {
h = document.body.innerHTML;
// Replace a=x with a="x" in IE
if (tinymce.isIE)
h = h.replace(/ (value|title|alt)=([^"][^\s>]+)/gi, ' $1="$2"')
document.dir = t.editor.getParam('directionality','');
if ((nv = t.editor.translate(h)) && nv != h)
document.body.innerHTML = nv;
if ((nv = t.editor.translate(ti)) && nv != ti)
document.title = ti = nv;
}
document.body.style.display = '';
// Restore selection in IE when focus is placed on a non textarea or input element of the type text
if (tinymce.isIE) {
document.attachEvent('onmouseup', tinyMCEPopup._restoreSelection);
// Add base target element for it since it would fail with modal dialogs
t.dom.add(t.dom.select('head')[0], 'base', {target : '_self'});
}
t.restoreSelection();
// Set inline title
if (!t.isWindow)
t.editor.windowManager.setTitle(window, ti);
else
window.focus();
if (!tinymce.isIE && !t.isWindow) {
tinymce.dom.Event._add(document, 'focus', function() {
t.editor.windowManager.focus(t.id);
});
}
// Patch for accessibility
tinymce.each(t.dom.select('select'), function(e) {
e.onkeydown = tinyMCEPopup._accessHandler;
});
// Call onInit
// Init must be called before focus so the selection won't get lost by the focus call
tinymce.each(t.listeners, function(o) {
o.func.call(o.scope, t.editor);
});
// Move focus to window
if (t.getWindowArg('mce_auto_focus', true)) {
window.focus();
// Focus element with mceFocus class
tinymce.each(document.forms, function(f) {
tinymce.each(f.elements, function(e) {
if (t.dom.hasClass(e, 'mceFocus') && !e.disabled) {
e.focus();
return false; // Break loop
}
});
});
}
document.onkeyup = tinyMCEPopup._closeWinKeyHandler;
},
_accessHandler : function(e) {
e = e || window.event;
if (e.keyCode == 13 || e.keyCode == 32) {
e = e.target || e.srcElement;
if (e.onchange)
e.onchange();
return tinymce.dom.Event.cancel(e);
}
},
_closeWinKeyHandler : function(e) {
e = e || window.event;
if (e.keyCode == 27)
tinyMCEPopup.close();
},
_wait : function() {
// Use IE method
if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", arguments.callee);
tinyMCEPopup._onDOMLoaded();
}
});
if (document.documentElement.doScroll && window == window.top) {
(function() {
if (tinyMCEPopup.domLoaded)
return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch (ex) {
setTimeout(arguments.callee, 0);
return;
}
tinyMCEPopup._onDOMLoaded();
})();
}
document.attachEvent('onload', tinyMCEPopup._onDOMLoaded);
} else if (document.addEventListener) {
window.addEventListener('DOMContentLoaded', tinyMCEPopup._onDOMLoaded, false);
window.addEventListener('load', tinyMCEPopup._onDOMLoaded, false);
}
}
};
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.WPDialogs', {
init : function(ed, url) {
tinymce.create('tinymce.WPWindowManager:tinymce.InlineWindowManager', {
WPWindowManager : function(ed) {
this.parent(ed);
},
open : function(f, p) {
var t = this, element;
if ( ! f.wpDialog )
return this.parent( f, p );
else if ( ! f.id )
return;
element = jQuery('#' + f.id);
if ( ! element.length )
return;
t.features = f;
t.params = p;
t.onOpen.dispatch(t, f, p);
t.element = t.windows[ f.id ] = element;
// Store selection
t.bookmark = t.editor.selection.getBookmark(1);
// Create the dialog if necessary
if ( ! element.data('wpdialog') ) {
element.wpdialog({
title: f.title,
width: f.width,
height: f.height,
modal: true,
dialogClass: 'wp-dialog',
zIndex: 300000
});
}
element.wpdialog('open');
},
close : function() {
if ( ! this.features.wpDialog )
return this.parent.apply( this, arguments );
this.element.wpdialog('close');
}
});
// Replace window manager
ed.onBeforeRenderUI.add(function() {
ed.windowManager = new tinymce.WPWindowManager(ed);
});
},
getInfo : function() {
return {
longname : 'WPDialogs',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : 'http://wordpress.org',
version : '0.1'
};
}
});
// Register plugin
tinymce.PluginManager.add('wpdialogs', tinymce.plugins.WPDialogs);
})();
| JavaScript |
/**
* This script contains embed functions for common plugins. This scripts are complety free to use for any purpose.
*/
function writeFlash(p) {
writeEmbed(
'D27CDB6E-AE6D-11cf-96B8-444553540000',
'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
'application/x-shockwave-flash',
p
);
}
function writeShockWave(p) {
writeEmbed(
'166B1BCA-3F9C-11CF-8075-444553540000',
'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0',
'application/x-director',
p
);
}
function writeQuickTime(p) {
writeEmbed(
'02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
'video/quicktime',
p
);
}
function writeRealMedia(p) {
writeEmbed(
'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA',
'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
'audio/x-pn-realaudio-plugin',
p
);
}
function writeWindowsMedia(p) {
p.url = p.src;
writeEmbed(
'6BF52A52-394A-11D3-B153-00C04F79FAA6',
'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701',
'application/x-mplayer2',
p
);
}
function writeEmbed(cls, cb, mt, p) {
var h = '', n;
h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
h += '>';
for (n in p)
h += '<param name="' + n + '" value="' + p[n] + '">';
h += '<embed type="' + mt + '"';
for (n in p)
h += n + '="' + p[n] + '" ';
h += '></embed></object>';
document.write(h);
}
| JavaScript |
(function() {
var url;
if (url = tinyMCEPopup.getParam("media_external_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
function get(id) {
return document.getElementById(id);
}
function getVal(id) {
var elm = get(id);
if (elm.nodeName == "SELECT")
return elm.options[elm.selectedIndex].value;
if (elm.type == "checkbox")
return elm.checked;
return elm.value;
}
function setVal(id, value) {
if (typeof(value) != 'undefined') {
var elm = get(id);
if (elm.nodeName == "SELECT")
selectByValue(document.forms[0], id, value);
else if (elm.type == "checkbox") {
if (typeof(value) == 'string')
elm.checked = value.toLowerCase() === 'true' ? true : false;
else
elm.checked = !!value;
} else
elm.value = value;
}
}
window.Media = {
init : function() {
var html, editor;
this.editor = editor = tinyMCEPopup.editor;
// Setup file browsers and color pickers
get('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media');
get('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','quicktime_qtsrc','media','media');
get('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor');
get('video_altsource1_filebrowser').innerHTML = getBrowserHTML('filebrowser_altsource1','video_altsource1','media','media');
get('video_altsource2_filebrowser').innerHTML = getBrowserHTML('filebrowser_altsource2','video_altsource2','media','media');
get('video_poster_filebrowser').innerHTML = getBrowserHTML('filebrowser_poster','video_poster','media','image');
html = this.getMediaListHTML('medialist', 'src', 'media', 'media');
if (html == "")
get("linklistrow").style.display = 'none';
else
get("linklistcontainer").innerHTML = html;
if (isVisible('filebrowser'))
get('src').style.width = '230px';
if (isVisible('filebrowser_altsource1'))
get('video_altsource1').style.width = '220px';
if (isVisible('filebrowser_altsource2'))
get('video_altsource2').style.width = '220px';
if (isVisible('filebrowser_poster'))
get('video_poster').style.width = '220px';
this.data = tinyMCEPopup.getWindowArg('data');
this.dataToForm();
this.preview();
},
insert : function() {
var editor = tinyMCEPopup.editor;
this.formToData();
editor.execCommand('mceRepaint');
tinyMCEPopup.restoreSelection();
editor.selection.setNode(editor.plugins.media.dataToImg(this.data));
tinyMCEPopup.close();
},
preview : function() {
get('prev').innerHTML = this.editor.plugins.media.dataToHtml(this.data, true);
},
moveStates : function(to_form, field) {
var data = this.data, editor = this.editor, data = this.data,
mediaPlugin = editor.plugins.media, ext, src, typeInfo, defaultStates, src;
defaultStates = {
// QuickTime
quicktime_autoplay : true,
quicktime_controller : true,
// Flash
flash_play : true,
flash_loop : true,
flash_menu : true,
// WindowsMedia
windowsmedia_autostart : true,
windowsmedia_enablecontextmenu : true,
windowsmedia_invokeurls : true,
// RealMedia
realmedia_autogotourl : true,
realmedia_imagestatus : true
};
function parseQueryParams(str) {
var out = {};
if (str) {
tinymce.each(str.split('&'), function(item) {
var parts = item.split('=');
out[unescape(parts[0])] = unescape(parts[1]);
});
}
return out;
};
function setOptions(type, names) {
var i, name, formItemName, value, list;
if (type == data.type || type == 'global') {
names = tinymce.explode(names);
for (i = 0; i < names.length; i++) {
name = names[i];
formItemName = type == 'global' ? name : type + '_' + name;
if (type == 'global')
list = data;
else if (type == 'video') {
list = data.video.attrs;
if (!list && !to_form)
data.video.attrs = list = {};
} else
list = data.params;
if (list) {
if (to_form) {
setVal(formItemName, list[name]);
} else {
delete list[name];
value = getVal(formItemName);
if (type == 'video' && value === true)
value = name;
if (defaultStates[formItemName]) {
if (value !== defaultStates[formItemName]) {
value = "" + value;
list[name] = value;
}
} else if (value) {
value = "" + value;
list[name] = value;
}
}
}
}
}
}
if (!to_form) {
data.type = get('media_type').options[get('media_type').selectedIndex].value;
data.width = getVal('width');
data.height = getVal('height');
// Switch type based on extension
src = getVal('src');
if (field == 'src') {
ext = src.replace(/^.*\.([^.]+)$/, '$1');
if (typeInfo = mediaPlugin.getType(ext))
data.type = typeInfo.name.toLowerCase();
setVal('media_type', data.type);
}
if (data.type == "video") {
if (!data.video.sources)
data.video.sources = [];
data.video.sources[0] = {src: getVal('src')};
}
}
// Hide all fieldsets and show the one active
get('video_options').style.display = 'none';
get('flash_options').style.display = 'none';
get('quicktime_options').style.display = 'none';
get('shockwave_options').style.display = 'none';
get('windowsmedia_options').style.display = 'none';
get('realmedia_options').style.display = 'none';
if (get(data.type + '_options'))
get(data.type + '_options').style.display = 'block';
setVal('media_type', data.type);
setOptions('flash', 'play,loop,menu,swliveconnect,quality,scale,salign,wmode,base,flashvars');
setOptions('quicktime', 'loop,autoplay,cache,controller,correction,enablejavascript,kioskmode,autohref,playeveryframe,targetcache,scale,starttime,endtime,target,qtsrcchokespeed,volume,qtsrc');
setOptions('shockwave', 'sound,progress,autostart,swliveconnect,swvolume,swstretchstyle,swstretchhalign,swstretchvalign');
setOptions('windowsmedia', 'autostart,enabled,enablecontextmenu,fullscreen,invokeurls,mute,stretchtofit,windowlessvideo,balance,baseurl,captioningid,currentmarker,currentposition,defaultframe,playcount,rate,uimode,volume');
setOptions('realmedia', 'autostart,loop,autogotourl,center,imagestatus,maintainaspect,nojava,prefetch,shuffle,console,controls,numloop,scriptcallbacks');
setOptions('video', 'poster,autoplay,loop,preload,controls');
setOptions('global', 'id,name,vspace,hspace,bgcolor,align,width,height');
if (to_form) {
if (data.type == 'video') {
if (data.video.sources[0])
setVal('src', data.video.sources[0].src);
src = data.video.sources[1];
if (src)
setVal('video_altsource1', src.src);
src = data.video.sources[2];
if (src)
setVal('video_altsource2', src.src);
} else {
// Check flash vars
if (data.type == 'flash') {
tinymce.each(editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}), function(value, name) {
if (value == '$url')
data.params.src = parseQueryParams(data.params.flashvars)[name] || data.params.src;
});
}
setVal('src', data.params.src);
}
} else {
src = getVal("src");
// YouTube
if (src.match(/youtube.com(.+)v=([^&]+)/)) {
data.width = 425;
data.height = 350;
data.params.frameborder = '0';
data.type = 'iframe';
src = 'http://www.youtube.com/embed/' + src.match(/v=([^&]+)/)[1];
setVal('src', src);
setVal('media_type', data.type);
}
// Google video
if (src.match(/video.google.com(.+)docid=([^&]+)/)) {
data.width = 425;
data.height = 326;
data.type = 'flash';
src = 'http://video.google.com/googleplayer.swf?docId=' + src.match(/docid=([^&]+)/)[1] + '&hl=en';
setVal('src', src);
setVal('media_type', data.type);
}
if (data.type == 'video') {
if (!data.video.sources)
data.video.sources = [];
data.video.sources[0] = {src : src};
src = getVal("video_altsource1");
if (src)
data.video.sources[1] = {src : src};
src = getVal("video_altsource2");
if (src)
data.video.sources[2] = {src : src};
} else
data.params.src = src;
// Set default size
setVal('width', data.width || 320);
setVal('height', data.height || 240);
}
},
dataToForm : function() {
this.moveStates(true);
},
formToData : function(field) {
if (field == "width" || field == "height")
this.changeSize(field);
if (field == 'source') {
this.moveStates(false, field);
setVal('source', this.editor.plugins.media.dataToHtml(this.data));
this.panel = 'source';
} else {
if (this.panel == 'source') {
this.data = this.editor.plugins.media.htmlToData(getVal('source'));
this.dataToForm();
this.panel = '';
}
this.moveStates(false, field);
this.preview();
}
},
beforeResize : function() {
this.width = parseInt(getVal('width') || "320", 10);
this.height = parseInt(getVal('height') || "240", 10);
},
changeSize : function(type) {
var width, height, scale, size;
if (get('constrain').checked) {
width = parseInt(getVal('width') || "320", 10);
height = parseInt(getVal('height') || "240", 10);
if (type == 'width') {
this.height = Math.round((width / this.width) * height);
setVal('height', this.height);
} else {
this.width = Math.round((height / this.height) * width);
setVal('width', this.width);
}
}
},
getMediaListHTML : function() {
if (typeof(tinyMCEMediaList) != "undefined" && tinyMCEMediaList.length > 0) {
var html = "";
html += '<select id="linklist" name="linklist" style="width: 250px" onchange="this.form.src.value=this.options[this.selectedIndex].value;Media.formToData(\'src\');">';
html += '<option value="">---</option>';
for (var i=0; i<tinyMCEMediaList.length; i++)
html += '<option value="' + tinyMCEMediaList[i][1] + '">' + tinyMCEMediaList[i][0] + '</option>';
html += '</select>';
return html;
}
return "";
}
};
tinyMCEPopup.requireLangPack();
tinyMCEPopup.onInit.add(function() {
Media.init();
});
})(); | JavaScript |
var tinymce = null, tinyMCEPopup, tinyMCE, wpImage;
tinyMCEPopup = {
init: function() {
var t = this, w, li, q, i, it;
li = ('' + document.location.search).replace(/^\?/, '').split('&');
q = {};
for ( i = 0; i < li.length; i++ ) {
it = li[i].split('=');
q[unescape(it[0])] = unescape(it[1]);
}
if (q.mce_rdomain)
document.domain = q.mce_rdomain;
// Find window & API
w = t.getWin();
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.params = t.editor.windowManager.params;
// Setup local DOM
t.dom = t.editor.windowManager.createInstance('tinymce.dom.DOMUtils', document);
t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window);
},
getWin : function() {
return window.dialogArguments || opener || parent || top;
},
getParam : function(n, dv) {
return this.editor.getParam(n, dv);
},
close : function() {
var t = this, win = t.getWin();
// To avoid domain relaxing issue in Opera
function close() {
win.tb_remove();
tinymce = tinyMCE = t.editor = t.dom = t.dom.doc = null; // Cleanup
};
if (tinymce.isOpera)
win.setTimeout(close, 0);
else
close();
},
execCommand : function(cmd, ui, val, a) {
a = a || {};
a.skip_focus = 1;
this.restoreSelection();
return this.editor.execCommand(cmd, ui, val, a);
},
storeSelection : function() {
this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark('simple');
},
restoreSelection : function() {
var t = tinyMCEPopup;
if (tinymce.isIE)
t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark);
}
}
tinyMCEPopup.init();
wpImage = {
preInit : function() {
// import colors stylesheet from parent
var win = tinyMCEPopup.getWin(), styles = win.document.styleSheets, url, i;
for ( i = 0; i < styles.length; i++ ) {
url = styles.item(i).href;
if ( url && url.indexOf('colors') != -1 )
document.write( '<link rel="stylesheet" href="'+url+'" type="text/css" media="all" />' );
}
},
I : function(e) {
return document.getElementById(e);
},
current : '',
link : '',
link_rel : '',
target_value : '',
current_size_sel : 's100',
width : '',
height : '',
align : '',
img_alt : '',
setTabs : function(tab) {
var t = this;
if ( 'current' == tab.className ) return false;
t.I('div_advanced').style.display = ( 'tab_advanced' == tab.id ) ? 'block' : 'none';
t.I('div_basic').style.display = ( 'tab_basic' == tab.id ) ? 'block' : 'none';
t.I('tab_basic').className = t.I('tab_advanced').className = '';
tab.className = 'current';
return false;
},
img_seturl : function(u) {
var t = this, rel = t.I('link_rel').value;
if ( 'current' == u ) {
t.I('link_href').value = t.current;
t.I('link_rel').value = t.link_rel;
} else {
t.I('link_href').value = t.link;
if ( rel ) {
rel = rel.replace( /attachment|wp-att-[0-9]+/gi, '' );
t.I('link_rel').value = tinymce.trim(rel);
}
}
},
imgAlignCls : function(v) {
var t = this, cls = t.I('img_classes').value;
t.I('img_demo').className = t.align = v;
cls = cls.replace( /align[^ "']+/gi, '' );
cls += (' ' + v);
cls = cls.replace( /\s+/g, ' ' ).replace( /^\s/, '' );
if ( 'aligncenter' == v ) {
t.I('hspace').value = '';
t.updateStyle('hspace');
}
t.I('img_classes').value = cls;
},
showSize : function(el) {
var t = this, demo = t.I('img_demo'), w = t.width, h = t.height, id = el.id || 's100', size;
size = parseInt(id.substring(1)) / 200;
demo.width = Math.round(w * size);
demo.height = Math.round(h * size);
t.showSizeClear();
el.style.borderColor = '#A3A3A3';
el.style.backgroundColor = '#E5E5E5';
},
showSizeSet : function() {
var t = this, s130, s120, s110;
if ( (t.width * 1.3) > parseInt(t.preloadImg.width) ) {
s130 = t.I('s130'), s120 = t.I('s120'), s110 = t.I('s110');
s130.onclick = s120.onclick = s110.onclick = null;
s130.onmouseover = s120.onmouseover = s110.onmouseover = null;
s130.style.color = s120.style.color = s110.style.color = '#aaa';
}
},
showSizeRem : function() {
var t = this, demo = t.I('img_demo'), f = document.forms[0];
demo.width = Math.round(f.width.value * 0.5);
demo.height = Math.round(f.height.value * 0.5);
t.showSizeClear();
t.I(t.current_size_sel).style.borderColor = '#A3A3A3';
t.I(t.current_size_sel).style.backgroundColor = '#E5E5E5';
return false;
},
showSizeClear : function() {
var divs = this.I('img_size').getElementsByTagName('div'), i;
for ( i = 0; i < divs.length; i++ ) {
divs[i].style.borderColor = '#f1f1f1';
divs[i].style.backgroundColor = '#f1f1f1';
}
},
imgEditSize : function(el) {
var t = this, f = document.forms[0], W, H, w, h, id;
if ( ! t.preloadImg || ! t.preloadImg.width || ! t.preloadImg.height )
return;
W = parseInt(t.preloadImg.width), H = parseInt(t.preloadImg.height), w = t.width || W, h = t.height || H, id = el.id || 's100';
size = parseInt(id.substring(1)) / 100;
w = Math.round(w * size);
h = Math.round(h * size);
f.width.value = Math.min(W, w);
f.height.value = Math.min(H, h);
t.current_size_sel = id;
t.demoSetSize();
},
demoSetSize : function(img) {
var demo = this.I('img_demo'), f = document.forms[0];
demo.width = f.width.value ? Math.round(f.width.value * 0.5) : '';
demo.height = f.height.value ? Math.round(f.height.value * 0.5) : '';
},
demoSetStyle : function() {
var f = document.forms[0], demo = this.I('img_demo'), dom = tinyMCEPopup.editor.dom;
if (demo) {
dom.setAttrib(demo, 'style', f.img_style.value);
dom.setStyle(demo, 'width', '');
dom.setStyle(demo, 'height', '');
}
},
origSize : function() {
var t = this, f = document.forms[0], el = t.I('s100');
f.width.value = t.width = t.preloadImg.width;
f.height.value = t.height = t.preloadImg.height;
t.showSizeSet();
t.demoSetSize();
t.showSize(el);
},
init : function() {
var ed = tinyMCEPopup.editor, h;
h = document.body.innerHTML;
document.body.innerHTML = ed.translate(h);
window.setTimeout( function(){wpImage.setup();}, 500 );
},
setup : function() {
var t = this, c, el, link, fname, f = document.forms[0], ed = tinyMCEPopup.editor,
d = t.I('img_demo'), dom = tinyMCEPopup.dom, DL, caption = '', dlc, pa;
document.dir = tinyMCEPopup.editor.getParam('directionality','');
if ( tinyMCEPopup.editor.getParam('wpeditimage_disable_captions', false) )
t.I('cap_field').style.display = 'none';
tinyMCEPopup.restoreSelection();
el = ed.selection.getNode();
if (el.nodeName != 'IMG')
return;
f.img_src.value = d.src = link = ed.dom.getAttrib(el, 'src');
ed.dom.setStyle(el, 'float', '');
t.getImageData();
c = ed.dom.getAttrib(el, 'class');
if ( DL = dom.getParent(el, 'dl') ) {
dlc = ed.dom.getAttrib(DL, 'class');
dlc = dlc.match(/align[^ "']+/i);
if ( dlc && ! dom.hasClass(el, dlc) ) {
c += ' '+dlc;
tinymce.trim(c);
}
tinymce.each(DL.childNodes, function(e) {
if ( e.nodeName == 'DD' && dom.hasClass(e, 'wp-caption-dd') ) {
caption = e.innerHTML;
return;
}
});
}
f.img_cap.value = caption;
f.img_title.value = ed.dom.getAttrib(el, 'title');
f.img_alt.value = ed.dom.getAttrib(el, 'alt');
f.border.value = ed.dom.getAttrib(el, 'border');
f.vspace.value = ed.dom.getAttrib(el, 'vspace');
f.hspace.value = ed.dom.getAttrib(el, 'hspace');
f.align.value = ed.dom.getAttrib(el, 'align');
f.width.value = t.width = ed.dom.getAttrib(el, 'width');
f.height.value = t.height = ed.dom.getAttrib(el, 'height');
f.img_classes.value = c;
f.img_style.value = ed.dom.getAttrib(el, 'style');
// Move attribs to styles
if ( dom.getAttrib(el, 'hspace') )
t.updateStyle('hspace');
if ( dom.getAttrib(el, 'border') )
t.updateStyle('border');
if ( dom.getAttrib(el, 'vspace') )
t.updateStyle('vspace');
if ( pa = ed.dom.getParent(el, 'A') ) {
f.link_href.value = t.current = ed.dom.getAttrib(pa, 'href');
f.link_title.value = ed.dom.getAttrib(pa, 'title');
f.link_rel.value = t.link_rel = ed.dom.getAttrib(pa, 'rel');
f.link_style.value = ed.dom.getAttrib(pa, 'style');
t.target_value = ed.dom.getAttrib(pa, 'target');
f.link_classes.value = ed.dom.getAttrib(pa, 'class');
}
f.link_target.checked = ( t.target_value && t.target_value == '_blank' ) ? 'checked' : '';
fname = link.substring( link.lastIndexOf('/') );
fname = fname.replace(/-[0-9]{2,4}x[0-9]{2,4}/, '' );
t.link = link.substring( 0, link.lastIndexOf('/') ) + fname;
if ( c.indexOf('alignleft') != -1 ) {
t.I('alignleft').checked = "checked";
d.className = t.align = "alignleft";
} else if ( c.indexOf('aligncenter') != -1 ) {
t.I('aligncenter').checked = "checked";
d.className = t.align = "aligncenter";
} else if ( c.indexOf('alignright') != -1 ) {
t.I('alignright').checked = "checked";
d.className = t.align = "alignright";
} else if ( c.indexOf('alignnone') != -1 ) {
t.I('alignnone').checked = "checked";
d.className = t.align = "alignnone";
}
if ( t.width && t.preloadImg.width ) t.showSizeSet();
document.body.style.display = '';
},
remove : function() {
var ed = tinyMCEPopup.editor, p, el;
tinyMCEPopup.restoreSelection();
el = ed.selection.getNode();
if (el.nodeName != 'IMG') return;
if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') )
ed.dom.remove(p);
else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 )
ed.dom.remove(p);
else ed.dom.remove(el);
ed.execCommand('mceRepaint');
tinyMCEPopup.close();
return;
},
update : function() {
var t = this, f = document.forms[0], ed = tinyMCEPopup.editor, el, b, fixSafari = null,
DL, P, A, DIV, do_caption = null, img_class = f.img_classes.value, html,
id, cap_id = '', cap, DT, DD, cap_width, div_cls, lnk = '', pa, aa;
tinyMCEPopup.restoreSelection();
el = ed.selection.getNode();
if (el.nodeName != 'IMG') return;
if (f.img_src.value === '') {
t.remove();
return;
}
if ( f.img_cap.value != '' && f.width.value != '' ) {
do_caption = 1;
img_class = img_class.replace( /align[^ "']+\s?/gi, '' );
}
A = ed.dom.getParent(el, 'a');
P = ed.dom.getParent(el, 'p');
DL = ed.dom.getParent(el, 'dl');
DIV = ed.dom.getParent(el, 'div');
tinyMCEPopup.execCommand("mceBeginUndoLevel");
ed.dom.setAttribs(el, {
src : f.img_src.value,
title : f.img_title.value,
alt : f.img_alt.value,
width : f.width.value,
height : f.height.value,
style : f.img_style.value,
'class' : img_class
});
if ( f.link_href.value ) {
// Create new anchor elements
if ( A == null ) {
if ( ! f.link_href.value.match(/https?:\/\//i) )
f.link_href.value = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.link_href.value);
if ( tinymce.isWebKit && ed.dom.hasClass(el, 'aligncenter') ) {
ed.dom.removeClass(el, 'aligncenter');
fixSafari = 1;
}
tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1});
if ( fixSafari ) ed.dom.addClass(el, 'aligncenter');
tinymce.each(ed.dom.select("a"), function(n) {
if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
ed.dom.setAttribs(n, {
href : f.link_href.value,
title : f.link_title.value,
rel : f.link_rel.value,
target : (f.link_target.checked == true) ? '_blank' : '',
'class' : f.link_classes.value,
style : f.link_style.value
});
}
});
} else {
ed.dom.setAttribs(A, {
href : f.link_href.value,
title : f.link_title.value,
rel : f.link_rel.value,
target : (f.link_target.checked == true) ? '_blank' : '',
'class' : f.link_classes.value,
style : f.link_style.value
});
}
}
if ( do_caption ) {
cap_width = 10 + parseInt(f.width.value);
div_cls = (t.align == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp';
if ( DL ) {
ed.dom.setAttribs(DL, {
'class' : 'wp-caption '+t.align,
style : 'width: '+cap_width+'px;'
});
if ( DIV )
ed.dom.setAttrib(DIV, 'class', div_cls);
if ( (DT = ed.dom.getParent(el, 'dt')) && (DD = DT.nextSibling) && ed.dom.hasClass(DD, 'wp-caption-dd') )
ed.dom.setHTML(DD, f.img_cap.value);
} else {
if ( (id = f.img_classes.value.match( /wp-image-([0-9]{1,6})/ )) && id[1] )
cap_id = 'attachment_'+id[1];
if ( f.link_href.value && (lnk = ed.dom.getParent(el, 'a')) ) {
if ( lnk.childNodes.length == 1 )
html = ed.dom.getOuterHTML(lnk);
else {
html = ed.dom.getOuterHTML(lnk);
html = html.match(/<a[^>]+>/i);
html = html+ed.dom.getOuterHTML(el)+'</a>';
}
} else html = ed.dom.getOuterHTML(el);
html = '<dl id="'+cap_id+'" class="wp-caption '+t.align+'" style="width: '+cap_width+
'px"><dt class="wp-caption-dt">'+html+'</dt><dd class="wp-caption-dd">'+f.img_cap.value+'</dd></dl>';
cap = ed.dom.create('div', {'class': div_cls}, html);
if ( P ) {
P.parentNode.insertBefore(cap, P);
if ( P.childNodes.length == 1 )
ed.dom.remove(P);
else if ( lnk && lnk.childNodes.length == 1 )
ed.dom.remove(lnk);
else ed.dom.remove(el);
} else if ( pa = ed.dom.getParent(el, 'TD,TH,LI') ) {
pa.appendChild(cap);
if ( lnk && lnk.childNodes.length == 1 )
ed.dom.remove(lnk);
else ed.dom.remove(el);
}
}
} else {
if ( DL && DIV ) {
if ( f.link_href.value && (aa = ed.dom.getParent(el, 'a')) ) html = ed.dom.getOuterHTML(aa);
else html = ed.dom.getOuterHTML(el);
P = ed.dom.create('p', {}, html);
DIV.parentNode.insertBefore(P, DIV);
ed.dom.remove(DIV);
}
}
if ( f.img_classes.value.indexOf('aligncenter') != -1 ) {
if ( P && ( ! P.style || P.style.textAlign != 'center' ) )
ed.dom.setStyle(P, 'textAlign', 'center');
} else {
if ( P && P.style && P.style.textAlign == 'center' )
ed.dom.setStyle(P, 'textAlign', '');
}
if ( ! f.link_href.value && A ) {
b = ed.selection.getBookmark();
ed.dom.remove(A, 1);
ed.selection.moveToBookmark(b);
}
tinyMCEPopup.execCommand("mceEndUndoLevel");
ed.execCommand('mceRepaint');
tinyMCEPopup.close();
},
updateStyle : function(ty) {
var dom = tinyMCEPopup.dom, v, f = document.forms[0], img = dom.create('img', {style : f.img_style.value});
if (tinyMCEPopup.editor.settings.inline_styles) {
// Handle align
if (ty == 'align') {
dom.setStyle(img, 'float', '');
dom.setStyle(img, 'vertical-align', '');
v = f.align.value;
if (v) {
if (v == 'left' || v == 'right')
dom.setStyle(img, 'float', v);
else
img.style.verticalAlign = v;
}
}
// Handle border
if (ty == 'border') {
dom.setStyle(img, 'border', '');
v = f.border.value;
if (v || v == '0') {
if (v == '0')
img.style.border = '0';
else
img.style.border = v + 'px solid black';
}
}
// Handle hspace
if (ty == 'hspace') {
dom.setStyle(img, 'marginLeft', '');
dom.setStyle(img, 'marginRight', '');
v = f.hspace.value;
if (v) {
img.style.marginLeft = v + 'px';
img.style.marginRight = v + 'px';
}
}
// Handle vspace
if (ty == 'vspace') {
dom.setStyle(img, 'marginTop', '');
dom.setStyle(img, 'marginBottom', '');
v = f.vspace.value;
if (v) {
img.style.marginTop = v + 'px';
img.style.marginBottom = v + 'px';
}
}
// Merge
f.img_style.value = dom.serializeStyle(dom.parseStyle(img.style.cssText));
this.demoSetStyle();
}
},
checkVal : function(f) {
if ( f.value == '' ) {
// if ( f.id == 'width' ) f.value = this.width || this.preloadImg.width;
// if ( f.id == 'height' ) f.value = this.height || this.preloadImg.height;
if ( f.id == 'img_src' ) f.value = this.I('img_demo').src || this.preloadImg.src;
}
},
resetImageData : function() {
var f = document.forms[0];
f.width.value = f.height.value = '';
},
updateImageData : function() {
var f = document.forms[0], t = wpImage, w = f.width.value, h = f.height.value;
if ( !w && h )
w = f.width.value = t.width = Math.round( t.preloadImg.width / (t.preloadImg.height / h) );
else if ( w && !h )
h = f.height.value = t.height = Math.round( t.preloadImg.height / (t.preloadImg.width / w) );
if ( !w )
f.width.value = t.width = t.preloadImg.width;
if ( !h )
f.height.value = t.height = t.preloadImg.height;
t.showSizeSet();
t.demoSetSize();
if ( f.img_style.value )
t.demoSetStyle();
},
getImageData : function() {
var t = wpImage, f = document.forms[0];
t.preloadImg = new Image();
t.preloadImg.onload = t.updateImageData;
t.preloadImg.onerror = t.resetImageData;
t.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.img_src.value);
}
};
window.onload = function(){wpImage.init();}
wpImage.preInit();
| JavaScript |
(function() {
tinymce.create('tinymce.plugins.wpEditImage', {
init : function(ed, url) {
var t = this;
t.url = url;
t._createButtons();
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...');
ed.addCommand('WP_EditImage', function() {
var el = ed.selection.getNode(), vp = tinymce.DOM.getViewPort(), H = vp.h, W = ( 720 < vp.w ) ? 720 : vp.w, cls = ed.dom.getAttrib(el, 'class');
if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 || el.nodeName != 'IMG' )
return;
tb_show('', url + '/editimage.html?ver=321&TB_iframe=true');
tinymce.DOM.setStyles('TB_window', {
'width':( W - 50 )+'px',
'height':( H - 45 )+'px',
'margin-left':'-'+parseInt((( W - 50 ) / 2),10) + 'px'
});
if ( ! tinymce.isIE6 ) {
tinymce.DOM.setStyles('TB_window', {
'top':'20px',
'marginTop':'0'
});
}
tinymce.DOM.setStyles('TB_iframeContent', {
'width':( W - 50 )+'px',
'height':( H - 75 )+'px'
});
tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' );
});
ed.onInit.add(function(ed) {
tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) {
if ( !tinymce.isGecko && e.target.nodeName == 'IMG' && ed.dom.getParent(e.target, 'dl.wp-caption') )
return tinymce.dom.Event.cancel(e);
});
});
// resize the caption <dl> when the image is soft-resized by the user (only possible in Firefox and IE)
ed.onMouseUp.add(function(ed, e) {
if ( tinymce.isWebKit || tinymce.isOpera )
return;
if ( ed.dom.getParent(e.target, 'div.mceTemp') || ed.dom.is(e.target, 'div.mceTemp') ) {
window.setTimeout(function(){
var ed = tinyMCE.activeEditor, n = ed.selection.getNode(), DL, width;
if ( 'IMG' == n.nodeName ) {
DL = ed.dom.getParent(n, 'dl.wp-caption');
width = ed.dom.getAttrib(n, 'width') || n.width;
width = parseInt(width, 10);
if ( DL && width != ( parseInt(ed.dom.getStyle(DL, 'width'), 10) - 10 ) ) {
ed.dom.setStyle(DL, 'width', 10 + width);
ed.execCommand('mceRepaint');
}
}
}, 100);
}
});
// show editimage buttons
ed.onMouseDown.add(function(ed, e) {
var p;
if ( e.target.nodeName == 'IMG' && ed.dom.getAttrib(e.target, 'class').indexOf('mceItem') == -1 ) {
ed.plugins.wordpress._showButtons(e.target, 'wp_editbtns');
if ( tinymce.isGecko && (p = ed.dom.getParent(e.target, 'dl.wp-caption')) && ed.dom.hasClass(p.parentNode, 'mceTemp') )
ed.selection.select(p.parentNode);
}
});
// when pressing Return inside a caption move the cursor to a new parapraph under it
ed.onKeyPress.add(function(ed, e) {
var n, DL, DIV, P;
if ( e.keyCode == 13 ) {
n = ed.selection.getNode();
DL = ed.dom.getParent(n, 'dl.wp-caption');
DIV = ed.dom.getParent(DL, 'div.mceTemp');
if ( DL && DIV ) {
P = ed.dom.create('p', {}, ' ');
ed.dom.insertAfter( P, DIV );
if ( P.firstChild )
ed.selection.select(P.firstChild);
else
ed.selection.select(P);
tinymce.dom.Event.cancel(e);
return false;
}
}
});
ed.onBeforeSetContent.add(function(ed, o) {
o.content = t._do_shcode(o.content);
});
ed.onPostProcess.add(function(ed, o) {
if (o.get)
o.content = t._get_shcode(o.content);
});
},
_do_shcode : function(co) {
return co.replace(/(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?[\s\u00a0]*/g, function(a,b,c){
var id, cls, w, cap, div_cls;
b = b.replace(/\\'|\\'|\\'/g, ''').replace(/\\"|\\"/g, '"');
c = c.replace(/\\'|\\'/g, ''').replace(/\\"/g, '"');
id = b.match(/id=['"]([^'"]+)/i);
cls = b.match(/align=['"]([^'"]+)/i);
w = b.match(/width=['"]([0-9]+)/);
cap = b.match(/caption=['"]([^'"]+)/i);
id = ( id && id[1] ) ? id[1] : '';
cls = ( cls && cls[1] ) ? cls[1] : 'alignnone';
w = ( w && w[1] ) ? w[1] : '';
cap = ( cap && cap[1] ) ? cap[1] : '';
if ( ! w || ! cap ) return c;
div_cls = (cls == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp';
return '<div class="'+div_cls+'" draggable><dl id="'+id+'" class="wp-caption '+cls+'" style="width: '+(10+parseInt(w))+
'px"><dt class="wp-caption-dt">'+c+'</dt><dd class="wp-caption-dd">'+cap+'</dd></dl></div>';
});
},
_get_shcode : function(co) {
return co.replace(/<div class="mceTemp[^"]*">\s*<dl([^>]+)>\s*<dt[^>]+>([\s\S]+?)<\/dt>\s*<dd[^>]+>(.+?)<\/dd>\s*<\/dl>\s*<\/div>\s*/gi, function(a,b,c,cap){
var id, cls, w;
id = b.match(/id=['"]([^'"]+)/i);
cls = b.match(/class=['"]([^'"]+)/i);
w = c.match(/width=['"]([0-9]+)/);
id = ( id && id[1] ) ? id[1] : '';
cls = ( cls && cls[1] ) ? cls[1] : 'alignnone';
w = ( w && w[1] ) ? w[1] : '';
if ( ! w || ! cap ) return c;
cls = cls.match(/align[^ '"]+/) || 'alignnone';
cap = cap.replace(/<\S[^<>]*>/gi, '').replace(/'/g, ''').replace(/"/g, '"');
return '[caption id="'+id+'" align="'+cls+'" width="'+w+'" caption="'+cap+'"]'+c+'[/caption]';
});
},
_createButtons : function() {
var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, editButton, dellButton;
DOM.remove('wp_editbtns');
DOM.add(document.body, 'div', {
id : 'wp_editbtns',
style : 'display:none;'
});
editButton = DOM.add('wp_editbtns', 'img', {
src : t.url+'/img/image.png',
id : 'wp_editimgbtn',
width : '24',
height : '24',
title : ed.getLang('wpeditimage.edit_img')
});
tinymce.dom.Event.add(editButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor;
ed.windowManager.bookmark = ed.selection.getBookmark('simple');
ed.execCommand("WP_EditImage");
});
dellButton = DOM.add('wp_editbtns', 'img', {
src : t.url+'/img/delete.png',
id : 'wp_delimgbtn',
width : '24',
height : '24',
title : ed.getLang('wpeditimage.del_img')
});
tinymce.dom.Event.add(dellButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor, el = ed.selection.getNode(), p;
if ( el.nodeName == 'IMG' && ed.dom.getAttrib(el, 'class').indexOf('mceItem') == -1 ) {
if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') )
ed.dom.remove(p);
else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 )
ed.dom.remove(p);
else
ed.dom.remove(el);
ed.execCommand('mceRepaint');
return false;
}
});
},
getInfo : function() {
return {
longname : 'Edit Image',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : '',
version : "1.0"
};
}
});
tinymce.PluginManager.add('wpeditimage', tinymce.plugins.wpEditImage);
})();
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.