code stringlengths 1 2.08M | language stringclasses 1
value |
|---|---|
/* Jquery popup */
(function($){
$.fn.popupWindow = function(instanceSettings){
return this.each(function(){
$(this).click(function(){
$.fn.popupWindow.defaultSettings = {
centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
height:500, // sets the height in pixels of the window.
left:0, // left position when the window appears.
location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
width:500, // sets the width in pixels of the window.
windowName:null, // name of window set from the name attribute of the element that invokes the click
windowURL:null, // url used for the popup
top:0, // top position when the window appears.
toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
};
settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
var windowFeatures = 'height=' + settings.height +
',width=' + settings.width +
',toolbar=' + settings.toolbar +
',scrollbars=' + settings.scrollbars +
',status=' + settings.status +
',resizable=' + settings.resizable +
',location=' + settings.location +
',menuBar=' + settings.menubar;
settings.windowName = this.name || settings.windowName;
settings.windowURL = this.href || settings.windowURL;
var centeredY,centeredX;
if(settings.centerBrowser){
if ($.browser.msie) {//hacked together for IE browsers
centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
}else{
centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
}
window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
}else if(settings.centerScreen){
centeredY = (screen.height - settings.height)/2;
centeredX = (screen.width - settings.width)/2;
window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
}else{
window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();
}
return false;
});
});
};
})(jQuery);
function expand_category()
{
document.getElementById("li_1").reset();
}
/*Load model list*/
function model_reload(object)
{
// Clear options
var popt = document.getElementById("model_id");
for ( var i = popt.length-1; i>= 0; i-- )
{
popt.remove(i);
}
// Add option
var data = object.options[object.selectedIndex].getAttribute("title");
data = data.split("||");
for ( var j = 0; j< data.length; j++ )
{
if ( data[j] )
{
var opt = document.createElement("option");
var item = data[j].split("|");
opt.text = item[1];
opt.value = item[0];
if ( popt.getAttribute("defaultvalue") == item[0] )
{
opt.selected = "selected";
}
popt.options.add(opt);
}
}
}
function comment_reload(object)
{
// Clear options
var popt = document.getElementById("model");
for ( var i = popt.length-1; i>= 0; i-- )
{
popt.remove(i);
}
// Add option
var data = object.options[object.selectedIndex].getAttribute("title");
data = data.split("||");
for ( var j = 0; j< data.length; j++ )
{
if ( data[j] )
{
var opt = document.createElement("option");
var item = data[j].split("|");
opt.text = item[1];
opt.value = item[0];
popt.options.add(opt);
}
}
}
function vsearch(theForm)
{
if (theForm.keyword.value=='' || theForm.keyword.value==theForm.keyword.defaultValue)
{
alert("Để tìm kiếm vui lòng nhập vào Nội Dung.");
theForm.keyword.focus();
return false;
}
if (theForm.keyword.value.length <=2)
{
alert("Từ khóa quá ngắn. Vui lòng nhập lại với từ khóa khác trên 2 kí tự.");
theForm.keyword.focus();
return false;
}
}
function vsearch_advance(theForm)
{
if (theForm.keyword.value!='' && theForm.keyword.value.length <=2)
{
alert("Từ khóa quá ngắn. Vui lòng nhập lại với từ khóa khác trên 2 kí tự.");
theForm.keyword.focus();
return false;
}
}
function vcontact(theForm)
{
if (theForm.name.value=='' || theForm.name.value==theForm.name.defaultValue)
{
alert("Bạn chưa nhập Họ Tên.");
theForm.name.focus();
return false;
}
if (theForm.email.value=='' || theForm.email.value==theForm.email.defaultValue)
{
alert("Vui lòng điền Email.");
theForm.email.focus();
return false;
}
if (theForm.email.value.indexOf('@', 0) == -1 || theForm.email.value.indexOf('.') == -1)
{
alert("Vui lòng điền đúng Email.");
theForm.email.focus();
return false;
}
if (theForm.title.value=='' || theForm.title.value==theForm.title.defaultValue)
{
alert("Bạn chưa nhập Tiêu Đề.");
theForm.title.focus();
return false;
}
if (theForm.message.value=='' || theForm.message.value==theForm.message.defaultValue)
{
alert("Bạn chưa nhập Nội Dung.");
theForm.message.focus();
return false;
}
return true;
}
function vcart(theForm)
{
if (theForm.cart_name.value=='' || theForm.cart_name.value==theForm.cart_name.defaultValue)
{
alert("Bạn chưa nhập Họ Tên.");
theForm.cart_name.focus();
return false;
}
if (theForm.cart_add.value=='' || theForm.cart_add.value==theForm.cart_add.defaultValue)
{
alert("Bạn chưa nhập địa chỉ giao hàng.");
theForm.cart_add.focus();
return false;
}
if (theForm.cart_add.value.length <=8)
{
alert("Vui lòng \"nhập đúng\" địa chỉ giao hàng!");
theForm.cart_add.focus();
return false;
}
if (theForm.cart_phone.value=='' || theForm.cart_phone.value==theForm.cart_phone.defaultValue)
{
alert("Bạn chưa nhập số điện thoại.");
theForm.cart_phone.focus();
return false;
}
if (isNaN(theForm.cart_phone.value) )
{
alert("Vui lòng nhập đúng số điện thoại!");
theForm.cart_phone.focus();
return false;
}
if (theForm.cart_add.value.length <=8)
{
alert("Vui lòng nhập đúng số điện thoại!");
theForm.cart_phone.focus();
return false;
}
if (theForm.cart_email.value=='' || theForm.cart_email.value==theForm.cart_email.defaultValue )
{
alert("Vui lòng điền Email.");
theForm.cart_email.focus();
return false;
}
if (theForm.cart_email.value.indexOf('@', 0) == -1 || theForm.cart_email.value.indexOf('.') == -1)
{
alert("Vui lòng điền đúng Email!");
theForm.cart_email.focus();
return false;
}
return true;
}
// CART UPDATE
function chk_cart_upt(product_id)
{
var the_form = document.getElementById("cart_step2_1");
for ( var i = 0; i < the_form.length; i++ )
{
// Period
if ( the_form[i].name == "count_"+product_id )
{
if (isNaN( the_form[i].value))
{
//UPDATE BTN
alert("Vui lòng nhập số!");
document.getElementById("cart_update").setAttribute("disabled","");
document.getElementById("cart_update").setAttribute("style","opacity: 0.4; font-weight: normal; color: rgb(0, 0, 0); cursor: default;");
// NEXT
document.getElementById("sub_mit").setAttribute("href",site_root_domain+"/gio-hang-cua-toi.html");
document.getElementById("sub_mit").setAttribute("disabled","");
document.getElementById("sub_mit").setAttribute("style","opacity: 0.4; font-weight: normal; color: rgb(0, 0, 0); cursor: default;");
return false;
}
if (document.getElementById("sp_"+product_id).value <=0)
{
alert("Số lượng phải lớn hơn 0");
//UPDATE BTN
document.getElementById("cart_update").setAttribute("disabled","disabled");
document.getElementById("cart_update").setAttribute("style","opacity: 0.4; font-weight: normal; color: rgb(0, 0, 0); cursor: default;");
// NEXT
document.getElementById("sub_mit").setAttribute("disabled","disabled");
document.getElementById("sub_mit").setAttribute("style","opacity: 0.4; font-weight: normal; color: rgb(0, 0, 0); cursor: default;");
return false;
}
else
{
//UPDATE BTN
document.getElementById("cart_update").removeAttribute("disabled");
document.getElementById("cart_update").removeAttribute("style");
// NEXT
document.getElementById("cart_steps2").setAttribute("href",site_root_domain+"/gio-hang-cua-toi/nhap-thong-tin.html");
document.getElementById("cart_steps2").removeAttribute("disabled","");
document.getElementById("cart_steps2").removeAttribute("style");
}
}
}
return true;
}
function turnon_button()
{
var the_form = document.getElementById("cart_step2_1");
for ( var i = 0; i < the_form.length; i++ )
{
document.getElementById("cart_update").removeAttribute("disabled");
document.getElementById("cart_update").setAttribute("style","cursor: pointer;");
}
var the_form = document.getElementById("cart_step2_2");
for ( var i = 0; i < the_form.length; i++ )
{
document.getElementById("sub_mit").removeAttribute("disabled");
document.getElementById("sub_mit").setAttribute("style","cursor: pointer;");
}
}
// Alert when add a product
function cart_messenger_add()
{
var r=confirm("Đã thêm 1 sản phẩm vào giỏ hàng");
if (r==true)
{
alert("Vào giỏ hàng");
}
else
{
alert("Tiếp tục mua hàng");
}
}
//############################################
// ADD CART
//############################################
function add_cart_once(product_id,product_name)
{
AjaxRequest.get(
{
'url': site_root_domain+'/gio-hang-cua-toi/them/'+product_id+'.html'
,'onLoading':function(req)
{
}
,'onSuccess':function(req)
{
// Popup choice
$.confirm({
'title' : 'Bạn đã thêm sản phẩm vào giỏ hàng',
'message' : '<b>' + product_name +'</b>',
'buttons' : {
'Vào giỏ hàng' : {
'class' : 'gray',
'action': function(){
$(window.location).attr('href', site_root_domain+'/gio-hang-cua-toi.html');
}
},
'Tiếp tục mua' : {
'class' : 'blue',
'action': function(){
//$(window.location).attr('href', site_referer+'#topcart');
}
}
}
});
// Insert cart HTML
document.getElementById("topcart_content").innerHTML = req.responseText;
open_cart();
}
}
);
}
function check_cart(cartc)
{
if ( cartc > 0 )
{
document.getElementById("topcart").style.display = "block";
}
}
function open_cart()
{
document.getElementById("topcart").style.display = "block";
}
| JavaScript |
/*!
* jQzoom Evolution Library v2.3 - Javascript Image magnifier
* http://www.mind-projects.it
*
* Copyright 2011, Engineer Marco Renzi
* Licensed under the BSD license.
*
* 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 organization nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Date: 03 May 2011 22:16:00
*/
(function ($) {
//GLOBAL VARIABLES
var isIE6 = ($.browser.msie && $.browser.version < 7);
var body = $(document.body);
var window = $(window);
var jqzoompluging_disabled = false; //disabilita globalmente il plugin
$.fn.jqzoom = function (options) {
return this.each(function () {
var node = this.nodeName.toLowerCase();
if (node == 'a') {
new jqzoom(this, options);
}
});
};
jqzoom = function (el, options) {
var api = null;
api = $(el).data("jqzoom");
if (api) return api;
var obj = this;
var settings = $.extend({}, $.jqzoom.defaults, options || {});
obj.el = el;
el.rel = $(el).attr('rel');
//ANCHOR ELEMENT
el.zoom_active = false;
el.zoom_disabled = false; //to disable single zoom instance
el.largeimageloading = false; //tell us if large image is loading
el.largeimageloaded = false; //tell us if large image is loaded
el.scale = {};
el.timer = null;
el.mousepos = {};
el.mouseDown = false;
$(el).css({
'outline-style': 'none',
'text-decoration': 'none'
});
//BASE IMAGE
var img = $("img:eq(0)", el);
el.title = $(el).attr('title');
el.imagetitle = img.attr('title');
var zoomtitle = ($.trim(el.title).length > 0) ? el.title : el.imagetitle;
var smallimage = new Smallimage(img);
var lens = new Lens();
var stage = new Stage();
var largeimage = new Largeimage();
var loader = new Loader();
//preventing default click,allowing the onclick event [exmple: lightbox]
$(el).bind('click', function (e) {
e.preventDefault();
return false;
});
//setting the default zoomType if not in settings
var zoomtypes = ['standard', 'drag', 'innerzoom', 'reverse'];
if ($.inArray($.trim(settings.zoomType), zoomtypes) < 0) {
settings.zoomType = 'standard';
}
$.extend(obj, {
create: function () { //create the main objects
//create ZoomPad
if ($(".zoomPad", el).length == 0) {
el.zoomPad = $('<div/>').addClass('zoomPad');
img.wrap(el.zoomPad);
}
if(settings.zoomType == 'innerzoom'){
settings.zoomWidth = smallimage.w;
settings.zoomHeight = smallimage.h;
}
//creating ZoomPup
if ($(".zoomPup", el).length == 0) {
lens.append();
}
//creating zoomWindow
if ($(".zoomWindow", el).length == 0) {
stage.append();
}
//creating Preload
if ($(".zoomPreload", el).length == 0) {
loader.append();
}
//preloading images
if (settings.preloadImages || settings.zoomType == 'drag' || settings.alwaysOn) {
obj.load();
}
obj.init();
},
init: function () {
//drag option
if (settings.zoomType == 'drag') {
$(".zoomPad", el).mousedown(function () {
el.mouseDown = true;
});
$(".zoomPad", el).mouseup(function () {
el.mouseDown = false;
});
document.body.ondragstart = function () {
return false;
};
$(".zoomPad", el).css({
cursor: 'default'
});
$(".zoomPup", el).css({
cursor: 'move'
});
}
if (settings.zoomType == 'innerzoom') {
$(".zoomWrapper", el).css({
cursor: 'crosshair'
});
}
$(".zoomPad", el).bind('mouseenter mouseover', function (event) {
img.attr('title', '');
$(el).attr('title', '');
el.zoom_active = true;
//if loaded then activate else load large image
smallimage.fetchdata();
if (el.largeimageloaded) {
obj.activate(event);
} else {
obj.load();
}
});
$(".zoomPad", el).bind('mouseleave', function (event) {
obj.deactivate();
});
$(".zoomPad", el).bind('mousemove', function (e) {
//prevent fast mouse mevements not to fire the mouseout event
if (e.pageX > smallimage.pos.r || e.pageX < smallimage.pos.l || e.pageY < smallimage.pos.t || e.pageY > smallimage.pos.b) {
lens.setcenter();
return false;
}
el.zoom_active = true;
if (el.largeimageloaded && !$('.zoomWindow', el).is(':visible')) {
obj.activate(e);
}
if (el.largeimageloaded && (settings.zoomType != 'drag' || (settings.zoomType == 'drag' && el.mouseDown))) {
lens.setposition(e);
}
});
var thumb_preload = new Array();
var i = 0;
//binding click event on thumbnails
var thumblist = new Array();
thumblist = $('a').filter(function () {
var regex = new RegExp("gallery[\\s]*:[\\s]*'" + $.trim(el.rel) + "'", "i");
var rel = $(this).attr('rel');
if (regex.test(rel)) {
return this;
}
});
if (thumblist.length > 0) {
//getting the first to the last
var first = thumblist.splice(0, 1);
thumblist.push(first);
}
thumblist.each(function () {
//preloading thumbs
if (settings.preloadImages) {
var thumb_options = $.extend({}, eval("(" + $.trim($(this).attr('rel')) + ")"));
thumb_preload[i] = new Image();
thumb_preload[i].src = thumb_options.largeimage;
i++;
}
$(this).click(function (e) {
if($(this).hasClass('zoomThumbActive')){
return false;
}
thumblist.each(function () {
$(this).removeClass('zoomThumbActive');
});
e.preventDefault();
obj.swapimage(this);
return false;
});
});
},
load: function () {
if (el.largeimageloaded == false && el.largeimageloading == false) {
var url = $(el).attr('href');
el.largeimageloading = true;
largeimage.loadimage(url);
}
},
activate: function (e) {
clearTimeout(el.timer);
//show lens and zoomWindow
lens.show();
stage.show();
},
deactivate: function (e) {
switch (settings.zoomType) {
case 'drag':
//nothing or lens.setcenter();
break;
default:
img.attr('title', el.imagetitle);
$(el).attr('title', el.title);
if (settings.alwaysOn) {
lens.setcenter();
} else {
stage.hide();
lens.hide();
}
break;
}
el.zoom_active = false;
},
swapimage: function (link) {
el.largeimageloading = false;
el.largeimageloaded = false;
var options = new Object();
options = $.extend({}, eval("(" + $.trim($(link).attr('rel')) + ")"));
if (options.smallimage && options.largeimage) {
var smallimage = options.smallimage;
var largeimage = options.largeimage;
$(link).addClass('zoomThumbActive');
$(el).attr('href', largeimage);
img.attr('src', smallimage);
lens.hide();
stage.hide();
obj.load();
} else {
alert('ERROR :: Missing parameter for largeimage or smallimage.');
throw 'ERROR :: Missing parameter for largeimage or smallimage.';
}
return false;
}
});
//sometimes image is already loaded and onload will not fire
if (img[0].complete) {
//fetching data from sallimage if was previously loaded
smallimage.fetchdata();
if ($(".zoomPad", el).length == 0) obj.create();
}
/*========================================================,
| Smallimage
|---------------------------------------------------------:
| Base image into the anchor element
`========================================================*/
function Smallimage(image) {
var $obj = this;
this.node = image[0];
this.findborder = function () {
var bordertop = 0;
bordertop = image.css('border-top-width');
btop = '';
var borderleft = 0;
borderleft = image.css('border-left-width');
bleft = '';
if (bordertop) {
for (i = 0; i < 3; i++) {
var x = [];
x = bordertop.substr(i, 1);
if (isNaN(x) == false) {
btop = btop + '' + bordertop.substr(i, 1);
} else {
break;
}
}
}
if (borderleft) {
for (i = 0; i < 3; i++) {
if (!isNaN(borderleft.substr(i, 1))) {
bleft = bleft + borderleft.substr(i, 1)
} else {
break;
}
}
}
$obj.btop = (btop.length > 0) ? eval(btop) : 0;
$obj.bleft = (bleft.length > 0) ? eval(bleft) : 0;
};
this.fetchdata = function () {
$obj.findborder();
$obj.w = image.width();
$obj.h = image.height();
$obj.ow = image.outerWidth();
$obj.oh = image.outerHeight();
$obj.pos = image.offset();
$obj.pos.l = image.offset().left + $obj.bleft;
$obj.pos.t = image.offset().top + $obj.btop;
$obj.pos.r = $obj.w + $obj.pos.l;
$obj.pos.b = $obj.h + $obj.pos.t;
$obj.rightlimit = image.offset().left + $obj.ow;
$obj.bottomlimit = image.offset().top + $obj.oh;
};
this.node.onerror = function () {
alert('Problems while loading image.');
throw 'Problems while loading image.';
};
this.node.onload = function () {
$obj.fetchdata();
if ($(".zoomPad", el).length == 0) obj.create();
};
return $obj;
};
/*========================================================,
| Loader
|---------------------------------------------------------:
| Show that the large image is loading
`========================================================*/
function Loader() {
var $obj = this;
this.append = function () {
this.node = $('<div/>').addClass('zoomPreload').css('visibility', 'hidden').html(settings.preloadText);
$('.zoomPad', el).append(this.node);
};
this.show = function () {
this.node.top = (smallimage.oh - this.node.height()) / 2;
this.node.left = (smallimage.ow - this.node.width()) / 2;
//setting position
this.node.css({
top: this.node.top,
left: this.node.left,
position: 'absolute',
visibility: 'visible'
});
};
this.hide = function () {
this.node.css('visibility', 'hidden');
};
return this;
}
/*========================================================,
| Lens
|---------------------------------------------------------:
| Lens over the image
`========================================================*/
function Lens() {
var $obj = this;
this.node = $('<div/>').addClass('zoomPup');
//this.nodeimgwrapper = $("<div/>").addClass('zoomPupImgWrapper');
this.append = function () {
$('.zoomPad', el).append($(this.node).hide());
if (settings.zoomType == 'reverse') {
this.image = new Image();
this.image.src = smallimage.node.src; // fires off async
$(this.node).empty().append(this.image);
}
};
this.setdimensions = function () {
this.node.w = (parseInt((settings.zoomWidth) / el.scale.x) > smallimage.w ) ? smallimage.w : (parseInt(settings.zoomWidth / el.scale.x));
this.node.h = (parseInt((settings.zoomHeight) / el.scale.y) > smallimage.h ) ? smallimage.h : (parseInt(settings.zoomHeight / el.scale.y));
this.node.top = (smallimage.oh - this.node.h - 2) / 2;
this.node.left = (smallimage.ow - this.node.w - 2) / 2;
//centering lens
this.node.css({
top: 0,
left: 0,
width: this.node.w + 'px',
height: this.node.h + 'px',
position: 'absolute',
display: 'none',
borderWidth: 1 + 'px'
});
if (settings.zoomType == 'reverse') {
this.image.src = smallimage.node.src;
$(this.node).css({
'opacity': 1
});
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
};
this.setcenter = function () {
//calculating center position
this.node.top = (smallimage.oh - this.node.h - 2) / 2;
this.node.left = (smallimage.ow - this.node.w - 2) / 2;
//centering lens
this.node.css({
top: this.node.top,
left: this.node.left
});
if (settings.zoomType == 'reverse') {
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
//centering large image
largeimage.setposition();
};
this.setposition = function (e) {
el.mousepos.x = e.pageX;
el.mousepos.y = e.pageY;
var lensleft = 0;
var lenstop = 0;
function overleft(lens) {
return el.mousepos.x - (lens.w) / 2 < smallimage.pos.l;
}
function overright(lens) {
return el.mousepos.x + (lens.w) / 2 > smallimage.pos.r;
}
function overtop(lens) {
return el.mousepos.y - (lens.h) / 2 < smallimage.pos.t;
}
function overbottom(lens) {
return el.mousepos.y + (lens.h) / 2 > smallimage.pos.b;
}
lensleft = el.mousepos.x + smallimage.bleft - smallimage.pos.l - (this.node.w + 2) / 2;
lenstop = el.mousepos.y + smallimage.btop - smallimage.pos.t - (this.node.h + 2) / 2;
if (overleft(this.node)) {
lensleft = smallimage.bleft - 1;
} else if (overright(this.node)) {
lensleft = smallimage.w + smallimage.bleft - this.node.w - 1;
}
if (overtop(this.node)) {
lenstop = smallimage.btop - 1;
} else if (overbottom(this.node)) {
lenstop = smallimage.h + smallimage.btop - this.node.h - 1;
}
this.node.left = lensleft;
this.node.top = lenstop;
this.node.css({
'left': lensleft + 'px',
'top': lenstop + 'px'
});
if (settings.zoomType == 'reverse') {
if ($.browser.msie && $.browser.version > 7) {
$(this.node).empty().append(this.image);
}
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
largeimage.setposition();
};
this.hide = function () {
img.css({
'opacity': 1
});
this.node.hide();
};
this.show = function () {
if (settings.zoomType != 'innerzoom' && (settings.lens || settings.zoomType == 'drag')) {
this.node.show();
}
if (settings.zoomType == 'reverse') {
img.css({
'opacity': settings.imageOpacity
});
}
};
this.getoffset = function () {
var o = {};
o.left = $obj.node.left;
o.top = $obj.node.top;
return o;
};
return this;
};
/*========================================================,
| Stage
|---------------------------------------------------------:
| Window area that contains the large image
`========================================================*/
function Stage() {
var $obj = this;
this.node = $("<div class='zoomWindow'><div class='zoomWrapper'><div class='zoomWrapperTitle'></div><div class='zoomWrapperImage'></div></div></div>");
this.ieframe = $('<iframe class="zoomIframe" src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" frameborder="0" ></iframe>');
this.setposition = function () {
this.node.leftpos = 0;
this.node.toppos = 0;
if (settings.zoomType != 'innerzoom') {
//positioning
switch (settings.position) {
case "left":
this.node.leftpos = (smallimage.pos.l - smallimage.bleft - Math.abs(settings.xOffset) - settings.zoomWidth > 0) ? (0 - settings.zoomWidth - Math.abs(settings.xOffset)) : (smallimage.ow + Math.abs(settings.xOffset));
this.node.toppos = Math.abs(settings.yOffset);
break;
case "top":
this.node.leftpos = Math.abs(settings.xOffset);
this.node.toppos = (smallimage.pos.t - smallimage.btop - Math.abs(settings.yOffset) - settings.zoomHeight > 0) ? (0 - settings.zoomHeight - Math.abs(settings.yOffset)) : (smallimage.oh + Math.abs(settings.yOffset));
break;
case "bottom":
this.node.leftpos = Math.abs(settings.xOffset);
this.node.toppos = (smallimage.pos.t - smallimage.btop + smallimage.oh + Math.abs(settings.yOffset) + settings.zoomHeight < screen.height) ? (smallimage.oh + Math.abs(settings.yOffset)) : (0 - settings.zoomHeight - Math.abs(settings.yOffset));
break;
default:
this.node.leftpos = (smallimage.rightlimit + Math.abs(settings.xOffset) + settings.zoomWidth < screen.width) ? (smallimage.ow + Math.abs(settings.xOffset)) : (0 - settings.zoomWidth - Math.abs(settings.xOffset));
this.node.toppos = Math.abs(settings.yOffset);
break;
}
}
this.node.css({
'left': this.node.leftpos + 'px',
'top': this.node.toppos + 'px'
});
return this;
};
this.append = function () {
$('.zoomPad', el).append(this.node);
this.node.css({
position: 'absolute',
display: 'none',
zIndex: 5001
});
if (settings.zoomType == 'innerzoom') {
this.node.css({
cursor: 'default'
});
var thickness = (smallimage.bleft == 0) ? 1 : smallimage.bleft;
$('.zoomWrapper', this.node).css({
borderWidth: thickness + 'px'
});
}
$('.zoomWrapper', this.node).css({
width: Math.round(settings.zoomWidth) + 'px' ,
borderWidth: thickness + 'px'
});
$('.zoomWrapperImage', this.node).css({
width: '100%',
height: Math.round(settings.zoomHeight) + 'px'
});
//zoom title
$('.zoomWrapperTitle', this.node).css({
width: '100%',
position: 'absolute'
});
$('.zoomWrapperTitle', this.node).hide();
if (settings.title && zoomtitle.length > 0) {
$('.zoomWrapperTitle', this.node).html(zoomtitle).show();
}
$obj.setposition();
};
this.hide = function () {
switch (settings.hideEffect) {
case 'fadeout':
this.node.fadeOut(settings.fadeoutSpeed, function () {});
break;
default:
this.node.hide();
break;
}
this.ieframe.hide();
};
this.show = function () {
switch (settings.showEffect) {
case 'fadein':
this.node.fadeIn();
this.node.fadeIn(settings.fadeinSpeed, function () {});
break;
default:
this.node.show();
break;
}
if (isIE6 && settings.zoomType != 'innerzoom') {
this.ieframe.width = this.node.width();
this.ieframe.height = this.node.height();
this.ieframe.left = this.node.leftpos;
this.ieframe.top = this.node.toppos;
this.ieframe.css({
display: 'block',
position: "absolute",
left: this.ieframe.left,
top: this.ieframe.top,
zIndex: 99,
width: this.ieframe.width + 'px',
height: this.ieframe.height + 'px'
});
$('.zoomPad', el).append(this.ieframe);
this.ieframe.show();
};
};
};
/*========================================================,
| LargeImage
|---------------------------------------------------------:
| The large detailed image
`========================================================*/
function Largeimage() {
var $obj = this;
this.node = new Image();
this.loadimage = function (url) {
//showing preload
loader.show();
this.url = url;
this.node.style.position = 'absolute';
this.node.style.border = '0px';
this.node.style.display = 'none';
this.node.style.left = '-5000px';
this.node.style.top = '0px';
document.body.appendChild(this.node);
this.node.src = url; // fires off async
};
this.fetchdata = function () {
var image = $(this.node);
var scale = {};
this.node.style.display = 'block';
$obj.w = image.width();
$obj.h = image.height();
$obj.pos = image.offset();
$obj.pos.l = image.offset().left;
$obj.pos.t = image.offset().top;
$obj.pos.r = $obj.w + $obj.pos.l;
$obj.pos.b = $obj.h + $obj.pos.t;
scale.x = ($obj.w / smallimage.w);
scale.y = ($obj.h / smallimage.h);
el.scale = scale;
document.body.removeChild(this.node);
$('.zoomWrapperImage', el).empty().append(this.node);
//setting lens dimensions;
lens.setdimensions();
};
this.node.onerror = function () {
alert('Problems while loading the big image.');
throw 'Problems while loading the big image.';
};
this.node.onload = function () {
//fetching data
$obj.fetchdata();
loader.hide();
el.largeimageloading = false;
el.largeimageloaded = true;
if (settings.zoomType == 'drag' || settings.alwaysOn) {
lens.show();
stage.show();
lens.setcenter();
}
};
this.setposition = function () {
var left = -el.scale.x * (lens.getoffset().left - smallimage.bleft + 1);
var top = -el.scale.y * (lens.getoffset().top - smallimage.btop + 1);
$(this.node).css({
'left': left + 'px',
'top': top + 'px'
});
};
return this;
};
$(el).data("jqzoom", obj);
};
//es. $.jqzoom.disable('#jqzoom1');
$.jqzoom = {
defaults: {
zoomType: 'standard',
//innerzoom/standard/reverse/drag
zoomWidth: 500,
//zoomWindow default width
zoomHeight: 500,
//zoomWindow default height
xOffset: 10,
//zoomWindow x offset, can be negative(more on the left) or positive(more on the right)
yOffset: 0,
//zoomWindow y offset, can be negative(more on the left) or positive(more on the right)
position: "right",
//zoomWindow default position
preloadImages: true,
//image preload
preloadText: 'Loading zoom',
title: true,
lens: true,
imageOpacity: 0.4,
alwaysOn: false,
showEffect: 'show',
//show/fadein
hideEffect: 'hide',
//hide/fadeout
fadeinSpeed: 'slow',
//fast/slow/number
fadeoutSpeed: '2000' //fast/slow/number
},
disable: function (el) {
var api = $(el).data('jqzoom');
api.disable();
return false;
},
enable: function (el) {
var api = $(el).data('jqzoom');
api.enable();
return false;
},
disableAll: function (el) {
jqzoompluging_disabled = true;
},
enableAll: function (el) {
jqzoompluging_disabled = false;
}
};
})(jQuery); | JavaScript |
function validate(theForm) {
if (theForm.comment_username.value=='' || theForm.comment_username.value==theForm.comment_username.defaultValue) {
alert("Bạn chưa nhập Họ Tên.");
theForm.comment_username.focus();
return false;
}
if (theForm.comment_email.value=='' || theForm.comment_email.value==theForm.comment_email.defaultValue || theForm.comment_email.value.indexOf('@', 0) == -1 || theForm.Email.value.indexOf('.') == -1) {
alert("Vui lòng điền đúng Email");
theForm.comment_email.focus();
return false;
}
if (theForm.comment_title.value=='' || theForm.comment_title.value==theForm.comment_title.defaultValue) {
alert("Bạn chưa nhập Tiêu Đề.");
theForm.comment_title.focus();
return false;
}
if (theForm.comment_content.value=='' || theForm.NoiDung.value==theForm.comment_content.defaultValue) {
alert("Bạn chưa nhập Nội Dung.");
theForm.comment_content.focus();
return false;
}
return true
}
| JavaScript |
/** @license
* DHTML Snowstorm! JavaScript-based Snow for web pages
* --------------------------------------------------------
* Version 1.43.20111201 (Previous rev: 1.42.20111120)
* Copyright (c) 2007, Scott Schiller. All rights reserved.
* Code provided under the BSD License:
* http://schillmania.com/projects/snowstorm/license.txt
*/
/*global window, document, navigator, clearInterval, setInterval */
/*jslint white: false, onevar: true, plusplus: false, undef: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true */
var snowStorm = (function(window, document) {
// --- common properties ---
this.autoStart = true; // Whether the snow should start automatically or not.
this.flakesMax = 110; // Limit total amount of snow made (falling + sticking)
this.flakesMaxActive = 64; // Limit amount of snow falling at once (less = lower CPU use)
this.animationInterval = 33; // Theoretical "miliseconds per frame" measurement. 20 = fast + smooth, but high CPU use. 50 = more conservative, but slower
this.excludeMobile = true; // Snow is likely to be bad news for mobile phones' CPUs (and batteries.) By default, be nice.
this.flakeBottom = null; // Integer for Y axis snow limit, 0 or null for "full-screen" snow effect
this.followMouse = true; // Snow movement can respond to the user's mouse
this.snowColor = '#fff'; // Don't eat (or use?) yellow snow.
this.snowCharacter = '•'; // • = bullet, · is square on some systems etc.
this.snowStick = false; // Whether or not snow should "stick" at the bottom. When off, will never collect.
this.targetElement = null; // element which snow will be appended to (null = document.body) - can be an element ID eg. 'myDiv', or a DOM node reference
this.useMeltEffect = true; // When recycling fallen snow (or rarely, when falling), have it "melt" and fade out if browser supports it
this.useTwinkleEffect = false; // Allow snow to randomly "flicker" in and out of view while falling
this.usePositionFixed = false; // true = snow does not shift vertically when scrolling. May increase CPU load, disabled by default - if enabled, used only where supported
// --- less-used bits ---
this.freezeOnBlur = true; // Only snow when the window is in focus (foreground.) Saves CPU.
this.flakeLeftOffset = 0; // Left margin/gutter space on edge of container (eg. browser window.) Bump up these values if seeing horizontal scrollbars.
this.flakeRightOffset = 0; // Right margin/gutter space on edge of container
this.flakeWidth = 8; // Max pixel width reserved for snow element
this.flakeHeight = 8; // Max pixel height reserved for snow element
this.vMaxX = 5; // Maximum X velocity range for snow
this.vMaxY = 4; // Maximum Y velocity range for snow
this.zIndex = 0; // CSS stacking order applied to each snowflake
// --- End of user section ---
var s = this, storm = this, i,
// UA sniffing and backCompat rendering mode checks for fixed position, etc.
isIE = navigator.userAgent.match(/msie/i),
isIE6 = navigator.userAgent.match(/msie 6/i),
isWin98 = navigator.appVersion.match(/windows 98/i),
isMobile = navigator.userAgent.match(/mobile|opera m(ob|in)/i),
isBackCompatIE = (isIE && document.compatMode === 'BackCompat'),
noFixed = (isMobile || isBackCompatIE || isIE6),
screenX = null, screenX2 = null, screenY = null, scrollY = null, vRndX = null, vRndY = null,
windOffset = 1,
windMultiplier = 2,
flakeTypes = 6,
fixedForEverything = false,
opacitySupported = (function(){
try {
document.createElement('div').style.opacity = '0.7';
} catch(e) {
return false;
}
return true;
}()),
didInit = false,
docFrag = document.createDocumentFragment();
this.timers = [];
this.flakes = [];
this.disabled = false;
this.active = false;
this.meltFrameCount = 20;
this.meltFrames = [];
this.events = (function() {
var old = (!window.addEventListener && window.attachEvent), slice = Array.prototype.slice,
evt = {
add: (old?'attachEvent':'addEventListener'),
remove: (old?'detachEvent':'removeEventListener')
};
function getArgs(oArgs) {
var args = slice.call(oArgs), len = args.length;
if (old) {
args[1] = 'on' + args[1]; // prefix
if (len > 3) {
args.pop(); // no capture
}
} else if (len === 3) {
args.push(false);
}
return args;
}
function apply(args, sType) {
var element = args.shift(),
method = [evt[sType]];
if (old) {
element[method](args[0], args[1]);
} else {
element[method].apply(element, args);
}
}
function addEvent() {
apply(getArgs(arguments), 'add');
}
function removeEvent() {
apply(getArgs(arguments), 'remove');
}
return {
add: addEvent,
remove: removeEvent
};
}());
function rnd(n,min) {
if (isNaN(min)) {
min = 0;
}
return (Math.random()*n)+min;
}
function plusMinus(n) {
return (parseInt(rnd(2),10)===1?n*-1:n);
}
this.randomizeWind = function() {
var i;
vRndX = plusMinus(rnd(s.vMaxX,0.2));
vRndY = rnd(s.vMaxY,0.2);
if (this.flakes) {
for (i=0; i<this.flakes.length; i++) {
if (this.flakes[i].active) {
this.flakes[i].setVelocities();
}
}
}
};
this.scrollHandler = function() {
var i;
// "attach" snowflakes to bottom of window if no absolute bottom value was given
scrollY = (s.flakeBottom?0:parseInt(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop,10));
if (isNaN(scrollY)) {
scrollY = 0; // Netscape 6 scroll fix
}
if (!fixedForEverything && !s.flakeBottom && s.flakes) {
for (i=s.flakes.length; i--;) {
if (s.flakes[i].active === 0) {
s.flakes[i].stick();
}
}
}
};
this.resizeHandler = function() {
if (window.innerWidth || window.innerHeight) {
screenX = window.innerWidth-16-s.flakeRightOffset;
screenY = (s.flakeBottom?s.flakeBottom:window.innerHeight);
} else {
screenX = (document.documentElement.clientWidth||document.body.clientWidth||document.body.scrollWidth)-(!isIE?8:0)-s.flakeRightOffset;
screenY = s.flakeBottom?s.flakeBottom:(document.documentElement.clientHeight||document.body.clientHeight||document.body.scrollHeight);
}
screenX2 = parseInt(screenX/2,10);
};
this.resizeHandlerAlt = function() {
screenX = s.targetElement.offsetLeft+s.targetElement.offsetWidth-s.flakeRightOffset;
screenY = s.flakeBottom?s.flakeBottom:s.targetElement.offsetTop+s.targetElement.offsetHeight;
screenX2 = parseInt(screenX/2,10);
};
this.freeze = function() {
// pause animation
var i;
if (!s.disabled) {
s.disabled = 1;
} else {
return false;
}
for (i=s.timers.length; i--;) {
clearInterval(s.timers[i]);
}
};
this.resume = function() {
if (s.disabled) {
s.disabled = 0;
} else {
return false;
}
s.timerInit();
};
this.toggleSnow = function() {
if (!s.flakes.length) {
// first run
s.start();
} else {
s.active = !s.active;
if (s.active) {
s.show();
s.resume();
} else {
s.stop();
s.freeze();
}
}
};
this.stop = function() {
var i;
this.freeze();
for (i=this.flakes.length; i--;) {
this.flakes[i].o.style.display = 'none';
}
s.events.remove(window,'scroll',s.scrollHandler);
s.events.remove(window,'resize',s.resizeHandler);
if (s.freezeOnBlur) {
if (isIE) {
s.events.remove(document,'focusout',s.freeze);
s.events.remove(document,'focusin',s.resume);
} else {
s.events.remove(window,'blur',s.freeze);
s.events.remove(window,'focus',s.resume);
}
}
};
this.show = function() {
var i;
for (i=this.flakes.length; i--;) {
this.flakes[i].o.style.display = 'block';
}
};
this.SnowFlake = function(parent,type,x,y) {
var s = this, storm = parent;
this.type = type;
this.x = x||parseInt(rnd(screenX-20),10);
this.y = (!isNaN(y)?y:-rnd(screenY)-12);
this.vX = null;
this.vY = null;
this.vAmpTypes = [1,1.2,1.4,1.6,1.8]; // "amplification" for vX/vY (based on flake size/type)
this.vAmp = this.vAmpTypes[this.type];
this.melting = false;
this.meltFrameCount = storm.meltFrameCount;
this.meltFrames = storm.meltFrames;
this.meltFrame = 0;
this.twinkleFrame = 0;
this.active = 1;
this.fontSize = (10+(this.type/5)*10);
this.o = document.createElement('div');
this.o.innerHTML = storm.snowCharacter;
this.o.style.color = storm.snowColor;
this.o.style.position = (fixedForEverything?'fixed':'absolute');
this.o.style.width = storm.flakeWidth+'px';
this.o.style.height = storm.flakeHeight+'px';
this.o.style.fontFamily = 'arial,verdana';
this.o.style.cursor = 'default';
this.o.style.overflow = 'hidden';
this.o.style.fontWeight = 'normal';
this.o.style.zIndex = storm.zIndex;
docFrag.appendChild(this.o);
this.refresh = function() {
if (isNaN(s.x) || isNaN(s.y)) {
// safety check
return false;
}
s.o.style.left = s.x+'px';
s.o.style.top = s.y+'px';
};
this.stick = function() {
if (noFixed || (storm.targetElement !== document.documentElement && storm.targetElement !== document.body)) {
s.o.style.top = (screenY+scrollY-storm.flakeHeight)+'px';
} else if (storm.flakeBottom) {
s.o.style.top = storm.flakeBottom+'px';
} else {
s.o.style.display = 'none';
s.o.style.top = 'auto';
s.o.style.bottom = '0px';
s.o.style.position = 'fixed';
s.o.style.display = 'block';
}
};
this.vCheck = function() {
if (s.vX>=0 && s.vX<0.2) {
s.vX = 0.2;
} else if (s.vX<0 && s.vX>-0.2) {
s.vX = -0.2;
}
if (s.vY>=0 && s.vY<0.2) {
s.vY = 0.2;
}
};
this.move = function() {
var vX = s.vX*windOffset, yDiff;
s.x += vX;
s.y += (s.vY*s.vAmp);
if (s.x >= screenX || screenX-s.x < storm.flakeWidth) { // X-axis scroll check
s.x = 0;
} else if (vX < 0 && s.x-storm.flakeLeftOffset < -storm.flakeWidth) {
s.x = screenX-storm.flakeWidth-1; // flakeWidth;
}
s.refresh();
yDiff = screenY+scrollY-s.y;
if (yDiff<storm.flakeHeight) {
s.active = 0;
if (storm.snowStick) {
s.stick();
} else {
s.recycle();
}
} else {
if (storm.useMeltEffect && s.active && s.type < 3 && !s.melting && Math.random()>0.998) {
// ~1/1000 chance of melting mid-air, with each frame
s.melting = true;
s.melt();
// only incrementally melt one frame
// s.melting = false;
}
if (storm.useTwinkleEffect) {
if (!s.twinkleFrame) {
if (Math.random()>0.9) {
s.twinkleFrame = parseInt(Math.random()*20,10);
}
} else {
s.twinkleFrame--;
s.o.style.visibility = (s.twinkleFrame && s.twinkleFrame%2===0?'hidden':'visible');
}
}
}
};
this.animate = function() {
// main animation loop
// move, check status, die etc.
s.move();
};
this.setVelocities = function() {
s.vX = vRndX+rnd(storm.vMaxX*0.12,0.1);
s.vY = vRndY+rnd(storm.vMaxY*0.12,0.1);
};
this.setOpacity = function(o,opacity) {
if (!opacitySupported) {
return false;
}
o.style.opacity = opacity;
};
this.melt = function() {
if (!storm.useMeltEffect || !s.melting) {
s.recycle();
} else {
if (s.meltFrame < s.meltFrameCount) {
s.setOpacity(s.o,s.meltFrames[s.meltFrame]);
s.o.style.fontSize = s.fontSize-(s.fontSize*(s.meltFrame/s.meltFrameCount))+'px';
s.o.style.lineHeight = storm.flakeHeight+2+(storm.flakeHeight*0.75*(s.meltFrame/s.meltFrameCount))+'px';
s.meltFrame++;
} else {
s.recycle();
}
}
};
this.recycle = function() {
s.o.style.display = 'none';
s.o.style.position = (fixedForEverything?'fixed':'absolute');
s.o.style.bottom = 'auto';
s.setVelocities();
s.vCheck();
s.meltFrame = 0;
s.melting = false;
s.setOpacity(s.o,1);
s.o.style.padding = '0px';
s.o.style.margin = '0px';
s.o.style.fontSize = s.fontSize+'px';
s.o.style.lineHeight = (storm.flakeHeight+2)+'px';
s.o.style.textAlign = 'center';
s.o.style.verticalAlign = 'baseline';
s.x = parseInt(rnd(screenX-storm.flakeWidth-20),10);
s.y = parseInt(rnd(screenY)*-1,10)-storm.flakeHeight;
s.refresh();
s.o.style.display = 'block';
s.active = 1;
};
this.recycle(); // set up x/y coords etc.
this.refresh();
};
this.snow = function() {
var active = 0, used = 0, waiting = 0, flake = null, i;
for (i=s.flakes.length; i--;) {
if (s.flakes[i].active === 1) {
s.flakes[i].move();
active++;
} else if (s.flakes[i].active === 0) {
used++;
} else {
waiting++;
}
if (s.flakes[i].melting) {
s.flakes[i].melt();
}
}
if (active<s.flakesMaxActive) {
flake = s.flakes[parseInt(rnd(s.flakes.length),10)];
if (flake.active === 0) {
flake.melting = true;
}
}
};
this.mouseMove = function(e) {
if (!s.followMouse) {
return true;
}
var x = parseInt(e.clientX,10);
if (x<screenX2) {
windOffset = -windMultiplier+(x/screenX2*windMultiplier);
} else {
x -= screenX2;
windOffset = (x/screenX2)*windMultiplier;
}
};
this.createSnow = function(limit,allowInactive) {
var i;
for (i=0; i<limit; i++) {
s.flakes[s.flakes.length] = new s.SnowFlake(s,parseInt(rnd(flakeTypes),10));
if (allowInactive || i>s.flakesMaxActive) {
s.flakes[s.flakes.length-1].active = -1;
}
}
storm.targetElement.appendChild(docFrag);
};
this.timerInit = function() {
s.timers = (!isWin98?[setInterval(s.snow,s.animationInterval)]:[setInterval(s.snow,s.animationInterval*3),setInterval(s.snow,s.animationInterval)]);
};
this.init = function() {
var i;
for (i=0; i<s.meltFrameCount; i++) {
s.meltFrames.push(1-(i/s.meltFrameCount));
}
s.randomizeWind();
s.createSnow(s.flakesMax); // create initial batch
s.events.add(window,'resize',s.resizeHandler);
s.events.add(window,'scroll',s.scrollHandler);
if (s.freezeOnBlur) {
if (isIE) {
s.events.add(document,'focusout',s.freeze);
s.events.add(document,'focusin',s.resume);
} else {
s.events.add(window,'blur',s.freeze);
s.events.add(window,'focus',s.resume);
}
}
s.resizeHandler();
s.scrollHandler();
if (s.followMouse) {
s.events.add(isIE?document:window,'mousemove',s.mouseMove);
}
s.animationInterval = Math.max(20,s.animationInterval);
s.timerInit();
};
this.start = function(bFromOnLoad) {
if (!didInit) {
didInit = true;
} else if (bFromOnLoad) {
// already loaded and running
return true;
}
if (typeof s.targetElement === 'string') {
var targetID = s.targetElement;
s.targetElement = document.getElementById(targetID);
if (!s.targetElement) {
throw new Error('Snowstorm: Unable to get targetElement "'+targetID+'"');
}
}
if (!s.targetElement) {
s.targetElement = (!isIE?(document.documentElement?document.documentElement:document.body):document.body);
}
if (s.targetElement !== document.documentElement && s.targetElement !== document.body) {
s.resizeHandler = s.resizeHandlerAlt; // re-map handler to get element instead of screen dimensions
}
s.resizeHandler(); // get bounding box elements
s.usePositionFixed = (s.usePositionFixed && !noFixed); // whether or not position:fixed is supported
fixedForEverything = s.usePositionFixed;
if (screenX && screenY && !s.disabled) {
s.init();
s.active = true;
}
};
function doDelayedStart() {
window.setTimeout(function() {
s.start(true);
}, 20);
// event cleanup
s.events.remove(isIE?document:window,'mousemove',doDelayedStart);
}
function doStart() {
if (!s.excludeMobile || !isMobile) {
if (s.freezeOnBlur) {
s.events.add(isIE?document:window,'mousemove',doDelayedStart);
} else {
doDelayedStart();
}
}
// event cleanup
s.events.remove(window, 'load', doStart);
}
// hooks for starting the snow
if (s.autoStart) {
s.events.add(window, 'load', doStart, false);
}
return this;
}(window, document)); | JavaScript |
// [0] - current id [1] - id prefix [2] - true = not auto open [3] - true = auto hide [4] - force current popuped block for show|hide onclick
var current_popuppeds=new Array(
new Array("","search-type_",true,true,true),
new Array("","category_",true,true,true),
new Array("","style_",true,true,true),
new Array("","author_",true,true,true)
);
var IE = 0;
if (navigator.userAgent.indexOf("MSIE")!=-1) IE = 1;
var IE70 = 0;
if (navigator.userAgent.indexOf("MSIE 7.0")!=-1) IE70 = 1;
var konqueror = 0;
if (navigator.userAgent.indexOf("Konqueror") !=-1) konqueror = 1;
var opera = 0;
if (navigator.userAgent.indexOf("Opera")!=-1) opera = 1;
var FF20 = 0;
if (navigator.userAgent.indexOf("Firefox/2.0")!=-1) FF20 = 1;
var FF15 = 0;
if (navigator.userAgent.indexOf("Firefox/1.5")!=-1) FF15 = 1;
var safari419_3 = 0;
if (navigator.userAgent.indexOf("Safari/419")!=-1) safari419_3 = 1;
function show_hide_block(block,id){
var div_block=document.getElementById(current_popuppeds[block][1]+id);
if(div_block.style.visibility == 'visible' && (!current_popuppeds[block][2] || current_popuppeds[block][4])) {
div_block.style.visibility = 'hidden';
removeBodyClickListener();
} else if(div_block!=null) {
auto_hide_blocks();
div_block.style.visibility = 'visible';
addBodyClickListener();
}
if((current_popuppeds[block][0]!="") && (current_popuppeds[block][0]!=id)){
var div_block=document.getElementById(current_popuppeds[block][1]+current_popuppeds[block][0]);
div_block.style.visibility = 'hidden';
removeBodyClickListener();
}
//change_visibility(current_popuppeds[block][1]);
current_popuppeds[block][0]=id;
}
/*
function change_visibility(elementId) {
if (elementId == "search-type_") {
var elementObject = document.getElementById(elementId);
if (elementObject != null) {
elementObject.disabled = false;
}
}
}
*/
function auto_hide_blocks(){
var i=0;
for(i=0;i<current_popuppeds.length;i++){
if(current_popuppeds[i][3] && current_popuppeds[i][0] != ""){
var div_block=document.getElementById(current_popuppeds[i][1]+current_popuppeds[i][0]);
if(div_block!=null) {
div_block.style.visibility = 'hidden';
//change_visibility(current_popuppeds[i][1]);
}
}
}
removeBodyClickListener();
}
function hide_all_blocks(event){
if((event.type=='mousedown'&&event.button==0) || event == 'mousedown'){
var i=0;
for(i=0;i<current_popuppeds.length;i++){
if(current_popuppeds[i][2] && current_popuppeds[i][0] != ""){
var div_block=document.getElementById(current_popuppeds[i][1]+current_popuppeds[i][0]);
if(div_block!=null)div_block.style.visibility = 'hidden';
//change_visibility(current_popuppeds[i][1]);
}
}
removeBodyClickListener();
}
return(true);
}
function hide_all_blocks_listener() {
hide_all_blocks('mousedown');
}
function cancelBubbleEvent(elementObject, event) {
event.cancelBubble=true;
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
}
if (event.stopPropagation) {
event.stopPropagation();
}
if (elementObject.stopPropagation) {
elementObject.stopPropagation();
}
return false;
}
function addBodyClickListener() {
AttachEvent(document.body, 'mousedown', hide_all_blocks_listener, false);
}
function removeBodyClickListener() {
if (document.body.removeEventListener){ //Mozilla
document.body.removeEventListener("mousedown", hide_all_blocks_listener, false);
} else if (document.detachEvent){ //IE
document.body.detachEvent('mousedown', hide_all_blocks_listener);
}
}
function AttachEvent(obj,evt,fnc,useCapture){
if (!useCapture) useCapture=false;
if (obj.addEventListener){
obj.addEventListener(evt,fnc,useCapture);
return true;
} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
else{
MyAttachEvent(obj,evt,fnc);
obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
}
}
//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
if (!obj.myEvents) obj.myEvents={};
if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
var evts = obj.myEvents[evt];
evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
var evts = obj.myEvents[evt];
for (var i=0,len=evts.length;i<len;i++) evts[i]();
}
//---------------------------------------------------------------------
function poppuperSearchType(elementObject, event) {
// if (!IE || IE70) {
// elementObject.size=4;
// elementObject.size=0;
// }
// if (!FF15 && !safari419_3) {
// elementObject.disabled = true;
// }
show_hide_block('0','search-type');
cancelBubbleEvent(elementObject, event);
//elementObject.blur();
//elementObject.disabled = false;
return false;
}
function poppuperCategory(elementObject, event) {
// if (!IE || IE70) {
// elementObject.size=4;
// elementObject.size=0;
// }
// if (!FF15 && !safari419_3) {
// elementObject.disabled = true;
// }
show_hide_block('1','category');
cancelBubbleEvent(elementObject, event);
//elementObject.blur();
//elementObject.disabled = false;
return false;
}
function poppuperStyle(elementObject, event) {
// if (!IE || IE70) {
// elementObject.size=4;
// elementObject.size=0;
// }
// if (!FF15 && !safari419_3) {
// elementObject.disabled = true;
// }
show_hide_block('2','style');
cancelBubbleEvent(elementObject, event);
//elementObject.blur();
//elementObject.disabled = false;
return false;
}
function poppuperAuthor(elementObject, event) {
// if (!IE || IE70) {
// elementObject.size=4;
// elementObject.size=0;
// }
// if (!FF15 && !safari419_3) {
// elementObject.disabled = true;
// }
show_hide_block('3','author');
cancelBubbleEvent(elementObject, event);
//elementObject.blur();
//elementObject.disabled = false;
return false;
} | JavaScript |
function file_get_contents (url, flags, context, offset, maxLen) {
// Read the entire file into a string
//
// version: 906.111
// discuss at: http://phpjs.org/functions/file_get_contents // + original by: Legaev Andrey
// + input by: Jani Hartikainen
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Raphael (Ao) RUDLER // + bugfixed by: Brett Zamir (http://brett-zamir.me)
// % note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain without modifications.
// % note 2: Synchronous by default (as in PHP) so may lock up browser. Can
// % note 2: get async by setting a custom "phpjs.async" property to true and "notification" for an
// % note 2: optional callback (both as context params, with responseText, and other JS-specific // % note 2: request properties available via 'this'). Note that file_get_contents() will not return the text
// % note 2: in such a case (use this.responseText within the callback). Or, consider using
// % note 2: jQuery's: $('#divId').load('http://url') instead.
// % note 3: The context argument is only implemented for http, and only partially (see below for
// % note 3: "Presently unimplemented HTTP context options"); also the arguments passed to // % note 3: notification are incomplete
// * example 1: file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
// * returns 1: '123'
// Note: could also be made to optionally add to global $http_response_header as per http://php.net/manual/en/reserved.variables.httpresponseheader.php
var tmp, headers = [], newTmp = [],
k = 0,
i = 0,
href = '',
pathPos = -1, flagNames = 0,
content = null,
http_stream = false;
var func = function (value) {
return value.substring(1) !== ''; };
// BEGIN REDUNDANT
this.php_js = this.php_js || {};
this.php_js.ini = this.php_js.ini || {}; // END REDUNDANT
var ini = this.php_js.ini;
context = context || this.php_js.default_streams_context || null;
if (!flags) { flags = 0;
}
var OPTS = {
FILE_USE_INCLUDE_PATH: 1,
FILE_TEXT: 32, FILE_BINARY: 64
};
if (typeof flags === 'number') { // Allow for a single string or an array of string flags
flagNames = flags;
} else { flags = [].concat(flags);
for (i = 0; i < flags.length; i++) {
if (OPTS[flags[i]]) {
flagNames = flagNames | OPTS[flags[i]];
} }
}
if (flagNames & OPTS.FILE_BINARY && (flagNames & OPTS.FILE_TEXT)) { // These flags shouldn't be together
throw 'You cannot pass both FILE_BINARY and FILE_TEXT to file_get_contents()'; }
if ((flagNames & OPTS.FILE_USE_INCLUDE_PATH) && ini.include_path && ini.include_path.local_value) {
var slash = ini.include_path.local_value.indexOf('/') !== -1 ? '/' : '\\';
url = ini.include_path.local_value + slash + url; } else if (!/^(https?|file):/.test(url)) { // Allow references within or below the same directory (should fix to allow other relative references or root reference; could make dependent on parse_url())
href = this.window.location.href;
pathPos = url.indexOf('/') === 0 ? href.indexOf('/', 8) - 1 : href.lastIndexOf('/');
url = href.slice(0, pathPos + 1) + url;
}
if (context) {
var http_options = context.stream_options && context.stream_options.http;
http_stream = !! http_options;
}
if (!context || http_stream) {
var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
if (!req) {
throw new Error('XMLHttpRequest not supported'); }
var method = http_stream ? http_options.method : 'GET';
var async = !! (context && context.stream_params && context.stream_params['phpjs.async']);
if (ini['phpjs.ajaxBypassCache'] && ini['phpjs.ajaxBypassCache'].local_value) {
url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(); // Give optional means of forcing bypass of cache
}
req.open(method, url, async); if (async) {
var notification = context.stream_params.notification;
if (typeof notification === 'function') {
// Fix: make work with req.addEventListener if available: https://developer.mozilla.org/En/Using_XMLHttpRequest
if (0 && req.addEventListener) { // Unimplemented so don't allow to get here
req.addEventListener('progress', updateProgress, false);
req.addEventListener('load', transferComplete, false);
req.addEventListener('error', transferFailed, false);
req.addEventListener('abort', transferCanceled, false);
} else {
req.onreadystatechange = function (aEvt) { // aEvt has stopPropagation(), preventDefault(); see https://developer.mozilla.org/en/NsIDOMEvent
// Other XMLHttpRequest properties: multipart, responseXML, status, statusText, upload, withCredentials
/* PHP Constants:
STREAM_NOTIFY_RESOLVE 1 A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT 2 A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED 3 Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS 4 The mime-type of resource has been identified, refer to message for a description of the discovered type. STREAM_NOTIFY_FILE_SIZE_IS 5 The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED 6 The external resource has redirected the stream to an alternate location. Refer to message .
STREAM_NOTIFY_PROGRESS 7 Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED 8 There is no more data available on the stream.
STREAM_NOTIFY_FAILURE 9 A generic error occurred on the stream, consult message and message_code for details. STREAM_NOTIFY_AUTH_RESULT 10 Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO 0 Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN 1 Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR 2 A critical error occurred. Processing cannot continue. */
var objContext = {
responseText: req.responseText,
responseXML: req.responseXML,
status: req.status, statusText: req.statusText,
readyState: req.readyState,
evt: aEvt
}; // properties are not available in PHP, but offered on notification via 'this' for convenience
// notification args: notification_code, severity, message, message_code, bytes_transferred, bytes_max (all int's except string 'message') // Need to add message, etc.
var bytes_transferred;
switch (req.readyState) {
case 0:
// UNINITIALIZED open() has not been called yet. notification.call(objContext, 0, 0, '', 0, 0, 0);
break;
case 1:
// LOADING send() has not been called yet.
notification.call(objContext, 0, 0, '', 0, 0, 0); break;
case 2:
// LOADED send() has been called, and headers and status are available.
notification.call(objContext, 0, 0, '', 0, 0, 0);
break; case 3:
// INTERACTIVE Downloading; responseText holds partial data.
bytes_transferred = req.responseText.length * 2; // One character is two bytes
notification.call(objContext, 7, 0, '', 0, bytes_transferred, 0);
break; case 4:
// COMPLETED The operation is complete.
if (req.status >= 200 && req.status < 400) {
bytes_transferred = req.responseText.length * 2; // One character is two bytes
notification.call(objContext, 8, 0, '', req.status, bytes_transferred, 0); } else if (req.status === 403) { // Fix: These two are finished except for message
notification.call(objContext, 10, 2, '', req.status, 0, 0);
} else { // Errors
notification.call(objContext, 9, 2, '', req.status, 0, 0);
} break;
default:
throw 'Unrecognized ready state for file_get_contents()';
}
} }
}
}
if (http_stream) { var sendHeaders = http_options.header && http_options.header.split(/\r?\n/);
var userAgentSent = false;
for (i = 0; i < sendHeaders.length; i++) {
var sendHeader = sendHeaders[i];
var breakPos = sendHeader.search(/:\s*/); var sendHeaderName = sendHeader.substring(0, breakPos);
req.setRequestHeader(sendHeaderName, sendHeader.substring(breakPos + 1));
if (sendHeaderName === 'User-Agent') {
userAgentSent = true;
} }
if (!userAgentSent) {
var user_agent = http_options.user_agent || (ini.user_agent && ini.user_agent.local_value);
if (user_agent) {
req.setRequestHeader('User-Agent', user_agent); }
}
content = http_options.content || null;
/*
// Presently unimplemented HTTP context options var request_fulluri = http_options.request_fulluri || false; // When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it.
var max_redirects = http_options.max_redirects || 20; // The max number of redirects to follow. Value 1 or less means that no redirects are followed.
var protocol_version = http_options.protocol_version || 1.0; // HTTP protocol version
var timeout = http_options.timeout || (ini.default_socket_timeout && ini.default_socket_timeout.local_value); // Read timeout in seconds, specified by a float
var ignore_errors = http_options.ignore_errors || false; // Fetch the content even on failure status codes. */
}
if (flagNames & OPTS.FILE_TEXT) { // Overrides how encoding is treated (regardless of what is returned from the server)
var content_type = 'text/html'; if (http_options && http_options['phpjs.override']) { // Fix: Could allow for non-HTTP as well
content_type = http_options['phpjs.override']; // We use this, e.g., in gettext-related functions if character set
// overridden earlier by bind_textdomain_codeset()
} else {
var encoding = (ini['unicode.stream_encoding'] && ini['unicode.stream_encoding'].local_value) || 'UTF-8'; if (http_options && http_options.header && (/^content-type:/im).test(http_options.header)) { // We'll assume a content-type expects its own specified encoding if present
content_type = http_options.header.match(/^content-type:\s*(.*)$/im)[1]; // We let any header encoding stand
}
if (!(/;\s*charset=/).test(content_type)) { // If no encoding
content_type += '; charset=' + encoding; }
}
req.overrideMimeType(content_type);
}
// Default is FILE_BINARY, but for binary, we apparently deviate from PHP in requiring the flag, since many if not // most people will also want a way to have it be auto-converted into native JavaScript text instead
else if (flagNames & OPTS.FILE_BINARY) { // Trick at https://developer.mozilla.org/En/Using_XMLHttpRequest to get binary
req.overrideMimeType('text/plain; charset=x-user-defined');
// Getting an individual byte then requires:
// responseText.charCodeAt(x) & 0xFF; // throw away high-order byte (f7) where x is 0 to responseText.length-1 (see notes in our substr()) }
if (http_options && http_options['phpjs.sendAsBinary']) { // For content sent in a POST or PUT request (use with file_put_contents()?)
req.sendAsBinary(content); // In Firefox, only available FF3+
} else { req.send(content);
}
tmp = req.getAllResponseHeaders();
if (tmp) { tmp = tmp.split('\n');
for (k = 0; k < tmp.length; k++) {
if (func(tmp[k])) {
newTmp.push(tmp[k]);
} }
tmp = newTmp;
for (i = 0; i < tmp.length; i++) {
headers[i] = tmp[i];
} this.$http_response_header = headers; // see http://php.net/manual/en/reserved.variables.httpresponseheader.php
}
if (offset || maxLen) {
if (maxLen) { return req.responseText.substr(offset || 0, maxLen);
}
return req.responseText.substr(offset);
}
return req.responseText; }
return false;
} | JavaScript |
/*
* transform: A jQuery cssHooks adding cross-browser 2d transform capabilities to $.fn.css() and $.fn.animate()
*
* limitations:
* - requires jQuery 1.4.3+
* - Should you use the *translate* property, then your elements need to be absolutely positionned in a relatively positionned wrapper **or it will fail in IE678**.
* - transformOrigin is not accessible
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery.transform.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*
* This saved you an hour of work?
* Send me music http://www.amazon.co.uk/wishlist/HNTU0468LQON
*
*/
(function( $ ) {
/*
* Feature tests and global variables
*/
var div = document.createElement('div'),
divStyle = div.style,
propertyName = 'transform',
suffix = 'Transform',
testProperties = [
'O' + suffix,
'ms' + suffix,
'Webkit' + suffix,
'Moz' + suffix,
// prefix-less property
propertyName
],
i = testProperties.length,
supportProperty,
supportMatrixFilter,
propertyHook,
propertyGet,
rMatrix = /Matrix([^)]*)/;
// test different vendor prefixes of this property
while ( i-- ) {
if ( testProperties[i] in divStyle ) {
$.support[propertyName] = supportProperty = testProperties[i];
continue;
}
}
// IE678 alternative
if ( !supportProperty ) {
$.support.matrixFilter = supportMatrixFilter = divStyle.filter === '';
}
// prevent IE memory leak
div = divStyle = null;
// px isn't the default unit of this property
$.cssNumber[propertyName] = true;
/*
* fn.css() hooks
*/
if ( supportProperty && supportProperty != propertyName ) {
// Modern browsers can use jQuery.cssProps as a basic hook
$.cssProps[propertyName] = supportProperty;
// Firefox needs a complete hook because it stuffs matrix with 'px'
if ( supportProperty == 'Moz' + suffix ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
// remove 'px' from the computed matrix
$.css( elem, supportProperty ).split('px').join(''):
elem.style[supportProperty]
)
},
set: function( elem, value ) {
// remove 'px' from matrices
elem.style[supportProperty] = /matrix[^)p]*\)/.test(value) ?
value.replace(/matrix((?:[^,]*,){4})([^,]*),([^)]*)/, 'matrix$1$2px,$3px'):
value;
}
}
/* Fix two jQuery bugs still present in 1.5.1
* - rupper is incompatible with IE9, see http://jqbug.com/8346
* - jQuery.css is not really jQuery.cssProps aware, see http://jqbug.com/8402
*/
} else if ( /^1\.[0-5](?:\.|$)/.test($.fn.jquery) ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
$.css( elem, supportProperty.replace(/^ms/, 'Ms') ):
elem.style[supportProperty]
)
}
}
}
/* TODO: leverage hardware acceleration of 3d transform in Webkit only
else if ( supportProperty == 'Webkit' + suffix && support3dTransform ) {
propertyHook = {
set: function( elem, value ) {
elem.style[supportProperty] =
value.replace();
}
}
}*/
} else if ( supportMatrixFilter ) {
propertyHook = {
get: function( elem, computed ) {
var elemStyle = ( computed && elem.currentStyle ? elem.currentStyle : elem.style ),
matrix;
if ( elemStyle && rMatrix.test( elemStyle.filter ) ) {
matrix = RegExp.$1.split(',');
matrix = [
matrix[0].split('=')[1],
matrix[2].split('=')[1],
matrix[1].split('=')[1],
matrix[3].split('=')[1]
];
} else {
matrix = [1,0,0,1];
}
matrix[4] = elemStyle ? elemStyle.left : 0;
matrix[5] = elemStyle ? elemStyle.top : 0;
return "matrix(" + matrix + ")";
},
set: function( elem, value, animate ) {
var elemStyle = elem.style,
currentStyle,
Matrix,
filter;
if ( !animate ) {
elemStyle.zoom = 1;
}
value = matrix(value);
// rotate, scale and skew
if ( !animate || animate.M ) {
Matrix = [
"Matrix("+
"M11="+value[0],
"M12="+value[2],
"M21="+value[1],
"M22="+value[3],
"SizingMethod='auto expand'"
].join();
filter = ( currentStyle = elem.currentStyle ) && currentStyle.filter || elemStyle.filter || "";
elemStyle.filter = rMatrix.test(filter) ?
filter.replace(rMatrix, Matrix) :
filter + " progid:DXImageTransform.Microsoft." + Matrix + ")";
// center the transform origin, from pbakaus's Transformie http://github.com/pbakaus/transformie
if ( (centerOrigin = $.transform.centerOrigin) ) {
elemStyle[centerOrigin == 'margin' ? 'marginLeft' : 'left'] = -(elem.offsetWidth/2) + (elem.clientWidth/2) + 'px';
elemStyle[centerOrigin == 'margin' ? 'marginTop' : 'top'] = -(elem.offsetHeight/2) + (elem.clientHeight/2) + 'px';
}
}
// translate
if ( !animate || animate.T ) {
// We assume that the elements are absolute positionned inside a relative positionned wrapper
elemStyle.left = value[4] + 'px';
elemStyle.top = value[5] + 'px';
}
}
}
}
// populate jQuery.cssHooks with the appropriate hook if necessary
if ( propertyHook ) {
$.cssHooks[propertyName] = propertyHook;
}
// we need a unique setter for the animation logic
propertyGet = propertyHook && propertyHook.get || $.css;
/*
* fn.animate() hooks
*/
$.fx.step.transform = function( fx ) {
var elem = fx.elem,
start = fx.start,
end = fx.end,
split,
pos = fx.pos,
transform,
translate,
rotate,
scale,
skew,
T = false,
M = false,
prop;
translate = rotate = scale = skew = '';
// fx.end and fx.start need to be converted to their translate/rotate/scale/skew components
// so that we can interpolate them
if ( !start || typeof start === "string" ) {
// the following block can be commented out with jQuery 1.5.1+, see #7912
if (!start) {
start = propertyGet( elem, supportProperty );
}
// force layout only once per animation
if ( supportMatrixFilter ) {
elem.style.zoom = 1;
}
// if the start computed matrix is in end, we are doing a relative animation
split = end.split(start);
if ( split.length == 2 ) {
// remove the start computed matrix to make animations more accurate
end = split.join('');
fx.origin = start;
start = 'none';
}
// start is either 'none' or a matrix(...) that has to be parsed
fx.start = start = start == 'none'?
{
translate: [0,0],
rotate: 0,
scale: [1,1],
skew: [0,0]
}:
unmatrix( toArray(start) );
// fx.end has to be parsed and decomposed
fx.end = end = ~end.indexOf('matrix')?
// bullet-proof parser
unmatrix(matrix(end)):
// faster and more precise parser
components(end);
// get rid of properties that do not change
for ( prop in start) {
if ( prop == 'rotate' ?
start[prop] == end[prop]:
start[prop][0] == end[prop][0] && start[prop][1] == end[prop][1]
) {
delete start[prop];
}
}
}
/*
* We want a fast interpolation algorithm.
* This implies avoiding function calls and sacrifying DRY principle:
* - avoid $.each(function(){})
* - round values using bitewise hacks, see http://jsperf.com/math-round-vs-hack/3
*/
if ( start.translate ) {
// round translate to the closest pixel
translate = ' translate('+
((start.translate[0] + (end.translate[0] - start.translate[0]) * pos + .5) | 0) +'px,'+
((start.translate[1] + (end.translate[1] - start.translate[1]) * pos + .5) | 0) +'px'+
')';
T = true;
}
if ( start.rotate != undefined ) {
rotate = ' rotate('+ (start.rotate + (end.rotate - start.rotate) * pos) +'rad)';
M = true;
}
if ( start.scale ) {
scale = ' scale('+
(start.scale[0] + (end.scale[0] - start.scale[0]) * pos) +','+
(start.scale[1] + (end.scale[1] - start.scale[1]) * pos) +
')';
M = true;
}
if ( start.skew ) {
skew = ' skew('+
(start.skew[0] + (end.skew[0] - start.skew[0]) * pos) +'rad,'+
(start.skew[1] + (end.skew[1] - start.skew[1]) * pos) +'rad'+
')';
M = true;
}
// In case of relative animation, restore the origin computed matrix here.
transform = fx.origin ?
fx.origin + translate + skew + scale + rotate:
translate + rotate + scale + skew;
propertyHook && propertyHook.set ?
propertyHook.set( elem, transform, {M: M, T: T} ):
elem.style[supportProperty] = transform;
};
/*
* Utility functions
*/
// turns a transform string into its 'matrix(A,B,C,D,X,Y)' form (as an array, though)
function matrix( transform ) {
transform = transform.split(')');
var
trim = $.trim
// last element of the array is an empty string, get rid of it
, i = transform.length -1
, split, prop, val
, A = 1
, B = 0
, C = 0
, D = 1
, A_, B_, C_, D_
, tmp1, tmp2
, X = 0
, Y = 0
;
// Loop through the transform properties, parse and multiply them
while (i--) {
split = transform[i].split('(');
prop = trim(split[0]);
val = split[1];
A_ = B_ = C_ = D_ = 0;
switch (prop) {
case 'translateX':
X += parseInt(val, 10);
continue;
case 'translateY':
Y += parseInt(val, 10);
continue;
case 'translate':
val = val.split(',');
X += parseInt(val[0], 10);
Y += parseInt(val[1] || 0, 10);
continue;
case 'rotate':
val = toRadian(val);
A_ = Math.cos(val);
B_ = Math.sin(val);
C_ = -Math.sin(val);
D_ = Math.cos(val);
break;
case 'scaleX':
A_ = val;
D_ = 1;
break;
case 'scaleY':
A_ = 1;
D_ = val;
break;
case 'scale':
val = val.split(',');
A_ = val[0];
D_ = val.length>1 ? val[1] : val[0];
break;
case 'skewX':
A_ = D_ = 1;
C_ = Math.tan(toRadian(val));
break;
case 'skewY':
A_ = D_ = 1;
B_ = Math.tan(toRadian(val));
break;
case 'skew':
A_ = D_ = 1;
val = val.split(',');
C_ = Math.tan(toRadian(val[0]));
B_ = Math.tan(toRadian(val[1] || 0));
break;
case 'matrix':
val = val.split(',');
A_ = +val[0];
B_ = +val[1];
C_ = +val[2];
D_ = +val[3];
X += parseInt(val[4], 10);
Y += parseInt(val[5], 10);
}
// Matrix product
tmp1 = A * A_ + B * C_;
B = A * B_ + B * D_;
tmp2 = C * A_ + D * C_;
D = C * B_ + D * D_;
A = tmp1;
C = tmp2;
}
return [A,B,C,D,X,Y];
}
// turns a matrix into its rotate, scale and skew components
// algorithm from http://hg.mozilla.org/mozilla-central/file/7cb3e9795d04/layout/style/nsStyleAnimation.cpp
function unmatrix(matrix) {
var
scaleX
, scaleY
, skew
, A = matrix[0]
, B = matrix[1]
, C = matrix[2]
, D = matrix[3]
;
// Make sure matrix is not singular
if ( A * D - B * C ) {
// step (3)
scaleX = Math.sqrt( A * A + B * B );
A /= scaleX;
B /= scaleX;
// step (4)
skew = A * C + B * D;
C -= A * skew;
D -= B * skew;
// step (5)
scaleY = Math.sqrt( C * C + D * D );
C /= scaleY;
D /= scaleY;
skew /= scaleY;
// step (6)
if ( A * D < B * C ) {
//scaleY = -scaleY;
//skew = -skew;
A = -A;
B = -B;
skew = -skew;
scaleX = -scaleX;
}
// matrix is singular and cannot be interpolated
} else {
rotate = scaleX = scaleY = skew = 0;
}
return {
translate: [+matrix[4], +matrix[5]],
rotate: Math.atan2(B, A),
scale: [scaleX, scaleY],
skew: [skew, 0]
}
}
// parse tranform components of a transform string not containing 'matrix(...)'
function components( transform ) {
// split the != transforms
transform = transform.split(')');
var translate = [0,0],
rotate = 0,
scale = [1,1],
skew = [0,0],
i = transform.length -1,
trim = $.trim,
split, name, value;
// add components
while ( i-- ) {
split = transform[i].split('(');
name = trim(split[0]);
value = split[1];
if (name == 'translateX') {
translate[0] += parseInt(value, 10);
} else if (name == 'translateY') {
translate[1] += parseInt(value, 10);
} else if (name == 'translate') {
value = value.split(',');
translate[0] += parseInt(value[0], 10);
translate[1] += parseInt(value[1] || 0, 10);
} else if (name == 'rotate') {
rotate += toRadian(value);
} else if (name == 'scaleX') {
scale[0] *= value;
} else if (name == 'scaleY') {
scale[1] *= value;
} else if (name == 'scale') {
value = value.split(',');
scale[0] *= value[0];
scale[1] *= (value.length>1? value[1] : value[0]);
} else if (name == 'skewX') {
skew[0] += toRadian(value);
} else if (name == 'skewY') {
skew[1] += toRadian(value);
} else if (name == 'skew') {
value = value.split(',');
skew[0] += toRadian(value[0]);
skew[1] += toRadian(value[1] || '0');
}
}
return {
translate: translate,
rotate: rotate,
scale: scale,
skew: skew
};
}
// converts an angle string in any unit to a radian Float
function toRadian(value) {
return ~value.indexOf('deg') ?
parseInt(value,10) * (Math.PI * 2 / 360):
~value.indexOf('grad') ?
parseInt(value,10) * (Math.PI/200):
parseFloat(value);
}
// Converts 'matrix(A,B,C,D,X,Y)' to [A,B,C,D,X,Y]
function toArray(matrix) {
// Fremove the unit of X and Y for Firefox
matrix = /\(([^,]*),([^,]*),([^,]*),([^,]*),([^,p]*)(?:px)?,([^)p]*)(?:px)?/.exec(matrix);
return [matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]];
}
$.transform = {
centerOrigin: 'margin'
};
})( jQuery ); | JavaScript |
var offsetfromcursorX = 14;
var offsetfromcursorY = 16;
var offsetdivfrompointerX = 10;
var offsetdivfrompointerY = 14;
document.write('<div id="dhtmltooltip"></div>');
document.write('<img id="dhtmlpointer" src="' + site_img_url + '/tooltiparrow.gif">');
var ie = document.all;
var ns6 = document.getElementById && ! document.all;
var enabletip = false;
if (ie || ns6)
var tipobj = document.all ? document.all["dhtmltooltip"] : document.getElementById ? document.getElementById("dhtmltooltip") : "";
var pointerobj = document.all ? document.all["dhtmlpointer"] : document.getElementById ? document.getElementById("dhtmlpointer") : "";
function ietruebody() {
return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function showtip(thetext, thewidth, thecolor) {
if (ns6 || ie) {
if (typeof thewidth != "undefined")
tipobj.style.width = thewidth + "px";
if (typeof thecolor != "undefined" && thecolor != "")
tipobj.style.backgroundColor = thecolor;
tipobj.innerHTML = thetext;
enabletip = true;
return false;
}
}
function positiontip(e) {
if (enabletip) {
var nondefaultpos = false;
var curX = (ns6) ? e.pageX : event.clientX + ietruebody().scrollLeft;
var curY = (ns6) ? e.pageY : event.clientY + ietruebody().scrollTop;
var winwidth = ie && ! window.opera ? ietruebody().clientWidth : window.innerWidth - 20;
var winheight = ie && ! window.opera ? ietruebody().clientHeight : window.innerHeight - 20;
var rightedge = ie && ! window.opera ? winwidth - event.clientX - offsetfromcursorX : winwidth - e.clientX - offsetfromcursorX;
var bottomedge = ie && ! window.opera ? winheight - event.clientY - offsetfromcursorY : winheight - e.clientY - offsetfromcursorY;
var leftedge = (offsetfromcursorX < 0) ? offsetfromcursorX * (- 1) : - 1000;
if (rightedge < tipobj.offsetWidth) {
tipobj.style.left = curX - tipobj.offsetWidth + "px";
nondefaultpos = true;
}
else if (curX < leftedge)
tipobj.style.left = "5px";
else {
tipobj.style.left = curX + offsetfromcursorX - offsetdivfrompointerX + "px";
pointerobj.style.left = curX + offsetfromcursorX + "px";
}
if (bottomedge < tipobj.offsetHeight) {
tipobj.style.top = curY - tipobj.offsetHeight - offsetfromcursorY + "px";
nondefaultpos = true;
}
else {
tipobj.style.top = curY + offsetfromcursorY + offsetdivfrompointerY + "px";
pointerobj.style.top = curY + offsetfromcursorY + "px";
}
tipobj.style.visibility = "visible";
if (! nondefaultpos)
pointerobj.style.visibility = "visible";
else
pointerobj.style.visibility = "hidden";
}
}
function hidetip() {
if (ns6 || ie) {
enabletip = false;
tipobj.style.visibility = "hidden";
pointerobj.style.visibility = "hidden";
tipobj.style.left = "-1000px";
tipobj.style.backgroundColor = '';
tipobj.style.width = '';
}
}
if ( typeof window.addEventListener != "undefined" )
document.addEventListener( "mousemove", positiontip, false );
else if ( typeof window.attachEvent != "undefined" )
document.attachEvent( "onmousemove", positiontip );
else {
if ( document.onmousemove != null ) {
var oldOnmousemove = document.onmousemove;
document.onmousemove = function ( e ) {
oldOnmousemove( e );
positiontip(e);
};
}
else
document.onmousemove = positiontip;
} | JavaScript |
$(document).ready(function(){
$('.item .addcartone').click(function(){
$.confirm({
'title' : 'Thông tin giỏ hàng của bạn',
'message' : 'Bạn đã thêm 1 sản phầm vào giỏ hàng. <br />',
'buttons' : {
'Vào giỏ hàng' : {
'class' : 'gray',
'action': function(){
alert("hahah");
}
},
'Tiếp tục mua hàng' : {
'class' : 'blue',
'action': function(){}
}
}
});
});
}); | JavaScript |
/*
* Treeview 1.4 - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 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.treeview.js 4684 2008-02-07 19:08:06Z joern.zaefferer $
*
*/
;(function($) {
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event) {
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea
this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
});
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if (settings.add) {
return this.trigger("add", [settings.add]);
}
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join("") );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); });
if ( current.length ) {
current.addClass("selected").parents("ul, li").add( current.next() ).show();
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this.bind("add", function(event, branches) {
$(branches).prev()
.removeClass(CLASSES.last)
.removeClass(CLASSES.lastCollapsable)
.removeClass(CLASSES.lastExpandable)
.find(">.hitarea")
.removeClass(CLASSES.lastCollapsableHitarea)
.removeClass(CLASSES.lastExpandableHitarea);
$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, toggler);
});
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
var CLASSES = $.fn.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
};
// provide backwards compability
$.fn.Treeview = $.fn.treeview;
})(jQuery);
| JavaScript |
(function($) {
$.fn.extend({
jsCarousel: function(options) {
var settings = $.extend({
scrollspeed: 1500,
delay: 5000,
itemstodisplay: 5,
autoscroll: false,
circular: false,
masked: true,
onthumbnailclick: null,
orientation: 'h'
}, options);
return this.each(function() {
var oclass = 'horizontal';
if (settings.orientation == 'v')
oclass = 'vertical';
var slidercontents = $(this).addClass('jscarousal-contents-' + oclass + '');
var slider = $('<div/>').addClass('jscarousal-' + oclass + '').attr('id', slidercontents.attr('id'));
var backbutton = $('<div/>').addClass('jscarousal-' + oclass + '-back');
var forwardbutton = $('<div/>').addClass('jscarousal-' + oclass + '-forward');
slidercontents.removeAttr('id');
slidercontents.before(slider);
slider.append(backbutton);
slider.append(slidercontents);
slider.append(forwardbutton);
var total = $('> div', slidercontents).css('display', 'none').length;
var index = 0;
var start = 0;
var current = $('<div/>');
var noOfBlocks;
var interval;
var display = settings.itemstodisplay;
var speed = settings.scrollspeed;
var top;
var left;
var height;
var containerHeight;
var containerWidth;
var direction = "forward";
var scrolling = true;
function initialize() {
index = -1;
noOfBlocks = parseInt(total / display);
if (total % display > 0) noOfBlocks++;
index = noOfBlocks - 1;
var startIndex = 0;
var endIndex = display;
var copy = false;
var allElements = $('> div', slidercontents);
$('> div', slidercontents).remove();
if (settings.masked)
allElements.addClass('thumbnail-inactive').hover(function() { $(this).removeClass('thumbnail-inactive').addClass('thumbnail-active'); }, function() { $(this).removeClass('thumbnail-active').addClass('thumbnail-inactive'); })
for (var i = 0; i < noOfBlocks; i++) {
if (total > display) {
startIndex = i * display;
endIndex = startIndex + display;
if (endIndex > total) {
startIndex -= (endIndex - total);
endIndex = startIndex + display;
copy = true;
}
}
else {
startIndex = 0;
endIndex = total;
}
var wrapper = $('<div/>')
allElements.slice(startIndex, endIndex).each(function(index, el) {
if (!copy)
wrapper.append(el);
else wrapper.append($(el).clone(true));
});
wrapper.find("img").click(
function() {
if (settings.onthumbnailclick != null) {
settings.onthumbnailclick($(this).attr('src'));
}
});
slidercontents.append(wrapper);
}
if (settings.onthumbnailclick != null)
$('> div > div', slidercontents).css('cursor', 'pointer');
$('> div', slidercontents).addClass('hidden');
$('> div > div', slidercontents).css('display', '');
/*vertical*/
if (settings.orientation == 'v') {
top = $('> div:eq(' + index + ')', slidercontents).css('top');
if (top == 'auto') top = "0px";
containerHeight = slidercontents.height();
height = slidercontents.get(0).offsetHeight;
$('> div', slidercontents).css('top', '-' + containerHeight + 'px');
$('> div:eq(' + index + ')', slidercontents).stop(false, true).animate({ 'top': top }, speed, function() { scrolling = false; });
}
/*horizontal*/
if (settings.orientation == 'h') {
left = $('> div:eq(' + index + ')', slidercontents).css('left');
containerWidth = slidercontents.width();
height = slidercontents.get(0).offsetHeight;
$('> div', slidercontents).css('left', '-' + containerWidth + 'px');
$('> div:eq(' + index + ')', slidercontents).stop(false, true).animate({ left: 0 }, speed, function() { scrolling = false; });
}
$('> div:eq(' + index + ')', slidercontents).addClass('visible').removeClass('hidden');
slider.mouseenter(function() { if (settings.autoscroll) stopAnimate(); }).mouseleave(function() { if (settings.autoscroll) animate(); });
if (settings.autoscroll)
animate();
forwardbutton.click(function() {
if (!scrolling) {
direction = "forward";
if (settings.circular)
if (index <= 0) index = noOfBlocks;
showThumbs();
}
});
backbutton.click(function() {
if (!scrolling) {
direction = "backward";
if (settings.circular)
if (index >= noOfBlocks - 1) index = -1;
showThumbs();
}
});
}
initialize();
function stopAnimate() {
scrolling = false;
clearTimeout(interval);
slider.children().clearQueue();
slider.children().stop(false, true);
}
function animate() {
clearTimeout(interval);
if (settings.autoscroll)
interval = setTimeout(changeSlide, settings.delay);
}
function changeSlide() {
if (direction == "forward") {
if (index <= 0) index = noOfBlocks;
} else {
if (index >= noOfBlocks - 1) { index = -1; }
}
showThumbs();
interval = setTimeout(changeSlide, settings.delay);
}
function getDimensions(value) {
return value + 'px';
}
function showThumbs() {
scrolling = true;
var current = $('.visible', slidercontents);
var scrollSpeed = speed;
if (direction == "forward") {
index--;
if (index >= 0) {
if (settings.orientation == 'v') {
$('>div:eq(' + index + ')', slidercontents).css('top', getDimensions(containerHeight)).removeClass('hidden').addClass('visible').stop(false, true).animate({ 'top': top }, scrollSpeed, function() { scrolling = false; });
current.stop(false, true).animate({ 'top': '-=' + getDimensions(containerHeight) }, scrollSpeed, function() {
$(this).removeClass('visible').addClass('hidden');
$(this).css('top', top);
scrolling = false;
});
}
else {
$('>div:eq(' + index + ')', slidercontents).css('left', getDimensions(containerWidth)).removeClass('hidden').addClass('visible').stop(false, true).animate({ 'left': '-=' + getDimensions(containerWidth) }, scrollSpeed, function() { scrolling = false; });
current.stop(false, true).animate({ 'left': '-=' + getDimensions(containerWidth) }, scrollSpeed, function() {
$(this).removeClass('visible').addClass('hidden');
$(this).css('left', left);
scrolling = false;
});
}
} else index = 0;
}
else if (direction == "backward") {
index++;
if (index < noOfBlocks) {
if (settings.orientation == 'v') {
$('>div:eq(' + index + ')', slidercontents).removeClass('hidden').addClass('visible').css({
'top': getDimensions(-containerHeight)
}).stop(false, true).animate({ 'top': top }, scrollSpeed, function() { scrolling = false; });
current.stop(false, true).animate({ 'top': '+=' + getDimensions(containerHeight) }, scrollSpeed,
function() {
$(this).removeClass('visible').addClass('hidden');
$(this).css('top', getDimensions(-containerHeight));
scrolling = false;
});
}
else {
$('>div:eq(' + index + ')', slidercontents).removeClass('hidden').addClass('visible').css({
'left': getDimensions(-containerWidth)
}).stop(false, true).animate({ 'left': '+=' + getDimensions(containerWidth) }, scrollSpeed, function() { scrolling = false; });
current.stop(false, true).animate({ 'left': '+=' + getDimensions(containerWidth) }, scrollSpeed,
function() {
$(this).removeClass('visible').addClass('hidden');
$(this).css('left', getDimensions(-containerWidth));
scrolling = false;
});
}
} else index = noOfBlocks - 1;
}
}
});
}
});
})(jQuery);
| JavaScript |
/* DropDown List */
startList = function() {
if (document.all&&document.getElementById) {
navRoot = document.getElementById("nav");
for (i=0; i<navRoot.childNodes.length; i++) {
node = navRoot.childNodes[i];
if (node.nodeName=="LI") {
node.onmouseover=function() {
this.className+=" over";
}
node.onmouseout=function() {
this.className=this.className.replace(" over", "");
}
}
}
}
}
window.onload=startList; | JavaScript |
/*
* Copyright 2009 by lyhuuloi, http://lyhuuloi.com
* ---------------------------------------------------------------------------
*
* The Javascript library of CRM Project
* Created date: 16/06/2009, 10:57:12 AM
*
*/
var site_var_cookieid = "";
var site_var_cookie_domain = "";
var site_var_cookie_path = "/";
var site_login_click = 0;
var site_login_status = 1;
var data_request_sent = 0;
var data_request_received = 0;
var startday = new Date();
var clockStart = startday.getTime();
var site_tips = "";
var is_ie = 0;
function initStopwatch()
{
var myTime = new Date();
var timeNow = myTime.getTime();
var timeDiff = timeNow - clockStart;
this.diffSecs = timeDiff/1000;
return(this.diffSecs);
}
if ( window.ActiveXObject )
{
var is_ie = 1;
}
function logout()
{
//ht = document.getElementsByTagName("html");
//ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
if ( confirm("Ban co chac la muon thoat ra ?") )
{
logout_request();
return false;
}
else
{
//ht[0].style.filter = "";
return false;
}
}
var on_mouse = 1;
function form_checkall(name)
{
if ( on_mouse == 0 )
{
for ( var i = 0; i < document.forms[name].elements.length; i++)
{
if ( document.forms[name].all.checked == true )
{
document.forms[name].elements[i].checked = true;
}
else
{
document.forms[name].elements[i].checked = false;
}
}
}
else
{
if ( document.forms[name].all.checked == false )
{
document.forms[name].all.checked = "checked";
}
else
{
document.forms[name].all.checked = false;
}
for ( var i = 0; i < document.forms[name].elements.length; i++)
{
if ( document.forms[name].all.checked == true )
{
document.forms[name].elements[i].checked = true;
}
else
{
document.forms[name].elements[i].checked = false;
}
}
}
}
function my_getcookie( name )
{
cname = site_var_cookieid + name + '=';
cpos = document.cookie.indexOf( cname );
if ( cpos != -1 )
{
cstart = cpos + cname.length;
cend = document.cookie.indexOf(";", cstart);
if (cend == -1)
{
cend = document.cookie.length;
}
return unescape( document.cookie.substring(cstart, cend) );
}
return null;
}
function my_setcookie( name, value, sticky )
{
expire = "";
domain = "";
path = "/";
if ( sticky )
{
expire = "; expires=Wed, 1 Jan 2020 00:00:00 GMT";
}
if ( site_var_cookie_domain != "" )
{
domain = '; domain=' + site_var_cookie_domain;
}
if ( site_var_cookie_path != "" )
{
path = site_var_cookie_path;
}
document.cookie = site_var_cookieid + name + "=" + value + "; path=" + path + expire + domain + ';';
}
function page_loading_html( text )
{
text = "<DIV style='width: 100%; padding-top: 7px; padding-bottom: 7px;' align='center'> " + text + " </div>";
return text;
}
function page_loading(type)
{
if ( type == 1 )
{
document.getElementById( this.clicked ).innerHTML = page_loading_html("<img align='absmiddle' src='" + site_root_domain + "/templates/images/warning.png'> <font size='2' face='verdana' color='red'>Kết nối bị lỗi....</font>");
}
else if ( type == 2 )
{
document.getElementById( this.clicked ).innerHTML = "";
}
else
{
document.getElementById( this.clicked ).innerHTML = page_loading_html("<font size='2' face='verdana'><img align='absmiddle' src='" + site_root_domain + "/templates/images/loading_layer.gif'>");
}
}
function data_request(request, url, type, form_id, no_status)
{
this.clicked = request;
data_request_sent++;
update_status(0);
this.no_status = no_status;
if ( no_status == 1 )
{
no_status = 1;
}
else
{
no_status = 0;
}
if ( ! type )
{
type = "GET";
}
else
{
type = "POST";
}
var fields_data = "";
var lhl_data_got = "";
if ( form_id )
{
if ( type == "GET" )
{
var fields_data = "?";
}
else if ( type == "POST" )
{
var fields_data = "";
}
var frm = document.forms[form_id];
var numberElements = frm.elements.length;
for( var i = 0; i < numberElements; i++ )
{
if( i < numberElements-1 )
{
if ( frm.elements[i].type == "select-one" )
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value+"&";
}
else if ( frm.elements[i].type == "select-multiple" )
{
art_name = frm.elements[i].name;
selmul = frm.elements[i];
var seldt = new Array();
var selcnt = 0;
for ( var i = 0; i < selmul.length; i++ )
{
if ( selmul.options[i].selected == true )
{
seldt[selcnt] = selmul.options[i].value;
selcnt++;
}
}
fields_data += art_name+"="+seldt+"&";
}
else if ( ( frm.elements[i].type == "radio" ) || ( frm.elements[i].type == "checkbox" ))
{
if (frm.elements[i].checked)
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value+"&";
}
}
else
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value+"&";
}
}
else
{
if (frm.elements[i].type == "radio")
{
if (frm.elements[i].checked)
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value;
}
}
else
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value;
}
}
}
}
http_request = false;
//this.lhl_id_packet_send_to = request;
if ( request )
{
if ( no_status != 1 )
{
page_loading();
}
}
if (window.XMLHttpRequest) // Mozilla, Safari,...
{
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) // IE
{
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
}
}
}
if ( ! http_request )
{
if ( request )
{
page_loading(1);
}
return false;
}
http_request.onreadystatechange = function(){if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
data_request_received++;
update_status(1);
if ( request )
{
if ( no_status != 1 )
{
page_loading(2);
}
data_request_time = 1;
document.getElementById( request ).innerHTML = http_request.responseText;
}
}
else
{
if ( request )
{
if ( no_status != 1 )
{
page_loading(1);
}
}
}
}};
if ( type == "POST" )
{
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http_request.setRequestHeader("Content-length", fields_data.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(fields_data);
}
else if ( type == "GET" )
{
http_request.open('GET', url + fields_data, true);
http_request.send(null);
}
}
function update_status(type)
{
if ( document.getElementById( 'SITE_request_sent' ) )
{
if ( type == 1 )
{
status_received = data_request_received;
document.getElementById( 'SITE_request_received' ).innerHTML = status_received;
}
else
{
status_sent = data_request_sent;
document.getElementById( 'SITE_request_sent' ).innerHTML = status_sent;
}
}
}
var IE = document.all?true:false
if ( ! IE )
{
document.captureEvents( Event.KEYPRESS );
}
document.onmousemove = getMouseXY;
function ietruebody()
{
return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
var tempX = 0;
var tempY = 0;
function getMouseXY(e)
{
if ( IE )
{
tempX = event.clientX + ietruebody().scrollLeft;
tempY = event.clientY + ietruebody().scrollTop;
}
else
{
tempX = e.pageX;
tempY = e.pageY;
}
if ( tempX < 0 )
{
tempX = 0
}
if ( tempY < 0 )
{
tempY = 0
}
return true;
}
function showfaq( text, faqid )
{
showtip(text, 180);
document.getElementById( faqid ).src = site_img_url +'/icon_notice_active.gif';
}
function hidefaq( faqid )
{
hidetip();
document.getElementById( faqid ).src = site_img_url + '/icon_notice.gif';
}
function href_close()
{
base_url = window.location.href;
base_url = base_url.split("#");
window.location.href = base_url[0] + "#";
}
function href_click( data )
{
//base_url = window.location.href;
//base_url = base_url.split("#");
//window.location.href = base_url[0] + "#" + data;
window.location.href = data;
}
function rating_over( num )
{
var numelse = 10 - num;
for ( i = 1; i <= num; i ++ )
{
document.getElementById( "star_" + i ).style.opacity = 1;
document.getElementById( "star_" + i ).style.filter = "alpha(opacity=100)";
}
for ( i = num+1; i <= numelse; i ++ )
{
document.getElementById( "star_" + i ).style.opacity = 0.4;
document.getElementById( "star_" + i ).style.filter = "alpha(opacity=60)";
}
document.getElementById("rating_star").innerHTML = num;
}
function rating_out()
{
for ( i = 1; i <= 10; i ++ )
{
document.getElementById( "star_" + i ).style.opacity = 0.4;
document.getElementById( "star_" + i ).style.filter = "alpha(opacity=60)";
}
}
function rating_click( target_to, target_id )
{
var star_select = document.getElementById("rating_star").innerHTML;
if ( star_select > 0 )
{
data_request( target_id, target_to + star_select + "/", "GET", "", 0 );
return false;
}
}
function add_favourite( name, URL )
{
if (window.sidebar)
{
window.sidebar.addPanel(name, url,"");
}
else if( window.external )
{
window.external.AddFavorite( url, name);
}
else if (window.opera && window.print)
{
return true;
}
}
var current_field = "";
var current_opacity = 0;
function close_warning()
{
if ( ! current_field )
{
return false;
}
var object = document.getElementById(current_field);
if ( document.getElementById(object.id+"_head_alert") )
{
var d = object.parentNode;
if ( object.parentNode ) // Set this condition to fix the error appeared when the user set the object as invisible
{
var olddiv = document.getElementById(object.id+"_head_alert");
d.removeChild(olddiv);
}
}
current_field = "";
current_opacity = 0;
}
function open_opacity()
{
if ( ! current_field )
{
return false;
}
var object = document.getElementById(current_field);
if ( current_opacity <= 10 )
{
document.getElementById(""+object.id+"_sub"+"").style.opacity = current_opacity * 0.1;
document.getElementById(""+object.id+"_sub"+"").style.filter = "alpha(opacity="+current_opacity * 10+")";
current_opacity++;
setTimeout("open_opacity()", 40);
}
}
function check_element( object )
{
if ( object.type == "select-one" )
{
var option_value = object.options[object.selectedIndex].value;
option_value = option_value.toLowerCase();
if ( option_value == "" || option_value == "none" )
{
return false;
}
}
else if ( ! object.value )
{
return false;
}
return true;
}
function open_warning( element_id, display_type )
{
var object = document.getElementById(element_id);
close_warning();
if ( (check_element(object) == false && object.getAttribute('emsg')) || (object.value && object.getAttribute('etype')) )
{
// Setup message
if( check_element(object) == false && object.getAttribute('emsg') )
{
var emsg = object.getAttribute('emsg');
}
else if ( object.getAttribute('etype') == "email" && check_email(object.value) == false )
{
var emsg = lang_invalid_email;
}
else if ( object.getAttribute('etype') == "phone" && check_phone(object.value) == false )
{
var emsg = lang_invalid_phone;
}
else if ( object.getAttribute('etype') == "number" && check_number(object.value) == false )
{
var emsg = lang_invalid_number;
}
else if ( object.getAttribute('etype') == "date" && check_date(object.value) == false )
{
var emsg = lang_invalid_date;
}
else if ( object.getAttribute('etype') == "ip" && check_ip_address(object.value) == false )
{
var emsg = lang_invalid_ip_address;
}
else if ( object.getAttribute('etype') == "domain" && check_domain(object.value) != true )
{
var emsg = check_domain(object.value);
}
else if ( object.getAttribute('maxvalue') && parseInt(object.value) > parseInt(object.getAttribute('maxvalue')) )
{
var emsg = lang_invalid_maxvalue.replace("%number%", parseInt(object.getAttribute('maxvalue')));
}
else if ( object.getAttribute('minvalue') && parseInt(object.value) < parseInt(object.getAttribute('minvalue')) )
{
var emsg = lang_invalid_minvalue.replace("%number%", parseInt(object.getAttribute('minvalue')));
}
else
{
return true;
}
// Get the co-ordinate of element
var x = object.offsetLeft;
var y = 0;
// Check existing the element
if ( ! document.getElementById(object.id+"_alert") )
{
object.parentNode.innerHTML = object.parentNode.innerHTML + "<div id='"+object.id+"_head_alert"+"' style='float: left; width: 10px;'><div id='"+object.id+"_alert"+"' style='position: absoulute;'></div></div>";
}
// Fix focus() by reload the element, very important with lyhuuloi, haha :))
object = document.getElementById(element_id);
var alert_table = document.getElementById(object.id+"_alert");
object.focus();
// Set queued name
current_field = object.name;
// Display the error board
if ( display_type == "table" )
{
document.getElementById(object.id+"_alert").style.paddingLeft = (x+object.offsetWidth)+"px";
}
alert_table.innerHTML = "<div id='"+object.id+"_sub"+"' style='opacity:0; filter:alpha(opacity=0);'> <img style='position: absolute; z-index: 1; padding-top: 1px;' src='"+site_img_url+"/icons/arrow_alertbox.gif'> <div onclick='javascript:close_warning();' style='position: absolute; z-index: 0; cursor: pointer; border: solid #F2DDDD 1px; margin-left: 5px;'><div style='border: solid #992A2A 1px; background: #F2DDDD; width: 250px; padding: 4px;'>"+emsg+"</div></div></div>";
setTimeout("open_opacity()", 1);
return false;
}
}
function check_ip_address( str )
{
//var filter = /^(([1-9][0-9]{0,2})|0)\.(([1-9][0-9]{0,2})|0)\.(([1-9][0-9]{0,2})|0)\.(([1-9][0-9]{0,2})|0)$/;
//if ( ! filter.test( str ) )
//{
// return false
//}
//else
//{
// return true;
//}
var ipaddr = str;
ipaddr = ipaddr.replace( /\s/g, "") //remove spaces for checking
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; //regex. check for digits and in all 4 quadrants of the IP
if (re.test(ipaddr)) {
//split into units with dots "."
var parts = ipaddr.split(".");
//if the first unit/quadrant of the IP is zero
if (parseInt(parseFloat(parts[0])) == 0) {
return false;
}
//if the fourth unit/quadrant of the IP is zero
if (parseInt(parseFloat(parts[3])) == 0) {
return false;
}
//if any part is greater than 255
for (var i=0; i<parts.length; i++) {
if (parseInt(parseFloat(parts[i])) > 255){
return false;
}
}
return true;
} else {
return false;
}
}
function check_domain(nname)
{
nname = nname.toLowerCase();
var arr = new Array(
'.com','.net','.org','.biz','.coop','.info','.museum','.name',
'.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
'.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
'.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
'.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
'.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
'.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
'.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
'.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
'.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
'.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
'.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
'.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
'.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
'.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
'.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
'.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
'.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
'.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
'.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
'.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
'.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
'.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
'.wf','.ye','.yt','.yu','.za','.zm','.zw',
'.asia','.me','.tel','.eu','.mobi');
var mai = nname;
var val = true;
var dot = mai.lastIndexOf(".");
var dname = mai.substring(0,dot);
var ext = mai.substring(dot,mai.length);
if(dot>2 && dot<57)
{
for(var i=0; i<arr.length; i++)
{
if(ext == arr[i])
{
val = true;
break;
}
else
{
val = false;
}
}
if(val == false)
{
return lang_invalid_domain_ext;
}
else
{
for(var j=0; j<dname.length; j++)
{
var dh = dname.charAt(j);
var hh = dh.charCodeAt(0);
if((hh > 47 && hh<59) || (hh > 64 && hh<91) || (hh > 96 && hh<123) || hh==45 || hh==46)
{
if((j==0 || j==dname.length-1) && hh == 45)
{
return lang_invalid_domain_start;
}
}
else
{
return lang_invalid_domain_char;
}
}
}
}
else
{
return lang_invalid_domain_length;
}
return true;
}
function check_email( str )
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(str);
}
function check_number(str)
{
if ( isNaN(str) == true )
{
return false;
}
return true;
}
function check_phone(str)
{
var error = "";
var stripped = str.replace(/[\(\)\.\-\ ]/g, '');
if ( str == "" )
{
return false;
}
else if ( str.length < 8 )
{
return false;
}
else if ( isNaN(stripped) == true )
{
return false;
}
else if ( stripped.length > 12 && stripped.substr(0,1) != "+" )
{
return false;
}
else if ( stripped.length > 13 && stripped.substr(0,1) == "+" )
{
return false;
}
return true;
}
function check_date(str)
{
var d = new Date();
str = str.split("\/");
if ( str.length < 3 || str[0] > 31 || str[1] > 12 )
{
return false;
}
}
function check_form( form_id )
{
var frm = document.forms[form_id];
var numberElements = frm.elements.length;
for( var i = 0; i < numberElements; i++ )
{
object = frm.elements[i];
if ( open_warning(object.name) == false )
{
return false;
}
}
}
var form_select_data = "";
function rebuild_form( form_id, type, marked )
{
var frm = document.forms[form_id];
var numberElements = frm.elements.length+5;
var sympol = "(*)";
var is_emsg = 0;
for( var i = 0; i < numberElements; i++ )
{
if ( frm.elements[i] )
{
object = frm.elements[i];
// Important, set attribute for the element, if not, no action will effect, lyhuuloi
object.setAttribute("id", object.name);
// Add suffix
var addsuffix = "";
if ( object.getAttribute("addsuffix") )
{
addsuffix = object.getAttribute("addsuffix");
}
if ( type == 1 )
{
object.setAttribute("autocomplete", "off");
}
if ( object.getAttribute("ehide") != 1 )
{
var x = object.offsetLeft + object.clientWidth - 5;
var y = object.offsetTop;
if ( object.offsetParent )
{
if ( object.getAttribute("addsuffix") && ! object.getAttribute("emsg") )
{
object.parentNode.innerHTML = object.parentNode.innerHTML + "<span style='padding-left: 4px;'>"+addsuffix+"</span>";
is_emsg = 1;
}
else if ( object.getAttribute("emsg") && ! document.getElementById("sympol_"+object.name) )
{
object.parentNode.innerHTML = object.parentNode.innerHTML + "<span style='padding-left: 4px;' id='sympol_"+object.name+"'>"+addsuffix+" <font color='red'>"+sympol+"</font></span>";
}
}
}
// Fix Default value for select-one and select-multi, very important :) Lyhuuloi
object = frm.elements[i];
if ( object.getAttribute("defaultvalue") )
{
//document.getElementById("insert").innerHTML += object.type + " + ";
if ( object.type == "select-one" )
{
for ( var j = 0; j < object.length; j++ )
{
if ( object.options[j].value == object.getAttribute("defaultvalue") )
{
object.options[j].selected = true;
break;
}
}
}
else if ( object.type == "radio" || object.type == "checkbox" )
{
if ( object.value == object.getAttribute("defaultvalue") )
{
object.checked = "checked";
}
}
}
if ( marked == 1 )
{
if ( object.value && object.name != "submit" )
{
object.style.border = "solid #FFCC00 1px";
object.style.background = "#FFFFCC";
object.style.color = "#333333";
object.style.fontWeight = "bold";
}
}
//document.getElementById("insert").innerHTML += object.name + " + " + object.getAttribute("defaultvalue") + " + " + object.value + "<br />";
}
}
if ( is_emsg == 1 )
{
document.writeln("<font style='color: #FF0000'>"+sympol+"</font> " + lang_required_field);
}
}
// lyhuuloi foundation date 23/1/2008, edited: 25/06/2009
function password_change( data )
{
close_warning();
var point = 0;
var value = data.value;
var simple = new Array("123456", "1234567", "12345678", "123456789", "321654", "654987", "321654987", "654321", "987654321");
var special = new Array("!", "@", "#", "$", "%", "^", "&", "*", "(", ")", ",", ".", ";", "/", "|", "`", "~", "?", "<", ">", ":", "+", "-");
if ( value.length > 0 )
{
document.getElementById("password_checker").style.display = "inline";
// step 1
point += Math.round(value.length / 2);
// step 2
var check1 = 0;
for ( var i = 0; i < simple.length-1; i++ )
{
if ( simple[i] == value )
{
check1 = 1;
}
}
if ( check1 == 0 && value.length >= 6 )
{
point += 2;
}
else
{
point -= 4;
}
// step 3
if ( value.length >= 6 )
{
for ( var i = 1; i <= 2; i++ )
{
// Calculate the value to filter
var max_value = Math.round(value.length/i)*i;
var remainder = max_value - value.length;
var real_value = value.length - remainder;
var value = value.substr(0, real_value);
// Start filter
var data2 = value;
var result = data2;
for ( var j = 0; j <= Math.round(data2.length/i); j++ )
{
var result = result.replace( data2.substr(0,i), "" );
}
if ( result != "" )
{
point += 2;
}
else
{
point -= 1;
}
}
}
// Step 4
if ( value.length >= 6 )
{
for ( var i = 0; i < special.length-1; i++ )
{
var str_base = value;
var str_replace = value.replace(special[i], "");
if ( str_base.length > str_replace.length )
{
point++;
}
}
}
}
else
{
document.getElementById("password_checker").style.display = "none";
}
if ( point >= 5 )
{
document.getElementById("pwd1").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd1").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 10 )
{
document.getElementById("pwd2").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd2").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 15 )
{
document.getElementById("pwd3").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd3").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 20 )
{
document.getElementById("pwd4").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd4").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 25 )
{
document.getElementById("pwd5").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd5").innerHTML = '<span class="password_1"> </span>';
}
}
function alert_delete(theURL)
{
if (confirm( lang_alert_delete ))
{
window.location.href=theURL;
}
else
{
return false;
}
}
function alert_empty(theURL)
{
if (confirm( lang_alert_empty ))
{
window.location.href=theURL;
}
else
{
return false;
}
}
function alert_sound(as)
{
var as = "alert_sound";
if ( IE == false )
{
obj = document.embeds[as];
if(obj.Play) obj.Play();
}
else
{
document.getElementById(as).play();
}
return true;
}
function showfaq( text, faqid )
{
showtip(text, 180);
document.getElementById( faqid ).src= site_img_url +'/icon_notice_active.gif';
}
function hidefaq( faqid )
{
hidetip();
document.getElementById( faqid ).src= site_img_url + '/icon_notice.gif';
}
function sharp_url()
{
var base_url = window.location.href;
base_url = base_url.split("#");
if ( ! base_url[1] )
{
base_url[1] = "&";
}
return base_url;
}
function count_sharp_url()
{
var url = sharp_url();
if ( url[1] == "&" )
{
return false;
}
var url_data = url[1].split("&");
return url_data.length;
}
function get_sharp_url( site_view )
{
var site_view = site_view ? site_view : "view";
var url = sharp_url();
var url_data = url[1].split("&");
for ( var i = 0; i < url_data.length; i++ )
{
var url_detail = url_data[i].split("=");
if ( site_view == url_detail[0] )
{
return url_detail[1];
}
}
return false;
}
function set_sharp_url( module_name )
{
if ( get_sharp_url() != module_name )
{
var base_url = sharp_url();
var new_url = "";
if ( count_sharp_url() == false )
{
new_url = "#" + "view=" + module_name;
}
else
{
new_url = "#" + base_url[1] + "&view=" + module_name;
}
window.location.href = base_url[0] + new_url;
}
my_setcookie("sharp_url", new_url);
return true;
}
function remove_sharp_url( module_name )
{
var newurl = window.location.href;
newurl = newurl.replace("&view=" + module_name, "");
newurl = newurl.replace("view=" + module_name, "");
my_setcookie("sharp_url", "");
window.location.href = newurl;
}
function auto_sharp_url()
{
var base_url = sharp_url();
var cookie_sharp_url = my_getcookie("sharp_url");
if ( cookie_sharp_url && cookie_sharp_url != "undefined" )
{
window.location.href = base_url[0] + cookie_sharp_url;
my_setcookie("sharp_url", "");
}
if ( get_sharp_url() )
{
var data = get_sharp_url()+"();";
eval(data);
}
}
var default_order = "";
var default_by = "";
function arrange_check( field_name, default_field )
{
var url_current = Url.decode(window.location.href);
//url_current = url_current.toLowerCase();
var url_array = url_current.split("&");
var new_url = "";
var remove_cnt = 1;
for ( var i = 0; i < url_array.length; i++ )
{
var url_item = url_array[i].split("=");
if ( url_item[0] == "order" )
{
default_order = url_item[1];
}
else if ( url_item[0] == "by" )
{
default_by = url_item[1];
}
else if ( url_item[0] )
{
new_url += url_item[0]+"="+url_item[1]+"&";
}
}
if ( field_name == default_order )
{
var by = default_by == "asc" ? "desc" : "asc";
}
else if ( field_name == default_field )
{
var by = "asc";
}
else
{
var by = "desc";
}
new_url += "order=" + field_name + "&by=" + by;
//document.getElementById("insert").innerHTML += new_url + " ==> " + site_url_return + "<br />" ;
new_url = new_url.replace(site_url_return, "");
new_url = new_url + site_url_return;
return new_url;
}
function arrange_setup( sort_data )
{
var sort_data = sort_data.split(",");
var default_field = sort_data[0];
for ( var i = 0; i < sort_data.length; i++ )
{
if ( sort_data[i] )
{
var sort_item = document.getElementById("order_"+sort_data[i]);
if ( sort_item )
{
sort_item.innerHTML = "<a href='"+arrange_check(sort_data[i], default_field)+"'>"+sort_item.innerHTML+"</a>";
}
}
}
if ( ! default_order )
{
document.getElementById("order_" + default_field).innerHTML += " <img align='absmiddle' src='"+site_img_url+"/desc_order.png' title='Z-A'>";
}
else
{
if ( default_by == "asc" )
{
document.getElementById("order_" + default_order).innerHTML += " <img align='absmiddle' src='"+site_img_url+"/asc_order.png' title='Z-A'>";
}
else
{
document.getElementById("order_" + default_order).innerHTML += " <img align='absmiddle' src='"+site_img_url+"/desc_order.png' title='Z-A'>";
}
}
}
function create_random_password( element_id )
{
var password = document.getElementById( element_id );
if ( password.value )
{
if ( confirm( lang_create_random_password ) == false )
{
return false;
}
}
var pwd_array = "0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z ! @ # $ % ^ & * < > ( ) { }";
pwd_array = pwd_array.split(" ");
var new_password = "";
for ( i = 0; i < 10; i ++ )
{
var result = Math.floor(Math.random()*pwd_array.length);
new_password = new_password + pwd_array[result];
}
password.value = new_password;
}
function image_resize(width,height)
{
maxheight = width ? width : 300;
maxwidth= height ? height : 300;
imgs=document.getElementsByTagName("img");
for (p=0; p<imgs.length; p++) {
//if (imgs[p].getAttribute("alt")=="user posted image")
//{
w=parseInt(imgs[p].width);
h=parseInt(imgs[p].height);
if (parseInt(imgs[p].width)>maxwidth) {
imgs[p].style.cursor="pointer";
imgs[p].onclick=new Function("iw=window.open(this.src,'ImageViewer','resizable=1');iw.focus()");
imgs[p].height=(maxwidth/imgs[p].width)*imgs[p].height;
imgs[p].width=maxwidth;
}
if (parseInt(imgs[p].height)>maxheight) {
imgs[p].style.cursor="pointer";
imgs[p].onclick=new
Function("iw=window.open(this.src,'ImageViewer','resizable=1');iw.focus()");
imgs[p].width=(maxheight/imgs[p].height)*imgs[p].width;
imgs[p].height=maxheight;
}
}
//}
}
function get_sub_pcategory(id)
{
AjaxRequest.get(
{
'url': site_root_domain+'/?site=admin&view=cart&mod=sub&id='+id
,'onLoading':function(req)
{
document.getElementById("product_list").innerHTML = "";
document.getElementById("product_list_end").innerHTML = "";
}
,'onSuccess':function(req)
{
document.getElementById("list_sub_pcategory").innerHTML = req.responseText;
}
});
}
function check_price(theForm)
{
var price_from = document.getElementById("price_from").value;
var price_to = document.getElementById("price_to").value;
var keyword = document.getElementById("keyword").value;
var parent = document.getElementById("parent_pcategory_id").value;
if (price_from == 0 && price_to == 0 && keyword == "" && parent == "0")
{
alert("Bạn chưa chọn mức giá muốn tìm kiếm.");
return false;
}
if (theForm.price_to.value > 0)
{
if (theForm.price_from.value == theForm.price_to.value)
{
alert("Sai giá.");
document.getElementById("price_from").value = 0;
document.getElementById("price_to").value = 0;
return false;
}
if (theForm.price_from.value > theForm.price_to.value)
{
alert("Giá từ không được lớn hơn giá đến.");
document.getElementById("price_from").value = 0;
return false;
}
}
}
function redirect( url )
{
window.location.href = url;
} | JavaScript |
var site_var_cookieid = "";
var site_var_cookie_domain = "";
var site_var_cookie_path = "/";
var site_login_click = 0;
var site_login_status = 1;
var data_request_sent = 0;
var data_request_received = 0;
var startday = new Date();
var clockStart = startday.getTime();
var site_tips = "";
var is_ie = 0;
function initStopwatch()
{
var myTime = new Date();
var timeNow = myTime.getTime();
var timeDiff = timeNow - clockStart;
this.diffSecs = timeDiff/1000;
return(this.diffSecs);
}
if ( window.ActiveXObject )
{
var is_ie = 1;
}
function logout()
{
//ht = document.getElementsByTagName("html");
//ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
if ( confirm("Ban co chac la muon thoat ra ?") )
{
logout_request();
return false;
}
else
{
//ht[0].style.filter = "";
return false;
}
}
function delete_messages(theURL)
{
if (confirm( "Ban co chac la muon xoa tin nhan nay ?" ))
{
window.location.href=theURL;
}
else
{
alert ( "Tin nhan khong duoc xoa!" );
}
}
function delete_script(theURL)
{
if (confirm( "Ban co chac la muon xoa Script nay ?" ))
{
window.location.href=theURL;
}
else
{
alert ( "Script khong duoc xoa!" );
}
}
function alert_msg(theURL)
{
if (confirm( "Are you sure to send this command ?" ))
{
window.location.href=theURL;
}
}
function check_login(the_form)
{
var the_name = the_form.name.value;
var the_password = the_form.password.value;
if ( (the_name=='')||(the_password==''))
{
alert("Nhap day du thong tin yeu cau");
the_form.name.focus();
return false;
}
}
function check_search(str)
{
if (str.value=='')
{
alert("Ban hay nhap noi dung tim kiem vao");
str.focus;
return false;
}
return true;
}
function delete_topic(theURL)
{
if (confirm( "Ban co chac la muon xoa bai viet nay ?" ))
{
window.location.href=theURL;
}
else
{
alert ( "Bai viet khong duoc xoa!" );
}
}
function fast_reply(isMsg)
{
document.quick_reply.submit.disabled = true;
return true;
}
function checkall(){
for (var i = 0; i < document.POSTS.elements.length; i++) {
if ( document.POSTS.all.checked==true ){
document.POSTS.elements[i].checked = true;
}
else{
document.POSTS.elements[i].checked = false;
}
}
}
function my_getcookie( name )
{
cname = site_var_cookieid + name + '=';
cpos = document.cookie.indexOf( cname );
if ( cpos != -1 )
{
cstart = cpos + cname.length;
cend = document.cookie.indexOf(";", cstart);
if (cend == -1)
{
cend = document.cookie.length;
}
return unescape( document.cookie.substring(cstart, cend) );
}
return null;
}
function my_setcookie( name, value, sticky )
{
expire = "";
domain = "";
path = "/";
if ( sticky )
{
expire = "; expires=Wed, 1 Jan 2020 00:00:00 GMT";
}
if ( site_var_cookie_domain != "" )
{
domain = '; domain=' + site_var_cookie_domain;
}
if ( site_var_cookie_path != "" )
{
path = site_var_cookie_path;
}
document.cookie = site_var_cookieid + name + "=" + value + "; path=" + path + expire + domain + ';';
}
function ShowHide(id1, id2)
{
if (id1 != '') toggleview(id1);
if (id2 != '') toggleview(id2);
}
function my_getbyid(id)
{
itm = null;
if (document.getElementById)
{
itm = document.getElementById(id);
}
else if (document.all)
{
itm = document.all[id];
}
else if (document.layers)
{
itm = document.layers[id];
}
return itm;
}
function toggleview(id)
{
if ( ! id ) return;
if ( itm = my_getbyid(id) )
{
if (itm.style.display == "none")
{
my_show_div(itm);
}
else
{
my_hide_div(itm);
}
}
}
function my_hide_div(itm)
{
if ( ! itm ) return;
itm.style.display = "none";
}
function my_show_div(itm)
{
if ( ! itm ) return;
itm.style.display = "";
}
function toggle( fid, add )
{
saved = new Array();
clean = new Array();
if ( tmp = my_getcookie('site_collapseprefs') )
{
saved = tmp.split(",");
}
for( i = 0 ; i < saved.length; i++ )
{
if ( saved[i] != fid && saved[i] != "" )
{
clean[clean.length] = saved[i];
}
}
if ( add )
{
clean[ clean.length ] = fid;
my_show_div( my_getbyid( 'fc_'+fid ) );
my_hide_div( my_getbyid( 'fo_'+fid ) );
}
else
{
my_show_div( my_getbyid( 'fo_'+fid ) );
my_hide_div( my_getbyid( 'fc_'+fid ) );
}
my_setcookie( 'site_collapseprefs', clean.join(','), 1 );
}
function page_loading_html( text )
{
text = "<DIV style='width: 100%; padding-top: 7px; padding-bottom: 7px;' align='center'> " + text + " </div>";
return text;
}
function page_loading(type)
{
if ( type == 1 )
{
document.getElementById( this.clicked ).innerHTML = page_loading_html("<img align='absmiddle' src='" + site_root_domain + "/templates/images/warning.png'> <font size='2' face='verdana' color='red'>Kết nối bị lỗi....</font>");
}
else if ( type == 2 )
{
document.getElementById( this.clicked ).innerHTML = "";
}
else
{
document.getElementById( this.clicked ).innerHTML = page_loading_html("<font size='2' face='verdana'><img align='absmiddle' src='" + site_root_domain + "/templates/images/loading_layer.gif'>");
}
}
function data_request(request, url, type, form_id, no_status)
{
this.clicked = request;
data_request_sent++;
update_status(0);
this.no_status = no_status;
if ( no_status == 1 )
{
no_status = 1;
}
else
{
no_status = 0;
}
if ( ! type )
{
type = "GET";
}
else
{
type = "POST";
}
var fields_data = "";
var lhl_data_got = "";
if ( form_id )
{
if ( type == "GET" )
{
var fields_data = "?";
}
else if ( type == "POST" )
{
var fields_data = "";
}
var frm = document.forms[form_id];
var numberElements = frm.elements.length;
for( var i = 0; i < numberElements; i++ )
{
if( i < numberElements-1 )
{
if ( frm.elements[i].type == "select-one" )
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value+"&";
}
else if ( frm.elements[i].type == "select-multiple" )
{
art_name = frm.elements[i].name;
selmul = frm.elements[i];
var seldt = new Array();
var selcnt = 0;
for ( var i = 0; i < selmul.length; i++ )
{
if ( selmul.options[i].selected == true )
{
seldt[selcnt] = selmul.options[i].value;
selcnt++;
}
}
fields_data += art_name+"="+seldt+"&";
}
else if ( ( frm.elements[i].type == "radio" ) || ( frm.elements[i].type == "checkbox" ))
{
if (frm.elements[i].checked)
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value+"&";
}
}
else
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value+"&";
}
}
else
{
if (frm.elements[i].type == "radio")
{
if (frm.elements[i].checked)
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value;
}
}
else
{
fields_data += frm.elements[i].name+"="+frm.elements[i].value;
}
}
}
}
http_request = false;
this.lhl_id_packet_send_to = request;
if ( lhl_id_packet_send_to )
{
if ( no_status != 1 )
{
page_loading();
}
}
if (window.XMLHttpRequest) // Mozilla, Safari,...
{
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) // IE
{
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
}
}
}
if ( ! http_request )
{
if ( lhl_id_packet_send_to )
{
page_loading(1);
}
return false;
}
http_request.onreadystatechange = contents;
if ( type == "POST" )
{
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http_request.setRequestHeader("Content-length", fields_data.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(fields_data);
}
else if ( type == "GET" )
{
http_request.open('GET', url + fields_data, true);
http_request.send(null);
}
}
function contents()
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
data_request_received++;
update_status(1);
if ( lhl_id_packet_send_to )
{
if ( no_status != 1 )
{
page_loading(2);
}
data_request_time = 1;
document.getElementById( lhl_id_packet_send_to ).innerHTML = http_request.responseText;
}
}
else
{
if ( lhl_id_packet_send_to )
{
if ( no_status != 1 )
{
page_loading(1);
}
}
}
}
}
function update_status(type)
{
if ( document.getElementById( 'SITE_request_sent' ) )
{
if ( type == 1 )
{
status_received = data_request_received;
document.getElementById( 'SITE_request_received' ).innerHTML = status_received;
}
else
{
status_sent = data_request_sent;
document.getElementById( 'SITE_request_sent' ).innerHTML = status_sent;
}
}
}
function site_menu()
{
var nodes = document.getElementById("topmenu").getElementsByTagName("a");
for( var i = 1 ; i < nodes.length; i++ )
{
nodes[i].onclick = function()
{
document.getElementById( "site_" + menuselect ).className = "";
document.getElementById( menuselect ).style.display = "none";
if(this.parentNode.current && this.parentNode.current != this)
{
document.getElementById(this.parentNode.current.getAttribute("menu")).style.display = "none";
this.parentNode.current.className = "";
}
this.parentNode.current = this;
if ( this.getAttribute("menu") )
{
document.getElementById(this.getAttribute("menu")).style.display = "block";
this.className = "selected";
}
}
}
nodes[1].parentNode.current = nodes[1];
}
var renew = 0;
function login_request()
{
data_request( "SITE_member", site_root_domain + "/?site=login&view=do&isa=1", "POST", "login", 0 );
}
function logout_request()
{
site_login_click = 0;
site_login_status = 1;
data_request( "SITE_member", site_root_domain + "/?site=login&view=logout&isa=1", "GET", "", 0 );
}
function login_effect( type )
{
lhl_Cron = initStopwatch();
lhl_Cron_exe = ""+lhl_Cron;
lhl_Cron_exe = lhl_Cron_exe.substring(0,lhl_Cron_exe.indexOf("."));
login = '<form name="login" id="login" method="post">Tên truy nhập: <input class="input_text_white" type="text" name="name" size="20"> Mật khẩu: <input class="input_text_white" type="password" name="password" size="20"> <input type="checkbox" name="remember" value="1" checked> Ghi nhớ ? <input class="input_submit" type="submit" name="submit" value="Đăng nhập" onclick="login_request();"></form>';
if ( ! type )
{
if ( is_ie == 1 )
{
document.getElementById("SITE_login").innerHTML = "<div style='background: #EEEEEE; position: absolute; left: 0px; top: 0px; width: 100%; border-bottom: solid #000000 1px; vertical-align: middle; height: 30px;'><div style='padding-left: 8px; padding-top: 4px;'><p class='align_right'><a onclick='javascript:SITE_login_effect();'><img src='" + site_root_domain + "/templates/images/icon_delete.gif'></a> </p>" + login + "</div></div>";
}
else
{
if ( site_login_status > 30 )
{
return false;
}
window.setTimeout('login_effect()', 1);
document.getElementById("SITE_login").innerHTML = "<div style='background: #EEEEEE; position: absolute; left: 0px; top: 0px; width: 100%; border-bottom: solid #000000 1px; vertical-align: middle; height: "+ site_login_status +"px;'><div style='padding-left: 8px; padding-top: 4px;'><p class='align_right'><a onclick='javascript:SITE_login_effect();'><img src='" + site_root_domain + "/templates/images/icon_delete.gif'></a> </p>" + login + "</div></div>";
site_login_status += 1;
}
}
else
{
if ( is_ie == 1 )
{
document.getElementById("SITE_login").innerHTML = "";
}
else
{
if ( site_login_status <= 0 )
{
document.getElementById("SITE_login").innerHTML = "";
return false;
}
window.setTimeout('login_effect(1)', 1);
document.getElementById("SITE_login").innerHTML = "<div style='background: #EEEEEE; position: absolute; left: 0px; top: 0px; width: 100%; border-bottom: solid #000000 1px; vertical-align: middle; height: "+ site_login_status +"px;'><div style='padding-left: 8px; padding-top: 4px;'><p class='align_right'><a onclick='javascript:SITE_login_effect();'><img src='" + site_root_domain + "/templates/images/icon_delete.gif'></a> </p>" + login + "</div></div>";
//document.getElementById("SITE_login").innerHTML = "<div style='background: #EEEEEE; border-bottom: solid #000000 1px; vertical-align: middle; padding-top: 4px; padding-left: 8px; padding-right: 8px; height: "+ site_login_status +"px;'>" + login + "</div>";
site_login_status -= 1;
}
}
}
function SITE_login_effect()
{
if ( site_login_click == 0 )
{
login_effect();
site_login_click = 1;
}
else
{
login_effect(1);
site_login_click = 0;
}
}
function SITE_change_tab( this_id )
{
if ( this_id != menu_tab_selected )
{
document.getElementById( this_id ).className = "block_tab_selected";
document.getElementById( menu_tab_selected ).className = "block_tab";
menu_tab_selected = this_id;
}
}
var IE = document.all?true:false
if ( ! IE )
{
document.captureEvents( Event.MOUSEMOVE );
}
document.onmousemove = getMouseXY;
function ietruebody()
{
return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
var tempX = 0;
var tempY = 0;
function getMouseXY(e)
{
if ( IE )
{
tempX = event.clientX + ietruebody().scrollLeft;
tempY = event.clientY + ietruebody().scrollTop;
}
else
{
tempX = e.pageX;
tempY = e.pageY;
}
if ( tempX < 0 )
{
tempX = 0
}
if ( tempY < 0 )
{
tempY = 0
}
return true;
}
var post_respond_id = 0;
function news_post_request( topic_id )
{
post_respond_id += 1;
document.getElementById("post_respond").id = "lhl_dattenginhi_" + post_respond_id;
document.getElementById( "lhl_dattenginhi_" + post_respond_id ).innerHTML = document.getElementById( "lhl_dattenginhi_" + post_respond_id ).innerHTML + "<div id='post_respond'></div>";
data_request( "post_respond", site_root_domain + "/?site=news&view=post&act=reply&id=" + topic_id + "&isa=1", "POST", "news_post", 0 );
}
function is_login()
{
return true;
if ( my_getcookie('member_id') && my_getcookie('member_id') != 0 && my_getcookie('pass_hash') != 0 )
{
return true;
}
else
{
alert("Xin vui long su dung chuc nang dang nhap nhanh de dang nhap truoc khi vao trang can vao.");
javascript:SITE_login_effect();
window.scrollTo(0,0);
return false;
}
}
function site_url()
{
base_url = window.location.href;
base_url = base_url.split("#");
real_url = base_url[0];
id_url = base_url[1];
base_url = real_url + id_url;
return base_url;
}
function site_url_check()
{
base_url = window.location.href;
base_url = base_url.split("#");
real_url = base_url[0];
id_url = base_url[1];
if ( id_url )
{
return true;
}
else
{
return false;
}
}
function showfaq( text, faqid )
{
showtip(text, 180);
document.getElementById( faqid ).src= site_img_url +'/icon_notice_active.gif';
}
function hidefaq( faqid )
{
hidetip();
document.getElementById( faqid ).src= site_img_url + '/icon_notice.gif';
}
function href_close()
{
base_url = window.location.href;
base_url = base_url.split("#");
window.location.href = base_url[0] + "#";
}
function href_click( data )
{
//base_url = window.location.href;
//base_url = base_url.split("#");
//window.location.href = base_url[0] + "#" + data;
window.location.href = data;
}
function rating_over( num )
{
var numelse = 10 - num;
for ( i = 1; i <= num; i ++ )
{
document.getElementById( "star_" + i ).style.opacity = 1;
document.getElementById( "star_" + i ).style.filter = "alpha(opacity=100)";
}
for ( i = num+1; i <= numelse; i ++ )
{
document.getElementById( "star_" + i ).style.opacity = 0.4;
document.getElementById( "star_" + i ).style.filter = "alpha(opacity=60)";
}
document.getElementById("rating_star").innerHTML = num;
}
function rating_out()
{
for ( i = 1; i <= 10; i ++ )
{
document.getElementById( "star_" + i ).style.opacity = 0.4;
document.getElementById( "star_" + i ).style.filter = "alpha(opacity=60)";
}
}
function rating_click( target_to, target_id )
{
var star_select = document.getElementById("rating_star").innerHTML;
if ( star_select > 0 )
{
data_request( target_id, target_to + star_select + "/", "GET", "", 0 );
return false;
}
}
function add_favourite( name, URL )
{
if (window.sidebar)
{
window.sidebar.addPanel(name, url,"");
}
else if( window.external )
{
window.external.AddFavorite( url, name);
}
else if (window.opera && window.print)
{
return true;
}
}
function check_form( form_id )
{
var frm = document.forms[form_id];
var numberElements = frm.elements.length;
for( var i = 0; i < numberElements; i++ )
{
test = frm.elements[i];
if ( ! document.getElementById(frm.elements[i].name).value && test.getAttribute('emsg') )
{
alert( test.getAttribute('emsg') );
document.getElementById(frm.elements[i].name).focus();
return false;
}
}
}
// lyhuuloi foundation date 23/1/2008
function password_change( data )
{
var point = 0;
var value = data.value;
var simple = new Array("123456", "1234567", "12345678", "123456789", "321654", "654987", "321654987", "654321", "987654321");
if ( value.length > 0 )
{
document.getElementById("password_checker").style.display = "inline";
// step 1
point += value.length;
// step 2
var check1 = 0;
for ( var i = 0; i < simple.length-1; i++ )
{
if ( simple[i] == value )
{
check1 = 1;
}
}
if ( check1 == 0 && value.length >= 6 )
{
point += 5;
}
// step 3
/*var check2 = 0;
if ( value.length >= 6 )
{
for ( var i = 1; i <= 3; i++ )
{
var data2 = value;
result = data2.replace( data2.substr(0,i), "" );
alert( data2.substr(0,i) + " = " + result);
if ( result == "" )
{
check2 = 1;
}
}
}
*/
}
else
{
document.getElementById("password_checker").style.display = "none";
}
if ( point >= 5 )
{
document.getElementById("pwd1").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd1").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 10 )
{
document.getElementById("pwd2").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd2").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 15 )
{
document.getElementById("pwd3").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd3").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 20 )
{
document.getElementById("pwd4").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd4").innerHTML = '<span class="password_1"> </span>';
}
if ( point >= 25 )
{
document.getElementById("pwd5").innerHTML = '<span class="password_2"> </span>';
}
else
{
document.getElementById("pwd5").innerHTML = '<span class="password_1"> </span>';
}
}
| JavaScript |
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += '<a href="#" class="button '+obj['class']+'">'+name+'<span></span></a>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery); | JavaScript |
/*!
* jQzoom Evolution Library v2.3 - Javascript Image magnifier
* http://www.mind-projects.it
*
* Copyright 2011, Engineer Marco Renzi
* Licensed under the BSD license.
*
* 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 organization nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Date: 03 May 2011 22:16:00
*/
(function ($) {
//GLOBAL VARIABLES
var isIE6 = ($.browser.msie && $.browser.version < 7);
var body = $(document.body);
var window = $(window);
var jqzoompluging_disabled = false; //disabilita globalmente il plugin
$.fn.jqzoom = function (options) {
return this.each(function () {
var node = this.nodeName.toLowerCase();
if (node == 'a') {
new jqzoom(this, options);
}
});
};
jqzoom = function (el, options) {
var api = null;
api = $(el).data("jqzoom");
if (api) return api;
var obj = this;
var settings = $.extend({}, $.jqzoom.defaults, options || {});
obj.el = el;
el.rel = $(el).attr('rel');
//ANCHOR ELEMENT
el.zoom_active = false;
el.zoom_disabled = false; //to disable single zoom instance
el.largeimageloading = false; //tell us if large image is loading
el.largeimageloaded = false; //tell us if large image is loaded
el.scale = {};
el.timer = null;
el.mousepos = {};
el.mouseDown = false;
$(el).css({
'outline-style': 'none',
'text-decoration': 'none'
});
//BASE IMAGE
var img = $("img:eq(0)", el);
el.title = $(el).attr('title');
el.imagetitle = img.attr('title');
var zoomtitle = ($.trim(el.title).length > 0) ? el.title : el.imagetitle;
var smallimage = new Smallimage(img);
var lens = new Lens();
var stage = new Stage();
var largeimage = new Largeimage();
var loader = new Loader();
//preventing default click,allowing the onclick event [exmple: lightbox]
$(el).bind('click', function (e) {
e.preventDefault();
return false;
});
//setting the default zoomType if not in settings
var zoomtypes = ['standard', 'drag', 'innerzoom', 'reverse'];
if ($.inArray($.trim(settings.zoomType), zoomtypes) < 0) {
settings.zoomType = 'standard';
}
$.extend(obj, {
create: function () { //create the main objects
//create ZoomPad
if ($(".zoomPad", el).length == 0) {
el.zoomPad = $('<div/>').addClass('zoomPad');
img.wrap(el.zoomPad);
}
if(settings.zoomType == 'innerzoom'){
settings.zoomWidth = smallimage.w;
settings.zoomHeight = smallimage.h;
}
//creating ZoomPup
if ($(".zoomPup", el).length == 0) {
lens.append();
}
//creating zoomWindow
if ($(".zoomWindow", el).length == 0) {
stage.append();
}
//creating Preload
if ($(".zoomPreload", el).length == 0) {
loader.append();
}
//preloading images
if (settings.preloadImages || settings.zoomType == 'drag' || settings.alwaysOn) {
obj.load();
}
obj.init();
},
init: function () {
//drag option
if (settings.zoomType == 'drag') {
$(".zoomPad", el).mousedown(function () {
el.mouseDown = true;
});
$(".zoomPad", el).mouseup(function () {
el.mouseDown = false;
});
document.body.ondragstart = function () {
return false;
};
$(".zoomPad", el).css({
cursor: 'default'
});
$(".zoomPup", el).css({
cursor: 'move'
});
}
if (settings.zoomType == 'innerzoom') {
$(".zoomWrapper", el).css({
cursor: 'crosshair'
});
}
$(".zoomPad", el).bind('mouseenter mouseover', function (event) {
img.attr('title', '');
$(el).attr('title', '');
el.zoom_active = true;
//if loaded then activate else load large image
smallimage.fetchdata();
if (el.largeimageloaded) {
obj.activate(event);
} else {
obj.load();
}
});
$(".zoomPad", el).bind('mouseleave', function (event) {
obj.deactivate();
});
$(".zoomPad", el).bind('mousemove', function (e) {
//prevent fast mouse mevements not to fire the mouseout event
if (e.pageX > smallimage.pos.r || e.pageX < smallimage.pos.l || e.pageY < smallimage.pos.t || e.pageY > smallimage.pos.b) {
lens.setcenter();
return false;
}
el.zoom_active = true;
if (el.largeimageloaded && !$('.zoomWindow', el).is(':visible')) {
obj.activate(e);
}
if (el.largeimageloaded && (settings.zoomType != 'drag' || (settings.zoomType == 'drag' && el.mouseDown))) {
lens.setposition(e);
}
});
var thumb_preload = new Array();
var i = 0;
//binding click event on thumbnails
var thumblist = new Array();
thumblist = $('a').filter(function () {
var regex = new RegExp("gallery[\\s]*:[\\s]*'" + $.trim(el.rel) + "'", "i");
var rel = $(this).attr('rel');
if (regex.test(rel)) {
return this;
}
});
if (thumblist.length > 0) {
//getting the first to the last
var first = thumblist.splice(0, 1);
thumblist.push(first);
}
thumblist.each(function () {
//preloading thumbs
if (settings.preloadImages) {
var thumb_options = $.extend({}, eval("(" + $.trim($(this).attr('rel')) + ")"));
thumb_preload[i] = new Image();
thumb_preload[i].src = thumb_options.largeimage;
i++;
}
$(this).click(function (e) {
if($(this).hasClass('zoomThumbActive')){
return false;
}
thumblist.each(function () {
$(this).removeClass('zoomThumbActive');
});
e.preventDefault();
obj.swapimage(this);
return false;
});
});
},
load: function () {
if (el.largeimageloaded == false && el.largeimageloading == false) {
var url = $(el).attr('href');
el.largeimageloading = true;
largeimage.loadimage(url);
}
},
activate: function (e) {
clearTimeout(el.timer);
//show lens and zoomWindow
lens.show();
stage.show();
},
deactivate: function (e) {
switch (settings.zoomType) {
case 'drag':
//nothing or lens.setcenter();
break;
default:
img.attr('title', el.imagetitle);
$(el).attr('title', el.title);
if (settings.alwaysOn) {
lens.setcenter();
} else {
stage.hide();
lens.hide();
}
break;
}
el.zoom_active = false;
},
swapimage: function (link) {
el.largeimageloading = false;
el.largeimageloaded = false;
var options = new Object();
options = $.extend({}, eval("(" + $.trim($(link).attr('rel')) + ")"));
if (options.smallimage && options.largeimage) {
var smallimage = options.smallimage;
var largeimage = options.largeimage;
$(link).addClass('zoomThumbActive');
$(el).attr('href', largeimage);
img.attr('src', smallimage);
lens.hide();
stage.hide();
obj.load();
} else {
alert('ERROR :: Missing parameter for largeimage or smallimage.');
throw 'ERROR :: Missing parameter for largeimage or smallimage.';
}
return false;
}
});
//sometimes image is already loaded and onload will not fire
if (img[0].complete) {
//fetching data from sallimage if was previously loaded
smallimage.fetchdata();
if ($(".zoomPad", el).length == 0) obj.create();
}
/*========================================================,
| Smallimage
|---------------------------------------------------------:
| Base image into the anchor element
`========================================================*/
function Smallimage(image) {
var $obj = this;
this.node = image[0];
this.findborder = function () {
var bordertop = 0;
bordertop = image.css('border-top-width');
btop = '';
var borderleft = 0;
borderleft = image.css('border-left-width');
bleft = '';
if (bordertop) {
for (i = 0; i < 3; i++) {
var x = [];
x = bordertop.substr(i, 1);
if (isNaN(x) == false) {
btop = btop + '' + bordertop.substr(i, 1);
} else {
break;
}
}
}
if (borderleft) {
for (i = 0; i < 3; i++) {
if (!isNaN(borderleft.substr(i, 1))) {
bleft = bleft + borderleft.substr(i, 1)
} else {
break;
}
}
}
$obj.btop = (btop.length > 0) ? eval(btop) : 0;
$obj.bleft = (bleft.length > 0) ? eval(bleft) : 0;
};
this.fetchdata = function () {
$obj.findborder();
$obj.w = image.width();
$obj.h = image.height();
$obj.ow = image.outerWidth();
$obj.oh = image.outerHeight();
$obj.pos = image.offset();
$obj.pos.l = image.offset().left + $obj.bleft;
$obj.pos.t = image.offset().top + $obj.btop;
$obj.pos.r = $obj.w + $obj.pos.l;
$obj.pos.b = $obj.h + $obj.pos.t;
$obj.rightlimit = image.offset().left + $obj.ow;
$obj.bottomlimit = image.offset().top + $obj.oh;
};
this.node.onerror = function () {
alert('Problems while loading image.');
throw 'Problems while loading image.';
};
this.node.onload = function () {
$obj.fetchdata();
if ($(".zoomPad", el).length == 0) obj.create();
};
return $obj;
};
/*========================================================,
| Loader
|---------------------------------------------------------:
| Show that the large image is loading
`========================================================*/
function Loader() {
var $obj = this;
this.append = function () {
this.node = $('<div/>').addClass('zoomPreload').css('visibility', 'hidden').html(settings.preloadText);
$('.zoomPad', el).append(this.node);
};
this.show = function () {
this.node.top = (smallimage.oh - this.node.height()) / 2;
this.node.left = (smallimage.ow - this.node.width()) / 2;
//setting position
this.node.css({
top: this.node.top,
left: this.node.left,
position: 'absolute',
visibility: 'visible'
});
};
this.hide = function () {
this.node.css('visibility', 'hidden');
};
return this;
}
/*========================================================,
| Lens
|---------------------------------------------------------:
| Lens over the image
`========================================================*/
function Lens() {
var $obj = this;
this.node = $('<div/>').addClass('zoomPup');
//this.nodeimgwrapper = $("<div/>").addClass('zoomPupImgWrapper');
this.append = function () {
$('.zoomPad', el).append($(this.node).hide());
if (settings.zoomType == 'reverse') {
this.image = new Image();
this.image.src = smallimage.node.src; // fires off async
$(this.node).empty().append(this.image);
}
};
this.setdimensions = function () {
this.node.w = (parseInt((settings.zoomWidth) / el.scale.x) > smallimage.w ) ? smallimage.w : (parseInt(settings.zoomWidth / el.scale.x));
this.node.h = (parseInt((settings.zoomHeight) / el.scale.y) > smallimage.h ) ? smallimage.h : (parseInt(settings.zoomHeight / el.scale.y));
this.node.top = (smallimage.oh - this.node.h - 2) / 2;
this.node.left = (smallimage.ow - this.node.w - 2) / 2;
//centering lens
this.node.css({
top: 0,
left: 0,
width: this.node.w + 'px',
height: this.node.h + 'px',
position: 'absolute',
display: 'none',
borderWidth: 1 + 'px'
});
if (settings.zoomType == 'reverse') {
this.image.src = smallimage.node.src;
$(this.node).css({
'opacity': 1
});
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
};
this.setcenter = function () {
//calculating center position
this.node.top = (smallimage.oh - this.node.h - 2) / 2;
this.node.left = (smallimage.ow - this.node.w - 2) / 2;
//centering lens
this.node.css({
top: this.node.top,
left: this.node.left
});
if (settings.zoomType == 'reverse') {
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
//centering large image
largeimage.setposition();
};
this.setposition = function (e) {
el.mousepos.x = e.pageX;
el.mousepos.y = e.pageY;
var lensleft = 0;
var lenstop = 0;
function overleft(lens) {
return el.mousepos.x - (lens.w) / 2 < smallimage.pos.l;
}
function overright(lens) {
return el.mousepos.x + (lens.w) / 2 > smallimage.pos.r;
}
function overtop(lens) {
return el.mousepos.y - (lens.h) / 2 < smallimage.pos.t;
}
function overbottom(lens) {
return el.mousepos.y + (lens.h) / 2 > smallimage.pos.b;
}
lensleft = el.mousepos.x + smallimage.bleft - smallimage.pos.l - (this.node.w + 2) / 2;
lenstop = el.mousepos.y + smallimage.btop - smallimage.pos.t - (this.node.h + 2) / 2;
if (overleft(this.node)) {
lensleft = smallimage.bleft - 1;
} else if (overright(this.node)) {
lensleft = smallimage.w + smallimage.bleft - this.node.w - 1;
}
if (overtop(this.node)) {
lenstop = smallimage.btop - 1;
} else if (overbottom(this.node)) {
lenstop = smallimage.h + smallimage.btop - this.node.h - 1;
}
this.node.left = lensleft;
this.node.top = lenstop;
this.node.css({
'left': lensleft + 'px',
'top': lenstop + 'px'
});
if (settings.zoomType == 'reverse') {
if ($.browser.msie && $.browser.version > 7) {
$(this.node).empty().append(this.image);
}
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
largeimage.setposition();
};
this.hide = function () {
img.css({
'opacity': 1
});
this.node.hide();
};
this.show = function () {
if (settings.zoomType != 'innerzoom' && (settings.lens || settings.zoomType == 'drag')) {
this.node.show();
}
if (settings.zoomType == 'reverse') {
img.css({
'opacity': settings.imageOpacity
});
}
};
this.getoffset = function () {
var o = {};
o.left = $obj.node.left;
o.top = $obj.node.top;
return o;
};
return this;
};
/*========================================================,
| Stage
|---------------------------------------------------------:
| Window area that contains the large image
`========================================================*/
function Stage() {
var $obj = this;
this.node = $("<div class='zoomWindow'><div class='zoomWrapper'><div class='zoomWrapperTitle'></div><div class='zoomWrapperImage'></div></div></div>");
this.ieframe = $('<iframe class="zoomIframe" src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" frameborder="0" ></iframe>');
this.setposition = function () {
this.node.leftpos = 0;
this.node.toppos = 0;
if (settings.zoomType != 'innerzoom') {
//positioning
switch (settings.position) {
case "left":
this.node.leftpos = (smallimage.pos.l - smallimage.bleft - Math.abs(settings.xOffset) - settings.zoomWidth > 0) ? (0 - settings.zoomWidth - Math.abs(settings.xOffset)) : (smallimage.ow + Math.abs(settings.xOffset));
this.node.toppos = Math.abs(settings.yOffset);
break;
case "top":
this.node.leftpos = Math.abs(settings.xOffset);
this.node.toppos = (smallimage.pos.t - smallimage.btop - Math.abs(settings.yOffset) - settings.zoomHeight > 0) ? (0 - settings.zoomHeight - Math.abs(settings.yOffset)) : (smallimage.oh + Math.abs(settings.yOffset));
break;
case "bottom":
this.node.leftpos = Math.abs(settings.xOffset);
this.node.toppos = (smallimage.pos.t - smallimage.btop + smallimage.oh + Math.abs(settings.yOffset) + settings.zoomHeight < screen.height) ? (smallimage.oh + Math.abs(settings.yOffset)) : (0 - settings.zoomHeight - Math.abs(settings.yOffset));
break;
default:
this.node.leftpos = (smallimage.rightlimit + Math.abs(settings.xOffset) + settings.zoomWidth < screen.width) ? (smallimage.ow + Math.abs(settings.xOffset)) : (0 - settings.zoomWidth - Math.abs(settings.xOffset));
this.node.toppos = Math.abs(settings.yOffset);
break;
}
}
this.node.css({
'left': this.node.leftpos + 'px',
'top': this.node.toppos + 'px'
});
return this;
};
this.append = function () {
$('.zoomPad', el).append(this.node);
this.node.css({
position: 'absolute',
display: 'none',
zIndex: 5001
});
if (settings.zoomType == 'innerzoom') {
this.node.css({
cursor: 'default'
});
var thickness = (smallimage.bleft == 0) ? 1 : smallimage.bleft;
$('.zoomWrapper', this.node).css({
borderWidth: thickness + 'px'
});
}
$('.zoomWrapper', this.node).css({
width: Math.round(settings.zoomWidth) + 'px' ,
borderWidth: thickness + 'px'
});
$('.zoomWrapperImage', this.node).css({
width: '100%',
height: Math.round(settings.zoomHeight) + 'px'
});
//zoom title
$('.zoomWrapperTitle', this.node).css({
width: '100%',
position: 'absolute'
});
$('.zoomWrapperTitle', this.node).hide();
if (settings.title && zoomtitle.length > 0) {
$('.zoomWrapperTitle', this.node).html(zoomtitle).show();
}
$obj.setposition();
};
this.hide = function () {
switch (settings.hideEffect) {
case 'fadeout':
this.node.fadeOut(settings.fadeoutSpeed, function () {});
break;
default:
this.node.hide();
break;
}
this.ieframe.hide();
};
this.show = function () {
switch (settings.showEffect) {
case 'fadein':
this.node.fadeIn();
this.node.fadeIn(settings.fadeinSpeed, function () {});
break;
default:
this.node.show();
break;
}
if (isIE6 && settings.zoomType != 'innerzoom') {
this.ieframe.width = this.node.width();
this.ieframe.height = this.node.height();
this.ieframe.left = this.node.leftpos;
this.ieframe.top = this.node.toppos;
this.ieframe.css({
display: 'block',
position: "absolute",
left: this.ieframe.left,
top: this.ieframe.top,
zIndex: 99,
width: this.ieframe.width + 'px',
height: this.ieframe.height + 'px'
});
$('.zoomPad', el).append(this.ieframe);
this.ieframe.show();
};
};
};
/*========================================================,
| LargeImage
|---------------------------------------------------------:
| The large detailed image
`========================================================*/
function Largeimage() {
var $obj = this;
this.node = new Image();
this.loadimage = function (url) {
//showing preload
loader.show();
this.url = url;
this.node.style.position = 'absolute';
this.node.style.border = '0px';
this.node.style.display = 'none';
this.node.style.left = '-5000px';
this.node.style.top = '0px';
document.body.appendChild(this.node);
this.node.src = url; // fires off async
};
this.fetchdata = function () {
var image = $(this.node);
var scale = {};
this.node.style.display = 'block';
$obj.w = image.width();
$obj.h = image.height();
$obj.pos = image.offset();
$obj.pos.l = image.offset().left;
$obj.pos.t = image.offset().top;
$obj.pos.r = $obj.w + $obj.pos.l;
$obj.pos.b = $obj.h + $obj.pos.t;
scale.x = ($obj.w / smallimage.w);
scale.y = ($obj.h / smallimage.h);
el.scale = scale;
document.body.removeChild(this.node);
$('.zoomWrapperImage', el).empty().append(this.node);
//setting lens dimensions;
lens.setdimensions();
};
this.node.onerror = function () {
alert('Problems while loading the big image.');
throw 'Problems while loading the big image.';
};
this.node.onload = function () {
//fetching data
$obj.fetchdata();
loader.hide();
el.largeimageloading = false;
el.largeimageloaded = true;
if (settings.zoomType == 'drag' || settings.alwaysOn) {
lens.show();
stage.show();
lens.setcenter();
}
};
this.setposition = function () {
var left = -el.scale.x * (lens.getoffset().left - smallimage.bleft + 1);
var top = -el.scale.y * (lens.getoffset().top - smallimage.btop + 1);
$(this.node).css({
'left': left + 'px',
'top': top + 'px'
});
};
return this;
};
$(el).data("jqzoom", obj);
};
//es. $.jqzoom.disable('#jqzoom1');
$.jqzoom = {
defaults: {
zoomType: 'standard',
//innerzoom/standard/reverse/drag
zoomWidth: 350,
//zoomWindow default width
zoomHeight: 250,
//zoomWindow default height
xOffset: 10,
//zoomWindow x offset, can be negative(more on the left) or positive(more on the right)
yOffset: 0,
//zoomWindow y offset, can be negative(more on the left) or positive(more on the right)
position: "right",
//zoomWindow default position
preloadImages: true,
//image preload
preloadText: 'Loading zoom',
title: true,
lens: true,
imageOpacity: 0.4,
alwaysOn: false,
showEffect: 'show',
//show/fadein
hideEffect: 'hide',
//hide/fadeout
fadeinSpeed: 'slow',
//fast/slow/number
fadeoutSpeed: '2000' //fast/slow/number
},
disable: function (el) {
var api = $(el).data('jqzoom');
api.disable();
return false;
},
enable: function (el) {
var api = $(el).data('jqzoom');
api.enable();
return false;
},
disableAll: function (el) {
jqzoompluging_disabled = true;
},
enableAll: function (el) {
jqzoompluging_disabled = false;
}
};
})(jQuery); | JavaScript |
/*
* AVIM JavaScript Vietnamese Input Method Source File dated 28-06-2006
*
* Copyright (C) 2004 Hieu Tran Dang <lt2hieu2004 (at) users (dot) sf (dot) net>
* Website: http://hdang.co.uk
* http://hieu.acunett.com
*
* You are allowed to use this software in any way you want providing:
* 1. You must retain this copyright notice at all time
* 2. You must not claim that you or any other third party is the author
* of this software in any way.
*/
va="password,cus_email".split(',') //Put the ID of the fields you DON'T want to let users type Vietnamese in, multiple fields allowed, separated by a comma (,)
fID="Post".split(',') //Put the ID of the iframes you want to let users type Vietnamese in separated by a comma (,)
method=2 //Default input method, 0=AUTO, 1=TELEX, 2=VNI, 3=VIQR
on_off=1 //Start H.I.M on
dockspell=0 //Start H.I.M with spell checking on
dauCu=0 //Start H.I.M with old way of marking accent (o`a, o`e, u`y)
useCookie=1 //Set this to 0 to NOT use cookies
radioID="".split(",")
var agt=navigator.userAgent.toLowerCase(),alphabet="QWERTYUIOPASDFGHJKLZXCVBNM\ ",them,spellerr,setCookie,getCookie
var is_ie=((agt.indexOf("msie")!=-1)&&(agt.indexOf("opera")==-1)),S,F,J,R,X,D,oc,sk,saveStr,wi,frame,is_opera=false,D2
var ver=0,support=true,changed=false,uni,uni2,g,h,SFJRX,DAWEO,Z,AEO,moc,trang,kl=0,tw5,range=null,doc
skey=new Array(97,226,259,101,234,105,111,244,417,117,432,121,65,194,258,69,202,73,79,212,416,85,431,89)
var skey2="a,a,a,e,e,i,o,o,o,u,u,y,A,A,A,E,E,I,O,O,O,U,U,Y".split(','),A,E,O,whit=false,english="ĐÂĂƠƯÊÔ",ds1="d,D".split(","),db1=new Array(273,272)
os1="o,O,ơ,Ơ,ó,Ó,ò,Ò,ọ,Ọ,ỏ,Ỏ,õ,Õ,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ".split(","),ob1="ô,Ô,ô,Ô,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ".split(",")
mocs1="o,O,ô,Ô,u,U,ó,Ó,ò,Ò,ọ,Ọ,ỏ,Ỏ,õ,Õ,ú,Ú,ù,Ù,ụ,Ụ,ủ,Ủ,ũ,Ũ,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ".split(",");mocb1="ơ,Ơ,ơ,Ơ,ư,Ư,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ,ứ,Ứ,ừ,Ừ,ự,Ự,ử,Ử,ữ,Ữ,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ".split(",")
trangs1="a,A,â,Â,á,Á,à,À,ạ,Ạ,ả,Ả,ã,Ã,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ".split(",");trangb1="ă,Ă,ă,Ă,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ".split(",")
as1="a,A,ă,Ă,á,Á,à,À,ạ,Ạ,ả,Ả,ã,Ã,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ,ế,Ế,ề,Ề,ệ,Ệ,ể,Ể,ễ,Ễ".split(",");ab1="â,Â,â,Â,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ,é,É,è,È,ẹ,Ẹ,ẻ,Ẻ,ẽ,Ẽ".split(",")
es1="e,E,é,É,è,È,ẹ,Ẹ,ẻ,Ẻ,ẽ,Ẽ".split(",");eb1="ê,Ê,ế,Ế,ề,Ề,ệ,Ệ,ể,Ể,ễ,Ễ".split(",")
arA="á,à,ả,ã,ạ,a,Á,À,Ả,Ã,Ạ,A".split(',');mocrA="ó,ò,ỏ,õ,ọ,o,ú,ù,ủ,ũ,ụ,u,Ó,Ò,Ỏ,Õ,Ọ,O,Ú,Ù,Ủ,Ũ,Ụ,U".split(',');erA="é,è,ẻ,ẽ,ẹ,e,É,È,Ẻ,Ẽ,Ẹ,E".split(',');orA="ó,ò,ỏ,õ,ọ,o,Ó,Ò,Ỏ,Õ,Ọ,O".split(',')
aA="ấ,ầ,ẩ,ẫ,ậ,â,Ấ,Ầ,Ẩ,Ẫ,Ậ,Â".split(',');mocA="ớ,ờ,ở,ỡ,ợ,ơ,ứ,ừ,ử,ữ,ự,ư,Ớ,Ờ,Ở,Ỡ,Ợ,Ơ,Ứ,Ừ,Ử,Ữ,Ự,Ư".split(',');trangA="ắ,ằ,ẳ,ẵ,ặ,ă,Ắ,Ằ,Ẳ,Ẵ,Ặ,Ă".split(',');eA="ế,ề,ể,ễ,ệ,ê,Ế,Ề,Ể,Ễ,Ệ,Ê".split(',');oA="ố,ồ,ổ,ỗ,ộ,ô,Ố,Ồ,Ổ,Ỗ,Ộ,Ô".split(',')
function notWord(w) {
var str="\ \r\n#,\\;.:-_()<>+-*/=?!\"$%{}[]\'~|^\@\&\t"+fcc(160)
return (str.indexOf(w)>=0)
}
function mozGetText(obj) {
var v,pos,w="";g=1
v=(obj.data)?obj.data:obj.value
if(v.length<=0) return false
if(!obj.data) {
if(!obj.setSelectionRange) return false
pos=obj.selectionStart
} else pos=obj.pos
if(obj.selectionStart!=obj.selectionEnd) return new Array("",pos)
while(1) {
if(pos-g<0) break
else if(notWord(v.substr(pos-g,1))) { if(v.substr(pos-g,1)=="\\") w=v.substr(pos-g,1)+w; break }
else w=v.substr(pos-g,1)+w; g++
}
return new Array(w,pos)
}
function start(obj,key) {
var w="";oc=obj;uni2=false;fixed=false
if(method==0) { uni="D,A,E,O,W,W".split(','); uni2="9,6,6,6,7,8".split(','); D2="DAWEO6789" }
else if(method==1) { uni="D,A,E,O,W,W".split(','); D2="DAWEO" }
else if(method==2) { uni="9,6,6,6,7,8".split(','); D2="6789" }
else if(method==3) { uni="D,^,^,^,+,(".split(','); D2="D^+(" }
else if(method==4) { uni="D,^,^,^,*,(".split(','); D2="D^*(" }
if(!is_ie) {
key=fcc(key.which)
w=mozGetText(obj)
if((!w)||(obj.sel)) return
main(w[0],key,w[1],uni)
if(!dockspell) w=mozGetText(obj)
if((w)&&(uni2)&&(!changed)) main(w[0],key,w[1],uni2)
} else {
obj=ieGetText(obj)
if(obj) {
var sT=obj.cW.text
w=main(obj.cW.text,key,0,uni)
if((uni2)&&((w==sT)||(typeof(w)=='undefined'))) w=main(obj.cW.text,key,0,uni2)
if(w) obj.cW.text=w
}
}
if(D2.indexOf(key.toUpperCase())>=0) {
if(!is_ie) {
w=mozGetText(obj)
if(!w) return
normC(w[0],key,w[1])
} else if(typeof(obj)=="object") {
obj=ieGetText(obj)
if(obj) {
w=obj.cW.text
if(!changed) { w+=key; changed=true }
obj.cW.text=w
w=normC(w,key,0)
if(w) { obj=ieGetText(obj); obj.cW.text=w }
}
}
}
}
function ieGetText(obj) {
var caret=obj.document.selection.createRange(),w=""
if(caret.text) caret.text=""
else {
while(1) {
caret.moveStart("character",-1)
if(w.length==caret.text.length) break
w=caret.text
if(notWord(w.charAt(0))) {
if(w.charCodeAt(0)==13) w=w.substr(2)
else if(w.charAt(0)!="\\") w=w.substr(1)
break
}
}
}
if(w.length) {
caret.collapse(false)
caret.moveStart("character",-w.length)
obj.cW=caret.duplicate()
return obj
} else return false
}
function ie_replaceChar(w,pos,c) {
var r="",uc=0
if(isNaN(c)) uc=c.toUpperCase()
if((whit)&&(w.substr(w.length-pos-1,1).toUpperCase()=='U')&&(pos!=1)&&(w.substr(w.length-pos-2,1).toUpperCase()!='Q')) {
whit=false
if((unV(fcc(c)).toUpperCase()=="Ơ")||(uc=="O")) {
if(w.substr(w.length-pos-1,1)=='u') r=fcc(432)
else r=fcc(431)
}
if(uc=="O") {
if(c=="o") c=417
else c=416
}
}
if(!isNaN(c)) {
changed=true;r+=fcc(c)
return w.substr(0,w.length-pos-r.length+1)+r+w.substr(w.length-pos+1)
} else return w.substr(0,w.length-pos)+c+w.substr(w.length-pos+1)
}
function tr(k,w,by,sf,i) {
var r,pos=findC(w,k,sf)
if(pos) {
if(pos[1]) {
if(is_ie) return ie_replaceChar(w,pos[0],pos[1])
else return replaceChar(oc,i-pos[0],pos[1])
} else {
var c,pC=w.substr(w.length-pos,1);r=sf
for(g=0;g<r.length;g++) {
if(isNaN(r[g])) var cmp=pC
else var cmp=pC.charCodeAt(0)
if(cmp==r[g]) {
if(!isNaN(by[g])) c=by[g]
else c=by[g].charCodeAt(0)
if(is_ie) return ie_replaceChar(w,pos,c)
else return replaceChar(oc,i-pos,c)
}
}
}
}
return false
}
function main(w,k,i,a) {
var uk=k.toUpperCase(),bya=new Array(db1,ab1,eb1,ob1,mocb1,trangb1),got=false,t="d,D,a,A,a,A,o,O,u,U,e,E,o,O".split(",")
var sfa=new Array(ds1,as1,es1,os1,mocs1,trangs1),by=new Array(),sf=new Array()
if((method==2)||((method==0)&&(a[0]=="9"))) {
DAWEO="6789";SFJRX="12534";S="1";F="2";J="5";R="3";X="4";Z="0";D="9";FRX="234";AEO="6";moc="7";trang="8";them="678";A="^";E="^";O="^"
} else if(method==3) {
DAWEO="^+(D";SFJRX="'`.?~";S="'";F="`";J=".";R="?";X="~";Z="-";D="D";FRX="`?~";AEO="^";moc="+";trang="(";them="^+(";A="^";E="^";O="^"
} else if(method==4) {
DAWEO="^*(D";SFJRX="'`.?~";S="'";F="`";J=".";R="?";X="~";Z="-";D="D";FRX="`?~";AEO="^";moc="*";trang="(";them="^*(";A="^";E="^";O="^"
} else if((method==1)||((method==0)&&(a[0]=="D"))) {
SFJRX="SFJRX";DAWEO="DAWEO";D='D';S='S';F='F';J='J';R='R';X='X';Z='Z';FRX="FRX";them="AOEW";trang="W";moc="W";A="A";E="E";O="O"
}
if(SFJRX.indexOf(uk)>=0) {
var ret=sr(w,k,i); got=true
if(ret) return ret
} else if(uk==Z) {
sf=repSign(null)
for(h=0;h<english.length;h++) {
sf[sf.length]=english.toLowerCase().charCodeAt(h)
sf[sf.length]=english.charCodeAt(h)
}
for(h=0;h<5;h++) for(g=0;g<skey.length;g++) by[by.length]=skey[g]
for(h=0;h<t.length;h++) by[by.length]=t[h]
got=true
}
else for(h=0;h<a.length;h++) if(a[h]==uk) { got=true; by=by.concat(bya[h]); sf=sf.concat(sfa[h]) }
if(uk==moc) whit=true;
if(!got) return normC(w,k,i)
return DAWEOZ(k,w,by,sf,i,uk)
}
function DAWEOZ(k,w,by,sf,i,uk) { if((DAWEO.indexOf(uk)>=0)||(Z.indexOf(uk)>=0)) return tr(k,w,by,sf,i) }
function normC(w,k,i) {
var uk=k.toUpperCase(),u=repSign(null),fS,c,j,space=(k.charCodeAt(0)==32)?true:false
if((!is_ie)&&(space)) return
for(j=1;j<=w.length;j++) {
for(h=0;h<u.length;h++) {
if(u[h]==w.charCodeAt(w.length-j)) {
if(h<=23) fS=S
else if(h<=47) fS=F
else if(h<=71) fS=J
else if(h<=95) fS=R
else fS=X
c=skey[h%24]; if((alphabet.indexOf(uk)<0)&&(D2.indexOf(uk)<0)) return w; w=unV(w)
if((!space)&&(!changed)) w+=k
if(!is_ie) {
if(!changed) {
if(!oc.data) {
var sp=oc.selectionStart,sst=oc.scrollTop
oc.value=oc.value.substr(0,oc.selectionStart)+k+oc.value.substr(oc.selectionEnd); changed=true
oc.setSelectionRange(sp+k.length,sp+k.length); oc.scrollTop=sst
} else { oc.insertData(oc.pos,k); range.setEnd(oc,oc.pos+1); oc.pos++; changed=true }
}
if(!ckspell(w,fS)) {
replaceChar(oc,i-j,c)
if(!oc.data) {
var pos=oc.selectionStart
var a=new Array(D)
main(w,fS,pos,a)
} else {
var ww=mozGetText(oc)
var a=new Array(D)
main(ww[0],fS,ww[1],a)
}
}
} else {
var ret=sr(w,fS,0)
if((space)&&(ret)) ret+=fcc(32)
if(ret) return ret
}
}
}
}
}
function nospell(w,k) { return false }
function ckspell(w,k) {
w=unV(w); var exc="UOU,IEU".split(','),z,next=true,noE="UU,UOU,UOI,IEU,AO,IA,AI,AY,AU,AO".split(','),noBE="YEU",test,a,b
var check=true,noM="UE,UYE,IU,EU,UY".split(','),noMT="AY,AU".split(','),noT="UA",t=-1,notV2="IAO"
var uw=w.toUpperCase(),tw=uw,update=false,gi="IO",noAOEW="OE,OO,AO,EO,IA,AI".split(','),noAOE="OA"
var notViet="AA,AE,EE,OU,YY,YI,IY,EY,EA,EI,II,IO,YO,YA,YU,OOO".split(','),uk=k.toUpperCase(),twE,uw2=unV2(uw)
var vSConsonant="B,C,D,G,H,K,L,M,N,P,Q,R,S,T,V,X".split(','),vDConsonant="CH,GI,KH,NGH,GH,NG,NH,PH,QU,TH,TR".split(',')
var vDConsonantE="CH,NG,NH".split(','),sConsonant="C,P,T,CH".split(','),vSConsonantE="C,M,N,P,T".split(',')
var noNHE="O,U,IE,Ô,Ơ,Ư,IÊ,Ă,Â,UYE,UYÊ,UO,ƯƠ,ƯO,UƠ,UA,ƯA,OĂ,OE,OÊ".split(','),oMoc="UU,UOU".split(',')
if(FRX.indexOf(uk)>=0) for(a=0;a<sConsonant.length;a++) if(uw.substr(uw.length-sConsonant[a].length,sConsonant[a].length)==sConsonant[a]) return true
for(a=0;a<uw.length;a++) {
if("FJZW1234567890".indexOf(uw.substr(a,1))>=0) return true
for(b=0;b<notViet.length;b++) {
if(uw2.substr(a,notViet[b].length)==notViet[b]) {
for(z=0;z<exc.length;z++) if(uw2.indexOf(exc[z])>=0) next=false
if((next)&&((gi.indexOf(notViet[b])<0)||(a<=0)||(uw2.substr(a-1,1)!='G'))) return true
}
}
}
for(b=0;b<vDConsonant.length;b++) if(tw.indexOf(vDConsonant[b])==0){tw=tw.substr(vDConsonant[b].length);update=true;t=b;break}
if(!update) for(b=0;b<vSConsonant.length;b++) if(tw.indexOf(vSConsonant[b])==0){tw=tw.substr(1);break}
update=false;twE=tw
for(b=0;b<vDConsonantE.length;b++) {
if(tw.substr(tw.length-vDConsonantE[b].length)==vDConsonantE[b]) {
tw=tw.substr(0,tw.length-vDConsonantE[b].length)
if(b==2){
for(z=0;z<noNHE.length;z++) if(tw==noNHE[z]) return true
if((uk==trang)&&((tw=="OA")||(tw=="A"))) return true
}
update=true;break
}
}
if(!update) for(b=0;b<vSConsonantE.length;b++) if(tw.substr(tw.length-1)==vSConsonantE[b]){tw=tw.substr(0,tw.length-1);break}
if(tw) {
for(a=0;a<vDConsonant.length;a++) {
for(b=0;b<tw.length;b++) { if(tw.substr(b,vDConsonant[a].length)==vDConsonant[a]) return true }
}
for(a=0;a<vSConsonant.length;a++) { if(tw.indexOf(vSConsonant[a])>=0) return true }
}
test=tw.substr(0,1)
if((t==3)&&((test=="A")||(test=="O")||(test=="U")||(test=="Y"))) return true
if((t==5)&&((test=="E")||(test=="I")||(test=="Y"))) return true
uw2=unV2(tw)
if(uw2==notV2) return true
if(tw!=twE) for(z=0;z<noE.length;z++) if(uw2==noE[z]) return true
if((tw!=uw)&&(uw2==noBE)) return true
if(uk!=moc) for(z=0;z<oMoc.length;z++) if(tw==oMoc[z]) return true
if((uw2.indexOf('UYE')>0)&&(uk=='E')) check=false
if((them.indexOf(uk)>=0)&&(check)) {
for(a=0;a<noAOEW.length;a++) if(uw2.indexOf(noAOEW[a])>=0) return true
if(uk!=trang) if(uw2==noAOE) return true
if((uk==trang)&&(trang!='W')) if(uw2==noT) return true
if(uk==moc) for(a=0;a<noM.length;a++) if(uw2==noM[a]) return true
if((uk==moc)||(uk==trang)) for(a=0;a<noMT.length;a++) if(uw2==noMT[a]) return true
}
tw5=tw
if((uw2.charCodeAt(0)==272)||(uw2.charCodeAt(0)==273)) { if(uw2.length>4) return true }
else if(uw2.length>3) return true
return false
}
function DAWEOF(cc,k) {
var ret=new Array(),kA=new Array(A,moc,trang,E,O),z,a;ret[0]=g
var ccA=new Array(aA,mocA,trangA,eA,oA),ccrA=new Array(arA,mocrA,arA,erA,orA)
for(a=0;a<kA.length;a++) if(k==kA[a]) for(z=0;z<ccA[a].length;z++) if(cc==ccA[a][z]) ret[1]=ccrA[a][z]
if(ret[1]) return ret
else return false
}
function findC(w,k,sf) {
if(((method==3)||(method==4))&&(w.substr(w.length-1,1)=="\\")) return new Array(1,k.charCodeAt(0))
var str="",res,cc="",pc="",tE="",vowA=new Array(),s="ÂĂÊÔƠƯ",c=0,dn=false,uw=w.toUpperCase(),tv;spellerr(w,k)
var DAWEOFA=aA.join()+eA.join()+mocA.join()+trangA.join()+oA.join()+english;DAWEOFA=DAWEOFA.toUpperCase()
for(g=0;g<sf.length;g++) {
if(isNaN(sf[g])) str+=sf[g]
else str+=fcc(sf[g])
}
var uk=k.toUpperCase(),i=w.length,uni_array=repSign(k),w2=unV2(unV(w).toUpperCase()),dont="ƯA,ƯU".split(',')
if (DAWEO.indexOf(uk)>=0) {
if(uk==moc) {
if((w2.indexOf("UU")>=0)&&(tw5!=dont[1])) {
if(w2.indexOf("UU")==(w.length-2)) res=2
else return false
} else if(w2.indexOf("UOU")>=0) {
if(w2.indexOf("UOU")==(w.length-3)) res=2
else return false
}
}
if(!res) {
for(g=1;g<=w.length;g++) {
cc=w.substr(w.length-g,1)
pc=w.substr(w.length-g-1,1).toUpperCase()
uc=cc.toUpperCase()
for(h=0;h<dont.length;h++) if((tw5==dont[h])&&(tw5==unV(pc+uc))) dn=true
if(dn) { dn=false; continue }
if(str.indexOf(uc)>=0) {
if(((uk==moc)&&(unV(uc)=="U")&&(unV(w.substr(w.length-g+1,1)).toUpperCase()=="A"))||((uk==trang)&&(unV(uc)=='A')&&(unV(pc)=='U'))) {
if(unV(uc)=="U") tv=1
else tv=2
ccc=w.substr(w.length-g-tv,1).toUpperCase()
if(ccc!="Q") res=g+tv-1
else if(uk==trang) res=g
else if(moc!=trang) return false
} else res=g
if((!whit)||(uw.indexOf("Ư")<0)||(uw.indexOf("W")<0)) break
} else if(DAWEOFA.indexOf(uc)>=0) {
if(uk==D) {
if(cc=="đ") res=new Array(g,'d')
else if(cc=="Đ") res=new Array(g,'D')
} else res=DAWEOF(cc,uk)
if(res) break
}
}
}
}
if((uk!=Z)&&(DAWEO.indexOf(uk)<0)) { var tEC=retKC(uk); for (g=0;g<tEC.length;g++) tE+=fcc(tEC[g]) }
for(g=1;g<=w.length;g++) {
if(DAWEO.indexOf(uk)<0) {
cc=w.substr(w.length-g,1).toUpperCase()
pc=w.substr(w.length-g-1,1).toUpperCase()
if(str.indexOf(cc)>=0) {
if(cc=='U') {
if(pc!='Q') { c++;vowA[vowA.length]=g }
} else if(cc=='I') {
if((pc!='G')||(c<=0)) { c++;vowA[vowA.length]=g }
} else { c++;vowA[vowA.length]=g }
} else if(uk!=Z) {
for(h=0;h<uni_array.length;h++) if(uni_array[h]==w.charCodeAt(w.length-g)) {
if(spellerr(w,k)) return false
return new Array(g,tEC[h%24])
}
for(h=0;h<tEC.length;h++) if(tEC[h]==w.charCodeAt(w.length-g)) return new Array(g,fcc(skey[h]))
}
}
}
if((uk!=Z)&&(typeof(res)!='object')) if(spellerr(w,k)) return false
if(DAWEO.indexOf(uk)<0) {
for(g=1;g<=w.length;g++) {
if((uk!=Z)&&(s.indexOf(w.substr(w.length-g,1).toUpperCase())>=0)) return g
else if(tE.indexOf(w.substr(w.length-g,1))>=0) {
for(h=0;h<tEC.length;h++) {
if(w.substr(w.length-g,1).charCodeAt(0)==tEC[h]) return new Array(g,fcc(skey[h]))
}
}
}
}
if(res) return res
if((c==1)||(uk==Z)) return vowA[0]
else if(c==2) {
var v=2
if(w.substr(w.length-1)==" ") v=3
var ttt=w.substr(w.length-v,2).toUpperCase()
if((dauCu==0)&&((ttt=="UY")||(ttt=="OA")||(ttt=="OE"))) return vowA[0]
var c2=0,fdconsonant,sc="BCD"+fcc(272)+"GHKLMNPQRSTVX",dc="CH,GI,KH,NGH,GH,NG,NH,PH,QU,TH,TR".split(',')
for(h=1;h<=w.length;h++) {
fdconsonant=false
for(g=0;g<dc.length;g++) {
if(w.substr(w.length-h-dc[g].length+1,dc[g].length).toUpperCase().indexOf(dc[g])>=0) {
c2++;fdconsonant=true
if(dc[g]!='NGH') h++
else h+=2
}
}
if(!fdconsonant) {
if(sc.indexOf(w.substr(w.length-h,1).toUpperCase())>=0) c2++
else break
}
}
if((c2==1)||(c2==2)) return vowA[0]
else return vowA[1]
} else if(c==3) return vowA[1]
else return false
}
function unV(w) {
var u=repSign(null),b,a
for(a=1;a<=w.length;a++) {
for(b=0;b<u.length;b++) {
if(u[b]==w.charCodeAt(w.length-a)) {
w=w.substr(0,w.length-a)+fcc(skey[b%24])+w.substr(w.length-a+1)
}
}
}
return w
}
function unV2(w) {
var a,b
for(a=1;a<=w.length;a++) {
for(b=0;b<skey.length;b++) {
if(skey[b]==w.charCodeAt(w.length-a)) {
w=w.substr(0,w.length-a)+skey2[b]+w.substr(w.length-a+1)
}
}
}
return w
}
function repSign(k) {
var t=new Array(),u=new Array(),a,b
for(a=0;a<5;a++) {
if((k==null)||(SFJRX.substr(a,1)!=k.toUpperCase())) {
t=retKC(SFJRX.substr(a,1))
for(b=0;b<t.length;b++) u[u.length]=t[b]
}
}
return u
}
function sr(w,k,i) {
var sf=getSF()
pos=findC(w,k,sf)
if(pos) {
if(pos[1]) {
if(!is_ie) replaceChar(oc,i-pos[0],pos[1])
else return ie_replaceChar(w,pos[0],pos[1])
} else {
var c=retUni(w,k,pos)
if (!is_ie) replaceChar(oc,i-pos,c)
else return ie_replaceChar(w,pos,c)
}
}
return false
}
function retUni(w,k,pos) {
var u=retKC(k.toUpperCase()),uC,lC,c=w.charCodeAt(w.length-pos),a
for (a=0;a<skey.length;a++) if (skey[a]==c) {
if (a<12) { lC=a;uC=a+12 }
else { lC=a-12;uC=a }
if (fcc(c)!=fcc(c).toUpperCase()) return u[lC]
return u[uC]
}
}
function replaceChar(o,pos,c) {
var bb=false; if(!isNaN(c)) { var replaceBy=fcc(c),wfix=unV(fcc(c)).toUpperCase(); changed=true }
else { var replaceBy=c; if((c.toUpperCase()=="O")&&(whit)) bb=true }
if(!o.data) {
var savePos=o.selectionStart,sst=o.scrollTop
if ((o.value.substr(pos-1,1).toUpperCase()=='U')&&(pos<savePos-1)&&(o.value.substr(pos-2,1).toUpperCase()!='Q')) {
if((wfix=="Ơ")||(bb))
{
if (o.value.substr(pos-1,1)=='u') var r=fcc(432)
else var r=fcc(431)
}
if(bb) {
changed=true; if(c=="o") replaceBy="ơ"
else replaceBy="Ơ"
}
}
o.setSelectionRange(pos,pos+1)
o.value=o.value.substr(0,o.selectionStart)+replaceBy+o.value.substr(o.selectionEnd)
if(r) {
o.setSelectionRange(pos-1,pos)
o.value=o.value.substr(0,o.selectionStart)+r+o.value.substr(o.selectionEnd)
}
o.setSelectionRange(savePos,savePos); o.scrollTop=sst
} else {
if ((o.data.substr(pos-1,1).toUpperCase()=='U')&&(pos<o.pos-1)) {
if((wfix=="Ơ")||(bb))
{
if (o.data.substr(pos-1,1)=='u') var r=fcc(432)
else var r=fcc(431)
}
if(bb) {
changed=true; if(c=="o") replaceBy="ơ"
else replaceBy="Ơ"
}
}
o.deleteData(pos,1); o.insertData(pos,replaceBy)
if(r) { o.deleteData(pos-1,1); o.insertData(pos-1,r) }
}
if(whit) whit=false
}
function retKC(k) {
if(k==S) return new Array(225,7845,7855,233,7871,237,243,7889,7899,250,7913,253,193,7844,7854,201,7870,205,211,7888,7898,218,7912,221)
if(k==F) return new Array(224,7847,7857,232,7873,236,242,7891,7901,249,7915,7923,192,7846,7856,200,7872,204,210,7890,7900,217,7914,7922)
if(k==J) return new Array(7841,7853,7863,7865,7879,7883,7885,7897,7907,7909,7921,7925,7840,7852,7862,7864,7878,7882,7884,7896,7906,7908,7920,7924)
if(k==R) return new Array(7843,7849,7859,7867,7875,7881,7887,7893,7903,7911,7917,7927,7842,7848,7858,7866,7874,7880,7886,7892,7902,7910,7916,7926)
if(k==X) return new Array(227,7851,7861,7869,7877,297,245,7895,7905,361,7919,7929,195,7850,7860,7868,7876,296,213,7894,7904,360,7918,7928)
}
function getEL(id) { return document.getElementById(id) }
function getSF() { var sf=new Array(),x; for(x=0;x<skey.length;x++) sf[sf.length]=fcc(skey[x]); return sf }
function statusMessage() {
var str='Kiểu gõ: '
if(on_off==0) str+='Tắt'
else if(method==1) str+='TELEX'
else if(method==2) str+='VNI'
else if(method==3) str+='VIQR'
else if(method==4) str+='VIQR*'
else if(method==0) str+='Tự động'
str+=" [F9] | Chính tả: "
str+=(dockspell==0)?"Tắt":"Bật"
str+=" [F8] | Bỏ dấu: "
str+=(dauCu==1)?"Cũ":"Mới"
str+=" [F7] | Bật/Tắt [F12] - AVIM 20060628"
window.status=str
}
function updateInfo() { setCookie(); if(support) statusMessage() }
function setMethod(m) {
if(m==-1) { on_off=0; if(getEL(radioID[5])) getEL(radioID[5]).checked=true }
else { on_off=1; method=m; if(getEL(radioID[m])) getEL(radioID[m]).checked=true }
setSpell(dockspell); setDauCu(dauCu); updateInfo()
}
function setDauCu(box) {
if(typeof(box)=="number") {
dauCu=box; if(getEL(radioID[7])) getEL(radioID[7]).checked=box
} else dauCu=(box.checked)?1:0
updateInfo()
}
function setSpell(box) {
if(typeof(box)=="number") {
spellerr=(box==1)?ckspell:nospell
if(getEL(radioID[6])) getEL(radioID[6]).checked=box
}
else {
if(box.checked) { spellerr=ckspell; dockspell=1 }
else { spellerr=nospell; dockspell=0 }
}
updateInfo()
}
function onKeyDown(e) {
if (e=='iframe') { frame=findF(); var key=frame.event.keyCode }
else var key=(!is_ie)?e.which:window.event.keyCode
if((key==120)||(key==123)||(key==119)||(key==118)) {
if(key==120) { on_off=1; setMethod(((method==4)?0:++method)) }
else if(key==118) { setDauCu(((dauCu==1)?0:1)) }
else if(key==119) { dockspell=(dockspell==0)?1:0; setSpell(dockspell) }
else if(key==123) {
on_off=(on_off==0)?1:0
if(on_off==0) setMethod(-1)
else setMethod(method)
}
updateInfo()
}
}
function ifInit(w) {
var sel=w.getSelection();w.focus()
range=sel?sel.getRangeAt(0):document.createRange()
}
function ifMoz(e) {
if((e.ctrlKey)||((e.altKey)&&(code!=92)&&(code!=126))) return;ifInit(e.target.parentNode.wi)
var code=e.which,node=range.endContainer;sk=fcc(code);saveStr=""
if(checkCode(code)||(!range.startOffset)||(typeof(node.data)=='undefined')) return;node.sel=false
if(node.data) {
saveStr=node.data.substr(range.endOffset)
if(range.startOffset!=range.endOffset) node.sel=true
node.deleteData(range.startOffset,node.data.length)
}
range.setEnd(node,range.endOffset)
range.setStart(node,0)
if(!node.data) return
node.value=node.data; node.pos=node.data.length; node.which=code
start(node,e)
node.insertData(node.data.length,saveStr)
range.setEnd(node,node.data.length-saveStr.length+kl)
range.setStart(node,node.data.length-saveStr.length+kl); kl=0
if(changed) { changed=false; e.preventDefault() }
}
function FKeyPress() {
var obj=findF()
sk=fcc(obj.event.keyCode)
if(checkCode(obj.event.keyCode)||((obj.event.ctrlKey)&&(obj.event.keyCode!=92)&&(obj.event.keyCode!=126))) return
start(obj,fcc(obj.event.keyCode))
}
function checkCode(code) { if(((on_off==0)||((code<45)&&(code!=42))||(code==145)||(code==255))&&(code!=32)&&(code!=39)&&(code!=40)&&(code!=43)) return true }
function fcc(x) { return String.fromCharCode(x) }
if(useCookie==1) { setCookie=doSetCookie; getCookie=doGetCookie }
else { setCookie=noCookie; getCookie=noCookie }
function noCookie() {}
function doSetCookie() {
var exp=new Date(11245711156480).toGMTString()
document.cookie='HIM_on_off='+on_off+';expires='+exp
document.cookie='HIM_method='+method+';expires='+exp
document.cookie='HIM_ckspell='+dockspell+';expires='+exp
document.cookie='HIM_daucu='+dauCu+';expires='+exp
}
function doGetCookie() {
var ck=document.cookie, res=/HIM_method/.test(ck)
if((!res)||(ck.indexOf('HIM_ckspell')<0)) { setCookie(); return }
var p,ckA=ck.split(';')
for(var i=0;i<ckA.length;i++) {
p=ckA[i].split('='); p[0]=p[0].replace(/^\s+/g,""); p[1]=parseInt(p[1])
if(p[0]=='HIM_on_off') on_off=p[1]
else if(p[0]=='HIM_method') method=p[1]
else if(p[0]=='HIM_ckspell') {
if(p[1]==0) { dockspell=0; spellerr=nospell }
else { dockspell=1; spellerr=ckspell }
} else if(p[0]=='HIM_daucu') dauCu=parseInt(p[1])
}
}
if(!is_ie) {
if(agt.indexOf("opera")<0) {
ver=agt.substr(agt.indexOf("rv:")+3)
ver=parseFloat(ver.substr(0,ver.indexOf(" ")))
if(agt.indexOf("mozilla")<0) ver=0
} else {
operaV=agt.split(" ")
if(parseInt(operaV[operaV.length-1])>=8) is_opera=true
else {
operaV=operaV[0].split("/")
if(parseInt(operaV[1])>=8) is_opera=true
}
}
}
if((is_ie)||(ver>=1.3)||(is_opera)) {
getCookie()
if(on_off==0) setMethod(-1)
else setMethod(method)
setSpell(dockspell);setDauCu(dauCu);statusMessage()
} else support=false
document.onkeydown=function(e) { onKeyDown(e) }
document.onkeypress=function(e) {
if(!support) return
if(!is_ie) { var el=e.target,code=e.which; if(e.ctrlKey) return; if((e.altKey)&&(code!=92)&&(code!=126)) return }
else { var el=window.event.srcElement,code=window.event.keyCode; if((event.ctrlKey)&&(code!=92)&&(code!=126)) return }
if(((el.type!='textarea')&&(el.type!='text'))||checkCode(code)) return
sk=fcc(code); for(i=0;i<va.length;i++) if((el.id==va[i])&&(va[i].length>0)) return
if(!is_ie) start(el,e)
else start(el,sk)
if(changed) { changed=false; return false }
}
function findF() {
for(g=0;g<fID.length;g++) {
frame=document.frames[fID[g]]
if((typeof(frame)!='undefined')&&(frame.document)&&(frame.event)) return frame
}
}
function init() {
if((support)&&(!is_opera)&&(fID.length>0)) {
for(g=0;g<fID.length;g++) {
if(is_ie) {
frame=document.frames[fID[g]]
if((typeof(frame)!='undefined')&&(frame.document)) {
doc=frame.document;doc.designMode="On"
doc.onkeydown=function() { onKeyDown('iframe') }
doc.onkeypress=function() { FKeyPress(); if(changed) { changed=false; return false } }
}
} else {
if(getEL(fID[g])) {
wi=getEL(fID[g]).contentWindow;iframedit=wi.document;iframedit.wi=wi;iframedit.designMode="On"
iframedit.addEventListener("keypress",ifMoz,false)
iframedit.addEventListener("keydown",onKeyDown,true)
}
}
}
}
}
function uglyF() { ugly=50;while(ugly<5000) {setTimeout("init()",ugly);ugly+=50} }
uglyF();document.onmousedown=function(e) { uglyF() } | JavaScript |
/*
Simple Image Trail script- By JavaScriptKit.com
Visit http://www.javascriptkit.com for this script and more
This notice must stay intact
*/
var offsetfrommouse=[15,25]; //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration=0; //duration in seconds image should remain visible. 0 for always.
var defaultimageheight = 40; // maximum image size.
var defaultimagewidth = 40; // maximum image size.
var timer;
function gettrailobj(){
if (document.getElementById)
return document.getElementById("preview_div").style
}
function gettrailobjnostyle(){
if (document.getElementById)
return document.getElementById("preview_div")
}
function truebody(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function hidetrail(){
gettrailobj().display= "none";
document.onmousemove=""
gettrailobj().left="-500px"
clearTimeout(timer);
}
function showtrail(imagename,title,width,height){
i = imagename
t = title
w = width
h = height
timer = setTimeout("show('"+i+"',t,w,h);",200);
}
function show(imagename,title,width,height){
var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth - offsetfrommouse[0]
var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)
if( (navigator.userAgent.indexOf("Konqueror")==-1 || navigator.userAgent.indexOf("Firefox")!=-1 || (navigator.userAgent.indexOf("Opera")==-1 && navigator.appVersion.indexOf("MSIE")!=-1)) && (docwidth>650 && docheight>500)) {
( width == 0 ) ? width = defaultimagewidth: '';
( height == 0 ) ? height = defaultimageheight: '';
width+=30;
height+=40;
defaultimageheight = height;
defaultimagewidth = width;
document.onmousemove=followmouse;
newHTML = '<div class="border_preview" style="width:'+ width +'px;height:'+ height +'px"><div id="loader_container"><div id="loader"><div align="center">Loading...</div><div id="loader_bg"><div id="progress"> </div></div></div></div>';
newHTML = newHTML + '<h2 class="preview_title">' + ' '+title + '</h2>'
newHTML = newHTML + '<div align="center"><img onload="javascript:remove_loading();" src="' + imagename + '" border="0"></div>';
newHTML = newHTML + '</div>';
if(navigator.userAgent.indexOf("MSIE")!=-1 && navigator.userAgent.indexOf("Opera")==-1 ){
newHTML = newHTML+'<iframe src="about:blank" scrolling="no" frameborder="0" width="'+width+'" height="'+height+'"></iframe>';
}
gettrailobjnostyle().innerHTML = newHTML;
gettrailobj().display="block";
}
}
function followmouse(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)
if (typeof e != "undefined"){
if (docwidth - e.pageX < defaultimagewidth + 2*offsetfrommouse[0]){
xcoord = e.pageX - xcoord - defaultimagewidth; // Move to the left side of the cursor
} else {
xcoord += e.pageX;
}
if (docheight - e.pageY < defaultimageheight + 2*offsetfrommouse[1]){
ycoord += e.pageY - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + e.pageY - docheight - truebody().scrollTop));
} else {
ycoord += e.pageY;
}
} else if (typeof window.event != "undefined"){
if (docwidth - event.clientX < defaultimagewidth + 2*offsetfrommouse[0]){
xcoord = event.clientX + truebody().scrollLeft - xcoord - defaultimagewidth; // Move to the left side of the cursor
} else {
xcoord += truebody().scrollLeft+event.clientX
}
if (docheight - event.clientY < (defaultimageheight + 2*offsetfrommouse[1])){
ycoord += event.clientY + truebody().scrollTop - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + event.clientY - docheight));
} else {
ycoord += truebody().scrollTop + event.clientY;
}
}
gettrailobj().left=xcoord+"px"
gettrailobj().top=ycoord+"px"
}
| JavaScript |
/*
* Image preview script
* powered by jQuery (http://www.jquery.com)
*
* written by Alen Grakalic (http://cssglobe.com)
*
* for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
*
*/
this.imagePreview = function(){
/* CONFIG */
xOffset = 10;
yOffset = 30;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$("a.preview").hover(function(e){
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");
$("#preview")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px")
.fadeIn("fast");
},
function(){
this.title = this.t;
$("#preview").remove();
});
$("a.preview").mousemove(function(e){
$("#preview")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px");
});
};
// starting the script on page load
$(document).ready(function(){
imagePreview();
}); | JavaScript |
/*
* nyroModal - jQuery Plugin
* http://nyromodal.nyrodev.com
*
* Copyright (c) 2008 Cedric Nirousset (nyrodev.com)
* Licensed under the MIT license
*
* Include this file AFTER nyroModal if you want absolutely no animation with nyroModal
*
* $Date: 2008-06-24 (Tue, 24 Jun 2008) $
* $version: 1.2.8
*/
jQuery(function($) {
$.fn.nyroModal.settings.showBackground = function(elts, settings, callback) {
elts.bg.css({opacity:0.75});
callback();
};
$.fn.nyroModal.settings.hideBackground = function(elts, settings, callback) {
elts.bg.hide();
callback();
};
$.fn.nyroModal.settings.showContent = function(elts, settings, callback) {
elts.contentWrapper
.css({
width: settings.width+'px',
marginLeft: (settings.marginLeft)+'px',
height: settings.height+'px',
marginTop: (settings.marginTop)+'px'
})
.show()
callback();
};
$.fn.nyroModal.settings.hideContent = function(elts, settings, callback) {
elts.contentWrapper.hide();
callback();
};
$.fn.nyroModal.settings.showLoading = function(elts, settings, callback) {
var h = elts.loading.height();
var w = elts.loading.width();
elts.loading
.css({
height: h+'px',
width: w+'px',
marginTop: (-h/2 + settings.marginScrollTop)+'px',
marginLeft: (-w/2 + settings.marginScrollLeft)+'px'
})
.show();
callback();
};
$.fn.nyroModal.settings.hideLoading = function(elts, settings, callback) {
elts.loading.hide();
callback();
};
$.fn.nyroModal.settings.showTransition = function(elts, settings, callback) {
// Put the loading with the same dimensions of the current content
elts.loading
.css({
marginTop: elts.contentWrapper.css('marginTop'),
marginLeft: elts.contentWrapper.css('marginLeft'),
height: elts.contentWrapper.css('height'),
width: elts.contentWrapper.css('width')
})
.show();
elts.contentWrapper.hide();
callback();
};
$.fn.nyroModal.settings.hideTransition = function(elts, settings, callback) {
// Place the content wrapper underneath the the loading with the right dimensions
elts.contentWrapper
.css({
width: settings.width+'px',
marginLeft: (settings.marginLeft)+'px',
height: settings.height+'px',
marginTop: (settings.marginTop)+'px'
})
.show();
elts.loading.hide();
callback();
};
$.fn.nyroModal.settings.resize = function(elts, settings, callback) {
elts.contentWrapper
.css({
width: settings.width+'px',
marginLeft: (settings.marginLeft)+'px',
height: settings.height+'px',
marginTop: (settings.marginTop)+'px'
});
callback();
};
$.fn.nyroModal.settings.updateBgColor = function(elts, settings, callback) {
elts.bg.css({backgroundColor: settings.bgColor});
callback();
};
}); | JavaScript |
(function($){
/* hoverIntent by Brian Cherne */
$.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]);
};
// A private function for handling mouse 'hovering'
var handleHover = function(e) {
// next three 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 ) { return false; }
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
var ob = this;
// 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 |
Site = {
MainMenu: function() {
$('#header .tab-center:not(.active-tab-center)').bind('mouseenter', function() {
$(this).addClass('active-tab-center')
.prev()
.addClass('active-tab-left')
.end()
.next()
.addClass('active-tab-right');
})
.bind('mouseleave', function() {
$(this).removeClass('active-tab-center')
.prev()
.removeClass('active-tab-left')
.end()
.next()
.removeClass('active-tab-right');
});
},
SideMenu: function() {
$('#content-left h3 a').click(function() {
if (!$(this).parent().hasClass('active')) {
$('#content-left h3.active')
.siblings('a')
.hide('normal')
.removeClass('active')
.end()
.removeClass('active')
.find('img')
.attr('src', 'common/img/small_arrow_collapsed.gif');
$(this).parent()
.addClass('active')
.find('img')
.attr('src', 'common/img/small_arrow_expanded.gif')
.parents('.menu-category')
.children('a')
.show('normal')
.addClass('active');
}
return false;
});
$('#content-left .menu-category a').click(function() {
$(this).next('.menu-inner').find('a').toggleClass('active');
return false;
});
},
InfoBox: function() {
var links = $('#info-top a');
var pictures = $('#info-content img');
var contents = $('#box-content > div');
links.click(function() {
pictures.removeClass('active');
contents.removeClass('box-content-active');
contents.addClass('box-content-inactive');
$('#' + this.id + '-picture').addClass('active');
$('#' + this.id + '-box').removeClass('box-content-inactive');
$('#' + this.id + '-box').addClass('box-content-active');
return false;
});
},
Buttons: function() {
$('.button').hover(function() {
var src = $(this).attr('src');
$(this).attr('src', src.replace('.gif', '_active.gif'));
},
function() {
var src = $(this).attr('src');
$(this).attr('src', src.replace('_active.gif', '.gif'));
});
},
Footer: function() {
$('a.more').toggle(
function() {
$(this).parents('#footer-box')
.css('background-position', '0 -43px')
.height('142px')
.find('#footer-separator, #footer-links')
.show();
return false;
},
function() {
$(this).parents('#footer-box')
.css('background-position', '0 0')
.height('32px')
.find('#footer-separator, #footer-links')
.hide();
return false;
}
);
},
FancyBox: function() {
$('a.fancy-box').fancybox({
hideOnContentClick: true
});
$("#lightbox_trigger").fancybox({hideOnContentClick: true});
$("#lightbox_trigger").trigger('click');
},
Checkboxes: function() {
$("#content-right input.input-radio").CheckImg('checkbox_inactive.gif', 'checkbox_active.gif', 'common/img/');
$("#news input.input-radio").CheckImg('checkbox_inactive.gif', 'checkbox_active.gif', 'common/img/');
},
SliderNews: function() {
$("#nowosci").jCarouselLite({
btnNext: "#news-left",
btnPrev: "#news-right",
mouseWheel: false,
auto: 2000,
speed: 300,
//easing: "linear",
//easing: "easein",
easing: "easeout",
//easing: "easeinout",
//easing: "expoin",
//easing: "expoout",
//easing: "expoinout",
//easing: "bounceout",
//easing: "bouncein",
//easing: "bounceinout",
//easing: "elasin",
//easing: "elasout",
//easing: "elasinout",
//easing: "backin",
//easing: "backout",
//easing: "backinout",
visible: 3,
vertical: false,
circular: true,
start: 0,
scroll: 1,
beforeStart: function(a) {
//alert("Before animation starts:" + a);
},
afterEnd: function(a) {
//alert("After animation ends:" + a);
}
});
},
SliderPromo1: function() {
$("#promocje").jCarouselLite({
btnNext: "#promo-left",
btnPrev: "#promo-right",
mouseWheel: false,
/*autoneg: 7000,*/
speed: 500,
//easing: "linear",
//easing: "easein",
//easing: "easeout",
//easing: "easeinout",
//easing: "expoin",
//easing: "expoout",
//easing: "expoinout",
//easing: "bounceout",
//easing: "bouncein",
//easing: "bounceinout",
//easing: "elasin",
//easing: "elasout",
//easing: "elasinout",
easing: "backin",
//easing: "backout",
//easing: "backinout",
visible: 2,
vertical: false,
circular: true,
start: 0,
scroll: 1,
beforeStart: function(a) {
//alert("Before animation starts:" + a);
},
afterEnd: function(a) {
//alert("After animation ends:" + a);
}
});
},
SliderPromo2: function() {
$("#promocje2").jCarouselLite({
btnNext: "#promo-left",
btnPrev: "#promo-right",
mouseWheel: false,
/*autoneg: 7000,*/
speed: 500,
//easing: "linear",
//easing: "easein",
//easing: "easeout",
//easing: "easeinout",
//easing: "expoin",
//easing: "expoout",
//easing: "expoinout",
//easing: "bounceout",
//easing: "bouncein",
//easing: "bounceinout",
//easing: "elasin",
//easing: "elasout",
//easing: "elasinout",
easing: "backin",
//easing: "backout",
//easing: "backinout",
visible: 3,
vertical: false,
circular: true,
start: 0,
scroll: 1,
beforeStart: function(a) {
//alert("Before animation starts:" + a);
},
afterEnd: function(a) {
//alert("After animation ends:" + a);
}
});
},
SliderTop10: function(count) {
$("#top10_slide").jCarouselLite({
btnNext: "#top10-up",
btnPrev: "#top10-down",
mouseWheel: false,
speed: 500,
easing: "easeout",
visible: count,
vertical: true,
circular: true,
start: 0,
scroll: 1
});
},
run: function() {
this.MainMenu();
//this.SideMenu();
this.InfoBox();
this.Buttons();
this.Footer();
this.FancyBox();
this.Checkboxes();
this.SliderNews();
this.SliderPromo1();
this.SliderPromo2();
var useragent = navigator.userAgent;
var bName = (useragent.indexOf('Opera') > -1) ? 'Opera' : navigator.appName;
var pos = useragent.indexOf('MSIE');
if (pos > -1) {
bVer = useragent.substring(pos + 5);
var pos = bVer.indexOf(';');
var bVer = bVer.substring(0,pos);
}
var pos = useragent.indexOf('Opera');
if (pos > -1) {
bVer = useragent.substring(pos + 6);
var pos = bVer.indexOf(' ');
var bVer = bVer.substring(0, pos);
}
if (bName == "Netscape") {
var bVer = useragent.substring(8);
var pos = bVer.indexOf(' ');
var bVer = bVer.substring(0, pos);
}
if (bName == "Netscape" && parseInt(navigator.appVersion) >= 5) {
var pos = useragent.lastIndexOf('/');
var bVer = useragent.substring(pos + 1);
}
if(bVer == "6.0")
{
cnt = 5;
}
else if(bVer == "7.0")
{
cnt = 6;
}
else
{
cnt = 6;
}
this.SliderTop10(cnt);
}
}
$(function() {
Site.run();
}); | JavaScript |
// ===================================================================
// Author: Matt Kruse <matt@ajaxtoolbox.com>
// WWW: http://www.AjaxToolbox.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================
/**
* The AjaxRequest class is a wrapper for the XMLHttpRequest objects which
* are available in most modern browsers. It simplifies the interfaces for
* making Ajax requests, adds commonly-used convenience methods, and makes
* the process of handling state changes more intuitive.
* An object may be instantiated and used, or the Class methods may be used
* which internally create an AjaxRequest object.
*/
function AjaxRequest() {
var req = new Object();
// -------------------
// Instance properties
// -------------------
/**
* Timeout period (in ms) until an async request will be aborted, and
* the onTimeout function will be called
*/
req.timeout = null;
/**
* Since some browsers cache GET requests via XMLHttpRequest, an
* additional parameter called AjaxRequestUniqueId will be added to
* the request URI with a unique numeric value appended so that the requested
* URL will not be cached.
*/
req.generateUniqueUrl = true;
/**
* The url that the request will be made to, which defaults to the current
* url of the window
*/
req.url = window.location.href;
/**
* The method of the request, either GET (default), POST, or HEAD
*/
req.method = "GET";
/**
* Whether or not the request will be asynchronous. In general, synchronous
* requests should not be used so this should rarely be changed from true
*/
req.async = true;
/**
* The username used to access the URL
*/
req.username = null;
/**
* The password used to access the URL
*/
req.password = null;
/**
* The parameters is an object holding name/value pairs which will be
* added to the url for a GET request or the request content for a POST request
*/
req.parameters = new Object();
/**
* The sequential index number of this request, updated internally
*/
req.requestIndex = AjaxRequest.numAjaxRequests++;
/**
* Indicates whether a response has been received yet from the server
*/
req.responseReceived = false;
/**
* The name of the group that this request belongs to, for activity
* monitoring purposes
*/
req.groupName = null;
/**
* The query string to be added to the end of a GET request, in proper
* URIEncoded format
*/
req.queryString = "";
/**
* After a response has been received, this will hold the text contents of
* the response - even in case of error
*/
req.responseText = null;
/**
* After a response has been received, this will hold the XML content
*/
req.responseXML = null;
/**
* After a response has been received, this will hold the status code of
* the response as returned by the server.
*/
req.status = null;
/**
* After a response has been received, this will hold the text description
* of the response code
*/
req.statusText = null;
/**
* An internal flag to indicate whether the request has been aborted
*/
req.aborted = false;
/**
* The XMLHttpRequest object used internally
*/
req.xmlHttpRequest = null;
// --------------
// Event handlers
// --------------
/**
* If a timeout period is set, and it is reached before a response is
* received, a function reference assigned to onTimeout will be called
*/
req.onTimeout = null;
/**
* A function reference assigned will be called when readyState=1
*/
req.onLoading = null;
/**
* A function reference assigned will be called when readyState=2
*/
req.onLoaded = null;
/**
* A function reference assigned will be called when readyState=3
*/
req.onInteractive = null;
/**
* A function reference assigned will be called when readyState=4
*/
req.onComplete = null;
/**
* A function reference assigned will be called after onComplete, if
* the statusCode=200
*/
req.onSuccess = null;
/**
* A function reference assigned will be called after onComplete, if
* the statusCode != 200
*/
req.onError = null;
/**
* If this request has a group name, this function reference will be called
* and passed the group name if this is the first request in the group to
* become active
*/
req.onGroupBegin = null;
/**
* If this request has a group name, and this request is the last request
* in the group to complete, this function reference will be called
*/
req.onGroupEnd = null;
// Get the XMLHttpRequest object itself
req.xmlHttpRequest = AjaxRequest.getXmlHttpRequest();
if (req.xmlHttpRequest==null) { return null; }
// -------------------------------------------------------
// Attach the event handlers for the XMLHttpRequest object
// -------------------------------------------------------
req.xmlHttpRequest.onreadystatechange =
function() {
if (req==null || req.xmlHttpRequest==null) { return; }
if (req.xmlHttpRequest.readyState==1) { req.onLoadingInternal(req); }
if (req.xmlHttpRequest.readyState==2) { req.onLoadedInternal(req); }
if (req.xmlHttpRequest.readyState==3) { req.onInteractiveInternal(req); }
if (req.xmlHttpRequest.readyState==4) { req.onCompleteInternal(req); }
};
// ---------------------------------------------------------------------------
// Internal event handlers that fire, and in turn fire the user event handlers
// ---------------------------------------------------------------------------
// Flags to keep track if each event has been handled, in case of
// multiple calls (some browsers may call the onreadystatechange
// multiple times for the same state)
req.onLoadingInternalHandled = false;
req.onLoadedInternalHandled = false;
req.onInteractiveInternalHandled = false;
req.onCompleteInternalHandled = false;
req.onLoadingInternal =
function() {
if (req.onLoadingInternalHandled) { return; }
AjaxRequest.numActiveAjaxRequests++;
if (AjaxRequest.numActiveAjaxRequests==1 && typeof(window['AjaxRequestBegin'])=="function") {
AjaxRequestBegin();
}
if (req.groupName!=null) {
if (typeof(AjaxRequest.numActiveAjaxGroupRequests[req.groupName])=="undefined") {
AjaxRequest.numActiveAjaxGroupRequests[req.groupName] = 0;
}
AjaxRequest.numActiveAjaxGroupRequests[req.groupName]++;
if (AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==1 && typeof(req.onGroupBegin)=="function") {
req.onGroupBegin(req.groupName);
}
}
if (typeof(req.onLoading)=="function") {
req.onLoading(req);
}
req.onLoadingInternalHandled = true;
};
req.onLoadedInternal =
function() {
if (req.onLoadedInternalHandled) { return; }
if (typeof(req.onLoaded)=="function") {
req.onLoaded(req);
}
req.onLoadedInternalHandled = true;
};
req.onInteractiveInternal =
function() {
if (req.onInteractiveInternalHandled) { return; }
if (typeof(req.onInteractive)=="function") {
req.onInteractive(req);
}
req.onInteractiveInternalHandled = true;
};
req.onCompleteInternal =
function() {
if (req.onCompleteInternalHandled || req.aborted) { return; }
req.onCompleteInternalHandled = true;
AjaxRequest.numActiveAjaxRequests--;
if (AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function") {
AjaxRequestEnd(req.groupName);
}
if (req.groupName!=null) {
AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--;
if (AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function") {
req.onGroupEnd(req.groupName);
}
}
req.responseReceived = true;
req.status = req.xmlHttpRequest.status;
req.statusText = req.xmlHttpRequest.statusText;
req.responseText = req.xmlHttpRequest.responseText;
req.responseXML = req.xmlHttpRequest.responseXML;
if (typeof(req.onComplete)=="function") {
req.onComplete(req);
}
if (req.xmlHttpRequest.status==200 && typeof(req.onSuccess)=="function") {
req.onSuccess(req);
}
else if (typeof(req.onError)=="function") {
req.onError(req);
}
// Clean up so IE doesn't leak memory
delete req.xmlHttpRequest['onreadystatechange'];
req.xmlHttpRequest = null;
};
req.onTimeoutInternal =
function() {
if (req!=null && req.xmlHttpRequest!=null && !req.onCompleteInternalHandled) {
req.aborted = true;
req.xmlHttpRequest.abort();
AjaxRequest.numActiveAjaxRequests--;
if (AjaxRequest.numActiveAjaxRequests==0 && typeof(window['AjaxRequestEnd'])=="function") {
AjaxRequestEnd(req.groupName);
}
if (req.groupName!=null) {
AjaxRequest.numActiveAjaxGroupRequests[req.groupName]--;
if (AjaxRequest.numActiveAjaxGroupRequests[req.groupName]==0 && typeof(req.onGroupEnd)=="function") {
req.onGroupEnd(req.groupName);
}
}
if (typeof(req.onTimeout)=="function") {
req.onTimeout(req);
}
// Opera won't fire onreadystatechange after abort, but other browsers do.
// So we can't rely on the onreadystate function getting called. Clean up here!
delete req.xmlHttpRequest['onreadystatechange'];
req.xmlHttpRequest = null;
}
};
// ----------------
// Instance methods
// ----------------
/**
* The process method is called to actually make the request. It builds the
* querystring for GET requests (the content for POST requests), sets the
* appropriate headers if necessary, and calls the
* XMLHttpRequest.send() method
*/
req.process =
function() {
if (req.xmlHttpRequest!=null) {
// Some logic to get the real request URL
if (req.generateUniqueUrl && req.method=="GET") {
req.parameters["AjaxRequestUniqueId"] = new Date().getTime() + "" + req.requestIndex;
}
var content = null; // For POST requests, to hold query string
for (var i in req.parameters) {
if (req.queryString.length>0) { req.queryString += "&"; }
req.queryString += encodeURIComponent(i) + "=" + encodeURIComponent(req.parameters[i]);
}
if (req.method=="GET") {
if (req.queryString.length>0) {
req.url += ((req.url.indexOf("?")>-1)?"&":"?") + req.queryString;
}
}
req.xmlHttpRequest.open(req.method,req.url,req.async,req.username,req.password);
if (req.method=="POST") {
if (typeof(req.xmlHttpRequest.setRequestHeader)!="undefined") {
req.xmlHttpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
content = req.queryString;
}
if (req.timeout>0) {
setTimeout(req.onTimeoutInternal,req.timeout);
}
req.xmlHttpRequest.send(content);
}
};
/**
* An internal function to handle an Object argument, which may contain
* either AjaxRequest field values or parameter name/values
*/
req.handleArguments =
function(args) {
for (var i in args) {
// If the AjaxRequest object doesn't have a property which was passed, treat it as a url parameter
if (typeof(req[i])=="undefined") {
req.parameters[i] = args[i];
}
else {
req[i] = args[i];
}
}
};
/**
* Returns the results of XMLHttpRequest.getAllResponseHeaders().
* Only available after a response has been returned
*/
req.getAllResponseHeaders =
function() {
if (req.xmlHttpRequest!=null) {
if (req.responseReceived) {
return req.xmlHttpRequest.getAllResponseHeaders();
}
alert("Cannot getAllResponseHeaders because a response has not yet been received");
}
};
/**
* Returns the the value of a response header as returned by
* XMLHttpRequest,getResponseHeader().
* Only available after a response has been returned
*/
req.getResponseHeader =
function(headerName) {
if (req.xmlHttpRequest!=null) {
if (req.responseReceived) {
return req.xmlHttpRequest.getResponseHeader(headerName);
}
alert("Cannot getResponseHeader because a response has not yet been received");
}
};
return req;
}
// ---------------------------------------
// Static methods of the AjaxRequest class
// ---------------------------------------
/**
* Returns an XMLHttpRequest object, either as a core object or an ActiveX
* implementation. If an object cannot be instantiated, it will return null;
*/
AjaxRequest.getXmlHttpRequest = function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// Based on http://jibbering.com/2002/4/httprequest.html
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
return null;
}
}
@end @*/
}
else {
return null;
}
};
/**
* See if any request is active in the background
*/
AjaxRequest.isActive = function() {
return (AjaxRequest.numActiveAjaxRequests>0);
};
/**
* Make a GET request. Pass an object containing parameters and arguments as
* the second argument.
* These areguments may be either AjaxRequest properties to set on the request
* object or name/values to set in the request querystring.
*/
AjaxRequest.get = function(args) {
AjaxRequest.doRequest("GET",args);
};
/**
* Make a POST request. Pass an object containing parameters and arguments as
* the second argument.
* These areguments may be either AjaxRequest properties to set on the request
* object or name/values to set in the request querystring.
*/
AjaxRequest.post = function(args) {
AjaxRequest.doRequest("POST",args);
};
/**
* The internal method used by the .get() and .post() methods
*/
AjaxRequest.doRequest = function(method,args) {
if (typeof(args)!="undefined" && args!=null) {
var myRequest = new AjaxRequest();
myRequest.method = method;
myRequest.handleArguments(args);
myRequest.process();
}
} ;
/**
* Submit a form. The requested URL will be the form's ACTION, and the request
* method will be the form's METHOD.
* Returns true if the submittal was handled successfully, else false so it
* can easily be used with an onSubmit event for a form, and fallback to
* submitting the form normally.
*/
AjaxRequest.submit = function(theform, args) {
var myRequest = new AjaxRequest();
if (myRequest==null) { return false; }
var serializedForm = AjaxRequest.serializeForm(theform);
myRequest.method = theform.method.toUpperCase();
myRequest.url = theform.action;
myRequest.handleArguments(args);
myRequest.queryString = serializedForm;
myRequest.process();
return true;
};
/**
* Serialize a form into a format which can be sent as a GET string or a POST
* content.It correctly ignores disabled fields, maintains order of the fields
* as in the elements[] array. The 'file' input type is not supported, as
* its content is not available to javascript. This method is used internally
* by the submit class method.
*/
AjaxRequest.serializeForm = function(theform) {
var els = theform.elements;
var len = els.length;
var queryString = "";
this.addField =
function(name,value) {
if (queryString.length>0) {
queryString += "&";
}
queryString += encodeURIComponent(name) + "=" + encodeURIComponent(value);
};
for (var i=0; i<len; i++) {
var el = els[i];
if (!el.disabled) {
switch(el.type) {
case 'text': case 'password': case 'hidden': case 'textarea':
this.addField(el.name,el.value);
break;
case 'select-one':
if (el.selectedIndex>=0) {
this.addField(el.name,el.options[el.selectedIndex].value);
}
break;
case 'select-multiple':
for (var j=0; j<el.options.length; j++) {
if (el.options[j].selected) {
this.addField(el.name,el.options[j].value);
}
}
break;
case 'checkbox': case 'radio':
if (el.checked) {
this.addField(el.name,el.value);
}
break;
}
}
}
return queryString;
};
// -----------------------
// Static Class variables
// -----------------------
/**
* The number of total AjaxRequest objects currently active and running
*/
AjaxRequest.numActiveAjaxRequests = 0;
/**
* An object holding the number of active requests for each group
*/
AjaxRequest.numActiveAjaxGroupRequests = new Object();
/**
* The total number of AjaxRequest objects instantiated
*/
AjaxRequest.numAjaxRequests = 0;
| JavaScript |
/*!
* jQuery JavaScript Library v1.3.2
* http://jquery.com/
*
* Copyright (c) 2009 John Resig
* Dual licensed under the MIT and GPL licenses.
* http://docs.jquery.com/License
*
* Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
* Revision: 6246
*/
(function(){
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/;
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
// Handle $(DOMElement)
if ( selector.nodeType ) {
this[0] = selector;
this.length = 1;
this.context = selector;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
var match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] )
selector = jQuery.clean( [ match[1] ], context );
// HANDLE: $("#id")
else {
var elem = document.getElementById( match[3] );
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem && elem.id != match[3] )
return jQuery().find( selector );
// Otherwise, we inject the element directly into the jQuery object
var ret = jQuery( elem || [] );
ret.context = document;
ret.selector = selector;
return ret;
}
// HANDLE: $(expr, [context])
// (which is just equivalent to: $(content).find(expr)
} else
return jQuery( context ).find( selector );
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) )
return jQuery( document ).ready( selector );
// Make sure that old selector state is passed along
if ( selector.selector && selector.context ) {
this.selector = selector.selector;
this.context = selector.context;
}
return this.setArray(jQuery.isArray( selector ) ?
selector :
jQuery.makeArray(selector));
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.3.2",
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num === undefined ?
// Return a 'clean' array
Array.prototype.slice.call( this ) :
// Return just the object
this[ num ];
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery( elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" )
ret.selector = this.selector + (this.selector ? " " : "") + selector;
else if ( name )
ret.selector = this.selector + "." + name + "(" + selector + ")";
// Return the newly-formed element set
return ret;
},
// Force the current matched set of elements to become
// the specified array of elements (destroying the stack in the process)
// You should use pushStack() in order to do this, but maintain the stack
setArray: function( elems ) {
// Resetting the length to 0, then using the native Array push
// is a super-fast way to populate an object with array-like properties
this.length = 0;
Array.prototype.push.apply( this, elems );
return this;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem && elem.jquery ? elem[0] : elem
, this );
},
attr: function( name, value, type ) {
var options = name;
// Look for the case where we're accessing a style value
if ( typeof name === "string" )
if ( value === undefined )
return this[0] && jQuery[ type || "attr" ]( this[0], name );
else {
options = {};
options[ name ] = value;
}
// Check to see if we're setting style values
return this.each(function(i){
// Set all the styles
for ( name in options )
jQuery.attr(
type ?
this.style :
this,
name, jQuery.prop( this, options[ name ], type, i, name )
);
});
},
css: function( key, value ) {
// ignore negative width and height values
if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
value = undefined;
return this.attr( key, value, "curCSS" );
},
text: function( text ) {
if ( typeof text !== "object" && text != null )
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
var ret = "";
jQuery.each( text || this, function(){
jQuery.each( this.childNodes, function(){
if ( this.nodeType != 8 )
ret += this.nodeType != 1 ?
this.nodeValue :
jQuery.fn.text( [ this ] );
});
});
return ret;
},
wrapAll: function( html ) {
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).clone();
if ( this[0].parentNode )
wrap.insertBefore( this[0] );
wrap.map(function(){
var elem = this;
while ( elem.firstChild )
elem = elem.firstChild;
return elem;
}).append(this);
}
return this;
},
wrapInner: function( html ) {
return this.each(function(){
jQuery( this ).contents().wrapAll( html );
});
},
wrap: function( html ) {
return this.each(function(){
jQuery( this ).wrapAll( html );
});
},
append: function() {
return this.domManip(arguments, true, function(elem){
if (this.nodeType == 1)
this.appendChild( elem );
});
},
prepend: function() {
return this.domManip(arguments, true, function(elem){
if (this.nodeType == 1)
this.insertBefore( elem, this.firstChild );
});
},
before: function() {
return this.domManip(arguments, false, function(elem){
this.parentNode.insertBefore( elem, this );
});
},
after: function() {
return this.domManip(arguments, false, function(elem){
this.parentNode.insertBefore( elem, this.nextSibling );
});
},
end: function() {
return this.prevObject || jQuery( [] );
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: [].push,
sort: [].sort,
splice: [].splice,
find: function( selector ) {
if ( this.length === 1 ) {
var ret = this.pushStack( [], "find", selector );
ret.length = 0;
jQuery.find( selector, this[0], ret );
return ret;
} else {
return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
return jQuery.find( selector, elem );
})), "find", selector );
}
},
clone: function( events ) {
// Do the clone
var ret = this.map(function(){
if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var html = this.outerHTML;
if ( !html ) {
var div = this.ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
html = div.innerHTML;
}
return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
} else
return this.cloneNode(true);
});
// Copy the events from the original to the clone
if ( events === true ) {
var orig = this.find("*").andSelf(), i = 0;
ret.find("*").andSelf().each(function(){
if ( this.nodeName !== orig[i].nodeName )
return;
var events = jQuery.data( orig[i], "events" );
for ( var type in events ) {
for ( var handler in events[ type ] ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
}
}
i++;
});
}
// Return the cloned set
return ret;
},
filter: function( selector ) {
return this.pushStack(
jQuery.isFunction( selector ) &&
jQuery.grep(this, function(elem, i){
return selector.call( elem, i );
}) ||
jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
return elem.nodeType === 1;
}) ), "filter", selector );
},
closest: function( selector ) {
var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
closer = 0;
return this.map(function(){
var cur = this;
while ( cur && cur.ownerDocument ) {
if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
jQuery.data(cur, "closest", closer);
return cur;
}
cur = cur.parentNode;
closer++;
}
});
},
not: function( selector ) {
if ( typeof selector === "string" )
// test special case where just one selector is passed in
if ( isSimple.test( selector ) )
return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
else
selector = jQuery.multiFilter( selector, this );
var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
return this.filter(function() {
return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
});
},
add: function( selector ) {
return this.pushStack( jQuery.unique( jQuery.merge(
this.get(),
typeof selector === "string" ?
jQuery( selector ) :
jQuery.makeArray( selector )
)));
},
is: function( selector ) {
return !!selector && jQuery.multiFilter( selector, this ).length > 0;
},
hasClass: function( selector ) {
return !!selector && this.is( "." + selector );
},
val: function( value ) {
if ( value === undefined ) {
var elem = this[0];
if ( elem ) {
if( jQuery.nodeName( elem, 'option' ) )
return (elem.attributes.value || {}).specified ? elem.value : elem.text;
// We need to handle select boxes special
if ( jQuery.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type == "select-one";
// Nothing was selected
if ( index < 0 )
return null;
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
if ( option.selected ) {
// Get the specifc value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one )
return value;
// Multi-Selects return an array
values.push( value );
}
}
return values;
}
// Everything else, we just grab the value
return (elem.value || "").replace(/\r/g, "");
}
return undefined;
}
if ( typeof value === "number" )
value += '';
return this.each(function(){
if ( this.nodeType != 1 )
return;
if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
this.checked = (jQuery.inArray(this.value, value) >= 0 ||
jQuery.inArray(this.name, value) >= 0);
else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(value);
jQuery( "option", this ).each(function(){
this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
jQuery.inArray( this.text, values ) >= 0);
});
if ( !values.length )
this.selectedIndex = -1;
} else
this.value = value;
});
},
html: function( value ) {
return value === undefined ?
(this[0] ?
this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
null) :
this.empty().append( value );
},
replaceWith: function( value ) {
return this.after( value ).remove();
},
eq: function( i ) {
return this.slice( i, +i + 1 );
},
slice: function() {
return this.pushStack( Array.prototype.slice.apply( this, arguments ),
"slice", Array.prototype.slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function(elem, i){
return callback.call( elem, i, elem );
}));
},
andSelf: function() {
return this.add( this.prevObject );
},
domManip: function( args, table, callback ) {
if ( this[0] ) {
var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
first = fragment.firstChild;
if ( first )
for ( var i = 0, l = this.length; i < l; i++ )
callback.call( root(this[i], first), this.length > 1 || i > 0 ?
fragment.cloneNode(true) : fragment );
if ( scripts )
jQuery.each( scripts, evalScript );
}
return this;
function root( elem, cur ) {
return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
}
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
function evalScript( i, elem ) {
if ( elem.src )
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
else
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
if ( elem.parentNode )
elem.parentNode.removeChild( elem );
}
function now(){
return +new Date;
}
jQuery.extend = jQuery.fn.extend = function() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) )
target = {};
// extend jQuery itself if only one argument is passed
if ( length == i ) {
target = this;
--i;
}
for ( ; i < length; i++ )
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null )
// Extend the base object
for ( var name in options ) {
var src = target[ name ], copy = options[ name ];
// Prevent never-ending loop
if ( target === copy )
continue;
// Recurse if we're merging object values
if ( deep && copy && typeof copy === "object" && !copy.nodeType )
target[ name ] = jQuery.extend( deep,
// Never move original objects, clone them
src || ( copy.length != null ? [ ] : { } )
, copy );
// Don't bring in undefined values
else if ( copy !== undefined )
target[ name ] = copy;
}
// Return the modified object
return target;
};
// exclude the following css properties to add px
var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
// cache defaultView
defaultView = document.defaultView || {},
toString = Object.prototype.toString;
jQuery.extend({
noConflict: function( deep ) {
window.$ = _$;
if ( deep )
window.jQuery = _jQuery;
return jQuery;
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return toString.call(obj) === "[object Function]";
},
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
// check if an element is in a (or is an) XML document
isXMLDoc: function( elem ) {
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
},
// Evalulates a script in a global context
globalEval: function( data ) {
if ( data && /\S/.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if ( jQuery.support.scriptEval )
script.appendChild( document.createTextNode( data ) );
else
script.text = data;
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
},
prop: function( elem, value, type, i, name ) {
// Handle executable functions
if ( jQuery.isFunction( value ) )
value = value.call( elem, i );
// Handle passing in a number to a CSS property
return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
value + "px" :
value;
},
className: {
// internal only, use addClass("class")
add: function( elem, classNames ) {
jQuery.each((classNames || "").split(/\s+/), function(i, className){
if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
elem.className += (elem.className ? " " : "") + className;
});
},
// internal only, use removeClass("class")
remove: function( elem, classNames ) {
if (elem.nodeType == 1)
elem.className = classNames !== undefined ?
jQuery.grep(elem.className.split(/\s+/), function(className){
return !jQuery.className.has( classNames, className );
}).join(" ") :
"";
},
// internal only, use hasClass("class")
has: function( elem, className ) {
return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( var name in options )
elem.style[ name ] = old[ name ];
},
css: function( elem, name, force, extra ) {
if ( name == "width" || name == "height" ) {
var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
function getWH() {
val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" )
return;
jQuery.each( which, function() {
if ( !extra )
val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
if ( extra === "margin" )
val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
else
val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
});
}
if ( elem.offsetWidth !== 0 )
getWH();
else
jQuery.swap( elem, props, getWH );
return Math.max(0, Math.round(val));
}
return jQuery.curCSS( elem, name, force );
},
curCSS: function( elem, name, force ) {
var ret, style = elem.style;
// We need to handle opacity special in IE
if ( name == "opacity" && !jQuery.support.opacity ) {
ret = jQuery.attr( style, "opacity" );
return ret == "" ?
"1" :
ret;
}
// Make sure we're using the right name for getting the float value
if ( name.match( /float/i ) )
name = styleFloat;
if ( !force && style && style[ name ] )
ret = style[ name ];
else if ( defaultView.getComputedStyle ) {
// Only "float" is needed here
if ( name.match( /float/i ) )
name = "float";
name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
var computedStyle = defaultView.getComputedStyle( elem, null );
if ( computedStyle )
ret = computedStyle.getPropertyValue( name );
// We should always get a number back from opacity
if ( name == "opacity" && ret == "" )
ret = "1";
} else if ( elem.currentStyle ) {
var camelCase = name.replace(/\-(\w)/g, function(all, letter){
return letter.toUpperCase();
});
ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
// Remember the original values
var left = style.left, rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
elem.runtimeStyle.left = elem.currentStyle.left;
style.left = ret || 0;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
elem.runtimeStyle.left = rsLeft;
}
}
return ret;
},
clean: function( elems, context, fragment ) {
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" )
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
if ( match )
return [ context.createElement( match[1] ) ];
}
var ret = [], scripts = [], div = context.createElement("div");
jQuery.each(elems, function(i, elem){
if ( typeof elem === "number" )
elem += '';
if ( !elem )
return;
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
all :
front + "></" + tag + ">";
});
// Trim whitespace, otherwise indexOf won't work as expected
var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
var wrap =
// option or optgroup
!tags.indexOf("<opt") &&
[ 1, "<select multiple='multiple'>", "</select>" ] ||
!tags.indexOf("<leg") &&
[ 1, "<fieldset>", "</fieldset>" ] ||
tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
[ 1, "<table>", "</table>" ] ||
!tags.indexOf("<tr") &&
[ 2, "<table><tbody>", "</tbody></table>" ] ||
// <thead> matched above
(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
!tags.indexOf("<col") &&
[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
// IE can't serialize <link> and <script> tags normally
!jQuery.support.htmlSerialize &&
[ 1, "div<div>", "</div>" ] ||
[ 0, "", "" ];
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( wrap[0]-- )
div = div.lastChild;
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = /<tbody/i.test(elem),
tbody = !tags.indexOf("<table") && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] == "<table>" && !hasBody ?
div.childNodes :
[];
for ( var j = tbody.length - 1; j >= 0 ; --j )
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
elem = jQuery.makeArray( div.childNodes );
}
if ( elem.nodeType )
ret.push( elem );
else
ret = jQuery.merge( ret, elem );
});
if ( fragment ) {
for ( var i = 0; ret[i]; i++ ) {
if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 )
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
fragment.appendChild( ret[i] );
}
}
return scripts;
}
return ret;
},
attr: function( elem, name, value ) {
// don't set attributes on text and comment nodes
if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
return undefined;
var notxml = !jQuery.isXMLDoc( elem ),
// Whether we are setting (or getting)
set = value !== undefined;
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
// Only do all the following if this is a node (faster for style)
// IE elem.getAttribute passes even for style
if ( elem.tagName ) {
// These attributes require special treatment
var special = /href|src|style/.test( name );
// Safari mis-reports the default selected property of a hidden option
// Accessing the parent's selectedIndex property fixes it
if ( name == "selected" && elem.parentNode )
elem.parentNode.selectedIndex;
// If applicable, access the attribute via the DOM 0 way
if ( name in elem && notxml && !special ) {
if ( set ){
// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
throw "type property can't be changed";
elem[ name ] = value;
}
// browsers index elements by id/name on forms, give priority to attributes.
if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
return elem.getAttributeNode( name ).nodeValue;
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
if ( name == "tabIndex" ) {
var attributeNode = elem.getAttributeNode( "tabIndex" );
return attributeNode && attributeNode.specified
? attributeNode.value
: elem.nodeName.match(/(button|input|object|select|textarea)/i)
? 0
: elem.nodeName.match(/^(a|area)$/i) && elem.href
? 0
: undefined;
}
return elem[ name ];
}
if ( !jQuery.support.style && notxml && name == "style" )
return jQuery.attr( elem.style, "cssText", value );
if ( set )
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
var attr = !jQuery.support.hrefNormalized && notxml && special
// Some attributes require a special call on IE
? elem.getAttribute( name, 2 )
: elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return attr === null ? undefined : attr;
}
// elem is actually elem.style ... set the style
// IE uses filters for opacity
if ( !jQuery.support.opacity && name == "opacity" ) {
if ( set ) {
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
elem.zoom = 1;
// Set the alpha filter to set the opacity
elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
}
return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
"";
}
name = name.replace(/-([a-z])/ig, function(all, letter){
return letter.toUpperCase();
});
if ( set )
elem[ name ] = value;
return elem[ name ];
},
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
},
makeArray: function( array ) {
var ret = [];
if( array != null ){
var i = array.length;
// The window, strings (and functions) also have 'length'
if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
ret[0] = array;
else
while( i )
ret[--i] = array[i];
}
return ret;
},
inArray: function( elem, array ) {
for ( var i = 0, length = array.length; i < length; i++ )
// Use === because on IE, window == document
if ( array[ i ] === elem )
return i;
return -1;
},
merge: function( first, second ) {
// We have to loop this way because IE & Opera overwrite the length
// expando of getElementsByTagName
var i = 0, elem, pos = first.length;
// Also, we need to make sure that the correct elements are being returned
// (IE returns comment nodes in a '*' query)
if ( !jQuery.support.getAll ) {
while ( (elem = second[ i++ ]) != null )
if ( elem.nodeType != 8 )
first[ pos++ ] = elem;
} else
while ( (elem = second[ i++ ]) != null )
first[ pos++ ] = elem;
return first;
},
unique: function( array ) {
var ret = [], done = {};
try {
for ( var i = 0, length = array.length; i < length; i++ ) {
var id = jQuery.data( array[ i ] );
if ( !done[ id ] ) {
done[ id ] = true;
ret.push( array[ i ] );
}
}
} catch( e ) {
ret = array;
}
return ret;
},
grep: function( elems, callback, inv ) {
var ret = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ )
if ( !inv != !callback( elems[ i ], i ) )
ret.push( elems[ i ] );
return ret;
},
map: function( elems, callback ) {
var ret = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
var value = callback( elems[ i ], i );
if ( value != null )
ret[ ret.length ] = value;
}
return ret.concat.apply( [], ret );
}
});
// Use of jQuery.browser is deprecated.
// It's included for backwards compatibility and plugins,
// although they should work to migrate away.
var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
jQuery.each({
parent: function(elem){return elem.parentNode;},
parents: function(elem){return jQuery.dir(elem,"parentNode");},
next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
children: function(elem){return jQuery.sibling(elem.firstChild);},
contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
}, function(name, fn){
jQuery.fn[ name ] = function( selector ) {
var ret = jQuery.map( this, fn );
if ( selector && typeof selector == "string" )
ret = jQuery.multiFilter( selector, ret );
return this.pushStack( jQuery.unique( ret ), name, selector );
};
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(name, original){
jQuery.fn[ name ] = function( selector ) {
var ret = [], insert = jQuery( selector );
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, selector );
};
});
jQuery.each({
removeAttr: function( name ) {
jQuery.attr( this, name, "" );
if (this.nodeType == 1)
this.removeAttribute( name );
},
addClass: function( classNames ) {
jQuery.className.add( this, classNames );
},
removeClass: function( classNames ) {
jQuery.className.remove( this, classNames );
},
toggleClass: function( classNames, state ) {
if( typeof state !== "boolean" )
state = !jQuery.className.has( this, classNames );
jQuery.className[ state ? "add" : "remove" ]( this, classNames );
},
remove: function( selector ) {
if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
// Prevent memory leaks
jQuery( "*", this ).add([this]).each(function(){
jQuery.event.remove(this);
jQuery.removeData(this);
});
if (this.parentNode)
this.parentNode.removeChild( this );
}
},
empty: function() {
// Remove element nodes and prevent memory leaks
jQuery(this).children().remove();
// Remove any remaining nodes
while ( this.firstChild )
this.removeChild( this.firstChild );
}
}, function(name, fn){
jQuery.fn[ name ] = function(){
return this.each( fn, arguments );
};
});
// Helper function used by the dimensions and offset modules
function num(elem, prop) {
return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
var expando = "jQuery" + now(), uuid = 0, windowData = {};
jQuery.extend({
cache: {},
data: function( elem, name, data ) {
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ];
// Compute a unique ID for the element
if ( !id )
id = elem[ expando ] = ++uuid;
// Only generate the data cache if we're
// trying to access or manipulate it
if ( name && !jQuery.cache[ id ] )
jQuery.cache[ id ] = {};
// Prevent overriding the named cache with undefined values
if ( data !== undefined )
jQuery.cache[ id ][ name ] = data;
// Return the named cache data, or the ID for the element
return name ?
jQuery.cache[ id ][ name ] :
id;
},
removeData: function( elem, name ) {
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ];
// If we want to remove a specific section of the element's data
if ( name ) {
if ( jQuery.cache[ id ] ) {
// Remove the section of cache data
delete jQuery.cache[ id ][ name ];
// If we've removed all the data, remove the element's cache
name = "";
for ( name in jQuery.cache[ id ] )
break;
if ( !name )
jQuery.removeData( elem );
}
// Otherwise, we want to remove all of the element's data
} else {
// Clean up the element expando
try {
delete elem[ expando ];
} catch(e){
// IE has trouble directly removing the expando
// but it's ok with using removeAttribute
if ( elem.removeAttribute )
elem.removeAttribute( expando );
}
// Completely remove the data cache
delete jQuery.cache[ id ];
}
},
queue: function( elem, type, data ) {
if ( elem ){
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type );
if ( !q || jQuery.isArray(data) )
q = jQuery.data( elem, type, jQuery.makeArray(data) );
else if( data )
q.push( data );
}
return q;
},
dequeue: function( elem, type ){
var queue = jQuery.queue( elem, type ),
fn = queue.shift();
if( !type || type === "fx" )
fn = queue[0];
if( fn !== undefined )
fn.call(elem);
}
});
jQuery.fn.extend({
data: function( key, value ){
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
if ( data === undefined && this.length )
data = jQuery.data( this[0], key );
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else
return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
jQuery.data( this, key, value );
});
},
removeData: function( key ){
return this.each(function(){
jQuery.removeData( this, key );
});
},
queue: function(type, data){
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined )
return jQuery.queue( this[0], type );
return this.each(function(){
var queue = jQuery.queue( this, type, data );
if( type == "fx" && queue.length == 1 )
queue[0].call(this);
});
},
dequeue: function(type){
return this.each(function(){
jQuery.dequeue( this, type );
});
}
});/*!
* Sizzle CSS Selector Engine - v0.9.3
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
done = 0,
toString = Object.prototype.toString;
var Sizzle = function(selector, context, results, seed) {
results = results || [];
context = context || document;
if ( context.nodeType !== 1 && context.nodeType !== 9 )
return [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, check, mode, extra, prune = true;
// Reset the position of the chunker regexp (start from head)
chunker.lastIndex = 0;
while ( (m = chunker.exec(selector)) !== null ) {
parts.push( m[1] );
if ( m[2] ) {
extra = RegExp.rightContext;
break;
}
}
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] )
selector += parts.shift();
set = posProcess( selector, set );
}
}
} else {
var ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
set = Sizzle.filter( ret.expr, ret.set );
if ( parts.length > 0 ) {
checkSet = makeArray(set);
} else {
prune = false;
}
while ( parts.length ) {
var cur = parts.pop(), pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, isXML(context) );
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
throw "Syntax error, unrecognized expression: " + (cur || selector);
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context.nodeType === 1 ) {
for ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, context, results, seed );
if ( sortOrder ) {
hasDuplicate = false;
results.sort(sortOrder);
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[i-1] ) {
results.splice(i--, 1);
}
}
}
}
}
return results;
};
Sizzle.matches = function(expr, set){
return Sizzle(expr, null, null, set);
};
Sizzle.find = function(expr, context, isXML){
var set, match;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.match[ type ].exec( expr )) ) {
var left = RegExp.leftContext;
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.match[ type ].exec( expr )) != null ) {
var filter = Expr.filter[ type ], found, item;
anyFound = false;
if ( curLoop == result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr == old ) {
if ( anyFound == null ) {
throw "Syntax error, unrecognized expression: " + expr;
} else {
break;
}
}
old = expr;
}
return curLoop;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part, isXML){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag && !isXML ) {
part = part.toUpperCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part, isXML){
var isPartStr = typeof part === "string";
if ( isPartStr && !/\W/.test(part) ) {
part = isXML ? part : part.toUpperCase();
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName === part ? parent : false;
}
}
} else {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( !part.match(/\W/) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( typeof part === "string" && !part.match(/\W/) ) {
var nodeCheck = part = isXML ? part : part.toUpperCase();
checkFn = dirNodeCheck;
}
checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
}
},
find: {
ID: function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? [m] : [];
}
},
NAME: function(match, context, isXML){
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [], results = context.getElementsByName(match[1]);
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function(match, context){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
if ( !inplace )
result.push( elem );
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
for ( var i = 0; curLoop[i] === false; i++ ){}
return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
},
CHILD: function(match){
if ( match[1] == "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function(match, curLoop, inplace, result, not){
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( match[3].match(chunker).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function(match){
match.unshift( true );
return match;
}
},
filters: {
enabled: function(elem){
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function(elem){
return elem.disabled === true;
},
checked: function(elem){
return elem.checked === true;
},
selected: function(elem){
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function(elem){
return !!elem.firstChild;
},
empty: function(elem){
return !elem.firstChild;
},
has: function(elem, i, match){
return !!Sizzle( match[3], elem ).length;
},
header: function(elem){
return /h\d/i.test( elem.nodeName );
},
text: function(elem){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
},
input: function(elem){
return /input|select|textarea|button/i.test(elem.nodeName);
}
},
setFilters: {
first: function(elem, i){
return i === 0;
},
last: function(elem, i, match, array){
return i === array.length - 1;
},
even: function(elem, i){
return i % 2 === 0;
},
odd: function(elem, i){
return i % 2 === 1;
},
lt: function(elem, i, match){
return i < match[3] - 0;
},
gt: function(elem, i, match){
return i > match[3] - 0;
},
nth: function(elem, i, match){
return match[3] - 0 == i;
},
eq: function(elem, i, match){
return match[3] - 0 == i;
}
},
filter: {
PSEUDO: function(elem, match, i, array){
var name = match[1], filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var i = 0, l = not.length; i < l; i++ ) {
if ( not[i] === elem ) {
return false;
}
}
return true;
}
},
CHILD: function(elem, match){
var type = match[1], node = elem;
switch (type) {
case 'only':
case 'first':
while (node = node.previousSibling) {
if ( node.nodeType === 1 ) return false;
}
if ( type == 'first') return true;
node = elem;
case 'last':
while (node = node.nextSibling) {
if ( node.nodeType === 1 ) return false;
}
return true;
case 'nth':
var first = match[2], last = match[3];
if ( first == 1 && last == 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first == 0 ) {
return diff == 0;
} else {
return ( diff % first == 0 && diff / first >= 0 );
}
}
},
ID: function(elem, match){
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function(elem, match){
return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value != check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function(elem, match, i, array){
var name = match[2], filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS;
for ( var type in Expr.match ) {
Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
}
var makeArray = function(array, results) {
array = Array.prototype.slice.call( array );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
try {
Array.prototype.slice.call( document.documentElement.childNodes );
// Provide a fallback method if it does not work
} catch(e){
makeArray = function(array, results) {
var ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var i = 0, l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( var i = 0; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( "sourceIndex" in document.documentElement ) {
sortOrder = function( a, b ) {
var ret = a.sourceIndex - b.sourceIndex;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( document.createRange ) {
sortOrder = function( a, b ) {
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.selectNode(a);
aRange.collapse(true);
bRange.selectNode(b);
bRange.collapse(true);
var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("form"),
id = "script" + (new Date).getTime();
form.innerHTML = "<input name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
var root = document.documentElement;
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( !!document.getElementById( id ) ) {
Expr.find.ID = function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
}
};
Expr.filter.ID = function(elem, match){
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function(match, context){
var results = context.getElementsByTagName(match[1]);
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function(elem){
return elem.getAttribute("href", 2);
};
}
})();
if ( document.querySelectorAll ) (function(){
var oldSizzle = Sizzle, div = document.createElement("div");
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function(query, context, extra, seed){
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && context.nodeType === 9 && !isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
Sizzle.find = oldSizzle.find;
Sizzle.filter = oldSizzle.filter;
Sizzle.selectors = oldSizzle.selectors;
Sizzle.matches = oldSizzle.matches;
})();
if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
if ( div.getElementsByClassName("e").length === 0 )
return;
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 )
return;
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function(match, context, isXML) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ){
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
var sibDir = dir == "previousSibling" && !isXML;
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
if ( sibDir && elem.nodeType === 1 ) {
elem.sizcache = doneName;
elem.sizset = i;
}
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
var contains = document.compareDocumentPosition ? function(a, b){
return a.compareDocumentPosition(b) & 16;
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
var isXML = function(elem){
return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
!!elem.ownerDocument && isXML( elem.ownerDocument );
};
var posProcess = function(selector, context){
var tmpSet = [], later = "", match,
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.filter = Sizzle.filter;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
Sizzle.selectors.filters.hidden = function(elem){
return elem.offsetWidth === 0 || elem.offsetHeight === 0;
};
Sizzle.selectors.filters.visible = function(elem){
return elem.offsetWidth > 0 || elem.offsetHeight > 0;
};
Sizzle.selectors.filters.animated = function(elem){
return jQuery.grep(jQuery.timers, function(fn){
return elem === fn.elem;
}).length;
};
jQuery.multiFilter = function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return Sizzle.matches(expr, elems);
};
jQuery.dir = function( elem, dir ){
var matched = [], cur = elem[dir];
while ( cur && cur != document ) {
if ( cur.nodeType == 1 )
matched.push( cur );
cur = cur[dir];
}
return matched;
};
jQuery.nth = function(cur, result, dir, elem){
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] )
if ( cur.nodeType == 1 && ++num == result )
break;
return cur;
};
jQuery.sibling = function(n, elem){
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && n != elem )
r.push( n );
}
return r;
};
return;
window.Sizzle = Sizzle;
})();
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function(elem, types, handler, data) {
if ( elem.nodeType == 3 || elem.nodeType == 8 )
return;
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( elem.setInterval && elem != window )
elem = window;
// Make sure that the function being executed has a unique ID
if ( !handler.guid )
handler.guid = this.guid++;
// if data is passed, bind to handler
if ( data !== undefined ) {
// Create temporary function pointer to original handler
var fn = handler;
// Create unique handler function, wrapped around original handler
handler = this.proxy( fn );
// Store data in unique handler
handler.data = data;
}
// Init the element's event structure
var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply(arguments.callee.elem, arguments) :
undefined;
});
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native
// event in IE.
handle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
jQuery.each(types.split(/\s+/), function(index, type) {
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
handler.type = namespaces.slice().sort().join(".");
// Get the current list of functions bound to this event
var handlers = events[type];
if ( jQuery.event.specialAll[type] )
jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
// Init the event handler queue
if (!handlers) {
handlers = events[type] = {};
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
// Bind the global event handler to the element
if (elem.addEventListener)
elem.addEventListener(type, handle, false);
else if (elem.attachEvent)
elem.attachEvent("on" + type, handle);
}
}
// Add the function to the element's handler list
handlers[handler.guid] = handler;
// Keep track of which events have been used, for global triggering
jQuery.event.global[type] = true;
});
// Nullify elem to prevent memory leaks in IE
elem = null;
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function(elem, types, handler) {
// don't do events on text and comment nodes
if ( elem.nodeType == 3 || elem.nodeType == 8 )
return;
var events = jQuery.data(elem, "events"), ret, index;
if ( events ) {
// Unbind all events for the element
if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
for ( var type in events )
this.remove( elem, type + (types || "") );
else {
// types is actually an event object here
if ( types.type ) {
handler = types.handler;
types = types.type;
}
// Handle multiple events seperated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
jQuery.each(types.split(/\s+/), function(index, type){
// Namespaced event handlers
var namespaces = type.split(".");
type = namespaces.shift();
var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
if ( events[type] ) {
// remove the given handler for the given type
if ( handler )
delete events[type][handler.guid];
// remove all handlers for the given type
else
for ( var handle in events[type] )
// Handle the removal of namespaced events
if ( namespace.test(events[type][handle].type) )
delete events[type][handle];
if ( jQuery.event.specialAll[type] )
jQuery.event.specialAll[type].teardown.call(elem, namespaces);
// remove generic event handler if no more handlers exist
for ( ret in events[type] ) break;
if ( !ret ) {
if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
if (elem.removeEventListener)
elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
else if (elem.detachEvent)
elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
}
ret = null;
delete events[type];
}
}
});
}
// Remove the expando if it's no longer used
for ( ret in events ) break;
if ( !ret ) {
var handle = jQuery.data( elem, "handle" );
if ( handle ) handle.elem = null;
jQuery.removeData( elem, "events" );
jQuery.removeData( elem, "handle" );
}
}
},
// bubbling is internal
trigger: function( event, data, elem, bubbling ) {
// Event object or event type
var type = event.type || event;
if( !bubbling ){
event = typeof event === "object" ?
// jQuery.Event object
event[expando] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( this.global[type] )
jQuery.each( jQuery.cache, function(){
if ( this.events && this.events[type] )
jQuery.event.trigger( event, data, this.handle.elem );
});
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
return undefined;
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray(data);
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = jQuery.data(elem, "handle");
if ( handle )
handle.apply( elem, data );
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
event.result = false;
// Trigger the native events (except for clicks on links)
if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
this.triggered = true;
try {
elem[ type ]();
// prevent IE from throwing an error for some hidden elements
} catch (e) {}
}
this.triggered = false;
if ( !event.isPropagationStopped() ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent )
jQuery.event.trigger(event, data, parent, true);
}
},
handle: function(event) {
// returned undefined or false
var all, handlers;
event = arguments[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
// Namespaced event handlers
var namespaces = event.type.split(".");
event.type = namespaces.shift();
// Cache this now, all = true means, any handler
all = !namespaces.length && !event.exclusive;
var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
handlers = ( jQuery.data(this, "events") || {} )[event.type];
for ( var j in handlers ) {
var handler = handlers[j];
// Filter the functions by class
if ( all || namespace.test(handler.type) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handler;
event.data = handler.data;
var ret = handler.apply(this, arguments);
if( ret !== undefined ){
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if( event.isImmediatePropagationStopped() )
break;
}
}
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function(event) {
if ( event[expando] )
return event;
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ){
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target )
event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
// check if target is a textnode (safari)
if ( event.target.nodeType == 3 )
event.target = event.target.parentNode;
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement )
event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
}
// Add which for key events
if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
event.which = event.charCode || event.keyCode;
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey )
event.metaKey = event.ctrlKey;
// Add which for click: 1 == left; 2 == middle; 3 == right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button )
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
return event;
},
proxy: function( fn, proxy ){
proxy = proxy || function(){ return fn.apply(this, arguments); };
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
// So proxy can be declared as an argument
return proxy;
},
special: {
ready: {
// Make sure the ready event is setup
setup: bindReady,
teardown: function() {}
}
},
specialAll: {
live: {
setup: function( selector, namespaces ){
jQuery.event.add( this, namespaces[0], liveHandler );
},
teardown: function( namespaces ){
if ( namespaces.length ) {
var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
jQuery.each( (jQuery.data(this, "events").live || {}), function(){
if ( name.test(this.type) )
remove++;
});
if ( remove < 1 )
jQuery.event.remove( this, namespaces[0], liveHandler );
}
}
}
}
};
jQuery.Event = function( src ){
// Allow instantiation without the 'new' keyword
if( !this.preventDefault )
return new jQuery.Event(src);
// Event object
if( src && src.type ){
this.originalEvent = src;
this.type = src.type;
// Event type
}else
this.type = src;
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = now();
// Mark it as fixed
this[expando] = true;
};
function returnFalse(){
return false;
}
function returnTrue(){
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if( !e )
return;
// if preventDefault exists run it on the original event
if (e.preventDefault)
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
e.returnValue = false;
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if( !e )
return;
// if stopPropagation exists run it on the original event
if (e.stopPropagation)
e.stopPropagation();
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation:function(){
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Traverse up the tree
while ( parent && parent != this )
try { parent = parent.parentNode; }
catch(e) { parent = this; }
if( parent != this ){
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
};
jQuery.each({
mouseover: 'mouseenter',
mouseout: 'mouseleave'
}, function( orig, fix ){
jQuery.event.special[ fix ] = {
setup: function(){
jQuery.event.add( this, orig, withinElement, fix );
},
teardown: function(){
jQuery.event.remove( this, orig, withinElement );
}
};
});
jQuery.fn.extend({
bind: function( type, data, fn ) {
return type == "unload" ? this.one(type, data, fn) : this.each(function(){
jQuery.event.add( this, type, fn || data, fn && data );
});
},
one: function( type, data, fn ) {
var one = jQuery.event.proxy( fn || data, function(event) {
jQuery(this).unbind(event, one);
return (fn || data).apply( this, arguments );
});
return this.each(function(){
jQuery.event.add( this, type, one, fn && data);
});
},
unbind: function( type, fn ) {
return this.each(function(){
jQuery.event.remove( this, type, fn );
});
},
trigger: function( type, data ) {
return this.each(function(){
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if( this[0] ){
var event = jQuery.Event(type);
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0] );
return event.result;
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments, i = 1;
// link all the functions, so any of them can unbind this click handler
while( i < args.length )
jQuery.event.proxy( fn, args[i++] );
return this.click( jQuery.event.proxy( fn, function(event) {
// Figure out which function to execute
this.lastToggle = ( this.lastToggle || 0 ) % i;
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ this.lastToggle++ ].apply( this, arguments ) || false;
}));
},
hover: function(fnOver, fnOut) {
return this.mouseenter(fnOver).mouseleave(fnOut);
},
ready: function(fn) {
// Attach the listeners
bindReady();
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
fn.call( document, jQuery );
// Otherwise, remember the function for later
else
// Add the function to the wait list
jQuery.readyList.push( fn );
return this;
},
live: function( type, fn ){
var proxy = jQuery.event.proxy( fn );
proxy.guid += this.selector + type;
jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );
return this;
},
die: function( type, fn ){
jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
return this;
}
});
function liveHandler( event ){
var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
stop = true,
elems = [];
jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
if ( check.test(fn.type) ) {
var elem = jQuery(event.target).closest(fn.data)[0];
if ( elem )
elems.push({ elem: elem, fn: fn });
}
});
elems.sort(function(a,b) {
return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
});
jQuery.each(elems, function(){
if ( this.fn.call(this.elem, event, this.fn.data) === false )
return (stop = false);
});
return stop;
}
function liveConvert(type, selector){
return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
}
jQuery.extend({
isReady: false,
readyList: [],
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( jQuery.readyList ) {
// Execute all of them
jQuery.each( jQuery.readyList, function(){
this.call( document, jQuery );
});
// Reset the list of functions
jQuery.readyList = null;
}
// Trigger any bound ready events
jQuery(document).triggerHandler("ready");
}
}
});
var readyBound = false;
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
"change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
// Handle event binding
jQuery.fn[name] = function(fn){
return fn ? this.bind(name, fn) : this.trigger(name);
};
});
// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery( window ).bind( 'unload', function(){
for ( var id in jQuery.cache )
// Skip the window
if ( id != 1 && jQuery.cache[ id ].handle )
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
});
(function(){
jQuery.support = {};
var root = document.documentElement,
script = document.createElement("script"),
div = document.createElement("div"),
id = "script" + (new Date).getTime();
div.style.display = "none";
div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return;
}
jQuery.support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType == 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that you can get all elements in an <object> element
// IE 7 always returns no results
objectAll: !!div.getElementsByTagName("object")[0]
.getElementsByTagName("*").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText insted)
style: /red/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
opacity: a.style.opacity === "0.5",
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Will be defined later
scriptEval: false,
noCloneEvent: true,
boxModel: null
};
script.type = "text/javascript";
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e){}
root.insertBefore( script, root.firstChild );
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
if ( window[ id ] ) {
jQuery.support.scriptEval = true;
delete window[ id ];
}
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function(){
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", arguments.callee);
});
div.cloneNode(true).fireEvent("onclick");
}
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function(){
var div = document.createElement("div");
div.style.width = div.style.paddingLeft = "1px";
document.body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
document.body.removeChild( div ).style.display = 'none';
});
})();
var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";
jQuery.props = {
"for": "htmlFor",
"class": "className",
"float": styleFloat,
cssFloat: styleFloat,
styleFloat: styleFloat,
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
tabindex: "tabIndex"
};
jQuery.fn.extend({
// Keep a copy of the old load
_load: jQuery.fn.load,
load: function( url, params, callback ) {
if ( typeof url !== "string" )
return this._load( url );
var off = url.indexOf(" ");
if ( off >= 0 ) {
var selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params )
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if( typeof params === "object" ) {
params = jQuery.param( params );
type = "POST";
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function(res, status){
// If successful, inject the HTML into all the matched elements
if ( status == "success" || status == "notmodified" )
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div/>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
if( callback )
self.each( callback, [res.responseText, status, res] );
}
});
return this;
},
serialize: function() {
return jQuery.param(this.serializeArray());
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray(this.elements) : this;
})
.filter(function(){
return this.name && !this.disabled &&
(this.checked || /select|textarea/i.test(this.nodeName) ||
/text|hidden|password|search/i.test(this.type));
})
.map(function(i, elem){
var val = jQuery(this).val();
return val == null ? null :
jQuery.isArray(val) ?
jQuery.map( val, function(val, i){
return {name: elem.name, value: val};
}) :
{name: elem.name, value: val};
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
jQuery.fn[o] = function(f){
return this.bind(o, f);
};
});
var jsc = now();
jQuery.extend({
get: function( url, data, callback, type ) {
// shift arguments if data argument was ommited
if ( jQuery.isFunction( data ) ) {
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
username: null,
password: null,
*/
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
// This function can be overriden by calling jQuery.ajaxSetup
xhr:function(){
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
},
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
script: "text/javascript, application/javascript",
json: "application/json, text/javascript",
text: "text/plain",
_default: "*/*"
}
},
// Last-Modified header cache for next request
lastModified: {},
ajax: function( s ) {
// Extend the settings, but re-extend 's' so that it can be
// checked again later (in the test suite, specifically)
s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
var jsonp, jsre = /=\?(&|$)/g, status, data,
type = s.type.toUpperCase();
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" )
s.data = jQuery.param(s.data);
// Handle JSONP Parameter Callbacks
if ( s.dataType == "jsonp" ) {
if ( type == "GET" ) {
if ( !s.url.match(jsre) )
s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
} else if ( !s.data || !s.data.match(jsre) )
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
jsonp = "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 ] = function(tmp){
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try{ delete window[ jsonp ]; } catch(e){}
if ( head )
head.removeChild( script );
};
}
if ( s.dataType == "script" && s.cache == null )
s.cache = false;
if ( s.cache === false && type == "GET" ) {
var ts = now();
// try replacing _= if it is there
var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
// if nothing was replaced, add timestamp to the end
s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
}
// If data is available, append data to url for get requests
if ( s.data && type == "GET" ) {
s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
// IE likes to send both get and post data, prevent this
s.data = null;
}
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
jQuery.event.trigger( "ajaxStart" );
// Matches an absolute URL, and saves the domain
var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType == "script" && type == "GET" && parts
&& ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = s.url;
if (s.scriptCharset)
script.charset = s.scriptCharset;
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
}
head.appendChild(script);
// We handle everything using the script element injection
return undefined;
}
var requestDone = false;
// Create the request object
var xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if( s.username )
xhr.open(type, s.url, s.async, s.username, s.password);
else
xhr.open(type, s.url, s.async);
// Need an extra try/catch for cross domain requests in Firefox 3
try {
// Set the correct header, if data is being sent
if ( s.data )
xhr.setRequestHeader("Content-Type", s.contentType);
// Set the If-Modified-Since header, if ifModified mode.
if ( s.ifModified )
xhr.setRequestHeader("If-Modified-Since",
jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
// Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
s.accepts[ s.dataType ] + ", */*" :
s.accepts._default );
} catch(e){}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// close opended socket
xhr.abort();
return false;
}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xhr, s]);
// Wait for a response to come back
var onreadystatechange = function(isTimeout){
// The request was aborted, clear the interval and decrement jQuery.active
if (xhr.readyState == 0) {
if (ival) {
// clear poll interval
clearInterval(ival);
ival = null;
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
requestDone = true;
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
status = isTimeout == "timeout" ? "timeout" :
!jQuery.httpSuccess( xhr ) ? "error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
"success";
if ( status == "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch(e) {
status = "parsererror";
}
}
// Make sure that the request was successful or notmodified
if ( status == "success" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes;
try {
modRes = xhr.getResponseHeader("Last-Modified");
} catch(e) {} // swallow exception thrown by FF if header is not available
if ( s.ifModified && modRes )
jQuery.lastModified[s.url] = modRes;
// JSONP handles its own success callback
if ( !jsonp )
success();
} else
jQuery.handleError(s, xhr, status);
// Fire the complete handlers
complete();
if ( isTimeout )
xhr.abort();
// Stop memory leaks
if ( s.async )
xhr = null;
}
};
if ( s.async ) {
// don't attach the handler to the request, just poll it instead
var ival = setInterval(onreadystatechange, 13);
// Timeout checker
if ( s.timeout > 0 )
setTimeout(function(){
// Check to see if the request is still happening
if ( xhr && !requestDone )
onreadystatechange( "timeout" );
}, s.timeout);
}
// Send the data
try {
xhr.send(s.data);
} catch(e) {
jQuery.handleError(s, xhr, null, e);
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async )
onreadystatechange();
function success(){
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
}
function complete(){
// Process result
if ( s.complete )
s.complete(xhr, status);
// The request was completed
if ( s.global )
jQuery.event.trigger( "ajaxComplete", [xhr, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
}
// return XMLHttpRequest to allow aborting the request etc.
return xhr;
},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) s.error( xhr, status, e );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xhr, s, e] );
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol == "file:" ||
( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
} catch(e){}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) {
try {
var xhrRes = xhr.getResponseHeader("Last-Modified");
// Firefox always returns 200. check Last-Modified date
return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
} catch(e){}
return false;
},
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.tagName == "parsererror" )
throw "parsererror";
// Allow a pre-filtering function to sanitize the response
// s != null is checked to keep backwards compatibility
if( s && s.dataFilter )
data = s.dataFilter( data, type );
// The filter can actually parse the response
if( typeof data === "string" ){
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
data = window["eval"]("(" + data + ")");
}
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a ) {
var s = [ ];
function add( key, value ){
s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
};
// If an array was passed in, assume that it is an array
// of form elements
if ( jQuery.isArray(a) || a.jquery )
// Serialize the form elements
jQuery.each( a, function(){
add( this.name, this.value );
});
// Otherwise, assume that it's an object of key/value pairs
else
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( jQuery.isArray(a[j]) )
jQuery.each( a[j], function(){
add( j, this );
});
else
add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
// Return the resulting serialization
return s.join("&").replace(/%20/g, "+");
}
});
var elemdisplay = {},
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
function genFx( type, num ){
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
obj[ this ] = type;
});
return obj;
}
jQuery.fn.extend({
show: function(speed,callback){
if ( speed ) {
return this.animate( genFx("show", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ){
var old = jQuery.data(this[i], "olddisplay");
this[i].style.display = old || "";
if ( jQuery.css(this[i], "display") === "none" ) {
var tagName = this[i].tagName, display;
if ( elemdisplay[ tagName ] ) {
display = elemdisplay[ tagName ];
} else {
var elem = jQuery("<" + tagName + " />").appendTo("body");
display = elem.css("display");
if ( display === "none" )
display = "block";
elem.remove();
elemdisplay[ tagName ] = display;
}
jQuery.data(this[i], "olddisplay", display);
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var i = 0, l = this.length; i < l; i++ ){
this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
}
return this;
}
},
hide: function(speed,callback){
if ( speed ) {
return this.animate( genFx("hide", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ){
var old = jQuery.data(this[i], "olddisplay");
if ( !old && old !== "none" )
jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var i = 0, l = this.length; i < l; i++ ){
this[i].style.display = "none";
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2 ){
var bool = typeof fn === "boolean";
return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
this._toggle.apply( this, arguments ) :
fn == null || bool ?
this.each(function(){
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
}) :
this.animate(genFx("toggle", 3), fn, fn2);
},
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
return this[ optall.queue === false ? "each" : "queue" ](function(){
var opt = jQuery.extend({}, optall), p,
hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
self = this;
for ( p in prop ) {
if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
return opt.complete.call(this);
if ( ( p == "height" || p == "width" ) && this.style ) {
// Store display property
opt.display = jQuery.css(this, "display");
// Make sure that nothing sneaks out
opt.overflow = this.style.overflow;
}
}
if ( opt.overflow != null )
this.style.overflow = "hidden";
opt.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function(name, val){
var e = new jQuery.fx( self, opt, name );
if ( /toggle|show|hide/.test(val) )
e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
else {
var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
start = e.cur(true) || 0;
if ( parts ) {
var end = parseFloat(parts[2]),
unit = parts[3] || "px";
// We need to compute starting value
if ( unit != "px" ) {
self.style[ name ] = (end || 1) + unit;
start = ((end || 1) / e.cur(true)) * start;
self.style[ name ] = start + unit;
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] )
end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
e.custom( start, end, unit );
} else
e.custom( start, val, "" );
}
});
// For JS strict compliance
return true;
});
},
stop: function(clearQueue, gotoEnd){
var timers = jQuery.timers;
if (clearQueue)
this.queue([]);
this.each(function(){
// go in reverse order so anything added to the queue during the loop is ignored
for ( var i = timers.length - 1; i >= 0; i-- )
if ( timers[i].elem == this ) {
if (gotoEnd)
// force the next step to be the last
timers[i](true);
timers.splice(i, 1);
}
});
// start the next in the queue if the last step wasn't forced
if (!gotoEnd)
this.dequeue();
return this;
}
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" }
}, function( name, props ){
jQuery.fn[ name ] = function( speed, callback ){
return this.animate( props, speed, callback );
};
});
jQuery.extend({
speed: function(speed, easing, fn) {
var opt = typeof speed === "object" ? speed : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function(){
if ( opt.queue !== false )
jQuery(this).dequeue();
if ( jQuery.isFunction( opt.old ) )
opt.old.call( this );
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ){
this.options = options;
this.elem = elem;
this.prop = prop;
if ( !options.orig )
options.orig = {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function(){
if ( this.options.step )
this.options.step.call( this.elem, this.now, this );
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
// Set display property to block for height/width animations
if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
this.elem.style.display = "block";
},
// Get the current size
cur: function(force){
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
return this.elem[ this.prop ];
var r = parseFloat(jQuery.css(this.elem, this.prop, force));
return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
},
// Start an animation from one number to another
custom: function(from, to, unit){
this.startTime = now();
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() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(function(){
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval( timerId );
timerId = undefined;
}
}, 13);
}
},
// Simple 'show' function
show: function(){
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery(this.elem).show();
},
// Simple 'hide' function
hide: function(){
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function(gotoEnd){
var t = now();
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.display != null ) {
// Reset the overflow
this.elem.style.overflow = this.options.overflow;
// Reset the display
this.elem.style.display = this.options.display;
if ( jQuery.css(this.elem, "display") == "none" )
this.elem.style.display = "block";
}
// Hide the element if the "hide" operation was done
if ( this.options.hide )
jQuery(this.elem).hide();
// Reset the properties, if the item has been hidden or shown
if ( this.options.hide || this.options.show )
for ( var p in this.options.curAnim )
jQuery.attr(this.elem.style, p, this.options.orig[p]);
// Execute the complete function
this.options.complete.call( this.elem );
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
speeds:{
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function(fx){
jQuery.attr(fx.elem.style, "opacity", fx.now);
},
_default: function(fx){
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;
}
}
});
if ( document.documentElement["getBoundingClientRect"] )
jQuery.fn.offset = function() {
if ( !this[0] ) return { top: 0, left: 0 };
if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
return { top: top, left: left };
};
else
jQuery.fn.offset = function() {
if ( !this[0] ) return { top: 0, left: 0 };
if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
jQuery.offset.initialized || jQuery.offset.initialize();
var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
body = doc.body, defaultView = doc.defaultView,
prevComputedStyle = defaultView.getComputedStyle(elem, null),
top = elem.offsetTop, left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
computedStyle = defaultView.getComputedStyle(elem, null);
top -= elem.scrollTop, left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop, left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
top += parseInt( computedStyle.borderTopWidth, 10) || 0,
left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
top += parseInt( computedStyle.borderTopWidth, 10) || 0,
left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
top += body.offsetTop,
left += body.offsetLeft;
if ( prevComputedStyle.position === "fixed" )
top += Math.max(docElem.scrollTop, body.scrollTop),
left += Math.max(docElem.scrollLeft, body.scrollLeft);
return { top: top, left: left };
};
jQuery.offset = {
initialize: function() {
if ( this.initialized ) return;
var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';
rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
for ( prop in rules ) container.style[prop] = rules[prop];
container.innerHTML = html;
body.insertBefore(container, body.firstChild);
innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
body.style.marginTop = '1px';
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
body.style.marginTop = bodyMarginTop;
body.removeChild(container);
this.initialized = true;
},
bodyOffset: function(body) {
jQuery.offset.initialized || jQuery.offset.initialize();
var top = body.offsetTop, left = body.offsetLeft;
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
top += parseInt( jQuery.curCSS(body, 'marginTop', true), 10 ) || 0,
left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
return { top: top, left: left };
}
};
jQuery.fn.extend({
position: function() {
var left = 0, top = 0, results;
if ( this[0] ) {
// Get *real* offsetParent
var offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= num( this, 'marginTop' );
offset.left -= num( this, 'marginLeft' );
// Add offsetParent borders
parentOffset.top += num( offsetParent, 'borderTopWidth' );
parentOffset.left += num( offsetParent, 'borderLeftWidth' );
// Subtract the two offsets
results = {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
return results;
},
offsetParent: function() {
var offsetParent = this[0].offsetParent || document.body;
while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
offsetParent = offsetParent.offsetParent;
return jQuery(offsetParent);
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
var method = 'scroll' + name;
jQuery.fn[ method ] = function(val) {
if (!this[0]) return null;
return val !== undefined ?
// Set the scroll offset
this.each(function() {
this == window || this == document ?
window.scrollTo(
!i ? val : jQuery(window).scrollLeft(),
i ? val : jQuery(window).scrollTop()
) :
this[ method ] = val;
}) :
// Return the scroll offset
this[0] == window || this[0] == document ?
self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
jQuery.boxModel && document.documentElement[ method ] ||
document.body[ method ] :
this[0][ method ];
};
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){
var tl = i ? "Left" : "Top", // top or left
br = i ? "Right" : "Bottom", // bottom or right
lower = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function(){
return this[0] ?
jQuery.css( this[0], lower, false, "padding" ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function(margin) {
return this[0] ?
jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
null;
};
var type = name.toLowerCase();
jQuery.fn[ type ] = function( size ) {
// Get window width or height
return this[0] == window ?
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
document.body[ "client" + name ] :
// Get document width or height
this[0] == document ?
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
Math.max(
document.documentElement["client" + name],
document.body["scroll" + name], document.documentElement["scroll" + name],
document.body["offset" + name], document.documentElement["offset" + name]
) :
// Get or set width or height on the element
size === undefined ?
// Get width or height on the element
(this.length ? jQuery.css( this[0], type ) : null) :
// Set the width or height on the element (default to pixels if value is unitless)
this.css( type, typeof size === "string" ? size : size + "px" );
};
});
})();
| JavaScript |
/*
* Superfish v1.4.8 - jQuery menu widget
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
*/
;(function($){
$.fn.superfish = function(op){
var sf = $.fn.superfish,
c = sf.c,
$arrow = $(['<span class="',c.arrowClass,'"> »</span>'].join('')),
over = function(){
var $$ = $(this), menu = getMenu($$);
clearTimeout(menu.sfTimer);
$$.showSuperfishUl().siblings().hideSuperfishUl();
},
out = function(){
var $$ = $(this), menu = getMenu($$), o = sf.op;
clearTimeout(menu.sfTimer);
menu.sfTimer=setTimeout(function(){
o.retainPath=($.inArray($$[0],o.$path)>-1);
$$.hideSuperfishUl();
if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
},o.delay);
},
getMenu = function($menu){
var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
sf.op = sf.o[menu.serial];
return menu;
},
addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
return this.each(function() {
var s = this.serial = sf.o.length;
var o = $.extend({},sf.defaults,op);
o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
$(this).addClass([o.hoverClass,c.bcClass].join(' '))
.filter('li:has(ul)').removeClass(o.pathClass);
});
sf.o[s] = sf.op = o;
$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
if (o.autoArrows) addArrow( $('>a:first-child',this) );
})
.not('.'+c.bcClass)
.hideSuperfishUl();
var $a = $('a',this);
$a.each(function(i){
var $li = $a.eq(i).parents('li');
$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
});
o.onInit.call(this);
}).each(function() {
var menuClasses = [c.menuClass];
if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
$(this).addClass(menuClasses.join(' '));
});
};
var sf = $.fn.superfish;
sf.o = [];
sf.op = {};
sf.IE7fix = function(){
var o = sf.op;
if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
this.toggleClass(sf.c.shadowClass+'-off');
};
sf.c = {
bcClass : 'sf-breadcrumb',
menuClass : 'sf-js-enabled',
anchorClass : 'sf-with-ul',
arrowClass : 'sf-sub-indicator',
shadowClass : 'sf-shadow'
};
sf.defaults = {
hoverClass : 'sfHover',
pathClass : 'overideThisToUse',
pathLevels : 1,
delay : 800,
animation : {opacity:'show'},
speed : 'normal',
autoArrows : true,
dropShadows : true,
disableHI : false, // true disables hoverIntent detection
onInit : function(){}, // callback functions
onBeforeShow: function(){},
onShow : function(){},
onHide : function(){}
};
$.fn.extend({
hideSuperfishUl : function(){
var o = sf.op,
not = (o.retainPath===true) ? o.$path : '';
o.retainPath = false;
var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
.find('>ul').hide().css('visibility','hidden');
o.onHide.call($ul);
return this;
},
showSuperfishUl : function(){
var o = sf.op,
sh = sf.c.shadowClass+'-off',
$ul = this.addClass(o.hoverClass)
.find('>ul:hidden').css('visibility','visible');
sf.IE7fix.call($ul);
o.onBeforeShow.call($ul);
$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
return this;
}
});
})(jQuery);
| JavaScript |
/*
* FancyBox - simple jQuery plugin for fancy image zooming
* Examples and documentation at: http://fancy.klade.lv/
* Version: 1.0.0 (29/04/2008)
* Copyright (c) 2008 Janis Skarnelis
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
* Requires: jQuery v1.2.1 or later
*/
(function($) {
var opts = {},
imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'],
loadingTimer, loadingFrame = 1;
$.fn.fancybox = function(settings) {
opts.settings = $.extend({}, $.fn.fancybox.defaults, settings);
$.fn.fancybox.init();
return this.each(function() {
var $this = $(this);
var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings;
$this.unbind('click').click(function() {
$.fn.fancybox.start(this, o); return false;
});
});
};
$.fn.fancybox.start = function(el, o) {
if (opts.animating) return false;
if (o.overlayShow) {
$("#fancy_wrap").prepend('<div id="fancy_overlay"></div>');
$("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity});
if ($.browser.msie) {
$("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>');
$("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0});
}
$("#fancy_overlay").click($.fn.fancybox.close);
}
opts.itemArray = [];
opts.itemNum = 0;
if (jQuery.isFunction(o.itemLoadCallback)) {
o.itemLoadCallback.apply(this, [opts]);
var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
for (var i = 0; i < opts.itemArray.length; i++) {
opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o);
if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
opts.itemArray[i].orig = tmp;
}
}
} else {
if (!el.rel || el.rel == '') {
var item = {url: el.href, title: el.title, o: o};
if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
}
opts.itemArray.push(item);
} else {
var arr = $("a[@rel=" + el.rel + "]").get();
for (var i = 0; i < arr.length; i++) {
var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o;
var item = {url: arr[i].href, title: arr[i].title, o: tmp};
if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el);
item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
}
if (arr[i].href == el.href) opts.itemNum = i;
opts.itemArray.push(item);
}
}
}
$.fn.fancybox.changeItem(opts.itemNum);
};
$.fn.fancybox.changeItem = function(n) {
$.fn.fancybox.showLoading();
opts.itemNum = n;
$("#fancy_nav").empty();
$("#fancy_outer").stop();
$("#fancy_title").hide();
$(document).unbind("keydown");
imgRegExp = imgTypes.join('|');
imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i');
var url = opts.itemArray[n].url;
if (url.match(/#/)) {
var target = window.location.href.split('#')[0]; target = url.replace(target,'');
$.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>');
$("#fancy_loading").hide();
} else if (url.match(imgRegExp)) {
$(imgPreloader).unbind('load').bind('load', function() {
$("#fancy_loading").hide();
opts.itemArray[n].o.frameWidth = imgPreloader.width;
opts.itemArray[n].o.frameHeight = imgPreloader.height;
$.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />');
}).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) );
} else {
$.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>');
}
};
$.fn.fancybox.showIframe = function() {
$("#fancy_loading").hide();
$("#fancy_frame").show();
};
$.fn.fancybox.showItem = function(val) {
$.fn.fancybox.preloadNeighborImages();
var viewportPos = $.fn.fancybox.getViewport();
var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight);
var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20;
var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40;
var itemOpts = {
'left': itemLeft,
'top': itemTop,
'width': itemSize[0] + 'px',
'height': itemSize[1] + 'px'
}
if (opts.active) {
$('#fancy_content').fadeOut("normal", function() {
$("#fancy_content").empty();
$("#fancy_outer").animate(itemOpts, "normal", function() {
$("#fancy_content").append($(val)).fadeIn("normal");
$.fn.fancybox.updateDetails();
});
});
} else {
opts.active = true;
$("#fancy_content").empty();
if ($("#fancy_content").is(":animated")) {
console.info('animated!');
}
if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) {
opts.animating = true;
itemOpts.opacity = "show";
$("#fancy_outer").css({
'top': opts.itemArray[opts.itemNum].orig.pos.top - 18,
'left': opts.itemArray[opts.itemNum].orig.pos.left - 18,
'height': opts.itemArray[opts.itemNum].orig.height,
'width': opts.itemArray[opts.itemNum].orig.width
});
$("#fancy_content").append($(val)).show();
$("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() {
opts.animating = false;
$.fn.fancybox.updateDetails();
});
} else {
$("#fancy_content").append($(val)).show();
$("#fancy_outer").css(itemOpts).show();
$.fn.fancybox.updateDetails();
}
}
};
$.fn.fancybox.updateDetails = function() {
$("#fancy_bg,#fancy_close").show();
if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') {
$('#fancy_title div').html(opts.itemArray[opts.itemNum].title);
$('#fancy_title').show();
}
if (opts.itemArray[opts.itemNum].o.hideOnContentClick) {
$("#fancy_content").click($.fn.fancybox.close);
} else {
$("#fancy_content").unbind('click');
}
if (opts.itemNum != 0) {
$("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>');
$('#fancy_left').click(function() {
$.fn.fancybox.changeItem(opts.itemNum - 1); return false;
});
}
if (opts.itemNum != (opts.itemArray.length - 1)) {
$("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>');
$('#fancy_right').click(function(){
$.fn.fancybox.changeItem(opts.itemNum + 1); return false;
});
}
$(document).keydown(function(event) {
if (event.keyCode == 27) {
$.fn.fancybox.close();
} else if(event.keyCode == 37 && opts.itemNum != 0) {
$.fn.fancybox.changeItem(opts.itemNum - 1);
} else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) {
$.fn.fancybox.changeItem(opts.itemNum + 1);
}
});
};
$.fn.fancybox.preloadNeighborImages = function() {
if ((opts.itemArray.length - 1) > opts.itemNum) {
preloadNextImage = new Image();
preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url;
}
if (opts.itemNum > 0) {
preloadPrevImage = new Image();
preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url;
}
};
$.fn.fancybox.close = function() {
if (opts.animating) return false;
$(imgPreloader).unbind('load');
$(document).unbind("keydown");
$("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide();
$("#fancy_nav").empty();
opts.active = false;
if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) {
var itemOpts = {
'top': opts.itemArray[opts.itemNum].orig.pos.top - 18,
'left': opts.itemArray[opts.itemNum].orig.pos.left - 18,
'height': opts.itemArray[opts.itemNum].orig.height,
'width': opts.itemArray[opts.itemNum].orig.width,
'opacity': 'hide'
};
opts.animating = true;
$("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() {
$("#fancy_content").hide().empty();
$("#fancy_overlay,#fancy_bigIframe").remove();
opts.animating = false;
});
} else {
$("#fancy_outer").hide();
$("#fancy_content").hide().empty();
$("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove();
}
};
$.fn.fancybox.showLoading = function() {
clearInterval(loadingTimer);
var pos = $.fn.fancybox.getViewport();
$("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show();
$("#fancy_loading").bind('click', $.fn.fancybox.close);
loadingTimer = setInterval($.fn.fancybox.animateLoading, 66);
};
$.fn.fancybox.animateLoading = function(el, o) {
if (!$("#fancy_loading").is(':visible')){
clearInterval(loadingTimer);
return;
}
$("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$.fn.fancybox.init = function() {
if (!$('#fancy_wrap').length) {
$('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body");
$('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner");
$('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title');
}
if ($.browser.msie) {
$("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>');
}
if (jQuery.fn.pngFix) $(document).pngFix();
$("#fancy_close").click($.fn.fancybox.close);
};
$.fn.fancybox.getPosition = function(el) {
var pos = el.offset();
pos.top += $.fn.fancybox.num(el, 'paddingTop');
pos.top += $.fn.fancybox.num(el, 'borderTopWidth');
pos.left += $.fn.fancybox.num(el, 'paddingLeft');
pos.left += $.fn.fancybox.num(el, 'borderLeftWidth');
return pos;
};
$.fn.fancybox.num = function (el, prop) {
return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};
$.fn.fancybox.getPageScroll = function() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return [xScroll, yScroll];
};
$.fn.fancybox.getViewport = function() {
var scroll = $.fn.fancybox.getPageScroll();
return [$(window).width(), $(window).height(), scroll[0], scroll[1]];
};
$.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) {
var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight);
return [Math.round(r * imageWidth), Math.round(r * imageHeight)];
};
$.fn.fancybox.defaults = {
hideOnContentClick: false,
zoomSpeedIn: 500,
zoomSpeedOut: 500,
frameWidth: 600,
frameHeight: 400,
overlayShow: false,
overlayOpacity: 0.4,
itemLoadCallback: null
};
})(jQuery); | JavaScript |
/***********************************************
* Cool DHTML tooltip script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var offsetfromcursorX = 12;
var offsetfromcursorY = 10;
var offsetdivfrompointerX = 10;
var offsetdivfrompointerY = 14;
var domain = 'http://' + window.location.hostname + '/';
document.write('<div id="dhtmltooltip"></div>');
document.write('<img id="dhtmlpointer" src="http://localhost:49455/WebBanHang/images/tooltiparrow.gif" />');
var ie = document.all;
var ns6 = document.getElementById && ! document.all;
var enabletip = false;
if (ie || ns6)
var tipobj = document.all ? document.all["dhtmltooltip"] : document.getElementById ? document.getElementById("dhtmltooltip") : "";
var pointerobj = document.all ? document.all["dhtmlpointer"] : document.getElementById ? document.getElementById("dhtmlpointer") : "";
function ietruebody() {
return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function showttip(thetext, thewidth, thecolor) {
if (ns6 || ie) {
if (typeof thewidth != "undefined")
tipobj.style.width = thewidth + "px";
if (typeof thecolor != "undefined" && thecolor != "")
tipobj.style.backgroundColor = thecolor;
tipobj.innerHTML = thetext;
tipobj.onmouseout = hidettip;
enabletip = true;
return false;
}
}
function positiontip(e) {
if (enabletip) {
var nondefaultpos = false;
var curX = (ns6) ? e.pageX : event.clientX + ietruebody().scrollLeft;
var curY = (ns6) ? e.pageY : event.clientY + ietruebody().scrollTop;
var winwidth = ie && ! window.opera ? ietruebody().clientWidth : window.innerWidth - 20;
var winheight = ie && ! window.opera ? ietruebody().clientHeight : window.innerHeight - 20;
var rightedge = ie && ! window.opera ? winwidth - event.clientX - offsetfromcursorX : winwidth - e.clientX - offsetfromcursorX;
var bottomedge = ie && ! window.opera ? winheight - event.clientY - offsetfromcursorY : winheight - e.clientY - offsetfromcursorY;
var leftedge = (offsetfromcursorX < 0) ? offsetfromcursorX * (- 1) : - 1000;
if (rightedge < tipobj.offsetWidth) {
tipobj.style.left = curX - tipobj.offsetWidth + "px";
nondefaultpos = true;
}
else if (curX < leftedge)
tipobj.style.left = "5px";
else {
tipobj.style.left = curX + offsetfromcursorX - offsetdivfrompointerX + "px";
pointerobj.style.left = curX + offsetfromcursorX + "px";
}
if (bottomedge < tipobj.offsetHeight) {
tipobj.style.top = curY - tipobj.offsetHeight - offsetfromcursorY + "px";
nondefaultpos = true;
}
else {
tipobj.style.top = curY + offsetfromcursorY + offsetdivfrompointerY + "px";
pointerobj.style.top = curY + offsetfromcursorY + "px";
}
tipobj.style.visibility = "visible";
if (! nondefaultpos)
pointerobj.style.visibility = "visible";
else
pointerobj.style.visibility = "hidden";
}
}
function hidettip() {
if (ns6 || ie) {
enabletip = false;
tipobj.style.visibility = "hidden";
pointerobj.style.visibility = "hidden";
tipobj.style.left = "-1000px";
tipobj.style.backgroundColor = '';
tipobj.style.width = '';
}
}
document.onmousemove = positiontip;
| JavaScript |
/* Simple AJAX Code-Kit (SACK) */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */
function sack(file)
{
this.AjaxFailedAlert = "Trình duyệt của bạn không hỗ trợ Load Ajax. Bạn nên chọn một trình duyệt khác để sử dụng được tất cả chức năng của hệ thống.\n";
this.requestFile = file;
this.method = "POST";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.onLoading = function() { };
this.onLoaded = function() { };
this.onInteractive = function() { };
this.onCompletion = function() { };
this.createAJAX = function()
{
try
{
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (err)
{
this.xmlhttp = null;
}
}
if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
this.xmlhttp = new XMLHttpRequest();
if (!this.xmlhttp)
{
this.failed = true;
}
};
this.setVar = function(name, value)
{
if (this.URLString.length < 3){
this.URLString = name + "=" + value;
} else {
this.URLString += "&" + name + "=" + value;
}
}
this.encVar = function(name, value)
{
var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
return varString;
}
this.encodeURLString = function(string)
{
varArray = string.split('&');
for (i = 0; i < varArray.length; i++)
{
urlVars = varArray[i].split('=');
if (urlVars[0].indexOf('amp;') != -1)
{
urlVars[0] = urlVars[0].substring(4);
}
varArray[i] = this.encVar(urlVars[0],urlVars[1]);
}
return varArray.join('&');
}
this.runResponse = function()
{
eval(this.response);
}
this.runAJAX = function(urlstring)
{
this.responseStatus = new Array(2);
if(this.failed && this.AjaxFailedAlert)
{
alert(this.AjaxFailedAlert);
}
else
{
if (urlstring)
{
if (this.URLString.length)
{
this.URLString = this.URLString + "&" + urlstring;
}
else
{
this.URLString = urlstring;
}
}
if (this.encodeURIString)
{
var timeval = new Date().getTime();
this.URLString = this.encodeURLString(this.URLString);
this.setVar("rndval", timeval);
}
if (this.element)
{
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp)
{
var self = this;
if (this.method == "GET")
{
var totalurlstring = this.requestFile + "?" + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
}
else
{
this.xmlhttp.open(this.method, this.requestFile, true);
}
if (this.method == "POST")
{
try
{
this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
}
catch (e) {}
}
this.xmlhttp.send(this.URLString);
this.xmlhttp.onreadystatechange = function()
{
switch (self.xmlhttp.readyState)
{
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
self.onCompletion();
if(self.execute)
{
self.runResponse();
}
if (self.elementObj)
{
var elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea")
{
self.elementObj.value = self.response;
}
else
{
self.elementObj.innerHTML = self.response;
}
}
self.URLString = "";
break;
}
};
}
}
};
this.createAJAX();
} | JavaScript |
/**
* jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
* @requires jQuery v1.2 or above
*
* http://gmarwaha.com/jquery/jcarousellite/
*
* Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Version: 1.0.1
* Note: Requires jquery 1.2 or above from version 1.0.1
*/
/**
* Creates a carousel-style navigation widget for images/any-content from a simple HTML markup.
*
* The HTML markup that is used to build the carousel can be as simple as...
*
* <div class="carousel">
* <ul>
* <li><img src="image/1.jpg" alt="1"></li>
* <li><img src="image/2.jpg" alt="2"></li>
* <li><img src="image/3.jpg" alt="3"></li>
* </ul>
* </div>
*
* As you can see, this snippet is nothing but a simple div containing an unordered list of images.
* You don't need any special "class" attribute, or a special "css" file for this plugin.
* I am using a class attribute just for the sake of explanation here.
*
* To navigate the elements of the carousel, you need some kind of navigation buttons.
* For example, you will need a "previous" button to go backward, and a "next" button to go forward.
* This need not be part of the carousel "div" itself. It can be any element in your page.
* Lets assume that the following elements in your document can be used as next, and prev buttons...
*
* <button class="prev"><<</button>
* <button class="next">>></button>
*
* Now, all you need to do is call the carousel component on the div element that represents it, and pass in the
* navigation buttons as options.
*
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev"
* });
*
* That's it, you would have now converted your raw div, into a magnificient carousel.
*
* There are quite a few other options that you can use to customize it though.
* Each will be explained with an example below.
*
* @param an options object - You can specify all the options shown below as an options object param.
*
* @option btnPrev, btnNext : string - no defaults
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev"
* });
* @desc Creates a basic carousel. Clicking "btnPrev" navigates backwards and "btnNext" navigates forward.
*
* @option btnGo - array - no defaults
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* btnGo: [".0", ".1", ".2"]
* });
* @desc If you don't want next and previous buttons for navigation, instead you prefer custom navigation based on
* the item number within the carousel, you can use this option. Just supply an array of selectors for each element
* in the carousel. The index of the array represents the index of the element. What i mean is, if the
* first element in the array is ".0", it means that when the element represented by ".0" is clicked, the carousel
* will slide to the first element and so on and so forth. This feature is very powerful. For example, i made a tabbed
* interface out of it by making my navigation elements styled like tabs in css. As the carousel is capable of holding
* any content, not just images, you can have a very simple tabbed navigation in minutes without using any other plugin.
* The best part is that, the tab will "slide" based on the provided effect. :-)
*
* @option mouseWheel : boolean - default is false
* @example
* $(".carousel").jCarouselLite({
* mouseWheel: true
* });
* @desc The carousel can also be navigated using the mouse wheel interface of a scroll mouse instead of using buttons.
* To get this feature working, you have to do 2 things. First, you have to include the mouse-wheel plugin from brandon.
* Second, you will have to set the option "mouseWheel" to true. That's it, now you will be able to navigate your carousel
* using the mouse wheel. Using buttons and mouseWheel or not mutually exclusive. You can still have buttons for navigation
* as well. They complement each other. To use both together, just supply the options required for both as shown below.
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* mouseWheel: true
* });
*
* @option auto : number - default is null, meaning autoscroll is disabled by default
* @example
* $(".carousel").jCarouselLite({
* auto: 800,
* speed: 500
* });
* @desc You can make your carousel auto-navigate itself by specfying a millisecond value in this option.
* The value you specify is the amount of time between 2 slides. The default is null, and that disables auto scrolling.
* Specify this value and magically your carousel will start auto scrolling.
*
* @option speed : number - 200 is default
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* speed: 800
* });
* @desc Specifying a speed will slow-down or speed-up the sliding speed of your carousel. Try it out with
* different speeds like 800, 600, 1500 etc. Providing 0, will remove the slide effect.
*
* @option easing : string - no easing effects by default.
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* easing: "bounceout"
* });
* @desc You can specify any easing effect. Note: You need easing plugin for that. Once specified,
* the carousel will slide based on the provided easing effect.
*
* @option vertical : boolean - default is false
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* vertical: true
* });
* @desc Determines the direction of the carousel. true, means the carousel will display vertically. The next and
* prev buttons will slide the items vertically as well. The default is false, which means that the carousel will
* display horizontally. The next and prev items will slide the items from left-right in this case.
*
* @option circular : boolean - default is true
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* circular: false
* });
* @desc Setting it to true enables circular navigation. This means, if you click "next" after you reach the last
* element, you will automatically slide to the first element and vice versa. If you set circular to false, then
* if you click on the "next" button after you reach the last element, you will stay in the last element itself
* and similarly for "previous" button and first element.
*
* @option visible : number - default is 3
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* visible: 4
* });
* @desc This specifies the number of items visible at all times within the carousel. The default is 3.
* You are even free to experiment with real numbers. Eg: "3.5" will have 3 items fully visible and the
* last item half visible. This gives you the effect of showing the user that there are more images to the right.
*
* @option start : number - default is 0
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* start: 2
* });
* @desc You can specify from which item the carousel should start. Remember, the first item in the carousel
* has a start of 0, and so on.
*
* @option scrool : number - default is 1
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* scroll: 2
* });
* @desc The number of items that should scroll/slide when you click the next/prev navigation buttons. By
* default, only one item is scrolled, but you may set it to any number. Eg: setting it to "2" will scroll
* 2 items when you click the next or previous buttons.
*
* @option beforeStart, afterEnd : function - callbacks
* @example
* $(".carousel").jCarouselLite({
* btnNext: ".next",
* btnPrev: ".prev",
* beforeStart: function(a) {
* alert("Before animation starts:" + a);
* },
* afterEnd: function(a) {
* alert("After animation ends:" + a);
* }
* });
* @desc If you wanted to do some logic in your page before the slide starts and after the slide ends, you can
* register these 2 callbacks. The functions will be passed an argument that represents an array of elements that
* are visible at the time of callback.
*
*
* @cat Plugins/Image Gallery
* @author Ganeshji Marwaha/ganeshread@gmail.com
*/
(function($) { // Compliant with jquery.noConflict()
$.fn.jCarouselLite = function(o) {
o = $.extend({
btnPrev: null,
btnNext: null,
btnGo: null,
mouseWheel: false,
auto: null,
speed: 200,
easing: null,
vertical: false,
circular: true,
visible: 2,
start: 0,
scroll: 1,
beforeStart: null,
afterEnd: null
}, o || {});
return this.each(function() { // Returns the element collection. Chainable.
var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;
if(o.circular) {
ul.prepend(tLi.slice(tl-v-1+1).clone())
.append(tLi.slice(0,v).clone());
o.start += v;
}
var li = $("li", ul), itemLength = li.size(), curr = o.start;
div.css("visibility", "visible");
li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "-25px"});
var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation
var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items)
var divSize = liSize * v; // size of entire div(total length for just the visible items)
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images
if(o.btnPrev)
$(o.btnPrev).click(function() {
return go(curr-o.scroll);
});
if(o.btnNext)
$(o.btnNext).click(function() {
return go(curr+o.scroll);
});
if(o.btnGo)
$.each(o.btnGo, function(i, val) {
$(val).click(function() {
return go(o.circular ? o.visible+i : i);
});
});
if(o.mouseWheel && div.mousewheel)
div.mousewheel(function(e, d) {
return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
});
if(o.auto)
setInterval(function() {
go(curr+o.scroll);
}, o.auto+o.speed);
if(o.autoneg)
setInterval(function() {
go(curr-o.scroll);
}, o.autoneg-o.speed);
function vis() {
return li.slice(curr).slice(0,v);
};
function go(to) {
if(!running) {
if(o.beforeStart)
o.beforeStart.call(this, vis());
if(o.circular) { // If circular we are in first or last, then goto the other end
if(to<=o.start-v-1) { // If first, then goto last
ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
// If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
} else if(to>=itemLength-v+1) { // If last, then goto first
ul.css(animCss, -( (v) * liSize ) + "px" );
// If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
} else curr = to;
} else { // If non-circular and to points to first or last, we just return.
if(to<0 || to>itemLength-v) return;
else curr = to;
} // If neither overrides it, the curr will still be "to" and we can proceed.
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
if(o.afterEnd)
o.afterEnd.call(this, vis());
running = false;
}
);
// Disable buttons when the carousel reaches the last/first, and enable when not
if(!o.circular) {
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength-v && o.btnNext)
||
[]
).addClass("disabled");
}
}
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery); | JavaScript |
/**********************************************************
Ajax dynamic content
Copyright (C) 2007 DTHMLGoodies.com, Alf Magne Kalleland
***********************************************************/
var enableCache = true;
var jsCache = new Array();
var dynamicContent_ajaxObjects = new Array();
// Ajax Show Content
function ajax_showContent(divId,ajaxIndex,url)
{
document.getElementById(divId).innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;
if(enableCache)
{
jsCache[url] = dynamicContent_ajaxObjects[ajaxIndex].response;
}
dynamicContent_ajaxObjects[ajaxIndex] = false;
}
// Ajax Load Content
function ajax_loadContent(divId,url)
{
if(document.getElementById(divId))
{
// Get Content From Cache
if(enableCache && jsCache[url])
{
document.getElementById(divId).innerHTML = jsCache[url];
return;
}
// Recieve content from Server
document.getElementById(divId).innerHTML = '<div style="margin-left:90px; margin-top:10px;vertical-align:top" ><img src="../images/ajax-loader.gif" style="border:0px; width:30px; height:30px;" /><span style="font-family:Arial, Sans-Serif; color:#C2D8E7; font-size:13px;vertical-align:top;line-height:28px">Đang tải dữ liệu</span></div>';
// Add new Ajax Object
var ajaxIndex = dynamicContent_ajaxObjects.length;
dynamicContent_ajaxObjects[ajaxIndex] = new sack();
var urlNew = url;
if(urlNew.indexOf('?') >= 0)
{
dynamicContent_ajaxObjects[ajaxIndex].method='GET';
var string = urlNew.substring(urlNew.indexOf('?'));
urlNew = urlNew.replace(string,'');
string = string.replace('?','');
var items = string.split(/&/g);
for(var no=0; no<items.length; no++)
{
var tokens = items[no].split('=');
if(tokens.length==2)
{
dynamicContent_ajaxObjects[ajaxIndex].setVar(tokens[0],tokens[1]);
}
}
urlNew = urlNew.replace(string,'');
}
// Specifying which file to get
dynamicContent_ajaxObjects[ajaxIndex].requestFile = urlNew;
// Specify function that will be executed after file has been found
dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function()
{
ajax_showContent(divId,ajaxIndex,url);
};
// Execute AJAX function
dynamicContent_ajaxObjects[ajaxIndex].runAJAX();
}
} | 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, #colorpickerField2, #colorpickerField3').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).ColorPickerHide();
},
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
*
* Dual licensed under the MIT and GPL licenses
*
*/
(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), cal.data('colorpicker').el);
},
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 = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
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));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
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));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
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('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
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.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery) | JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
};
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','en',{devTools:{title:'Element Information',dialogName:'Dialog window name',tabName:'Tab name',elementId:'Element ID',elementType:'Element type'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('docprops',{init:function(a){var b=new CKEDITOR.dialogCommand('docProps');b.modes={wysiwyg:a.config.fullPage};a.addCommand('docProps',b);CKEDITOR.dialog.add('docProps',this.path+'dialogs/docprops.js');a.ui.addButton('DocProps',{label:a.lang.docprops.label,command:'docProps'});}});
| JavaScript |
/**
* jscolor, JavaScript Color Picker
*
* @version 1.4.0
* @license GNU Lesser General Public License, http://www.gnu.org/copyleft/lesser.html
* @author Jan Odvarko, http://odvarko.cz
* @created 2008-06-15
* @updated 2012-07-06
* @link http://jscolor.com
*/
var jscolor = {
dir : 'scripts/jscolor/', // location of jscolor directory (leave empty to autodetect)
bindClass : 'color', // class name
binding : true, // automatic binding via <input class="...">
preloading : true, // use image preloading?
install : function() {
jscolor.addEvent(window, 'load', jscolor.init);
},
init : function() {
if(jscolor.binding) {
jscolor.bind();
}
if(jscolor.preloading) {
jscolor.preload();
}
},
getDir : function() {
if(!jscolor.dir) {
var detected = jscolor.detectDir();
jscolor.dir = detected!==false ? detected : 'jscolor/';
}
return jscolor.dir;
},
detectDir : function() {
var base = location.href;
var e = document.getElementsByTagName('base');
for(var i=0; i<e.length; i+=1) {
if(e[i].href) { base = e[i].href; }
}
var e = document.getElementsByTagName('script');
for(var i=0; i<e.length; i+=1) {
if(e[i].src && /(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)) {
var src = new jscolor.URI(e[i].src);
var srcAbs = src.toAbsolute(base);
srcAbs.path = srcAbs.path.replace(/[^\/]+$/, ''); // remove filename
srcAbs.query = null;
srcAbs.fragment = null;
return srcAbs.toString();
}
}
return false;
},
bind : function() {
var matchClass = new RegExp('(^|\\s)('+jscolor.bindClass+')\\s*(\\{[^}]*\\})?', 'i');
var e = document.getElementsByTagName('input');
for(var i=0; i<e.length; i+=1) {
var m;
if(!e[i].color && e[i].className && (m = e[i].className.match(matchClass))) {
var prop = {};
if(m[3]) {
try {
prop = (new Function ('return (' + m[3] + ')'))();
} catch(eInvalidProp) {}
}
e[i].color = new jscolor.color(e[i], prop);
}
}
},
preload : function() {
for(var fn in jscolor.imgRequire) {
if(jscolor.imgRequire.hasOwnProperty(fn)) {
jscolor.loadImage(fn);
}
}
},
images : {
pad : [ 181, 101 ],
sld : [ 16, 101 ],
cross : [ 15, 15 ],
arrow : [ 7, 11 ]
},
imgRequire : {},
imgLoaded : {},
requireImage : function(filename) {
jscolor.imgRequire[filename] = true;
},
loadImage : function(filename) {
if(!jscolor.imgLoaded[filename]) {
jscolor.imgLoaded[filename] = new Image();
jscolor.imgLoaded[filename].src = jscolor.getDir()+filename;
}
},
fetchElement : function(mixed) {
return typeof mixed === 'string' ? document.getElementById(mixed) : mixed;
},
addEvent : function(el, evnt, func) {
if(el.addEventListener) {
el.addEventListener(evnt, func, false);
} else if(el.attachEvent) {
el.attachEvent('on'+evnt, func);
}
},
fireEvent : function(el, evnt) {
if(!el) {
return;
}
if(document.createEvent) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent(evnt, true, true);
el.dispatchEvent(ev);
} else if(document.createEventObject) {
var ev = document.createEventObject();
el.fireEvent('on'+evnt, ev);
} else if(el['on'+evnt]) { // alternatively use the traditional event model (IE5)
el['on'+evnt]();
}
},
getElementPos : function(e) {
var e1=e, e2=e;
var x=0, y=0;
if(e1.offsetParent) {
do {
x += e1.offsetLeft;
y += e1.offsetTop;
} while(e1 = e1.offsetParent);
}
while((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') {
x -= e2.scrollLeft;
y -= e2.scrollTop;
}
return [x, y];
},
getElementSize : function(e) {
return [e.offsetWidth, e.offsetHeight];
},
getRelMousePos : function(e) {
var x = 0, y = 0;
if (!e) { e = window.event; }
if (typeof e.offsetX === 'number') {
x = e.offsetX;
y = e.offsetY;
} else if (typeof e.layerX === 'number') {
x = e.layerX;
y = e.layerY;
}
return { x: x, y: y };
},
getViewPos : function() {
if(typeof window.pageYOffset === 'number') {
return [window.pageXOffset, window.pageYOffset];
} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
return [document.body.scrollLeft, document.body.scrollTop];
} else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
} else {
return [0, 0];
}
},
getViewSize : function() {
if(typeof window.innerWidth === 'number') {
return [window.innerWidth, window.innerHeight];
} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
return [document.body.clientWidth, document.body.clientHeight];
} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
return [document.documentElement.clientWidth, document.documentElement.clientHeight];
} else {
return [0, 0];
}
},
URI : function(uri) { // See RFC3986
this.scheme = null;
this.authority = null;
this.path = '';
this.query = null;
this.fragment = null;
this.parse = function(uri) {
var m = uri.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);
this.scheme = m[3] ? m[2] : null;
this.authority = m[5] ? m[6] : null;
this.path = m[7];
this.query = m[9] ? m[10] : null;
this.fragment = m[12] ? m[13] : null;
return this;
};
this.toString = function() {
var result = '';
if(this.scheme !== null) { result = result + this.scheme + ':'; }
if(this.authority !== null) { result = result + '//' + this.authority; }
if(this.path !== null) { result = result + this.path; }
if(this.query !== null) { result = result + '?' + this.query; }
if(this.fragment !== null) { result = result + '#' + this.fragment; }
return result;
};
this.toAbsolute = function(base) {
var base = new jscolor.URI(base);
var r = this;
var t = new jscolor.URI;
if(base.scheme === null) { return false; }
if(r.scheme !== null && r.scheme.toLowerCase() === base.scheme.toLowerCase()) {
r.scheme = null;
}
if(r.scheme !== null) {
t.scheme = r.scheme;
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if(r.authority !== null) {
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if(r.path === '') {
t.path = base.path;
if(r.query !== null) {
t.query = r.query;
} else {
t.query = base.query;
}
} else {
if(r.path.substr(0,1) === '/') {
t.path = removeDotSegments(r.path);
} else {
if(base.authority !== null && base.path === '') {
t.path = '/'+r.path;
} else {
t.path = base.path.replace(/[^\/]+$/,'')+r.path;
}
t.path = removeDotSegments(t.path);
}
t.query = r.query;
}
t.authority = base.authority;
}
t.scheme = base.scheme;
}
t.fragment = r.fragment;
return t;
};
function removeDotSegments(path) {
var out = '';
while(path) {
if(path.substr(0,3)==='../' || path.substr(0,2)==='./') {
path = path.replace(/^\.+/,'').substr(1);
} else if(path.substr(0,3)==='/./' || path==='/.') {
path = '/'+path.substr(3);
} else if(path.substr(0,4)==='/../' || path==='/..') {
path = '/'+path.substr(4);
out = out.replace(/\/?[^\/]*$/, '');
} else if(path==='.' || path==='..') {
path = '';
} else {
var rm = path.match(/^\/?[^\/]*/)[0];
path = path.substr(rm.length);
out = out + rm;
}
}
return out;
}
if(uri) {
this.parse(uri);
}
},
/*
* Usage example:
* var myColor = new jscolor.color(myInputElement)
*/
color : function(target, prop) {
this.required = true; // refuse empty values?
this.adjust = true; // adjust value to uniform notation?
this.hash = false; // prefix color with # symbol?
this.caps = true; // uppercase?
this.slider = true; // show the value/saturation slider?
this.valueElement = target; // value holder
this.styleElement = target; // where to reflect current color
this.onImmediateChange = null; // onchange callback (can be either string or function)
this.hsv = [0, 0, 1]; // read-only 0-6, 0-1, 0-1
this.rgb = [1, 1, 1]; // read-only 0-1, 0-1, 0-1
this.minH = 0; // read-only 0-6
this.maxH = 6; // read-only 0-6
this.minS = 0; // read-only 0-1
this.maxS = 1; // read-only 0-1
this.minV = 0; // read-only 0-1
this.maxV = 1; // read-only 0-1
this.pickerOnfocus = true; // display picker on focus?
this.pickerMode = 'HSV'; // HSV | HVS
this.pickerPosition = 'bottom'; // left | right | top | bottom
this.pickerSmartPosition = true; // automatically adjust picker position when necessary
this.pickerButtonHeight = 20; // px
this.pickerClosable = false;
this.pickerCloseText = 'Close';
this.pickerButtonColor = 'ButtonText'; // px
this.pickerFace = 10; // px
this.pickerFaceColor = 'ThreeDFace'; // CSS color
this.pickerBorder = 1; // px
this.pickerBorderColor = 'ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight'; // CSS color
this.pickerInset = 1; // px
this.pickerInsetColor = 'ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow'; // CSS color
this.pickerZIndex = 10000;
for(var p in prop) {
if(prop.hasOwnProperty(p)) {
this[p] = prop[p];
}
}
this.hidePicker = function() {
if(isPickerOwner()) {
removePicker();
}
};
this.showPicker = function() {
if(!isPickerOwner()) {
var tp = jscolor.getElementPos(target); // target pos
var ts = jscolor.getElementSize(target); // target size
var vp = jscolor.getViewPos(); // view pos
var vs = jscolor.getViewSize(); // view size
var ps = getPickerDims(this); // picker size
var a, b, c;
switch(this.pickerPosition.toLowerCase()) {
case 'left': a=1; b=0; c=-1; break;
case 'right':a=1; b=0; c=1; break;
case 'top': a=0; b=1; c=-1; break;
default: a=0; b=1; c=1; break;
}
var l = (ts[b]+ps[b])/2;
// picker pos
if (!this.pickerSmartPosition) {
var pp = [
tp[a],
tp[b]+ts[b]-l+l*c
];
} else {
var pp = [
-vp[a]+tp[a]+ps[a] > vs[a] ?
(-vp[a]+tp[a]+ts[a]/2 > vs[a]/2 && tp[a]+ts[a]-ps[a] >= 0 ? tp[a]+ts[a]-ps[a] : tp[a]) :
tp[a],
-vp[b]+tp[b]+ts[b]+ps[b]-l+l*c > vs[b] ?
(-vp[b]+tp[b]+ts[b]/2 > vs[b]/2 && tp[b]+ts[b]-l-l*c >= 0 ? tp[b]+ts[b]-l-l*c : tp[b]+ts[b]-l+l*c) :
(tp[b]+ts[b]-l+l*c >= 0 ? tp[b]+ts[b]-l+l*c : tp[b]+ts[b]-l-l*c)
];
}
drawPicker(pp[a], pp[b]);
}
};
this.importColor = function() {
if(!valueElement) {
this.exportColor();
} else {
if(!this.adjust) {
if(!this.fromString(valueElement.value, leaveValue)) {
styleElement.style.backgroundImage = styleElement.jscStyle.backgroundImage;
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
}
} else if(!this.required && /^\s*$/.test(valueElement.value)) {
valueElement.value = '';
styleElement.style.backgroundImage = styleElement.jscStyle.backgroundImage;
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
} else if(this.fromString(valueElement.value)) {
// OK
} else {
this.exportColor();
}
}
};
this.exportColor = function(flags) {
if(!(flags & leaveValue) && valueElement) {
var value = this.toString();
if(this.caps) { value = value.toUpperCase(); }
if(this.hash) { value = '#'+value; }
valueElement.value = value;
}
if(!(flags & leaveStyle) && styleElement) {
styleElement.style.backgroundImage = "none";
styleElement.style.backgroundColor =
'#'+this.toString();
styleElement.style.color =
0.213 * this.rgb[0] +
0.715 * this.rgb[1] +
0.072 * this.rgb[2]
< 0.5 ? '#FFF' : '#000';
}
if(!(flags & leavePad) && isPickerOwner()) {
redrawPad();
}
if(!(flags & leaveSld) && isPickerOwner()) {
redrawSld();
}
};
this.fromHSV = function(h, s, v, flags) { // null = don't change
if(h !== null) { h = Math.max(0.0, this.minH, Math.min(6.0, this.maxH, h)); }
if(s !== null) { s = Math.max(0.0, this.minS, Math.min(1.0, this.maxS, s)); }
if(v !== null) { v = Math.max(0.0, this.minV, Math.min(1.0, this.maxV, v)); }
this.rgb = HSV_RGB(
h===null ? this.hsv[0] : (this.hsv[0]=h),
s===null ? this.hsv[1] : (this.hsv[1]=s),
v===null ? this.hsv[2] : (this.hsv[2]=v)
);
this.exportColor(flags);
};
this.fromRGB = function(r, g, b, flags) { // null = don't change
if(r !== null) { r = Math.max(0.0, Math.min(1.0, r)); }
if(g !== null) { g = Math.max(0.0, Math.min(1.0, g)); }
if(b !== null) { b = Math.max(0.0, Math.min(1.0, b)); }
var hsv = RGB_HSV(
r===null ? this.rgb[0] : r,
g===null ? this.rgb[1] : g,
b===null ? this.rgb[2] : b
);
if(hsv[0] !== null) {
this.hsv[0] = Math.max(0.0, this.minH, Math.min(6.0, this.maxH, hsv[0]));
}
if(hsv[2] !== 0) {
this.hsv[1] = hsv[1]===null ? null : Math.max(0.0, this.minS, Math.min(1.0, this.maxS, hsv[1]));
}
this.hsv[2] = hsv[2]===null ? null : Math.max(0.0, this.minV, Math.min(1.0, this.maxV, hsv[2]));
// update RGB according to final HSV, as some values might be trimmed
var rgb = HSV_RGB(this.hsv[0], this.hsv[1], this.hsv[2]);
this.rgb[0] = rgb[0];
this.rgb[1] = rgb[1];
this.rgb[2] = rgb[2];
this.exportColor(flags);
};
this.fromString = function(hex, flags) {
var m = hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i);
if(!m) {
return false;
} else {
if(m[1].length === 6) { // 6-char notation
this.fromRGB(
parseInt(m[1].substr(0,2),16) / 255,
parseInt(m[1].substr(2,2),16) / 255,
parseInt(m[1].substr(4,2),16) / 255,
flags
);
} else { // 3-char notation
this.fromRGB(
parseInt(m[1].charAt(0)+m[1].charAt(0),16) / 255,
parseInt(m[1].charAt(1)+m[1].charAt(1),16) / 255,
parseInt(m[1].charAt(2)+m[1].charAt(2),16) / 255,
flags
);
}
return true;
}
};
this.toString = function() {
return (
(0x100 | Math.round(255*this.rgb[0])).toString(16).substr(1) +
(0x100 | Math.round(255*this.rgb[1])).toString(16).substr(1) +
(0x100 | Math.round(255*this.rgb[2])).toString(16).substr(1)
);
};
function RGB_HSV(r, g, b) {
var n = Math.min(Math.min(r,g),b);
var v = Math.max(Math.max(r,g),b);
var m = v - n;
if(m === 0) { return [ null, 0, v ]; }
var h = r===n ? 3+(b-g)/m : (g===n ? 5+(r-b)/m : 1+(g-r)/m);
return [ h===6?0:h, m/v, v ];
}
function HSV_RGB(h, s, v) {
if(h === null) { return [ v, v, v ]; }
var i = Math.floor(h);
var f = i%2 ? h-i : 1-(h-i);
var m = v * (1 - s);
var n = v * (1 - s*f);
switch(i) {
case 6:
case 0: return [v,n,m];
case 1: return [n,v,m];
case 2: return [m,v,n];
case 3: return [m,n,v];
case 4: return [n,m,v];
case 5: return [v,m,n];
}
}
function removePicker() {
delete jscolor.picker.owner;
document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB);
}
function drawPicker(x, y) {
if(!jscolor.picker) {
jscolor.picker = {
box : document.createElement('div'),
boxB : document.createElement('div'),
pad : document.createElement('div'),
padB : document.createElement('div'),
padM : document.createElement('div'),
sld : document.createElement('div'),
sldB : document.createElement('div'),
sldM : document.createElement('div'),
btn : document.createElement('div'),
btnS : document.createElement('span'),
btnT : document.createTextNode(THIS.pickerCloseText)
};
for(var i=0,segSize=4; i<jscolor.images.sld[1]; i+=segSize) {
var seg = document.createElement('div');
seg.style.height = segSize+'px';
seg.style.fontSize = '1px';
seg.style.lineHeight = '0';
jscolor.picker.sld.appendChild(seg);
}
jscolor.picker.sldB.appendChild(jscolor.picker.sld);
jscolor.picker.box.appendChild(jscolor.picker.sldB);
jscolor.picker.box.appendChild(jscolor.picker.sldM);
jscolor.picker.padB.appendChild(jscolor.picker.pad);
jscolor.picker.box.appendChild(jscolor.picker.padB);
jscolor.picker.box.appendChild(jscolor.picker.padM);
jscolor.picker.btnS.appendChild(jscolor.picker.btnT);
jscolor.picker.btn.appendChild(jscolor.picker.btnS);
jscolor.picker.box.appendChild(jscolor.picker.btn);
jscolor.picker.boxB.appendChild(jscolor.picker.box);
}
var p = jscolor.picker;
// controls interaction
p.box.onmouseup =
p.box.onmouseout = function() { target.focus(); };
p.box.onmousedown = function() { abortBlur=true; };
p.box.onmousemove = function(e) {
if (holdPad || holdSld) {
holdPad && setPad(e);
holdSld && setSld(e);
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
dispatchImmediateChange();
}
};
p.padM.onmouseup =
p.padM.onmouseout = function() { if(holdPad) { holdPad=false; jscolor.fireEvent(valueElement,'change'); } };
p.padM.onmousedown = function(e) {
// if the slider is at the bottom, move it up
switch(modeID) {
case 0: if (THIS.hsv[2] === 0) { THIS.fromHSV(null, null, 1.0); }; break;
case 1: if (THIS.hsv[1] === 0) { THIS.fromHSV(null, 1.0, null); }; break;
}
holdPad=true;
setPad(e);
dispatchImmediateChange();
};
p.sldM.onmouseup =
p.sldM.onmouseout = function() { if(holdSld) { holdSld=false; jscolor.fireEvent(valueElement,'change'); } };
p.sldM.onmousedown = function(e) {
holdSld=true;
setSld(e);
dispatchImmediateChange();
};
// picker
var dims = getPickerDims(THIS);
p.box.style.width = dims[0] + 'px';
p.box.style.height = dims[1] + 'px';
// picker border
p.boxB.style.position = 'absolute';
p.boxB.style.clear = 'both';
p.boxB.style.left = x+'px';
p.boxB.style.top = y+'px';
p.boxB.style.zIndex = THIS.pickerZIndex;
p.boxB.style.border = THIS.pickerBorder+'px solid';
p.boxB.style.borderColor = THIS.pickerBorderColor;
p.boxB.style.background = THIS.pickerFaceColor;
// pad image
p.pad.style.width = jscolor.images.pad[0]+'px';
p.pad.style.height = jscolor.images.pad[1]+'px';
// pad border
p.padB.style.position = 'absolute';
p.padB.style.left = THIS.pickerFace+'px';
p.padB.style.top = THIS.pickerFace+'px';
p.padB.style.border = THIS.pickerInset+'px solid';
p.padB.style.borderColor = THIS.pickerInsetColor;
// pad mouse area
p.padM.style.position = 'absolute';
p.padM.style.left = '0';
p.padM.style.top = '0';
p.padM.style.width = THIS.pickerFace + 2*THIS.pickerInset + jscolor.images.pad[0] + jscolor.images.arrow[0] + 'px';
p.padM.style.height = p.box.style.height;
p.padM.style.cursor = 'crosshair';
// slider image
p.sld.style.overflow = 'hidden';
p.sld.style.width = jscolor.images.sld[0]+'px';
p.sld.style.height = jscolor.images.sld[1]+'px';
// slider border
p.sldB.style.display = THIS.slider ? 'block' : 'none';
p.sldB.style.position = 'absolute';
p.sldB.style.right = THIS.pickerFace+'px';
p.sldB.style.top = THIS.pickerFace+'px';
p.sldB.style.border = THIS.pickerInset+'px solid';
p.sldB.style.borderColor = THIS.pickerInsetColor;
// slider mouse area
p.sldM.style.display = THIS.slider ? 'block' : 'none';
p.sldM.style.position = 'absolute';
p.sldM.style.right = '0';
p.sldM.style.top = '0';
p.sldM.style.width = jscolor.images.sld[0] + jscolor.images.arrow[0] + THIS.pickerFace + 2*THIS.pickerInset + 'px';
p.sldM.style.height = p.box.style.height;
try {
p.sldM.style.cursor = 'pointer';
} catch(eOldIE) {
p.sldM.style.cursor = 'hand';
}
// "close" button
function setBtnBorder() {
var insetColors = THIS.pickerInsetColor.split(/\s+/);
var pickerOutsetColor = insetColors.length < 2 ? insetColors[0] : insetColors[1] + ' ' + insetColors[0] + ' ' + insetColors[0] + ' ' + insetColors[1];
p.btn.style.borderColor = pickerOutsetColor;
}
p.btn.style.display = THIS.pickerClosable ? 'block' : 'none';
p.btn.style.position = 'absolute';
p.btn.style.left = THIS.pickerFace + 'px';
p.btn.style.bottom = THIS.pickerFace + 'px';
p.btn.style.padding = '0 15px';
p.btn.style.height = '18px';
p.btn.style.border = THIS.pickerInset + 'px solid';
setBtnBorder();
p.btn.style.color = THIS.pickerButtonColor;
p.btn.style.font = '12px sans-serif';
p.btn.style.textAlign = 'center';
try {
p.btn.style.cursor = 'pointer';
} catch(eOldIE) {
p.btn.style.cursor = 'hand';
}
p.btn.onmousedown = function () {
THIS.hidePicker();
};
p.btnS.style.lineHeight = p.btn.style.height;
// load images in optimal order
switch(modeID) {
case 0: var padImg = 'hs.png'; break;
case 1: var padImg = 'hv.png'; break;
}
p.padM.style.backgroundImage = "url('"+jscolor.getDir()+"cross.gif')";
p.padM.style.backgroundRepeat = "no-repeat";
p.sldM.style.backgroundImage = "url('"+jscolor.getDir()+"arrow.gif')";
p.sldM.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundImage = "url('"+jscolor.getDir()+padImg+"')";
p.pad.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundPosition = "0 0";
// place pointers
redrawPad();
redrawSld();
jscolor.picker.owner = THIS;
document.getElementsByTagName('body')[0].appendChild(p.boxB);
}
function getPickerDims(o) {
var dims = [
2*o.pickerInset + 2*o.pickerFace + jscolor.images.pad[0] +
(o.slider ? 2*o.pickerInset + 2*jscolor.images.arrow[0] + jscolor.images.sld[0] : 0),
o.pickerClosable ?
4*o.pickerInset + 3*o.pickerFace + jscolor.images.pad[1] + o.pickerButtonHeight :
2*o.pickerInset + 2*o.pickerFace + jscolor.images.pad[1]
];
return dims;
}
function redrawPad() {
// redraw the pad pointer
switch(modeID) {
case 0: var yComponent = 1; break;
case 1: var yComponent = 2; break;
}
var x = Math.round((THIS.hsv[0]/6) * (jscolor.images.pad[0]-1));
var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.pad[1]-1));
jscolor.picker.padM.style.backgroundPosition =
(THIS.pickerFace+THIS.pickerInset+x - Math.floor(jscolor.images.cross[0]/2)) + 'px ' +
(THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.cross[1]/2)) + 'px';
// redraw the slider image
var seg = jscolor.picker.sld.childNodes;
switch(modeID) {
case 0:
var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 1);
for(var i=0; i<seg.length; i+=1) {
seg[i].style.backgroundColor = 'rgb('+
(rgb[0]*(1-i/seg.length)*100)+'%,'+
(rgb[1]*(1-i/seg.length)*100)+'%,'+
(rgb[2]*(1-i/seg.length)*100)+'%)';
}
break;
case 1:
var rgb, s, c = [ THIS.hsv[2], 0, 0 ];
var i = Math.floor(THIS.hsv[0]);
var f = i%2 ? THIS.hsv[0]-i : 1-(THIS.hsv[0]-i);
switch(i) {
case 6:
case 0: rgb=[0,1,2]; break;
case 1: rgb=[1,0,2]; break;
case 2: rgb=[2,0,1]; break;
case 3: rgb=[2,1,0]; break;
case 4: rgb=[1,2,0]; break;
case 5: rgb=[0,2,1]; break;
}
for(var i=0; i<seg.length; i+=1) {
s = 1 - 1/(seg.length-1)*i;
c[1] = c[0] * (1 - s*f);
c[2] = c[0] * (1 - s);
seg[i].style.backgroundColor = 'rgb('+
(c[rgb[0]]*100)+'%,'+
(c[rgb[1]]*100)+'%,'+
(c[rgb[2]]*100)+'%)';
}
break;
}
}
function redrawSld() {
// redraw the slider pointer
switch(modeID) {
case 0: var yComponent = 2; break;
case 1: var yComponent = 1; break;
}
var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.sld[1]-1));
jscolor.picker.sldM.style.backgroundPosition =
'0 ' + (THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.arrow[1]/2)) + 'px';
}
function isPickerOwner() {
return jscolor.picker && jscolor.picker.owner === THIS;
}
function blurTarget() {
if(valueElement === target) {
THIS.importColor();
}
if(THIS.pickerOnfocus) {
THIS.hidePicker();
}
}
function blurValue() {
if(valueElement !== target) {
THIS.importColor();
}
}
function setPad(e) {
var mpos = jscolor.getRelMousePos(e);
var x = mpos.x - THIS.pickerFace - THIS.pickerInset;
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch(modeID) {
case 0: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), 1 - y/(jscolor.images.pad[1]-1), null, leaveSld); break;
case 1: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), null, 1 - y/(jscolor.images.pad[1]-1), leaveSld); break;
}
}
function setSld(e) {
var mpos = jscolor.getRelMousePos(e);
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch(modeID) {
case 0: THIS.fromHSV(null, null, 1 - y/(jscolor.images.sld[1]-1), leavePad); break;
case 1: THIS.fromHSV(null, 1 - y/(jscolor.images.sld[1]-1), null, leavePad); break;
}
}
function dispatchImmediateChange() {
if (THIS.onImmediateChange) {
var callback;
if (typeof THIS.onImmediateChange === 'string') {
callback = new Function (THIS.onImmediateChange);
} else {
callback = THIS.onImmediateChange;
}
callback.call(THIS);
}
}
var THIS = this;
var modeID = this.pickerMode.toLowerCase()==='hvs' ? 1 : 0;
var abortBlur = false;
var
valueElement = jscolor.fetchElement(this.valueElement),
styleElement = jscolor.fetchElement(this.styleElement);
var
holdPad = false,
holdSld = false;
var
leaveValue = 1<<0,
leaveStyle = 1<<1,
leavePad = 1<<2,
leaveSld = 1<<3;
// target
jscolor.addEvent(target, 'focus', function() {
if(THIS.pickerOnfocus) { THIS.showPicker(); }
});
jscolor.addEvent(target, 'blur', function() {
if(!abortBlur) {
window.setTimeout(function(){ abortBlur || blurTarget(); abortBlur=false; }, 0);
} else {
abortBlur = false;
}
});
// valueElement
if(valueElement) {
var updateField = function() {
THIS.fromString(valueElement.value, leaveValue);
dispatchImmediateChange();
};
jscolor.addEvent(valueElement, 'keyup', updateField);
jscolor.addEvent(valueElement, 'input', updateField);
jscolor.addEvent(valueElement, 'blur', blurValue);
valueElement.setAttribute('autocomplete', 'off');
}
// styleElement
if(styleElement) {
styleElement.jscStyle = {
backgroundImage : styleElement.style.backgroundImage,
backgroundColor : styleElement.style.backgroundColor,
color : styleElement.style.color
};
}
// require images
switch(modeID) {
case 0: jscolor.requireImage('hs.png'); break;
case 1: jscolor.requireImage('hv.png'); break;
}
jscolor.requireImage('cross.gif');
jscolor.requireImage('arrow.gif');
this.importColor();
}
};
jscolor.install();
| JavaScript |
var RoomConstruction = new function(){
var roomConstruction=this;
this.pass='';
this.setPass=function(pass){
roomConstruction.pass=pass;
};
this.getPass=function(){
return roomConstruction.pass;
};
this.joinRoom=function(roomId, roomName, usageTypeId, rangeArray) {
var room= App.get_room(roomId, 'room');
if(room)
return goToRoom(room);
var joinRoomFunctionURL = 'http://localhost/x7/pages/joinroom.php';
var argJson = {
'room_id' : roomId,
'roomName': roomName,
'usageTypeId':usageTypeId,
'rangeArray':rangeArray
};
if(RoomConstruction.getPass()){
argJson["password"]=RoomConstruction.getPass();
}
$.ajax({
type : "POST",
url : joinRoomFunctionURL,
dataType : "json",
data : argJson,
success : function(jSonRoomComponents) {
getRoomFromPHPtoJS(jSonRoomComponents);
},
error : function(xhr, ajaxOptions, thrownError) {
alert('joinroom.js:1:' + xhr.status);
alert(thrownError);
}
});
// AJAX ICINDEN CAGRILAN FONKSIYONLAR
var users ='';
var messages = '';
function getRoomFromPHPtoJS(jSonRoomComponents) {
var url=jSonRoomComponents.url;
if(url){
open_content_area(url);
return false;
}
var type=jSonRoomComponents.type;
if(type){
var message=jSonRoomComponents.message;
var urlRoom=jSonRoomComponents.urlRoom;
var navigate=jSonRoomComponents.navigate;
UtilJS.showMessages(type, message,navigate,urlRoom );
return false;
}
users = jSonRoomComponents.users;
room = new App.Room(jSonRoomComponents.room);
messages = jSonRoomComponents.messages;
room.type = 'room';
App.add_room(room);
for ( var key in users) {
App.add_user_room(users[key], 1);
}
for ( var key in messages) {
var message = new App.Message(messages[key]);
App.add_message(message);
}
goToRoom(room);
}
function goToRoom(room){
App.set_active_room(room);
close_content_area();
toggleUsageDiv();
return false;
}
}
} | JavaScript |
/*!
fancyInput v1.3.0
(c) 2013 Yair Even Or <http://dropthebit.com>
MIT-style license.
*/
(function($){
"use strict";
var isIe = !!window.ActiveXObject,
isWebkit = 'webkitRequestAnimationFrame' in window,
letterHeight;
$.fn.fancyInput = function(){
if( !isIe || 'ontouchstart' in document.documentElement )
init( this );
return this;
}
var fancyInput = {
classToggler : 'state1',
keypress : function(e){
var charString = String.fromCharCode(e.charCode),
textCont = this.nextElementSibling,
appendIndex = this.selectionEnd,
newLine = this.tagName == 'TEXTAREA' && e.keyCode == 13;
if( (this.selectionEnd - this.selectionStart) > 0 && e.charCode && !(e.metaKey || e.ctrlKey) ){
var rangeToDel = [this.selectionStart, this.selectionEnd];
appendIndex = this.selectionStart;
if( charDir.lastDir == 'rtl' ){ // BIDI support
rangeToDel = [this.value.length - this.selectionEnd, this.value.length - this.selectionStart + 1];
//appendIndex = this.value.length;
}
fancyInput.removeChars(textCont, rangeToDel);
}
if( e.charCode && !(e.metaKey || e.ctrlKey) || newLine ){
var dir = charDir.check(charString); // BIDI support
if( dir == 'rtl' || (dir == '' && charDir.lastDir == 'rtl' ) )
appendIndex = this.value.length - this.selectionStart;
if( newLine )
charString = '';
/*
setTimeout(function(){
console.log( e.target.value.slice(-1) );
},0);
*/
fancyInput.maskPassword(this);
fancyInput.writer(charString, this, appendIndex);
}
},
input : function(){
fancyInput.textLength = this.value.length; // save a referece to later check if text was added in the "allEvents" callback
fancyInput.inputResize( this );
},
// if password field, delete all content
maskPassword : function(input){
if( input.type == 'password' )
$(input.nextElementSibling).find('span').each(function(){
this.innerHTML = '';
});
},
// Clalculate letter height for the Carot, after first letter have been typed, or text pasted (only once)
setCaretHeight : function(input){
var lettersWrap = $(input.nextElementSibling);
if( !lettersWrap.find('span').length )
return false;
letterHeight = lettersWrap.find('span')[0].clientHeight;
lettersWrap.find('b').height(letterHeight);
},
writer : function(charString, input, appendIndex){
var chars = $(input.nextElementSibling).children().not('b'), // select all characters including <br> (which is a new line)
newCharElm = document.createElement('span');
if( charString == ' ' ) // space
charString = ' ';
if( charString ){
newCharElm.innerHTML = charString;
this.classToggler = this.classToggler == 'state2' ? 'state1' : 'state2';
newCharElm.className = this.classToggler;
}
else
newCharElm = document.createElement('br');
if( chars.length ){
if( appendIndex == 0 )
$(input.nextElementSibling).prepend(newCharElm);
else{
var appendPos = chars.eq(--appendIndex);
appendPos.after(newCharElm);
}
}
else
input.nextElementSibling.appendChild(newCharElm);
// let the render tree settle down with the new class, then remove it
if( charString)
setTimeout(function(){
newCharElm.removeAttribute("class");
},20);
return this;
},
clear : function(textCont){
var caret = $(textCont.parentNode).find('.caret');
$(textCont).html(caret);
},
// insert bulk text (unlike the "writer" fucntion which is for single character only)
fillText : function(text, input){
var charsCont = input.nextElementSibling,
newCharElm,
frag = document.createDocumentFragment();
fancyInput.clear( input.nextElementSibling );
setTimeout( function(){
var length = text.length;
for( var i=0; i < length; i++ ){
var newElm = 'span';
//fancyInput.writer( text[i], input, i);
if( text[i] == '\n' )
newElm = 'br';
newCharElm = document.createElement(newElm);
newCharElm.innerHTML = (text[i] == ' ') ? ' ' : text[i];
frag.appendChild(newCharElm);
}
charsCont.appendChild(frag);
},0);
},
// Handles characters removal from the fake text input
removeChars : function(el, range){
var allChars = $(el).children().not('b').not('.deleted'),
caret = $(el).find('b'),
charsToRemove;
if( range[0] == range[1] )
range[0]--;
charsToRemove = allChars.slice(range[0], range[1]);
if( range[1] - range[0] == 1 ){
charsToRemove.css('position','absolute');
if(isWebkit && charsToRemove[0] )
charsToRemove[0].offsetLeft;
charsToRemove.addClass('deleted');
setTimeout(function(){
charsToRemove.remove();
},140);
}
else
charsToRemove.remove();
},
// recalculate textarea height or input width
inputResize : function(el){
if( el.tagName == 'TEXTAREA' ){
setTimeout(function(){
el.style.top = '-999px';
var newHeight = el.parentNode.scrollHeight;
if( $(el).outerHeight() < el.parentNode.scrollHeight )
newHeight += 10;
el.style.height = newHeight + 'px';
el.style.top = '0';
// must re-adjust scrollTop after pasting long text
setTimeout(function(){
el.scrollTop = 0;
el.parentNode.scrollTop = 9999;
},50);
},0);
}
if( el.tagName == 'INPUT' && el.type == 'text' ){
el.style.width = 0;
var newWidth = el.parentNode.scrollWidth
// if there is a scroll (or should be) adjust with some extra width
if( el.parentNode.scrollWidth > el.parentNode.clientWidth )
newWidth += 20;
el.style.width = newWidth + 'px';
// re-adjustment
//el.scrollLeft = 9999;
//el.parentNode.scrollLeft += offset;
}
},
keydown : function(e){
var charString = String.fromCharCode(e.charCode),
textCont = this.nextElementSibling, // text container DIV
appendIndex = this.selectionEnd,
undo = ((e.metaKey || e.ctrlKey) && e.keyCode == 90) || (e.altKey && e.keyCode == 8),
redo = (e.metaKey || e.ctrlKey) && e.keyCode == 89,
selectAll = (e.metaKey || e.ctrlKey) && e.keyCode == 65,
caretAtEndNoSelection = (this.selectionEnd == this.selectionStart && this.selectionEnd == this.value.length ),
deleteKey = e.keyCode == 46 && !caretAtEndNoSelection;
fancyInput.setCaret(this);
if( selectAll )
return true;
if( undo || redo ){
// give the undo time actually remove the text from the DOM
setTimeout( function(){
fancyInput.fillText(e.target.value, e.target);
}, 50);
return true;
}
// if BACKSPACE or DELETE
if( e.keyCode == 8 || deleteKey ){
var selectionRange = [this.selectionStart, this.selectionEnd];
if( charDir.lastDir == 'rtl' ) // BIDI support
selectionRange = [this.value.length - this.selectionEnd, this.value.length - this.selectionStart + 1];
// on pressing 'delete' while nothing is selected, and caret is not at the end
if( deleteKey && (this.selectionEnd == this.selectionStart && this.selectionEnd < this.value.length) ){
selectionRange[0] += 1;
selectionRange[1] += 1;
fancyInput.removeChars(textCont, selectionRange);
}
else
setTimeout(function(){
if( e.metaKey || e.ctrlKey ) // when doing CTRL + BACKSPACE, needs to wait until the text was actually removed
selectionRange = [e.target.selectionStart, selectionRange[0]];
fancyInput.removeChars(textCont, selectionRange);
},0);
}
// make sure to reset the container scrollLeft when caret is the the START or ar the END
if( this.selectionStart == 0 )
this.parentNode.scrollLeft = 0;
return true;
},
allEvents : function(e){
fancyInput.setCaret(this);
if( e.type == 'paste' ){
setTimeout(function(){
fancyInput.fillText(e.target.value, e.target);
fancyInput.inputResize(e.target);
},20);
}
if( e.type == 'cut' ){
fancyInput.removeChars(this.nextElementSibling, [this.selectionStart, this.selectionEnd]);
}
// I use 50 but most numbers under 65 will do i believe
if( !e.keyCode || e.keyCode < 50 )
fancyInput.maskPassword(this);
// The caret height should be set. only once after the first character was entered.
if( !letterHeight ){
// in case text was pasted, wait for it to actually render
setTimeout(function(){ fancyInput.setCaretHeight(e.target) }, 150);
}
if( this.selectionStart == this.value.length )
this.parentNode.scrollLeft = 999999; // this.parentNode.scrollLeftMax
},
setCaret : function(input){
var caret = $(input.parentNode).find('.caret'),
allChars = $(input.nextElementSibling).children().not('b'),
chars = allChars.not('.deleted'),
pos = fancyInput.getCaretPosition(input);
if( charDir.lastDir == 'rtl' ) // BIDI support
pos = input.value.length - pos;
var insertPos = chars.eq(pos);
if(pos == input.value.length ){
//if( !chars.length )
// caret.prependTo( input.nextElementSibling );
//else
caret.appendTo( input.nextElementSibling );
}
else
caret.insertBefore( insertPos );
},
getCaretPosition : function(input){
var caretPos, direction = getSelectionDirection.direction || 'right';
if( input.selectionStart || input.selectionStart == '0' )
caretPos = direction == 'left' ? input.selectionStart : input.selectionEnd;
return caretPos || 0;
}
},
getSelectionDirection = {
direction : null,
lastOffset : null,
set : function(e){
var d;
if( e.shiftKey && e.keyCode == 37 )
d = 'left';
else if( e.shiftKey && e.keyCode == 39 )
d = 'right';
if( e.type == 'mousedown' )
getSelectionDirection.lastOffset = e.clientX;
else if( e.type == 'mouseup' )
d = e.clientX < getSelectionDirection.lastOffset ? 'left' : 'right';
getSelectionDirection.direction = d;
}
},
charDir = {
lastDir : null,
check : function(s){
var ltrChars = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF'+'\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',
rtlChars = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',
ltrDirCheck = new RegExp('^[^'+rtlChars+']*['+ltrChars+']'),
rtlDirCheck = new RegExp('^[^'+ltrChars+']*['+rtlChars+']');
var dir = rtlDirCheck.test(s) ? 'rtl' : (ltrDirCheck.test(s) ? 'ltr' : '');
if( dir ) this.lastDir = dir;
return dir;
}
}
function init(inputs){
var selector = inputs.selector;
inputs.each(function(){
var className = 'fancyInput',
template = $('<div><b class="caret">​</b></div>');
if( this.tagName == 'TEXTAREA' )
className += ' textarea';
// add need DOM for the plugin to work
$(this.parentNode).append(template).addClass(className);
// populate the fake field if there was any text in the real input
if( this.value )
fancyInput.fillText(this.value, this);
});
// bind all the events to simulate an input type text (yes, alot)
$(document)
.off('.fi', selector)
.on('input.fi', selector, fancyInput.input)
.on('keypress.fi', selector, fancyInput.keypress)
.on('keyup.fi select.fi mouseup.fi cut.fi paste.fi blur.fi', selector, fancyInput.allEvents)
.on('mousedown.fi mouseup.fi keydown.fi', selector, getSelectionDirection.set)
.on('keydown.fi', selector , fancyInput.keydown);
}
window.fancyInput = fancyInput;
})(window.jQuery);
| JavaScript |
var UtilJS = new function(){
this.showMessages= function(type, message,navigate,urlRoom){
var messageSpan = $('#messageSpan');
messageSpan.addClass(type);
if(navigate>=0) // if usage_type is DICTIONARY
{
message=message.trim();
var roomNameStr=message.replace(/\s+/g, '+').toLowerCase();
urlRoom=urlRoom
+"&usageTypeId="+navigate
+"&roomNameStr="+ roomNameStr;
urlRoom='<a onclick=open_content_area("'+urlRoom+'")>Sen kur!</a>';
messageSpan.html(message+":"+urlRoom);
}else{
messageSpan.text(message);
}
};
}; | JavaScript |
/* ------------------------------------------------------------------------
Class: prettyPhoto
Use: Lightbox clone for jQuery
Author: Stephane Caron (http://www.no-margin-for-errors.com)
Version: 3.1.5
------------------------------------------------------------------------- */
(function (e) {
function t() {
var e = location.href;
hashtag = e.indexOf("#prettyPhoto") !== -1 ? decodeURI(e.substring(e.indexOf("#prettyPhoto") + 1, e.length)) : false;
return hashtag
}
function n() {
if (typeof theRel == "undefined") return;
location.hash = theRel + "/" + rel_index + "/"
}
function r() {
if (location.href.indexOf("#prettyPhoto") !== -1) location.hash = "prettyPhoto"
}
function i(e, t) {
e = e.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var n = "[\\?&]" + e + "=([^&#]*)";
var r = new RegExp(n);
var i = r.exec(t);
return i == null ? "" : i[1]
}
e.prettyPhoto = {
version: "3.1.5"
};
e.fn.prettyPhoto = function (s) {
function g() {
e(".pp_loaderIcon").hide();
projectedTop = scroll_pos["scrollTop"] + (d / 2 - a["containerHeight"] / 2);
if (projectedTop < 0) projectedTop = 0;
$ppt.fadeTo(settings.animation_speed, 1);
$pp_pic_holder.find(".pp_content").animate({
height: a["contentHeight"],
width: a["contentWidth"]
}, settings.animation_speed);
$pp_pic_holder.animate({
top: projectedTop,
left: v / 2 - a["containerWidth"] / 2 < 0 ? 0 : v / 2 - a["containerWidth"] / 2,
width: a["containerWidth"]
}, settings.animation_speed, function () {
$pp_pic_holder.find(".pp_hoverContainer,#fullResImage").height(a["height"]).width(a["width"]);
$pp_pic_holder.find(".pp_fade").fadeIn(settings.animation_speed);
if (isSet && S(pp_images[set_position]) == "image") {
$pp_pic_holder.find(".pp_hoverContainer").show()
} else {
$pp_pic_holder.find(".pp_hoverContainer").hide()
} if (settings.allow_expand) {
if (a["resized"]) {
e("a.pp_expand,a.pp_contract").show()
} else {
e("a.pp_expand").hide()
}
}
if (settings.autoplay_slideshow && !m && !f) e.prettyPhoto.startSlideshow();
settings.changepicturecallback();
f = true
});
C();
s.ajaxcallback()
}
function y(t) {
$pp_pic_holder.find("#pp_full_res object,#pp_full_res embed").css("visibility", "hidden");
$pp_pic_holder.find(".pp_fade").fadeOut(settings.animation_speed, function () {
e(".pp_loaderIcon").show();
t()
})
}
function b(t) {
t > 1 ? e(".pp_nav").show() : e(".pp_nav").hide()
}
function w(e, t) {
resized = false;
E(e, t);
imageWidth = e, imageHeight = t;
if ((p > v || h > d) && doresize && settings.allow_resize && !u) {
resized = true, fitting = false;
while (!fitting) {
if (p > v) {
imageWidth = v - 200;
imageHeight = t / e * imageWidth
} else if (h > d) {
imageHeight = d - 200;
imageWidth = e / t * imageHeight
} else {
fitting = true
}
h = imageHeight, p = imageWidth
}
if (p > v || h > d) {
w(p, h)
}
E(imageWidth, imageHeight)
}
return {
width: Math.floor(imageWidth),
height: Math.floor(imageHeight),
containerHeight: Math.floor(h),
containerWidth: Math.floor(p) + settings.horizontal_padding * 2,
contentHeight: Math.floor(l),
contentWidth: Math.floor(c),
resized: resized
}
}
function E(t, n) {
t = parseFloat(t);
n = parseFloat(n);
$pp_details = $pp_pic_holder.find(".pp_details");
$pp_details.width(t);
detailsHeight = parseFloat($pp_details.css("marginTop")) + parseFloat($pp_details.css("marginBottom"));
$pp_details = $pp_details.clone().addClass(settings.theme).width(t).appendTo(e("body")).css({
position: "absolute",
top: -1e4
});
detailsHeight += $pp_details.height();
detailsHeight = detailsHeight <= 34 ? 36 : detailsHeight;
$pp_details.remove();
$pp_title = $pp_pic_holder.find(".ppt");
$pp_title.width(t);
titleHeight = parseFloat($pp_title.css("marginTop")) + parseFloat($pp_title.css("marginBottom"));
$pp_title = $pp_title.clone().appendTo(e("body")).css({
position: "absolute",
top: -1e4
});
titleHeight += $pp_title.height();
$pp_title.remove();
l = n + detailsHeight;
c = t;
h = l + titleHeight + $pp_pic_holder.find(".pp_top").height() + $pp_pic_holder.find(".pp_bottom").height();
p = t
}
function S(e) {
if (e.match(/youtube\.com\/watch/i) || e.match(/youtu\.be/i)) {
return "youtube"
} else if (e.match(/vimeo\.com/i)) {
return "vimeo"
} else if (e.match(/dailymotion\.com/i)) {
return "dailymotion"
} else if (e.match(/zapkolik\.com/i)) {
return "zapkolik"
} else if (e.match(/nytimes\.com/i)) {
return "nytimes"
} else if (e.match(/reuters\.com/i)) {
return "reuters"
} else if (e.match(/ustream\.tv/i)) {
return "ustream"
} else if (e.match(/ted\.com/i)) {
return "ted"
} else if (e.match(/\b.mov\b/i)) {
return "quicktime"
} else if (e.match(/\b.swf\b/i)) {
return "flash"
} else if (e.match(/\biframe=true\b/i)) {
return "iframe"
} else if (e.match(/\bajax=true\b/i)) {
return "ajax"
} else if (e.match(/\bcustom=true\b/i)) {
return "custom"
} else if (e.substr(0, 1) == "#") {
return "inline"
} else {
return "image"
}
}
function x() {
if (doresize && typeof $pp_pic_holder != "undefined") {
scroll_pos = T();
contentHeight = $pp_pic_holder.height(), contentwidth = $pp_pic_holder.width();
projectedTop = d / 2 + scroll_pos["scrollTop"] - contentHeight / 2;
if (projectedTop < 0) projectedTop = 0;
if (contentHeight > d) return;
$pp_pic_holder.css({
top: projectedTop,
left: v / 2 + scroll_pos["scrollLeft"] - contentwidth / 2
})
}
}
function T() {
if (self.pageYOffset) {
return {
scrollTop: self.pageYOffset,
scrollLeft: self.pageXOffset
}
} else if (document.documentElement && document.documentElement.scrollTop) {
return {
scrollTop: document.documentElement.scrollTop,
scrollLeft: document.documentElement.scrollLeft
}
} else if (document.body) {
return {
scrollTop: document.body.scrollTop,
scrollLeft: document.body.scrollLeft
}
}
}
function N() {
d = e(window).height(), v = e(window).width();
if (typeof $pp_overlay != "undefined") $pp_overlay.height(e(document).height()).width(v)
}
function C() {
if (isSet && settings.overlay_gallery && S(pp_images[set_position]) == "image") {
itemWidth = 52 + 5;
navWidth = settings.theme == "facebook" || settings.theme == "pp_default" ? 50 : 30;
itemsPerPage = Math.floor((a["containerWidth"] - 100 - navWidth) / itemWidth);
itemsPerPage = itemsPerPage < pp_images.length ? itemsPerPage : pp_images.length;
totalPage = Math.ceil(pp_images.length / itemsPerPage) - 1;
if (totalPage == 0) {
navWidth = 0;
$pp_gallery.find(".pp_arrow_next,.pp_arrow_previous").hide()
} else {
$pp_gallery.find(".pp_arrow_next,.pp_arrow_previous").show()
}
galleryWidth = itemsPerPage * itemWidth;
fullGalleryWidth = pp_images.length * itemWidth;
$pp_gallery.css("margin-left", -(galleryWidth / 2 + navWidth / 2)).find("div:first").width(galleryWidth + 5).find("ul").width(fullGalleryWidth).find("li.selected").removeClass("selected");
goToPage = Math.floor(set_position / itemsPerPage) < totalPage ? Math.floor(set_position / itemsPerPage) : totalPage;
e.prettyPhoto.changeGalleryPage(goToPage);
$pp_gallery_li.filter(":eq(" + set_position + ")").addClass("selected")
} else {
$pp_pic_holder.find(".pp_content").unbind("mouseenter mouseleave")
}
}
function k(t) {
if (settings.social_tools) facebook_like_link = settings.social_tools.replace("{location_href}", encodeURIComponent(location.href));
settings.markup = settings.markup.replace("{pp_social}", "");
e("body").append(settings.markup);
$pp_pic_holder = e(".pp_pic_holder"), $ppt = e(".ppt"), $pp_overlay = e("div.pp_overlay");
if (isSet && settings.overlay_gallery) {
currentGalleryPage = 0;
toInject = "";
for (var n = 0; n < pp_images.length; n++) {
if (!pp_images[n].match(/\b(jpg|jpeg|png|gif)\b/gi)) {
classname = "default";
img_src = ""
} else {
classname = "";
img_src = pp_images[n]
}
toInject += "<li class='" + classname + "'><a href='#'><img src='" + img_src + "' width='50' alt='' /></a></li>"
}
toInject = settings.gallery_markup.replace(/{gallery}/g, toInject);
$pp_pic_holder.find("#pp_full_res").after(toInject);
$pp_gallery = e(".pp_pic_holder .pp_gallery"), $pp_gallery_li = $pp_gallery.find("li");
$pp_gallery.find(".pp_arrow_next").click(function () {
e.prettyPhoto.changeGalleryPage("next");
e.prettyPhoto.stopSlideshow();
return false
});
$pp_gallery.find(".pp_arrow_previous").click(function () {
e.prettyPhoto.changeGalleryPage("previous");
e.prettyPhoto.stopSlideshow();
return false
});
$pp_pic_holder.find(".pp_content").hover(function () {
$pp_pic_holder.find(".pp_gallery:not(.disabled)").fadeIn()
}, function () {
$pp_pic_holder.find(".pp_gallery:not(.disabled)").fadeOut()
});
itemWidth = 52 + 5;
$pp_gallery_li.each(function (t) {
e(this).find("a").click(function () {
e.prettyPhoto.changePage(t);
e.prettyPhoto.stopSlideshow();
return false
})
})
}
if (settings.slideshow) {
$pp_pic_holder.find(".pp_nav").prepend('<a href="#" class="pp_play">Play</a>');
$pp_pic_holder.find(".pp_nav .pp_play").click(function () {
e.prettyPhoto.startSlideshow();
return false
})
}
$pp_pic_holder.attr("class", "pp_pic_holder " + settings.theme);
$pp_overlay.css({
opacity: 0,
height: e(document).height(),
width: e(window).width()
}).bind("click", function () {
if (!settings.modal) e.prettyPhoto.close()
});
e("a.pp_close").bind("click", function () {
e.prettyPhoto.close();
return false
});
if (settings.allow_expand) {
e("a.pp_expand").bind("click", function (t) {
if (e(this).hasClass("pp_expand")) {
e(this).removeClass("pp_expand").addClass("pp_contract");
doresize = false
} else {
e(this).removeClass("pp_contract").addClass("pp_expand");
doresize = true
}
y(function () {
e.prettyPhoto.open()
});
return false
})
}
$pp_pic_holder.find(".pp_previous, .pp_nav .pp_arrow_previous").bind("click", function () {
e.prettyPhoto.changePage("previous");
e.prettyPhoto.stopSlideshow();
return false
});
$pp_pic_holder.find(".pp_next, .pp_nav .pp_arrow_next").bind("click", function () {
e.prettyPhoto.changePage("next");
e.prettyPhoto.stopSlideshow();
return false
});
x()
}
s = jQuery.extend({
hook: "rel",
animation_speed: "fast",
ajaxcallback: function () {},
slideshow: 5e3,
autoplay_slideshow: false,
opacity: .8,
show_title: true,
allow_resize: true,
allow_expand: true,
default_width: 500,
default_height: 344,
counter_separator_label: "/",
theme: "pp_default",
horizontal_padding: 20,
hideflash: false,
wmode: "opaque",
autoplay: true,
modal: false,
deeplinking: true,
overlay_gallery: true,
overlay_gallery_max: 30,
keyboard_shortcuts: true,
changepicturecallback: function () {},
callback: function () {},
ie6_fallback: true,
markup: '<div class="pp_pic_holder"> <div class="ppt"> </div> <div class="pp_top"> <div class="pp_left"></div> <div class="pp_middle"></div> <div class="pp_right"></div> </div> <div class="pp_content_container"> <div class="pp_left"> <div class="pp_right"> <div class="pp_content"> <div class="pp_loaderIcon"></div> <div class="pp_fade"> <a href="#" class="pp_expand" title="Expand the image">Expand</a> <div class="pp_hoverContainer"> <a class="pp_next" href="#">next</a> <a class="pp_previous" href="#">previous</a> </div> <div id="pp_full_res"></div> <div class="pp_details"> <div class="pp_nav"> <a href="#" class="pp_arrow_previous">Previous</a> <p class="currentTextHolder">0/0</p> <a href="#" class="pp_arrow_next">Next</a> </div> <p class="pp_description"></p> <div class="pp_social">{pp_social}</div> <a class="pp_close" href="#">Close</a> </div> </div> </div> </div> </div> </div> <div class="pp_bottom"> <div class="pp_left"></div> <div class="pp_middle"></div> <div class="pp_right"></div> </div> </div> <div class="pp_overlay"></div>',
gallery_markup: '<div class="pp_gallery"> <a href="#" class="pp_arrow_previous">Previous</a> <div> <ul> {gallery} </ul> </div> <a href="#" class="pp_arrow_next">Next</a> </div>',
image_markup: '<img id="fullResImage" src="{path}" />',
flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
inline_markup: '<div class="pp_inline">{content}</div>',
custom_markup: "",
social_tools: '<div class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="facebook"><iframe src="//www.facebook.com/plugins/like.php?locale=en_US&href={location_href}&layout=button_count&show_faces=true&width=500&action=like&font&colorscheme=light&height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div>'
}, s);
var o = this,
u = false,
a, f, l, c, h, p, d = e(window).height(),
v = e(window).width(),
m;
doresize = true, scroll_pos = T();
e(window).unbind("resize.prettyphoto").bind("resize.prettyphoto", function () {
x();
N()
});
if (s.keyboard_shortcuts) {
e(document).unbind("keydown.prettyphoto").bind("keydown.prettyphoto", function (t) {
if (typeof $pp_pic_holder != "undefined") {
if ($pp_pic_holder.is(":visible")) {
switch (t.keyCode) {
case 37:
e.prettyPhoto.changePage("previous");
t.preventDefault();
break;
case 39:
e.prettyPhoto.changePage("next");
t.preventDefault();
break;
case 27:
if (!settings.modal) e.prettyPhoto.close();
t.preventDefault();
break
}
}
}
})
}
e.prettyPhoto.initialize = function () {
settings = s;
if (settings.theme == "pp_default") settings.horizontal_padding = 16;
theRel = e(this).attr(settings.hook);
galleryRegExp = /\[(?:.*)\]/;
isSet = galleryRegExp.exec(theRel) ? true : false;
pp_images = isSet ? jQuery.map(o, function (t, n) {
if (e(t).attr(settings.hook).indexOf(theRel) != -1) return e(t).attr("href")
}) : e.makeArray(e(this).attr("href"));
pp_titles = isSet ? jQuery.map(o, function (t, n) {
if (e(t).attr(settings.hook).indexOf(theRel) != -1) return e(t).find("img").attr("alt") ? e(t).find("img").attr("alt") : ""
}) : e.makeArray(e(this).find("img").attr("alt"));
pp_descriptions = isSet ? jQuery.map(o, function (t, n) {
if (e(t).attr(settings.hook).indexOf(theRel) != -1) return e(t).attr("title") ? e(t).attr("title") : ""
}) : e.makeArray(e(this).attr("title"));
if (pp_images.length > settings.overlay_gallery_max) settings.overlay_gallery = false;
set_position = jQuery.inArray(e(this).attr("href"), pp_images);
rel_index = isSet ? set_position : e("a[" + settings.hook + "^='" + theRel + "']").index(e(this));
k(this);
if (settings.allow_resize) e(window).bind("scroll.prettyphoto", function () {
x()
});
e.prettyPhoto.open();
return false
};
e.prettyPhoto.open = function (t) {
if (typeof settings == "undefined") {
settings = s;
pp_images = e.makeArray(arguments[0]);
pp_titles = arguments[1] ? e.makeArray(arguments[1]) : e.makeArray("");
pp_descriptions = arguments[2] ? e.makeArray(arguments[2]) : e.makeArray("");
isSet = pp_images.length > 1 ? true : false;
set_position = arguments[3] ? arguments[3] : 0;
k(t.target)
}
if (settings.hideflash) e("object,embed,iframe[src*=youtube],iframe[src*=vimeo],iframe[src*=dailymotion], iframe[src*=zapkolik], iframe[src*=nytimes], iframe[src*=reuters], iframe[src*=ustream], iframe[src*=ted]").css("visibility", "hidden");
b(e(pp_images).size());
e(".pp_loaderIcon").show();
if (settings.deeplinking) n();
if (settings.social_tools) {
facebook_like_link = settings.social_tools.replace("{location_href}", encodeURIComponent(location.href));
$pp_pic_holder.find(".pp_social").html(facebook_like_link)
}
if ($ppt.is(":hidden")) $ppt.css("opacity", 0).show();
$pp_overlay.show().fadeTo(settings.animation_speed, settings.opacity);
$pp_pic_holder.find(".currentTextHolder").text(set_position + 1 + settings.counter_separator_label + e(pp_images).size());
if (typeof pp_descriptions[set_position] != "undefined" && pp_descriptions[set_position] != "") {
$pp_pic_holder.find(".pp_description").show().html(unescape(pp_descriptions[set_position]))
} else {
$pp_pic_holder.find(".pp_description").hide()
}
movie_width = parseFloat(i("width", pp_images[set_position])) ? i("width", pp_images[set_position]) : settings.default_width.toString();
movie_height = parseFloat(i("height", pp_images[set_position])) ? i("height", pp_images[set_position]) : settings.default_height.toString();
u = false;
if (movie_height.indexOf("%") != -1) {
movie_height = parseFloat(e(window).height() * parseFloat(movie_height) / 100 - 150);
u = true
}
if (movie_width.indexOf("%") != -1) {
movie_width = parseFloat(e(window).width() * parseFloat(movie_width) / 100 - 150);
u = true
}
$pp_pic_holder.fadeIn(function () {
settings.show_title && pp_titles[set_position] != "" && typeof pp_titles[set_position] != "undefined" ? $ppt.html(unescape(pp_titles[set_position])) : $ppt.html(" ");
imgPreloader = "";
skipInjection = false;
switch (S(pp_images[set_position])) {
case "image":
imgPreloader = new Image;
nextImage = new Image;
if (isSet && set_position < e(pp_images).size() - 1) nextImage.src = pp_images[set_position + 1];
prevImage = new Image;
if (isSet && pp_images[set_position - 1]) prevImage.src = pp_images[set_position - 1];
$pp_pic_holder.find("#pp_full_res")[0].innerHTML = settings.image_markup.replace(/{path}/g, pp_images[set_position]);
imgPreloader.onload = function () {
a = w(imgPreloader.width, imgPreloader.height);
g()
};
imgPreloader.onerror = function () {
alert("Image cannot be loaded. Make sure the path is correct and image exist.");
e.prettyPhoto.close()
};
imgPreloader.src = pp_images[set_position];
break;
case "youtube":
a = w(movie_width, movie_height);
movie_id = i("v", pp_images[set_position]);
if (movie_id == "") {
movie_id = pp_images[set_position].split("youtu.be/");
movie_id = movie_id[1];
if (movie_id.indexOf("?") > 0) movie_id = movie_id.substr(0, movie_id.indexOf("?"));
if (movie_id.indexOf("&") > 0) movie_id = movie_id.substr(0, movie_id.indexOf("&"))
}
movie = "http://www.youtube.com/embed/" + movie_id;
movie += "?rel=1";
if (settings.autoplay) movie += "&autoplay=1";
toInject = settings.iframe_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, movie);
break;
case "vimeo":
a = w(movie_width, movie_height);
movie_id = pp_images[set_position];
var t = /http(s?):\/\/(www\.)?vimeo.com\/(\d+)/;
var n = movie_id.match(t);
movie = "http://player.vimeo.com/video/" + n[3] + "?title=0&byline=0&portrait=0";
if (settings.autoplay) movie += "&autoplay=1;";
vimeo_width = a["width"] + "/embed/?moog_width=" + a["width"];
toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie);
break;
case "dailymotion":
a = w(movie_width, movie_height);
movie_id = pp_images[set_position];
var n = movie_id.split("www.dailymotion.com/video/");
n=n[1];
n= n.split("_");
movie = "http://www.dailymotion.com/embed/video/" + n[0];
//if (settings.autoplay) movie += "&autoplay=1;";
vimeo_width = a["width"];
toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie);
break;
case "zapkolik":
a = w(movie_width, movie_height);
movie_id = pp_images[set_position];
var n = movie_id.split("http://www.zapkolik.com/video/");
n=n[1];
n= n.split("-");
movie = "http://www.zapkolik.com/api/embed/" + n[n.length - 1];
//if (settings.autoplay) movie += "&autoplay=1;";
vimeo_width = a["width"];
toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie);
break;
case "nytimes":
a = w(movie_width, movie_height);
movie_id = pp_images[set_position];
var n = movie_id.split("/");
movie = "http://graphics8.nytimes.com/bcvideo/1.0/iframe/embed.html?videoId=" + n[5]+"&playerType=embed";
//if (settings.autoplay) movie += "&autoplay=1;";
vimeo_width = a["width"];
toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie);
break;
case "reuters":
a = w(movie_width, movie_height);
movie_id = pp_images[set_position];
var n = movie_id.split("videoId=");
movie = "http://www.reuters.com/resources_v2/flash/video_embed.swf?videoId=" + n[1];
//if (settings.autoplay) movie += "&autoplay=1;";
vimeo_width = a["width"];
toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie);
break;
case "ustream":
a = w(movie_width, movie_height);
movie_id = pp_images[set_position];
var n = movie_id.split("/channel/");
movie = "http://www.ustream.tv/embed/" + n[1]+"?v=3&wmode=direct";
//if (settings.autoplay) movie += "&autoplay=1;";
vimeo_width = a["width"];
toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie);
break;
case "ted":
a = w(movie_width, movie_height);
movie_id = pp_images[set_position];
var n = movie_id.replace("www.", "embed.");
movie = n;
//if (settings.autoplay) movie += "&autoplay=1;";
vimeo_width = a["width"];
toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie);
break;
case "quicktime":
a = w(movie_width, movie_height);
a["height"] += 15;
a["contentHeight"] += 15;
a["containerHeight"] += 15;
toInject = settings.quicktime_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, pp_images[set_position]).replace(/{autoplay}/g, settings.autoplay);
break;
case "flash":
a = w(movie_width, movie_height);
flash_vars = pp_images[set_position];
flash_vars = flash_vars.substring(pp_images[set_position].indexOf("flashvars") + 10, pp_images[set_position].length);
filename = pp_images[set_position];
filename = filename.substring(0, filename.indexOf("?"));
toInject = settings.flash_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, filename + "?" + flash_vars);
break;
case "iframe":
a = w(movie_width, movie_height);
frame_url = pp_images[set_position];
frame_url = frame_url.substr(0, frame_url.indexOf("iframe") - 1);
toInject = settings.iframe_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{path}/g, frame_url);
break;
case "ajax":
doresize = false;
a = w(movie_width, movie_height);
doresize = true;
skipInjection = true;
e.get(pp_images[set_position], function (e) {
toInject = settings.inline_markup.replace(/{content}/g, e);
$pp_pic_holder.find("#pp_full_res")[0].innerHTML = toInject;
g()
});
break;
case "custom":
a = w(movie_width, movie_height);
toInject = settings.custom_markup;
break;
case "inline":
myClone = e(pp_images[set_position]).clone().append('<br clear="all" />').css({
width: settings.default_width
}).wrapInner('<div id="pp_full_res"><div class="pp_inline"></div></div>').appendTo(e("body")).show();
doresize = false;
a = w(e(myClone).width(), e(myClone).height());
doresize = true;
e(myClone).remove();
toInject = settings.inline_markup.replace(/{content}/g, e(pp_images[set_position]).html());
break
}
if (!imgPreloader && !skipInjection) {
$pp_pic_holder.find("#pp_full_res")[0].innerHTML = toInject;
g()
}
});
return false
};
e.prettyPhoto.changePage = function (t) {
currentGalleryPage = 0;
if (t == "previous") {
set_position--;
if (set_position < 0) set_position = e(pp_images).size() - 1
} else if (t == "next") {
set_position++;
if (set_position > e(pp_images).size() - 1) set_position = 0
} else {
set_position = t
}
rel_index = set_position;
if (!doresize) doresize = true;
if (settings.allow_expand) {
e(".pp_contract").removeClass("pp_contract").addClass("pp_expand")
}
y(function () {
e.prettyPhoto.open()
})
};
e.prettyPhoto.changeGalleryPage = function (e) {
if (e == "next") {
currentGalleryPage++;
if (currentGalleryPage > totalPage) currentGalleryPage = 0
} else if (e == "previous") {
currentGalleryPage--;
if (currentGalleryPage < 0) currentGalleryPage = totalPage
} else {
currentGalleryPage = e
}
slide_speed = e == "next" || e == "previous" ? settings.animation_speed : 0;
slide_to = currentGalleryPage * itemsPerPage * itemWidth;
$pp_gallery.find("ul").animate({
left: -slide_to
}, slide_speed)
};
e.prettyPhoto.startSlideshow = function () {
if (typeof m == "undefined") {
$pp_pic_holder.find(".pp_play").unbind("click").removeClass("pp_play").addClass("pp_pause").click(function () {
e.prettyPhoto.stopSlideshow();
return false
});
m = setInterval(e.prettyPhoto.startSlideshow, settings.slideshow)
} else {
e.prettyPhoto.changePage("next")
}
};
e.prettyPhoto.stopSlideshow = function () {
$pp_pic_holder.find(".pp_pause").unbind("click").removeClass("pp_pause").addClass("pp_play").click(function () {
e.prettyPhoto.startSlideshow();
return false
});
clearInterval(m);
m = undefined
};
e.prettyPhoto.close = function () {
if ($pp_overlay.is(":animated")) return;
e.prettyPhoto.stopSlideshow();
$pp_pic_holder.stop().find("object,embed").css("visibility", "hidden");
e("div.pp_pic_holder,div.ppt,.pp_fade").fadeOut(settings.animation_speed, function () {
e(this).remove()
});
$pp_overlay.fadeOut(settings.animation_speed, function () {
if (settings.hideflash) e("object,embed,iframe[src*=youtube],iframe[src*=vimeo],iframe[src*=dailymotion],iframe[src*=zapkolik],iframe[src*=nytimes], iframe[src*=nytimes]").css("visibility", "visible");
e(this).remove();
e(window).unbind("scroll.prettyphoto");
r();
settings.callback();
doresize = true;
f = false;
delete settings
})
};
if (!pp_alreadyInitialized && t()) {
pp_alreadyInitialized = true;
hashIndex = t();
hashRel = hashIndex;
hashIndex = hashIndex.substring(hashIndex.indexOf("/") + 1, hashIndex.length - 1);
hashRel = hashRel.substring(0, hashRel.indexOf("/"));
setTimeout(function () {
e("a[" + s.hook + "^='" + hashRel + "']:eq(" + hashIndex + ")").trigger("click")
}, 50)
}
return this.unbind("click.prettyphoto").bind("click.prettyphoto", e.prettyPhoto.initialize)
};
})(jQuery);
var pp_alreadyInitialized = false | JavaScript |
/**
* jscolor, JavaScript Color Picker
*
* @version 1.4.0
* @license GNU Lesser General Public License, http://www.gnu.org/copyleft/lesser.html
* @author Jan Odvarko, http://odvarko.cz
* @created 2008-06-15
* @updated 2012-07-06
* @link http://jscolor.com
*/
var jscolor = {
dir : 'scripts/jscolor/', // location of jscolor directory (leave empty to autodetect)
bindClass : 'color', // class name
binding : true, // automatic binding via <input class="...">
preloading : true, // use image preloading?
install : function() {
jscolor.addEvent(window, 'load', jscolor.init);
},
init : function() {
if(jscolor.binding) {
jscolor.bind();
}
if(jscolor.preloading) {
jscolor.preload();
}
},
getDir : function() {
if(!jscolor.dir) {
var detected = jscolor.detectDir();
jscolor.dir = detected!==false ? detected : 'jscolor/';
}
return jscolor.dir;
},
detectDir : function() {
var base = location.href;
var e = document.getElementsByTagName('base');
for(var i=0; i<e.length; i+=1) {
if(e[i].href) { base = e[i].href; }
}
var e = document.getElementsByTagName('script');
for(var i=0; i<e.length; i+=1) {
if(e[i].src && /(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)) {
var src = new jscolor.URI(e[i].src);
var srcAbs = src.toAbsolute(base);
srcAbs.path = srcAbs.path.replace(/[^\/]+$/, ''); // remove filename
srcAbs.query = null;
srcAbs.fragment = null;
return srcAbs.toString();
}
}
return false;
},
bind : function() {
var matchClass = new RegExp('(^|\\s)('+jscolor.bindClass+')\\s*(\\{[^}]*\\})?', 'i');
var e = document.getElementsByTagName('input');
for(var i=0; i<e.length; i+=1) {
var m;
if(!e[i].color && e[i].className && (m = e[i].className.match(matchClass))) {
var prop = {};
if(m[3]) {
try {
prop = (new Function ('return (' + m[3] + ')'))();
} catch(eInvalidProp) {}
}
e[i].color = new jscolor.color(e[i], prop);
}
}
},
preload : function() {
for(var fn in jscolor.imgRequire) {
if(jscolor.imgRequire.hasOwnProperty(fn)) {
jscolor.loadImage(fn);
}
}
},
images : {
pad : [ 181, 101 ],
sld : [ 16, 101 ],
cross : [ 15, 15 ],
arrow : [ 7, 11 ]
},
imgRequire : {},
imgLoaded : {},
requireImage : function(filename) {
jscolor.imgRequire[filename] = true;
},
loadImage : function(filename) {
if(!jscolor.imgLoaded[filename]) {
jscolor.imgLoaded[filename] = new Image();
jscolor.imgLoaded[filename].src = jscolor.getDir()+filename;
}
},
fetchElement : function(mixed) {
return typeof mixed === 'string' ? document.getElementById(mixed) : mixed;
},
addEvent : function(el, evnt, func) {
if(el.addEventListener) {
el.addEventListener(evnt, func, false);
} else if(el.attachEvent) {
el.attachEvent('on'+evnt, func);
}
},
fireEvent : function(el, evnt) {
if(!el) {
return;
}
if(document.createEvent) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent(evnt, true, true);
el.dispatchEvent(ev);
} else if(document.createEventObject) {
var ev = document.createEventObject();
el.fireEvent('on'+evnt, ev);
} else if(el['on'+evnt]) { // alternatively use the traditional event model (IE5)
el['on'+evnt]();
}
},
getElementPos : function(e) {
var e1=e, e2=e;
var x=0, y=0;
if(e1.offsetParent) {
do {
x += e1.offsetLeft;
y += e1.offsetTop;
} while(e1 = e1.offsetParent);
}
while((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') {
x -= e2.scrollLeft;
y -= e2.scrollTop;
}
return [x, y];
},
getElementSize : function(e) {
return [e.offsetWidth, e.offsetHeight];
},
getRelMousePos : function(e) {
var x = 0, y = 0;
if (!e) { e = window.event; }
if (typeof e.offsetX === 'number') {
x = e.offsetX;
y = e.offsetY;
} else if (typeof e.layerX === 'number') {
x = e.layerX;
y = e.layerY;
}
return { x: x, y: y };
},
getViewPos : function() {
if(typeof window.pageYOffset === 'number') {
return [window.pageXOffset, window.pageYOffset];
} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
return [document.body.scrollLeft, document.body.scrollTop];
} else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
} else {
return [0, 0];
}
},
getViewSize : function() {
if(typeof window.innerWidth === 'number') {
return [window.innerWidth, window.innerHeight];
} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
return [document.body.clientWidth, document.body.clientHeight];
} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
return [document.documentElement.clientWidth, document.documentElement.clientHeight];
} else {
return [0, 0];
}
},
URI : function(uri) { // See RFC3986
this.scheme = null;
this.authority = null;
this.path = '';
this.query = null;
this.fragment = null;
this.parse = function(uri) {
var m = uri.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);
this.scheme = m[3] ? m[2] : null;
this.authority = m[5] ? m[6] : null;
this.path = m[7];
this.query = m[9] ? m[10] : null;
this.fragment = m[12] ? m[13] : null;
return this;
};
this.toString = function() {
var result = '';
if(this.scheme !== null) { result = result + this.scheme + ':'; }
if(this.authority !== null) { result = result + '//' + this.authority; }
if(this.path !== null) { result = result + this.path; }
if(this.query !== null) { result = result + '?' + this.query; }
if(this.fragment !== null) { result = result + '#' + this.fragment; }
return result;
};
this.toAbsolute = function(base) {
var base = new jscolor.URI(base);
var r = this;
var t = new jscolor.URI;
if(base.scheme === null) { return false; }
if(r.scheme !== null && r.scheme.toLowerCase() === base.scheme.toLowerCase()) {
r.scheme = null;
}
if(r.scheme !== null) {
t.scheme = r.scheme;
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if(r.authority !== null) {
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if(r.path === '') {
t.path = base.path;
if(r.query !== null) {
t.query = r.query;
} else {
t.query = base.query;
}
} else {
if(r.path.substr(0,1) === '/') {
t.path = removeDotSegments(r.path);
} else {
if(base.authority !== null && base.path === '') {
t.path = '/'+r.path;
} else {
t.path = base.path.replace(/[^\/]+$/,'')+r.path;
}
t.path = removeDotSegments(t.path);
}
t.query = r.query;
}
t.authority = base.authority;
}
t.scheme = base.scheme;
}
t.fragment = r.fragment;
return t;
};
function removeDotSegments(path) {
var out = '';
while(path) {
if(path.substr(0,3)==='../' || path.substr(0,2)==='./') {
path = path.replace(/^\.+/,'').substr(1);
} else if(path.substr(0,3)==='/./' || path==='/.') {
path = '/'+path.substr(3);
} else if(path.substr(0,4)==='/../' || path==='/..') {
path = '/'+path.substr(4);
out = out.replace(/\/?[^\/]*$/, '');
} else if(path==='.' || path==='..') {
path = '';
} else {
var rm = path.match(/^\/?[^\/]*/)[0];
path = path.substr(rm.length);
out = out + rm;
}
}
return out;
}
if(uri) {
this.parse(uri);
}
},
/*
* Usage example:
* var myColor = new jscolor.color(myInputElement)
*/
color : function(target, prop) {
this.required = true; // refuse empty values?
this.adjust = true; // adjust value to uniform notation?
this.hash = false; // prefix color with # symbol?
this.caps = true; // uppercase?
this.slider = true; // show the value/saturation slider?
this.valueElement = target; // value holder
this.styleElement = target; // where to reflect current color
this.onImmediateChange = null; // onchange callback (can be either string or function)
this.hsv = [0, 0, 1]; // read-only 0-6, 0-1, 0-1
this.rgb = [1, 1, 1]; // read-only 0-1, 0-1, 0-1
this.minH = 0; // read-only 0-6
this.maxH = 6; // read-only 0-6
this.minS = 0; // read-only 0-1
this.maxS = 1; // read-only 0-1
this.minV = 0; // read-only 0-1
this.maxV = 1; // read-only 0-1
this.pickerOnfocus = true; // display picker on focus?
this.pickerMode = 'HSV'; // HSV | HVS
this.pickerPosition = 'bottom'; // left | right | top | bottom
this.pickerSmartPosition = true; // automatically adjust picker position when necessary
this.pickerButtonHeight = 20; // px
this.pickerClosable = false;
this.pickerCloseText = 'Close';
this.pickerButtonColor = 'ButtonText'; // px
this.pickerFace = 10; // px
this.pickerFaceColor = 'ThreeDFace'; // CSS color
this.pickerBorder = 1; // px
this.pickerBorderColor = 'ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight'; // CSS color
this.pickerInset = 1; // px
this.pickerInsetColor = 'ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow'; // CSS color
this.pickerZIndex = 10000;
for(var p in prop) {
if(prop.hasOwnProperty(p)) {
this[p] = prop[p];
}
}
this.hidePicker = function() {
if(isPickerOwner()) {
removePicker();
}
};
this.showPicker = function() {
if(!isPickerOwner()) {
var tp = jscolor.getElementPos(target); // target pos
var ts = jscolor.getElementSize(target); // target size
var vp = jscolor.getViewPos(); // view pos
var vs = jscolor.getViewSize(); // view size
var ps = getPickerDims(this); // picker size
var a, b, c;
switch(this.pickerPosition.toLowerCase()) {
case 'left': a=1; b=0; c=-1; break;
case 'right':a=1; b=0; c=1; break;
case 'top': a=0; b=1; c=-1; break;
default: a=0; b=1; c=1; break;
}
var l = (ts[b]+ps[b])/2;
// picker pos
if (!this.pickerSmartPosition) {
var pp = [
tp[a],
tp[b]+ts[b]-l+l*c
];
} else {
var pp = [
-vp[a]+tp[a]+ps[a] > vs[a] ?
(-vp[a]+tp[a]+ts[a]/2 > vs[a]/2 && tp[a]+ts[a]-ps[a] >= 0 ? tp[a]+ts[a]-ps[a] : tp[a]) :
tp[a],
-vp[b]+tp[b]+ts[b]+ps[b]-l+l*c > vs[b] ?
(-vp[b]+tp[b]+ts[b]/2 > vs[b]/2 && tp[b]+ts[b]-l-l*c >= 0 ? tp[b]+ts[b]-l-l*c : tp[b]+ts[b]-l+l*c) :
(tp[b]+ts[b]-l+l*c >= 0 ? tp[b]+ts[b]-l+l*c : tp[b]+ts[b]-l-l*c)
];
}
drawPicker(pp[a], pp[b]);
}
};
this.importColor = function() {
if(!valueElement) {
this.exportColor();
} else {
if(!this.adjust) {
if(!this.fromString(valueElement.value, leaveValue)) {
styleElement.style.backgroundImage = styleElement.jscStyle.backgroundImage;
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
}
} else if(!this.required && /^\s*$/.test(valueElement.value)) {
valueElement.value = '';
styleElement.style.backgroundImage = styleElement.jscStyle.backgroundImage;
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
} else if(this.fromString(valueElement.value)) {
// OK
} else {
this.exportColor();
}
}
};
this.exportColor = function(flags) {
if(!(flags & leaveValue) && valueElement) {
var value = this.toString();
if(this.caps) { value = value.toUpperCase(); }
if(this.hash) { value = '#'+value; }
valueElement.value = value;
}
if(!(flags & leaveStyle) && styleElement) {
styleElement.style.backgroundImage = "none";
styleElement.style.backgroundColor =
'#'+this.toString();
styleElement.style.color =
0.213 * this.rgb[0] +
0.715 * this.rgb[1] +
0.072 * this.rgb[2]
< 0.5 ? '#FFF' : '#000';
}
if(!(flags & leavePad) && isPickerOwner()) {
redrawPad();
}
if(!(flags & leaveSld) && isPickerOwner()) {
redrawSld();
}
};
this.fromHSV = function(h, s, v, flags) { // null = don't change
if(h !== null) { h = Math.max(0.0, this.minH, Math.min(6.0, this.maxH, h)); }
if(s !== null) { s = Math.max(0.0, this.minS, Math.min(1.0, this.maxS, s)); }
if(v !== null) { v = Math.max(0.0, this.minV, Math.min(1.0, this.maxV, v)); }
this.rgb = HSV_RGB(
h===null ? this.hsv[0] : (this.hsv[0]=h),
s===null ? this.hsv[1] : (this.hsv[1]=s),
v===null ? this.hsv[2] : (this.hsv[2]=v)
);
this.exportColor(flags);
};
this.fromRGB = function(r, g, b, flags) { // null = don't change
if(r !== null) { r = Math.max(0.0, Math.min(1.0, r)); }
if(g !== null) { g = Math.max(0.0, Math.min(1.0, g)); }
if(b !== null) { b = Math.max(0.0, Math.min(1.0, b)); }
var hsv = RGB_HSV(
r===null ? this.rgb[0] : r,
g===null ? this.rgb[1] : g,
b===null ? this.rgb[2] : b
);
if(hsv[0] !== null) {
this.hsv[0] = Math.max(0.0, this.minH, Math.min(6.0, this.maxH, hsv[0]));
}
if(hsv[2] !== 0) {
this.hsv[1] = hsv[1]===null ? null : Math.max(0.0, this.minS, Math.min(1.0, this.maxS, hsv[1]));
}
this.hsv[2] = hsv[2]===null ? null : Math.max(0.0, this.minV, Math.min(1.0, this.maxV, hsv[2]));
// update RGB according to final HSV, as some values might be trimmed
var rgb = HSV_RGB(this.hsv[0], this.hsv[1], this.hsv[2]);
this.rgb[0] = rgb[0];
this.rgb[1] = rgb[1];
this.rgb[2] = rgb[2];
this.exportColor(flags);
};
this.fromString = function(hex, flags) {
var m = hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i);
if(!m) {
return false;
} else {
if(m[1].length === 6) { // 6-char notation
this.fromRGB(
parseInt(m[1].substr(0,2),16) / 255,
parseInt(m[1].substr(2,2),16) / 255,
parseInt(m[1].substr(4,2),16) / 255,
flags
);
} else { // 3-char notation
this.fromRGB(
parseInt(m[1].charAt(0)+m[1].charAt(0),16) / 255,
parseInt(m[1].charAt(1)+m[1].charAt(1),16) / 255,
parseInt(m[1].charAt(2)+m[1].charAt(2),16) / 255,
flags
);
}
return true;
}
};
this.toString = function() {
return (
(0x100 | Math.round(255*this.rgb[0])).toString(16).substr(1) +
(0x100 | Math.round(255*this.rgb[1])).toString(16).substr(1) +
(0x100 | Math.round(255*this.rgb[2])).toString(16).substr(1)
);
};
function RGB_HSV(r, g, b) {
var n = Math.min(Math.min(r,g),b);
var v = Math.max(Math.max(r,g),b);
var m = v - n;
if(m === 0) { return [ null, 0, v ]; }
var h = r===n ? 3+(b-g)/m : (g===n ? 5+(r-b)/m : 1+(g-r)/m);
return [ h===6?0:h, m/v, v ];
}
function HSV_RGB(h, s, v) {
if(h === null) { return [ v, v, v ]; }
var i = Math.floor(h);
var f = i%2 ? h-i : 1-(h-i);
var m = v * (1 - s);
var n = v * (1 - s*f);
switch(i) {
case 6:
case 0: return [v,n,m];
case 1: return [n,v,m];
case 2: return [m,v,n];
case 3: return [m,n,v];
case 4: return [n,m,v];
case 5: return [v,m,n];
}
}
function removePicker() {
delete jscolor.picker.owner;
document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB);
}
function drawPicker(x, y) {
if(!jscolor.picker) {
jscolor.picker = {
box : document.createElement('div'),
boxB : document.createElement('div'),
pad : document.createElement('div'),
padB : document.createElement('div'),
padM : document.createElement('div'),
sld : document.createElement('div'),
sldB : document.createElement('div'),
sldM : document.createElement('div'),
btn : document.createElement('div'),
btnS : document.createElement('span'),
btnT : document.createTextNode(THIS.pickerCloseText)
};
for(var i=0,segSize=4; i<jscolor.images.sld[1]; i+=segSize) {
var seg = document.createElement('div');
seg.style.height = segSize+'px';
seg.style.fontSize = '1px';
seg.style.lineHeight = '0';
jscolor.picker.sld.appendChild(seg);
}
jscolor.picker.sldB.appendChild(jscolor.picker.sld);
jscolor.picker.box.appendChild(jscolor.picker.sldB);
jscolor.picker.box.appendChild(jscolor.picker.sldM);
jscolor.picker.padB.appendChild(jscolor.picker.pad);
jscolor.picker.box.appendChild(jscolor.picker.padB);
jscolor.picker.box.appendChild(jscolor.picker.padM);
jscolor.picker.btnS.appendChild(jscolor.picker.btnT);
jscolor.picker.btn.appendChild(jscolor.picker.btnS);
jscolor.picker.box.appendChild(jscolor.picker.btn);
jscolor.picker.boxB.appendChild(jscolor.picker.box);
}
var p = jscolor.picker;
// controls interaction
p.box.onmouseup =
p.box.onmouseout = function() { target.focus(); };
p.box.onmousedown = function() { abortBlur=true; };
p.box.onmousemove = function(e) {
if (holdPad || holdSld) {
holdPad && setPad(e);
holdSld && setSld(e);
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
dispatchImmediateChange();
}
};
p.padM.onmouseup =
p.padM.onmouseout = function() { if(holdPad) { holdPad=false; jscolor.fireEvent(valueElement,'change'); } };
p.padM.onmousedown = function(e) {
// if the slider is at the bottom, move it up
switch(modeID) {
case 0: if (THIS.hsv[2] === 0) { THIS.fromHSV(null, null, 1.0); }; break;
case 1: if (THIS.hsv[1] === 0) { THIS.fromHSV(null, 1.0, null); }; break;
}
holdPad=true;
setPad(e);
dispatchImmediateChange();
};
p.sldM.onmouseup =
p.sldM.onmouseout = function() { if(holdSld) { holdSld=false; jscolor.fireEvent(valueElement,'change'); } };
p.sldM.onmousedown = function(e) {
holdSld=true;
setSld(e);
dispatchImmediateChange();
};
// picker
var dims = getPickerDims(THIS);
p.box.style.width = dims[0] + 'px';
p.box.style.height = dims[1] + 'px';
// picker border
p.boxB.style.position = 'absolute';
p.boxB.style.clear = 'both';
p.boxB.style.left = x+'px';
p.boxB.style.top = y+'px';
p.boxB.style.zIndex = THIS.pickerZIndex;
p.boxB.style.border = THIS.pickerBorder+'px solid';
p.boxB.style.borderColor = THIS.pickerBorderColor;
p.boxB.style.background = THIS.pickerFaceColor;
// pad image
p.pad.style.width = jscolor.images.pad[0]+'px';
p.pad.style.height = jscolor.images.pad[1]+'px';
// pad border
p.padB.style.position = 'absolute';
p.padB.style.left = THIS.pickerFace+'px';
p.padB.style.top = THIS.pickerFace+'px';
p.padB.style.border = THIS.pickerInset+'px solid';
p.padB.style.borderColor = THIS.pickerInsetColor;
// pad mouse area
p.padM.style.position = 'absolute';
p.padM.style.left = '0';
p.padM.style.top = '0';
p.padM.style.width = THIS.pickerFace + 2*THIS.pickerInset + jscolor.images.pad[0] + jscolor.images.arrow[0] + 'px';
p.padM.style.height = p.box.style.height;
p.padM.style.cursor = 'crosshair';
// slider image
p.sld.style.overflow = 'hidden';
p.sld.style.width = jscolor.images.sld[0]+'px';
p.sld.style.height = jscolor.images.sld[1]+'px';
// slider border
p.sldB.style.display = THIS.slider ? 'block' : 'none';
p.sldB.style.position = 'absolute';
p.sldB.style.right = THIS.pickerFace+'px';
p.sldB.style.top = THIS.pickerFace+'px';
p.sldB.style.border = THIS.pickerInset+'px solid';
p.sldB.style.borderColor = THIS.pickerInsetColor;
// slider mouse area
p.sldM.style.display = THIS.slider ? 'block' : 'none';
p.sldM.style.position = 'absolute';
p.sldM.style.right = '0';
p.sldM.style.top = '0';
p.sldM.style.width = jscolor.images.sld[0] + jscolor.images.arrow[0] + THIS.pickerFace + 2*THIS.pickerInset + 'px';
p.sldM.style.height = p.box.style.height;
try {
p.sldM.style.cursor = 'pointer';
} catch(eOldIE) {
p.sldM.style.cursor = 'hand';
}
// "close" button
function setBtnBorder() {
var insetColors = THIS.pickerInsetColor.split(/\s+/);
var pickerOutsetColor = insetColors.length < 2 ? insetColors[0] : insetColors[1] + ' ' + insetColors[0] + ' ' + insetColors[0] + ' ' + insetColors[1];
p.btn.style.borderColor = pickerOutsetColor;
}
p.btn.style.display = THIS.pickerClosable ? 'block' : 'none';
p.btn.style.position = 'absolute';
p.btn.style.left = THIS.pickerFace + 'px';
p.btn.style.bottom = THIS.pickerFace + 'px';
p.btn.style.padding = '0 15px';
p.btn.style.height = '18px';
p.btn.style.border = THIS.pickerInset + 'px solid';
setBtnBorder();
p.btn.style.color = THIS.pickerButtonColor;
p.btn.style.font = '12px sans-serif';
p.btn.style.textAlign = 'center';
try {
p.btn.style.cursor = 'pointer';
} catch(eOldIE) {
p.btn.style.cursor = 'hand';
}
p.btn.onmousedown = function () {
THIS.hidePicker();
};
p.btnS.style.lineHeight = p.btn.style.height;
// load images in optimal order
switch(modeID) {
case 0: var padImg = 'hs.png'; break;
case 1: var padImg = 'hv.png'; break;
}
p.padM.style.backgroundImage = "url('"+jscolor.getDir()+"cross.gif')";
p.padM.style.backgroundRepeat = "no-repeat";
p.sldM.style.backgroundImage = "url('"+jscolor.getDir()+"arrow.gif')";
p.sldM.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundImage = "url('"+jscolor.getDir()+padImg+"')";
p.pad.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundPosition = "0 0";
// place pointers
redrawPad();
redrawSld();
jscolor.picker.owner = THIS;
document.getElementsByTagName('body')[0].appendChild(p.boxB);
}
function getPickerDims(o) {
var dims = [
2*o.pickerInset + 2*o.pickerFace + jscolor.images.pad[0] +
(o.slider ? 2*o.pickerInset + 2*jscolor.images.arrow[0] + jscolor.images.sld[0] : 0),
o.pickerClosable ?
4*o.pickerInset + 3*o.pickerFace + jscolor.images.pad[1] + o.pickerButtonHeight :
2*o.pickerInset + 2*o.pickerFace + jscolor.images.pad[1]
];
return dims;
}
function redrawPad() {
// redraw the pad pointer
switch(modeID) {
case 0: var yComponent = 1; break;
case 1: var yComponent = 2; break;
}
var x = Math.round((THIS.hsv[0]/6) * (jscolor.images.pad[0]-1));
var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.pad[1]-1));
jscolor.picker.padM.style.backgroundPosition =
(THIS.pickerFace+THIS.pickerInset+x - Math.floor(jscolor.images.cross[0]/2)) + 'px ' +
(THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.cross[1]/2)) + 'px';
// redraw the slider image
var seg = jscolor.picker.sld.childNodes;
switch(modeID) {
case 0:
var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 1);
for(var i=0; i<seg.length; i+=1) {
seg[i].style.backgroundColor = 'rgb('+
(rgb[0]*(1-i/seg.length)*100)+'%,'+
(rgb[1]*(1-i/seg.length)*100)+'%,'+
(rgb[2]*(1-i/seg.length)*100)+'%)';
}
break;
case 1:
var rgb, s, c = [ THIS.hsv[2], 0, 0 ];
var i = Math.floor(THIS.hsv[0]);
var f = i%2 ? THIS.hsv[0]-i : 1-(THIS.hsv[0]-i);
switch(i) {
case 6:
case 0: rgb=[0,1,2]; break;
case 1: rgb=[1,0,2]; break;
case 2: rgb=[2,0,1]; break;
case 3: rgb=[2,1,0]; break;
case 4: rgb=[1,2,0]; break;
case 5: rgb=[0,2,1]; break;
}
for(var i=0; i<seg.length; i+=1) {
s = 1 - 1/(seg.length-1)*i;
c[1] = c[0] * (1 - s*f);
c[2] = c[0] * (1 - s);
seg[i].style.backgroundColor = 'rgb('+
(c[rgb[0]]*100)+'%,'+
(c[rgb[1]]*100)+'%,'+
(c[rgb[2]]*100)+'%)';
}
break;
}
}
function redrawSld() {
// redraw the slider pointer
switch(modeID) {
case 0: var yComponent = 2; break;
case 1: var yComponent = 1; break;
}
var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.sld[1]-1));
jscolor.picker.sldM.style.backgroundPosition =
'0 ' + (THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.arrow[1]/2)) + 'px';
}
function isPickerOwner() {
return jscolor.picker && jscolor.picker.owner === THIS;
}
function blurTarget() {
if(valueElement === target) {
THIS.importColor();
}
if(THIS.pickerOnfocus) {
THIS.hidePicker();
}
}
function blurValue() {
if(valueElement !== target) {
THIS.importColor();
}
}
function setPad(e) {
var mpos = jscolor.getRelMousePos(e);
var x = mpos.x - THIS.pickerFace - THIS.pickerInset;
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch(modeID) {
case 0: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), 1 - y/(jscolor.images.pad[1]-1), null, leaveSld); break;
case 1: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), null, 1 - y/(jscolor.images.pad[1]-1), leaveSld); break;
}
}
function setSld(e) {
var mpos = jscolor.getRelMousePos(e);
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch(modeID) {
case 0: THIS.fromHSV(null, null, 1 - y/(jscolor.images.sld[1]-1), leavePad); break;
case 1: THIS.fromHSV(null, 1 - y/(jscolor.images.sld[1]-1), null, leavePad); break;
}
}
function dispatchImmediateChange() {
if (THIS.onImmediateChange) {
var callback;
if (typeof THIS.onImmediateChange === 'string') {
callback = new Function (THIS.onImmediateChange);
} else {
callback = THIS.onImmediateChange;
}
callback.call(THIS);
}
}
var THIS = this;
var modeID = this.pickerMode.toLowerCase()==='hvs' ? 1 : 0;
var abortBlur = false;
var
valueElement = jscolor.fetchElement(this.valueElement),
styleElement = jscolor.fetchElement(this.styleElement);
var
holdPad = false,
holdSld = false;
var
leaveValue = 1<<0,
leaveStyle = 1<<1,
leavePad = 1<<2,
leaveSld = 1<<3;
// target
jscolor.addEvent(target, 'focus', function() {
if(THIS.pickerOnfocus) { THIS.showPicker(); }
});
jscolor.addEvent(target, 'blur', function() {
if(!abortBlur) {
window.setTimeout(function(){ abortBlur || blurTarget(); abortBlur=false; }, 0);
} else {
abortBlur = false;
}
});
// valueElement
if(valueElement) {
var updateField = function() {
THIS.fromString(valueElement.value, leaveValue);
dispatchImmediateChange();
};
jscolor.addEvent(valueElement, 'keyup', updateField);
jscolor.addEvent(valueElement, 'input', updateField);
jscolor.addEvent(valueElement, 'blur', blurValue);
valueElement.setAttribute('autocomplete', 'off');
}
// styleElement
if(styleElement) {
styleElement.jscStyle = {
backgroundImage : styleElement.style.backgroundImage,
backgroundColor : styleElement.style.backgroundColor,
color : styleElement.style.color
};
}
// require images
switch(modeID) {
case 0: jscolor.requireImage('hs.png'); break;
case 1: jscolor.requireImage('hv.png'); break;
}
jscolor.requireImage('cross.gif');
jscolor.requireImage('arrow.gif');
this.importColor();
}
};
jscolor.install();
| JavaScript |
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range='', text='',
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
text=el.value.substring(start, end);
} else {
range = document.selection.createRange();
text=range.text;
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
text: text,
end: end
};
}
function replaceSelectedText(el, text1, text2) {
var sel = getInputSelection(el), val = el.value;
var newValue=text1 +sel.text+text2;
el.value = val.slice(0, sel.start) + newValue +val.slice(sel.end);
var returnArray={
"newValue":newValue,
"len": sel.text.length
}
return returnArray;
}
function render(){
var $t = {};
var i = 0;
$('compa').each(function(){
$t[i] = $(this).text();
var valueStr=$t[i].trim();
var strLink="<a href=\"#\" onclick=\"RoomConstruction.joinRoom(0,'"+valueStr+"',0)\">$"+valueStr+"</a>";
$(this).replaceWith(strLink);
i++;
});
$t = {};
i = 0;
$('miss').each(function(){
$t[i] = $(this).text();
var valueStr=$t[i].trim();
var strLink="<a href=\"#\" onclick=\"RoomConstruction.joinRoom(0,'"+valueStr+"',1)\">!"+valueStr+"</a>";
$(this).replaceWith(strLink);
i++;
});
$t = {};
i = 0;
$('dict').each(function(){
$t[i] = $(this).text();
var valueStr=$t[i].trim();
var strLink="<a href=\"#\" onclick=\"RoomConstruction.joinRoom(0,'"+valueStr+"',2)\">~"+valueStr+"</a>";
$(this).replaceWith(strLink);
i++;
});
$t = {};
i = 0;
$('ircc').each(function(){
$t[i] = $(this).text();
var valueStr=$t[i].trim();
var strLink="<a href=\"#\" onclick=\"RoomConstruction.joinRoom(0,'"+valueStr+"',3)\">#"+valueStr+"</a>";
$(this).replaceWith(strLink);
i++;
});
$t = {};
i = 0;
$('ablog').each(function(){
$t[i] = $(this).text();
var valueStr=$t[i].trim();
var strLink="<a href=\"#\" onclick=\"RoomConstruction.joinRoom(0,'"+valueStr+"',4)\">@"+valueStr+"</a>";
$(this).replaceWith(strLink);
i++;
});
$('v').each(function(){
var dataTitle= $(this).attr("dt");
var dataContent=$(this).attr("dc");
var source = $(this).attr("s");
var imgUrl= $(this).attr("i");
var imgStr='';
if(!(typeof imgUrl === 'undefined')){
// your code here.
imgStr= '<ul class="gallery clearfix">'
+'<li>'
+'<a href="'+source+ '" rel="prettyPhoto">'
+'<img onclick="callPrettyPhoto();" src="'+imgUrl+'" width="60" alt="" />'
+'</a></li>'
+'</ul>';
}
var htmlInput=
'<div>'
+ imgStr
+'</div>'
+'<div>'
+'<div><a href='+ source +'>'+dataTitle+'</a></div>'
+'<div>'+dataContent+'</div>'
+'</div>';
$(this).replaceWith("<p>"+htmlInput+"</p>");
});
$('i').each(function(){
var value = $(this).attr("s");
var htmlInput='<ul class="gallery clearfix"><li><a href='+value+' rel="prettyPhoto[gallery1]">'
+'<img width="60px" height="60px" onclick="callPrettyPhoto();" src='+value+'></img></a></li></ul>';
$(this).replaceWith("<p>"+htmlInput+"</p>");
});
$('c').each(function(){
var imgUrl= $(this).attr("i");
var imgStr='';
if(!(typeof imgUrl === 'undefined')){
// your code here.
imgStr= '<img width="60px" height="60px" onclick="callPrettyPhoto();" src='+imgUrl+'></img>';
}
var dataTitle= $(this).attr("dt");
var dataContent=$(this).attr("dc");
var source = $(this).attr("s");
var htmlInput=
'<div> <a href='+source+' target="_blank">'
+ imgStr
+'</a></div>'
+'<div>'
+'<div><a href='+ source +' target="_blank">'+dataTitle+'</a></div>'
+'<div>'+dataContent+'</div>'
+'</div>';
$(this).replaceWith("<p>"+htmlInput+"</p>");
});
}
function callPrettyPhoto() {
$("area[rel^='prettyPhoto']").prettyPhoto();
$(".gallery:first a[rel^='prettyPhoto']").prettyPhoto({
animation_speed: 'normal',
theme: 'light_square',
slideshow: 3000,
autoplay_slideshow: true
});
$(".gallery:gt(0) a[rel^='prettyPhoto']").prettyPhoto({
animation_speed: 'fast',
slideshow: 10000,
hideflash: true
});
$("#custom_content a[rel^='prettyPhoto']:first").prettyPhoto({
custom_markup: '<div id="map_canvas" style="width:260px; height:265px"></div>',
changepicturecallback: function () {
initialize();
}
});
$("#custom_content a[rel^='prettyPhoto']:last").prettyPhoto({
custom_markup: '<div id="bsap_1259344" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div><div id="bsap_1237859" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6" style="height:260px"></div><div id="bsap_1251710" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div>',
changepicturecallback: function () {
_bsap.exec();
}
});
}
var imgSrc='';
function chooseMsg(messageInput){
var tempMsg='';
if (!isBlank(App.content)) {
// set the chosen image for message.
if(imgSrc!='')
App.content= App.content.replace('<c', '<c i="'+ imgSrc+'" ');
App.content= App.content.replace('<v', '<v i="'+ imgSrc+'" ');
tempMsg= App.content;
} else{
tempMsg=messageInput;
}
imgSrc='';
return tempMsg;
}
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
var turnBack = false;
function IsValidImageUrl(url) {
$("<img>", {
src: url,
error: function () {
sertTurnBack(false);
},
load: function () {
sertTurnBack(true);
}
});
return turnBack;
}
function sertTurnBack(bool) {
turnBack = bool;
}
function UrlGetir(gelenBilgi) {
//var UrlRegex = new RegExp(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g);
var UrlRegex = new RegExp(/(\b(?:(https?|ftp):\/\/)?((?:www\d{0,3}\.)?([a-z0-9.-]+\.(?:[a-z]{2,4}|museum|travel)(?:\/[^\/\s]+)*))\b)/gi);
var Dizi = gelenBilgi.split(/\s/g);
var Sonuc = null;
$.each(Dizi, function(Key, Value){
Sonuc = Value.match(UrlRegex);
});
return Sonuc;
}
$(document).ready(function () {
var getUrl = $('#globalTextArea'); //url to extract from text field
var extracted_images;
$("#globalTextArea").keyup(function(event){
if(event.keyCode == 13){
$("#send_button").click();
}
});
getUrl.bind('input propertychange', function()
{ //user types url in text field
//url to match in the text field
result = "";
// var match_url = new RegExp("\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|]");
extracted_url=UrlGetir($.trim(getUrl.val()));
//returns true and continue if matched url is found in text field
if (extracted_url!=null) {
$("#loading_indicator").show(); //show loading indicator image
extracted_url=extracted_url[0];
// var extracted_url = getUrl.val().match(match_url)[0]; //extracted first url from text filed
if (IsValidImageUrl(extracted_url)) {
turnBack = false;
// 1- For database.
App.content= '<i s="' + extracted_url + '"/>';
// 2-Just for demonstrate on results div.
var htmlInput = '<ul class="gallery clearfix"><li><a href=' + extracted_url + ' rel="prettyPhoto[gallery1]">' + '<img width="60px" height="60px" onclick="callPrettyPhoto();" src=' + extracted_url + '></img></a></li></ul>';
$("#results").html("<p>" + htmlInput + "</p>");
$("#results").slideDown(); //show results with slide down effect
$("#loading_indicator").hide(); //hide loading indicator image
} else //If it is not just image and has URL content...
{
var htmlInput='';
var total_images ='';
var img_arr_pos =1;
var dataContent='';
var dataTitle='';
var imgSelect='';
var functionUrl = 'templates/default/pages/extract-process.php';
var argJson = {
'url': extracted_url
};
$.ajax({
type: "POST",
url: functionUrl,
dataType: "json",
data:argJson,
success:function (data) {
extracted_images = data.images;
if(extracted_images!='')
total_images = parseInt(extracted_images.length);
if (total_images -1> 0) {
imgSrc=data.images[img_arr_pos-1];
inc_image = '<div class="extracted_thumb" id="extracted_thumb"><img src="' + imgSrc + '" width="100" height="100"></div>';
imgSelect= '<span class="prev_thumb" id="thumb_prev"> </span>'
+'<span class="next_thumb" id="thumb_next"> </span>'
+' </div><span class="small_text" id="total_imgs">'
+ img_arr_pos
+ ' of '
+ total_images
+ '</span>'
+'<span class="small_text"> Choose a Thumbnail</span>'
} else {
inc_image = '';
}
//content to be loaded in #results element
dataContent=data.content;
dataTitle=data.title;
htmlInput = '<div class="extracted_url">'
+ inc_image
+ '<div class="extracted_content"><h4><a href="'
+ extracted_url
+ '" target="_blank">'
+ dataTitle
+ '</a></h4><p>'
+ dataContent
+ '</p>'
+'<div class="thumb_sel">'
+ imgSelect
+'</div></div>';
//user clicks previous thumbail
$("body").on("click", "#thumb_prev", function (e) {
if (img_arr_pos > 1) {
img_arr_pos--; //thmubnail array position decrement
//replace with new thumbnail
//imgSrc to write selected img into database.
imgSrc= extracted_images[img_arr_pos-1];
$("#extracted_thumb").html('<img src="' + imgSrc + '" width="100" height="100">');
//show thmubnail position
$("#total_imgs").html((img_arr_pos) + ' of ' + total_images);
}
});
//user clicks next thumbail
$("body").on("click", "#thumb_next", function (e) {
if (img_arr_pos < total_images) {
img_arr_pos++; //thmubnail array position increment
//replace with new thumbnail
//imgSrc to write selected img into database. Murat.
imgSrc= extracted_images[img_arr_pos-1];
$("#extracted_thumb").html('<img src="' + imgSrc + '" width="100" height="100">');
//replace thmubnail position text
$("#total_imgs").html((img_arr_pos) + ' of ' + total_images);
}
});
var value = extracted_url;
//If it is a video url.
if (value!=null)
if ( value.match('(http(s)?://)?(www.)?youtube|youtu\.be')
|| value.match(/vimeo\.com/i)
|| value.match(/dailymotion\.com/i)
|| value.match(/zapkolik\.com/i)
|| value.match(/nytimes\.com/i)
|| value.match(/reuters\.com/i)
|| value.match(/ustream\.tv/i)
|| value.match(/ted\.com/i)
)
{
//v: video content
App.content= '<v ';
} else {
//c: Custom Content
App.content= '<c ';
}
App.content=App.content +'s="'
+ value
+'" dc="' + dataContent
+'" dt="' + dataTitle
+ '"/>';
alert(App.content);
$("#results").html("<p>" + htmlInput + "</p>");
$("#results").slideDown(); //show results with slide down effect
$("#loading_indicator").hide(); //hide loading indicator image
}
});
}
}
});
}); | JavaScript |
$(function() {
$("#dbform").bind('submit', function(ev) {
ev.preventDefault();
$('#continue').attr('disabled', 'disabled');
$('#continue').attr('value', 'Please Wait');
$.post('install.php', $(this).serialize(), function(data) {
$('#continue').attr('disabled', false);
$('#continue').attr('value', 'Continue');
$("#upper_content").html(data);
});
});
}); | JavaScript |
$(document).ready(function() {
var page = document.getElementById('page'),
ua = navigator.userAgent,
iphone = ~ua.indexOf('iPhone') || ~ua.indexOf('iPod'),
ipad = ~ua.indexOf('iPad'),
ios = iphone || ipad,
// Detect if this is running as a fullscreen app from the homescreen
fullscreen = window.navigator.standalone,
android = ~ua.indexOf('Android'),
lastWidth = 0;
if (android) {
// Android's browser adds the scroll position to the innerHeight, just to
// make this really fucking difficult. Thus, once we are scrolled, the
// page height value needs to be corrected in case the page is loaded
// when already scrolled down. The pageYOffset is of no use, since it always
// returns 0 while the address bar is displayed.
window.onscroll = function() {
page.style.height = window.innerHeight + 'px';
}
}
var setupScroll = window.onload = function() {
// Start out by adding the height of the location bar to the width, so that
// we can scroll past it
if (ios) {
// iOS reliably returns the innerWindow size for documentElement.clientHeight
// but window.innerHeight is sometimes the wrong value after rotating
// the orientation
var height = document.documentElement.clientHeight;
// Only add extra padding to the height on iphone / ipod, since the ipad
// browser doesn't scroll off the location bar.
if (iphone && !fullscreen) height += 60;
page.style.height = height + 'px';
} else if (android) {
// The stock Android browser has a location bar height of 56 pixels, but
// this very likely could be broken in other Android browsers.
page.style.height = (window.innerHeight + 56) + 'px';
}
// Scroll after a timeout, since iOS will scroll to the top of the page
// after it fires the onload event
setTimeout(scrollTo, 0, 0, 1);
};
(window.onresize = function() {
var pageWidth = page.offsetWidth;
// Android doesn't support orientation change, so check for when the width
// changes to figure out when the orientation changes
if (lastWidth == pageWidth) return;
lastWidth = pageWidth;
setupScroll();
})();
}); | JavaScript |
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - (media.duration * 0.05), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + (media.duration * 0.05), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var capsTagName = tagName.substring(0,1).toUpperCase() + tagName.substring(1);
if (t.options[tagName + 'Width'] > 0 || t.options[tagName + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagName + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagName + 'Height'] > 0 || t.options[tagName + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagName + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0) {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.media.setVideoSize)
t.media.setVideoSize(parentWidth, newHeight);
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType == 'flash') {
t.media.remove();
} else if (t.media.pluginType == 'native') {
t.media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
//player.container.bind('webkitfullscreenchange', function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
if (track.isTranslation) {
// translate the first track
mejs.TrackFormatParser.translateTrackText(t.tracks[0].entries, t.tracks[0].srclang, track.srclang, t.options.googleApiKey, function(newOne) {
// store the new translation
track.entries = newOne;
after();
});
} else {
$.ajax({
url: track.src,
success: function(d) {
// parse the loaded file
track.entries = mejs.TrackFormatParser.parse(d);
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
}
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
},
parse: function(trackText) {
var
i = 0,
lines = this.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: mejs.Utility.timeCodeToSeconds(timecode[1]),
stop: mejs.Utility.timeCodeToSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.1';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 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;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
return result;
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + ext;
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - (media.duration * 0.05), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + (media.duration * 0.05), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var capsTagName = tagName.substring(0,1).toUpperCase() + tagName.substring(1);
if (t.options[tagName + 'Width'] > 0 || t.options[tagName + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagName + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagName + 'Height'] > 0 || t.options[tagName + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagName + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0) {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.media.setVideoSize)
t.media.setVideoSize(parentWidth, newHeight);
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType == 'flash') {
t.media.remove();
} else if (t.media.pluginType == 'native') {
t.media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
//player.container.bind('webkitfullscreenchange', function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
if (track.isTranslation) {
// translate the first track
mejs.TrackFormatParser.translateTrackText(t.tracks[0].entries, t.tracks[0].srclang, track.srclang, t.options.googleApiKey, function(newOne) {
// store the new translation
track.entries = newOne;
after();
});
} else {
$.ajax({
url: track.src,
success: function(d) {
// parse the loaded file
track.entries = mejs.TrackFormatParser.parse(d);
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
}
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
},
parse: function(trackText) {
var
i = 0,
lines = this.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: mejs.Utility.timeCodeToSeconds(timecode[1]),
stop: mejs.Utility.timeCodeToSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.1';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 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;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
return result;
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + ext;
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
| JavaScript |
$(function () {
$('.table-highlight table').dataTable( {
sDom: "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
sPaginationType: "bootstrap",
oLanguage: {
"sLengthMenu": "_MENU_ records per page"
}
});
}); | JavaScript |
$(function () {
$('#datepicker-inline').datepicker ();
$('#datepicker-inline2').datepicker ();
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar-holder').fullCalendar({
header: {
left: 'prev, next',
center: 'title',
right: 'month,basicWeek,basicDay,'
},
events: [
{
title: 'Long Event',
start: new Date(y, m, d-5),
end: new Date(y, m, d-2),
color: Slate.chartColors[1]
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, 19, 16, 0),
end: new Date (y, m, 22, 16, 0),
allDay: false,
color: Slate.chartColors[1]
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d+4, 16, 0),
end: new Date(y, m, d+6, 16, 0),
allDay: false,
color: Slate.chartColors[0]
},
{
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false,
color: Slate.chartColors[1]
},
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false,
color: Slate.chartColors[0]
},
{
title: 'Birthday Party',
start: new Date(y, m, d+1, 19, 0),
end: new Date(y, m, d+1, 22, 30),
allDay: false,
color: Slate.chartColors[0]
},
{
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: '../../../google.com/default.htm',
color: Slate.chartColors[0]
}
]
});
}); | JavaScript |
$(function () {
/*--------------------------------------------------
Plugin: Type Ahead
--------------------------------------------------*/
$('#typeahead').typeahead ();
/*--------------------------------------------------
Plugin: Color Picker
--------------------------------------------------*/
$('#colorpicker-component').colorpicker({ format: 'hex' });
/*--------------------------------------------------
Plugin: Time Picker
--------------------------------------------------*/
$('#timepicker-basic').timepicker ({});
/*--------------------------------------------------
Plugin: Date Picker
--------------------------------------------------*/
$("#datepicker-basic").datepicker();
$("#datepicker-multi").datepicker({
numberOfMonths: 3,
showButtonPanel: true
});
/*--------------------------------------------------
Plugin: Msg Growl
--------------------------------------------------*/
$('.growl_type').live ('click', function (e) {
$.msgGrowl ({
type: $(this).attr ('data-type')
, title: 'Header'
, text: 'Lorem ipsum dolor sit amet, consectetur ipsum dolor sit amet, consectetur.'
});
});
/*--------------------------------------------------
Plugin: Msg Alert
--------------------------------------------------*/
$('.alert_type').live ('click', function (e) {
$.msgAlert ({
type: $(this).attr ('data-type')
, title: 'Title'
, text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.'
});
});
/*--------------------------------------------------
Plugin: Slider
--------------------------------------------------*/
/* Increment Slider */
$( "#incrementSlider" ).slider({
range: "min",
value:50,
min: 0,
max: 500,
step: 50,
slide: function( event, ui ) {
$( "#incrementAmount" ).text ( "$" + ui.value );
}
});
$( "#incrementAmount" ).text ( "$" + $( "#incrementSlider" ).slider( "value" ) );
/* Min Value Slider */
$( "#rangeMinSlider" ).slider({
range: "min",
value: 100,
min: 50,
max: 700,
slide: function( event, ui ) {
$( "#rangeMinAmount" ).text ( "$" + ui.value );
}
});
$( "#rangeMinAmount" ).text ( "$" + $( "#rangeMinSlider" ).slider( "value" ) );
/* Default Slider */
$( "#defaultSlider" ).slider({ range: 'min' });
/* Vertical Slider */
$("#eq > span").each(function() {
var value = parseInt($(this).text());
$(this).empty().slider({
value: value,
range: "min",
animate: true,
orientation: "vertical"
});
});
/* Horizontal Slider */
$( "#rangeSlider" ).slider({
range: true,
min: 0,
max: 500,
values: [ 75, 250 ],
slide: function( event, ui ) {
$( "#amount" ).text ( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
}
});
$( "#amount" ).text( "$" + $( "#rangeSlider" ).slider( "values", 0 ) +
" - $" + $( "#rangeSlider" ).slider( "values", 1 ) );
}); | JavaScript |
$(function () {
// we use an inline data source in the example, usually data would
// be fetched from a server
var data = [], totalPoints = 200;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0)
y = 0;
if (y > 100)
y = 100;
data.push(y);
}
var res = [];
for (var i = 0; i < data.length; ++i)
res.push([i, data[i]])
return res;
}
// setup plot
var options = {
yaxis: { min: 0, max: 100 },
xaxis: { min: 0, max: 100 },
colors: Slate.chartColors,
series: {
lines: {
lineWidth: 2,
fill: true,
fillColor: { colors: [ { opacity: 0.6 }, { opacity: 0.2 } ] },
steps: false
}
}
};
var plot = $.plot($("#area-chart"), [ getRandomData() ], options);
}); | JavaScript |
$(function () {
var sin = [], cos = [];
for (var i = 0; i < 10; i += 0.5) {
sin.push([i, Math.sin(i)]);
cos.push([i, Math.cos(i)]);
}
var plot = $.plot($("#line-chart"),
[ { data: sin, label: "sin(x)"}, { data: cos, label: "cos(x)" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: -1.1, max: 1.1 },
xaxis: { min: 0, max: 9 },
colors: Slate.chartColors
});
}); | JavaScript |
$(function () {
var data = [];
var series = Math.floor(Math.random()*10)+1;
var series = 4;
for( var i = 0; i<series; i++)
{
data[i] = { label: "Series"+(i+1), data: Math.floor(Math.random()*100)+1 }
}
$.plot($("#pie-chart"), data,
{
colors: Slate.chartColors,
series: {
pie: {
show: true,
label: {
show: false,
formatter: function(label, series){
return '<div style="font-size:11px;text-align:center;padding:4px;color:white;">'+label+'<br/>'+Math.round(series.percent)+'%</div>';
},
threshold: 0.1
}
}
},
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#888", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: [5, 10], // distance from grid edge to default legend container within plot
backgroundOpacity: 0 // set to 0 to avoid background
},
grid: {
hoverable: false,
clickable: false
},
});
}); | JavaScript |
$(function () {
var data = [];
var series = 3;
for( var i = 0; i<series; i++)
{
data[i] = { label: "Series "+(i+1), data: Math.floor(Math.random()*100)+1 }
}
$.plot($("#donut-chart"), data,
{
colors: Slate.chartColors,
//colors: ["#0A69C0", "#3C4049", "#777", "#AAA"],
series: {
pie: {
innerRadius: 0.5,
show: true
}
}
});
}); | JavaScript |
$(function () {
var data = new Array ();
var ds = new Array ();
data.push ([[1,25],[2,34],[3,37],[4,45],[5,56]]);
data.push ([[1,13],[2,29],[3,25],[4,23],[5,31]]);
data.push ([[1,8],[2,13],[3,19],[4,15],[5,14]]);
data.push ([[1,20],[2,43],[3,29],[4,23],[5,25]]);
for (var i=0, j=data.length; i<j; i++) {
ds.push({
data:data[i],
grid:{
hoverable:true
},
bars: {
show: true,
barWidth: 0.2,
order: 1,
lineWidth: 0.5,
fillColor: { colors: [ { opacity: 0.65 }, { opacity: 1 } ] }
}
});
}
$.plot($("#bar-chart"), ds, {
colors: Slate.chartColors,
//colors: ["#0A69C0", "#3C4049", "#666", "#BBB"]
});
}); | JavaScript |
$(function () {
$('#wizard').smartWizard({transitionEffect:'slideleft',enableFinishButton:false});
}); | JavaScript |
//
// jQuery Validate example script
//
// Prepared by David Cochran
//
// Free for your use -- No warranties, no guarantees!
//
$(document).ready(function(){
// Validate
// http://bassistance.de/jquery-plugins/jquery-plugin-validation/
// http://docs.jquery.com/Plugins/Validation/
// http://docs.jquery.com/Plugins/Validation/validate#toptions
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
subject: {
minlength: 2,
required: true
},
message: {
minlength: 2,
required: true
},
validateSelect: {
required: true
},
validateCheckbox: {
required: true,
minlength: 2
},
validateRadio: {
required: true
}
},
focusCleanup: false,
highlight: function(label) {
$(label).closest('.control-group').removeClass ('success').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
},
errorPlacement: function(error, element) {
error.appendTo( element.parents ('.controls') );
}
});
$('.form').eq (0).find ('input').eq (0).focus ();
}); // end document.ready | JavaScript |
$(function () {
var timeout = '';
$('.gallery').find ('.frame').append ('<img src="img/gallery/frame.png" alt="Frame" />');
$('.gallery li').live ('mouseenter', function (e) {
var $this = $(this);
timeout = setTimeout (function () {
$this.find ('.actions').fadeIn ();
$this.find ('.img img').animate ({ opacity: '.35' });
}, 550);
}).live ('mouseleave', function (e) {
clearTimeout (timeout);
$(this).find ('.actions').hide ();
$(this).find ('.img img').animate ({ opacity: '1' });
});
}); | JavaScript |
$(function () {
$('.faq-list').goFaq ();
}); | JavaScript |
var Slate = function () {
var chartColors, nav, navTop;
chartColors = ["#263849", "#F90", "#666", "#BBB"];
return { start: start, chartColors: chartColors };
function start () {
nav = $('#nav');
navTop = nav.offset ().top;
bindNavEvents ();
bindWidgetEvents ();
bindAccordionEvents ();
enableAutoPlugins ();
}
function enableAutoPlugins () {
if ($.fn.tooltip) {
$('.ui-tooltip').tooltip ();
}
if ($.fn.popover) {
$('.ui-popover').popover ();
}
if ($.fn.lightbox) {
$('.ui-lightbox').lightbox();
}
if ($.fn.dataTable) {
$('.data-table').dataTable( {
sDom: "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
sPaginationType: "bootstrap",
oLanguage: {
"sLengthMenu": "_MENU_ records per page"
}
});
}
}
function bindNavEvents () {
var msie8 = $.browser.version === '8.0' && $.browser.msie;
if (!msie8) {
$(window).bind ('scroll', navScroll);
}
$('#info-trigger').live ('click', function (e) {
e.preventDefault ();
$('#info-menu').toggleClass ('toggle-menu-show');
$(document).bind ('click.info', function (e) {
if ($(e.target).is ('#info-menu')) { return false; }
if ($(e.target).parents ('#info-menu').length == 1) { return false; }
$('#info-menu').removeClass ('toggle-menu-show');
$(document).unbind ('click.info');
});
});
}
function navScroll () {
var p = $(window).scrollTop ();
((p)>navTop) ? $('body').addClass ('nav-fixed') : $('body').removeClass ('nav-fixed');
}
function bindWidgetEvents () {
$('.widget-tabs .nav-tabs a').live ('click', widgetTabClickHandler);
}
function bindAccordionEvents () {
$('.widget-accordion .accordion').on('show', function (e) {
$(e.target).prev('.accordion-heading').parent ().addClass('open');
});
$('.widget-accordion .accordion').on('hide', function (e) {
$(this).find('.accordion-toggle').not($(e.target)).parents ('.accordion-group').removeClass('open');
});
$('.widget-accordion .accordion').each (function () {
$(this).find ('.accordion-body.in').parent ().addClass ('open');
});
}
function widgetTabClickHandler (e) {
e.preventDefault();
$(this).tab('show');
}
}();
$(function () {
Slate.start ();
}); | JavaScript |
$(document).ready(function() {
var switched = false;
var updateTables = function() {
if (($(window).width() < 767) && !switched ){
switched = true;
$(".responsive table.items").each(function(i, element) {
splitTable($(element));
});
return true;
}
else if (switched && ($(window).width() > 767)) {
switched = false;
$(".responsive table.items").each(function(i, element) {
unsplitTable($(element));
});
}
};
$(window).load(updateTables);
$(window).bind("resize", updateTables);
function splitTable(original)
{
original.wrap("<div class='table-wrapper' />");
var copy = original.clone();
copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
copy.removeClass("responsive");
original.closest(".table-wrapper").append(copy);
copy.wrap("<div class='pinned' />");
original.wrap("<div class='scrollable' />");
}
function unsplitTable(original) {
original.closest(".table-wrapper").find(".pinned").remove();
original.unwrap();
original.unwrap();
}
}); | JavaScript |
/**
* @name FAQ Plugin
* @author Rod Howard
* @url http://goideate.com
* @date April 28, 2012
* @license GNU/GPL Version 3
*
*
* Example:
*
* $(function() {
* $("element, #id, .class").technify({
* // #{EDIT-HERE}# Your run-time options go here ...
* });
* });
*/
/**
* Create an anonymous function to avoid library conflicts
*/
(function($) {
/**
* Add our plugin to the jQuery.fn object
*/
$.fn.goFaq = function(options) {
/**
* Define some default settings
*/
var defaults = {
enableSearch: true,
enableToc: true,
enableStyling: true,
//numberHtml: '{{#}}.',
numberHtml: '<div class="faq-number">{{#}}</div>'
};
/**
* Merge the runtime options with the default settings
*/
var options = $.extend({}, defaults, options);
/**
* Iterate through the collection of elements and
* return the object to preserve method chaining
*/
return this.each(function(i) {
/**
* Wrap the current element in an instance of jQuery
*/
var $this = $(this);
var $container = $this.wrap ('<div class="faq-container"></div>');
$this.addClass ('faq-list');
if (options.enableSearch) {
var $form = generateSearchForm ();
$form.insertBefore ($this);
}
if (options.enableToc) {
var $toc = generateToc ($this);
$toc.insertBefore ($this);
}
var $empty = generateEmptySearch ();
$empty.appendTo ($container);
generateAnswerNumbers ($this);
});
function search (e) {
var el, container, filter, count, pattern, container, answers, toc, tocs, empty;
el = $(this);
container = el.parents ('.faq-container');
filter = el.val ();
toc = container.find ('.faq-toc');
answers = container.find ('.faq-list').find ('li');
tocs = container.find ('.faq-toc').find('li');
empty = container.find ('.faq-empty');
pattern = new RegExp (filter, 'i');
answers.hide ();
tocs.hide ();
$.grep (answers.find ('.faq-text'), function (input) {
if (pattern.test ($(input).text ())) {
$(input).parents ('li').show ();
var index = $(input).parents ('li').index ();
tocs.eq (index).show ();
}
});
if (!answers.is (':visible')) {
empty.show ();
toc.hide ();
} else {
empty.hide ();
toc.show ();
}
}
function generateEmptySearch () {
var $empty = $('<div>', { 'class': 'faq-empty' });
return $empty.html ('Nothing Found');
}
function generateSearchForm () {
var $form = $('<form>', { 'class': 'faq-search' });
var $input = $('<input>', { 'type': 'text', 'name': 'search', 'placeholder': 'Search by Keyword' });
$input.appendTo ($form);
$input.bind ('keyup', search)
return $form;
}
function generateAnswerNumbers ($list) {
$list.find ('li').each (function (i) {
var id = parseInt (i+1);
$(this).wrapInner ('<div class="faq-text"></div>');
if (options.enableStyling) {
var icon = '<div class="faq-icon">' + options.numberHtml + '</div>';
icon = icon.replace ('{{#}}', id);
$(this).prepend (icon);
}
});
}
function generateToc ($list) {
var html = '<ol>';
$list.find ('li').each (function (i) {
var id = parseInt (i+1);
html += '<li>' + id + '. <a href="#faq-' + id + '">' + $(this).find ('h4').text () + '</a></li>';
$(this).attr ('id', 'faq-' + id);
});
html += '</ol>';
var $toc = $('<div>', { 'class': 'faq-toc' });
$toc.html (html);
return $toc;
}
};
})(jQuery); | JavaScript |
/*
* SmartWizard 2.0 plugin
* jQuery Wizard control Plugin
* by Dipu
*
* http://www.techlaboratory.net
* http://tech-laboratory.blogspot.com
*/
(function($){
$.fn.smartWizard = function(action) {
var options = $.extend({}, $.fn.smartWizard.defaults, action);
var args = arguments;
return this.each(function(){
var obj = $(this);
var curStepIdx = options.selected;
var steps = $("ul > li > a", obj); // Get all anchors in this array
var contentWidth = 0;
var loader,msgBox,elmActionBar,elmStepContainer,btNext,btPrevious,btFinish;
elmActionBar = $('.actionBar',obj);
if(elmActionBar.length == 0){
elmActionBar = $('<div></div>').addClass("actionBar");
}
msgBox = $('.msgBox',obj);
if(msgBox.length == 0){
msgBox = $('<div class="msgBox"><div class="content"></div><a href="#" class="close">X</a></div>');
elmActionBar.append(msgBox);
}
$('.close',msgBox).click(function() {
msgBox.fadeOut("normal");
return false;
});
// Method calling logic
if (!action || action === 'init' || typeof action === 'object') {
init();
}else if (action === 'showMessage') {
//showMessage(Array.prototype.slice.call( args, 1 ));
var ar = Array.prototype.slice.call( args, 1 );
showMessage(ar[0]);
return true;
}else if (action === 'setError') {
var ar = Array.prototype.slice.call( args, 1 );
setError(ar[0].stepnum,ar[0].iserror);
return true;
} else {
$.error( 'Method ' + action + ' does not exist' );
}
function init(){
var allDivs =obj.children('div'); //$("div", obj);
obj.children('ul').addClass("anchor");
allDivs.addClass("content");
// Create Elements
loader = $('<div>Loading</div>').addClass("loader");
elmActionBar = $('<div></div>').addClass("actionBar");
elmStepContainer = $('<div></div>').addClass("stepContainer");
btNext = $('<a>'+options.labelNext+'</a>').attr("href","#").addClass("buttonNext btn btn-tertiary");
btPrevious = $('<a>'+options.labelPrevious+'</a>').attr("href","#").addClass("buttonPrevious btn");
btFinish = $('<a>'+options.labelFinish+'</a>').attr("href","#").addClass("buttonFinish btn btn-primary");
// highlight steps with errors
if(options.errorSteps && options.errorSteps.length>0){
$.each(options.errorSteps, function(i, n){
setError(n,true);
});
}
elmStepContainer.append(allDivs);
elmActionBar.append(loader);
obj.append(elmStepContainer);
obj.append(elmActionBar);
elmActionBar.append(btFinish).append(btNext).append(btPrevious);
contentWidth = elmStepContainer.width();
$(btNext).click(function() {
doForwardProgress();
return false;
});
$(btPrevious).click(function() {
doBackwardProgress();
return false;
});
$(btFinish).click(function() {
if(!$(this).hasClass('buttonDisabled')){
if($.isFunction(options.onFinish)) {
if(!options.onFinish.call(this,$(steps))){
return false;
}
}else{
var frm = obj.parents('form');
if(frm && frm.length){
frm.submit();
}
}
}
return false;
});
$(steps).bind("click", function(e){
if(steps.index(this) == curStepIdx){
return false;
}
var nextStepIdx = steps.index(this);
var isDone = steps.eq(nextStepIdx).attr("isDone") - 0;
if(isDone == 1){
LoadContent(nextStepIdx);
}
return false;
});
// Enable keyboard navigation
if(options.keyNavigation){
$(document).keyup(function(e){
if(e.which==39){ // Right Arrow
doForwardProgress();
}else if(e.which==37){ // Left Arrow
doBackwardProgress();
}
});
}
// Prepare the steps
prepareSteps();
// Show the first slected step
LoadContent(curStepIdx);
}
function prepareSteps(){
if(!options.enableAllSteps){
$(steps, obj).removeClass("selected").removeClass("done").addClass("disabled");
$(steps, obj).attr("isDone",0);
}else{
$(steps, obj).removeClass("selected").removeClass("disabled").addClass("done");
$(steps, obj).attr("isDone",1);
}
$(steps, obj).each(function(i){
$($(this).attr("href"), obj).hide();
$(this).attr("rel",i+1);
});
}
function LoadContent(stepIdx){
var selStep = steps.eq(stepIdx);
var ajaxurl = options.contentURL;
var hasContent = selStep.data('hasContent');
stepNum = stepIdx+1;
if(ajaxurl && ajaxurl.length>0){
if(options.contentCache && hasContent){
showStep(stepIdx);
}else{
$.ajax({
url: ajaxurl,
type: "POST",
data: ({step_number : stepNum}),
dataType: "text",
beforeSend: function(){ loader.show(); },
error: function(){loader.hide();},
success: function(res){
loader.hide();
if(res && res.length>0){
selStep.data('hasContent',true);
$($(selStep, obj).attr("href"), obj).html(res);
showStep(stepIdx);
}
}
});
}
}else{
showStep(stepIdx);
}
}
function showStep(stepIdx){
var selStep = steps.eq(stepIdx);
var curStep = steps.eq(curStepIdx);
if(stepIdx != curStepIdx){
if($.isFunction(options.onLeaveStep)) {
if(!options.onLeaveStep.call(this,$(curStep))){
return false;
}
}
}
elmStepContainer.height($($(selStep, obj).attr("href"), obj).outerHeight());
if(options.transitionEffect == 'slide'){
$($(curStep, obj).attr("href"), obj).slideUp("fast",function(e){
$($(selStep, obj).attr("href"), obj).slideDown("fast");
curStepIdx = stepIdx;
SetupStep(curStep,selStep);
});
} else if(options.transitionEffect == 'fade'){
$($(curStep, obj).attr("href"), obj).fadeOut("fast",function(e){
$($(selStep, obj).attr("href"), obj).fadeIn("fast");
curStepIdx = stepIdx;
SetupStep(curStep,selStep);
});
} else if(options.transitionEffect == 'slideleft'){
var nextElmLeft = 0;
var curElementLeft = 0;
if(stepIdx > curStepIdx){
nextElmLeft1 = contentWidth + 10;
nextElmLeft2 = 0;
curElementLeft = 0 - $($(curStep, obj).attr("href"), obj).outerWidth();
} else {
nextElmLeft1 = 0 - $($(selStep, obj).attr("href"), obj).outerWidth() + 20;
nextElmLeft2 = 0;
curElementLeft = 10 + $($(curStep, obj).attr("href"), obj).outerWidth();
}
if(stepIdx == curStepIdx){
nextElmLeft1 = $($(selStep, obj).attr("href"), obj).outerWidth() + 20;
nextElmLeft2 = 0;
curElementLeft = 0 - $($(curStep, obj).attr("href"), obj).outerWidth();
}else{
$($(curStep, obj).attr("href"), obj).animate({left:curElementLeft},"fast",function(e){
$($(curStep, obj).attr("href"), obj).hide();
});
}
$($(selStep, obj).attr("href"), obj).css("left",nextElmLeft1);
$($(selStep, obj).attr("href"), obj).show();
$($(selStep, obj).attr("href"), obj).animate({left:nextElmLeft2},"fast",function(e){
curStepIdx = stepIdx;
SetupStep(curStep,selStep);
});
} else{
$($(curStep, obj).attr("href"), obj).hide();
$($(selStep, obj).attr("href"), obj).show();
curStepIdx = stepIdx;
SetupStep(curStep,selStep);
}
return true;
}
function SetupStep(curStep,selStep){
$(curStep, obj).removeClass("selected");
$(curStep, obj).addClass("done");
$(selStep, obj).removeClass("disabled");
$(selStep, obj).removeClass("done");
$(selStep, obj).addClass("selected");
$(selStep, obj).attr("isDone",1);
adjustButton();
if($.isFunction(options.onShowStep)) {
if(!options.onShowStep.call(this,$(selStep))){
return false;
}
}
}
function doForwardProgress(){
var nextStepIdx = curStepIdx + 1;
if(steps.length <= nextStepIdx){
if(!options.cycleSteps){
return false;
}
nextStepIdx = 0;
}
LoadContent(nextStepIdx);
}
function doBackwardProgress(){
var nextStepIdx = curStepIdx-1;
if(0 > nextStepIdx){
if(!options.cycleSteps){
return false;
}
nextStepIdx = steps.length - 1;
}
LoadContent(nextStepIdx);
}
function adjustButton(){
if(!options.cycleSteps){
if(0 >= curStepIdx){
$(btPrevious).addClass("buttonDisabled");
}else{
$(btPrevious).removeClass("buttonDisabled");
}
if((steps.length-1) <= curStepIdx){
$(btNext).addClass("buttonDisabled");
}else{
$(btNext).removeClass("buttonDisabled");
}
}
// Finish Button
if(!steps.hasClass('disabled') || options.enableFinishButton){
$(btFinish).removeClass("buttonDisabled");
}else{
$(btFinish).addClass("buttonDisabled");
}
}
function showMessage(msg){
$('.content',msgBox).html(msg);
msgBox.show();
}
function setError(stepnum,iserror){
if(iserror){
$(steps.eq(stepnum-1), obj).addClass('error')
}else{
$(steps.eq(stepnum-1), obj).removeClass("error");
}
}
});
};
// Default Properties and Events
$.fn.smartWizard.defaults = {
selected: 0, // Selected Step, 0 = first step
keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled)
enableAllSteps: false,
transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft
contentURL:null, // content url, Enables Ajax content loading
contentCache:true, // cache step contents, if false content is fetched always from ajax url
cycleSteps: false, // cycle step navigation
enableFinishButton: false, // make finish button enabled always
errorSteps:[], // Array Steps with errors
labelNext:'Next',
labelPrevious:'Previous',
labelFinish:'Finish',
onLeaveStep: null, // triggers when leaving a step
onShowStep: null, // triggers when showing a step
onFinish: null // triggers when Finish button is clicked
};
})(jQuery); | JavaScript |
/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
}
/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function( oSettings, nPaging, fnDraw ) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function ( e ) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
fnDraw( oSettings );
}
};
$(nPaging).addClass('pagination').append(
'<ul>'+
'<li class="prev disabled"><a href="#">← '+oLang.sPrevious+'</a></li>'+
'<li class="next disabled"><a href="#">'+oLang.sNext+' → </a></li>'+
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
$(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
},
"fnUpdate": function ( oSettings, fnDraw ) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);
if ( oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
}
else if ( oPaging.iPage <= iHalf ) {
iStart = 1;
iEnd = iListLength;
} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for ( i=0, iLen=an.length ; i<iLen ; i++ ) {
// Remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// Add the new list items and their event handlers
for ( j=iStart ; j<=iEnd ; j++ ) {
sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
$('<li '+sClass+'><a href="#">'+j+'</a></li>')
.insertBefore( $('li:last', an[i])[0] )
.bind('click', function (e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
fnDraw( oSettings );
} );
}
// Add / remove disabled classes from the static elements
if ( oPaging.iPage === 0 ) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
} ); | JavaScript |
/*
Flot plugin for automatically redrawing plots when the placeholder
size changes, e.g. on window resizes.
It works by listening for changes on the placeholder div (through the
jQuery resize event plugin) - if the size changes, it will redraw the
plot.
There are no options. If you need to disable the plugin for some
plots, you can just fix the size of their placeholders.
*/
/* Inline dependency:
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this);
(function ($) {
var redrawing = 0;
var options = { }; // no options
function init(plot) {
function bindEvents(plot, eventHolder) {
if (!redrawing)
plot.getPlaceholder().resize(onResize);
function onResize() {
var placeholder = plot.getPlaceholder();
// somebody might have hidden us and we can't plot
// when we don't have the dimensions
if (placeholder.width() == 0 || placeholder.height() == 0)
return;
++redrawing;
$.plot(placeholder, plot.getData(), plot.getOptions());
--redrawing;
}
}
plot.hooks.bindEvents.push(bindEvents);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'resize',
version: '1.0'
});
})(jQuery); | JavaScript |
/*
Flot plugin for rendering pie charts. The plugin assumes the data is
coming is as a single data value for each series, and each of those
values is a positive value or zero (negative numbers don't make
any sense and will cause strange effects). The data values do
NOT need to be passed in as percentage values because it
internally calculates the total and percentages.
* Created by Brian Medendorp, June 2009
* Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars
* Changes:
2009-10-22: lineJoin set to round
2009-10-23: IE full circle fix, donut
2009-11-11: Added basic hover from btburnett3 - does not work in IE, and center is off in Chrome and Opera
2009-11-17: Added IE hover capability submitted by Anthony Aragues
2009-11-18: Added bug fix submitted by Xavi Ivars (issues with arrays when other JS libraries are included as well)
Available options are:
series: {
pie: {
show: true/false
radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
offset: {
top: integer value to move the pie up or down
left: integer value to move the pie left or right, or 'auto'
},
stroke: {
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
width: integer pixel width of the stroke
},
label: {
show: true/false, or 'auto'
formatter: a user-defined function that modifies the text/style of the label text
radius: 0-1 for percentage of fullsize, or a specified pixel length
background: {
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
opacity: 0-1
},
threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
},
combine: {
threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
label: any text value of what the combined slice should be labeled
}
highlight: {
opacity: 0-1
}
}
}
More detail and specific examples can be found in the included HTML file.
*/
(function ($)
{
function init(plot) // this is the "body" of the plugin
{
var canvas = null;
var target = null;
var maxRadius = null;
var centerLeft = null;
var centerTop = null;
var total = 0;
var redraw = true;
var redrawAttempts = 10;
var shrink = 0.95;
var legendWidth = 0;
var processed = false;
var raw = false;
// interactive variables
var highlights = [];
// add hook to determine if pie plugin in enabled, and then perform necessary operations
plot.hooks.processOptions.push(checkPieEnabled);
plot.hooks.bindEvents.push(bindEvents);
// check to see if the pie plugin is enabled
function checkPieEnabled(plot, options)
{
if (options.series.pie.show)
{
//disable grid
options.grid.show = false;
// set labels.show
if (options.series.pie.label.show=='auto')
if (options.legend.show)
options.series.pie.label.show = false;
else
options.series.pie.label.show = true;
// set radius
if (options.series.pie.radius=='auto')
if (options.series.pie.label.show)
options.series.pie.radius = 3/4;
else
options.series.pie.radius = 1;
// ensure sane tilt
if (options.series.pie.tilt>1)
options.series.pie.tilt=1;
if (options.series.pie.tilt<0)
options.series.pie.tilt=0;
// add processData hook to do transformations on the data
plot.hooks.processDatapoints.push(processDatapoints);
plot.hooks.drawOverlay.push(drawOverlay);
// add draw hook
plot.hooks.draw.push(draw);
}
}
// bind hoverable events
function bindEvents(plot, eventHolder)
{
var options = plot.getOptions();
if (options.series.pie.show && options.grid.hoverable)
eventHolder.unbind('mousemove').mousemove(onMouseMove);
if (options.series.pie.show && options.grid.clickable)
eventHolder.unbind('click').click(onClick);
}
// debugging function that prints out an object
function alertObject(obj)
{
var msg = '';
function traverse(obj, depth)
{
if (!depth)
depth = 0;
for (var i = 0; i < obj.length; ++i)
{
for (var j=0; j<depth; j++)
msg += '\t';
if( typeof obj[i] == "object")
{ // its an object
msg += ''+i+':\n';
traverse(obj[i], depth+1);
}
else
{ // its a value
msg += ''+i+': '+obj[i]+'\n';
}
}
}
traverse(obj);
alert(msg);
}
function calcTotal(data)
{
for (var i = 0; i < data.length; ++i)
{
var item = parseFloat(data[i].data[0][1]);
if (item)
total += item;
}
}
function processDatapoints(plot, series, data, datapoints)
{
if (!processed)
{
processed = true;
canvas = plot.getCanvas();
target = $(canvas).parent();
options = plot.getOptions();
plot.setData(combine(plot.getData()));
}
}
function setupPie()
{
legendWidth = target.children().filter('.legend').children().width();
// calculate maximum radius and center point
maxRadius = Math.min(canvas.width,(canvas.height/options.series.pie.tilt))/2;
centerTop = (canvas.height/2)+options.series.pie.offset.top;
centerLeft = (canvas.width/2);
if (options.series.pie.offset.left=='auto')
if (options.legend.position.match('w'))
centerLeft += legendWidth/2;
else
centerLeft -= legendWidth/2;
else
centerLeft += options.series.pie.offset.left;
if (centerLeft<maxRadius)
centerLeft = maxRadius;
else if (centerLeft>canvas.width-maxRadius)
centerLeft = canvas.width-maxRadius;
}
function fixData(data)
{
for (var i = 0; i < data.length; ++i)
{
if (typeof(data[i].data)=='number')
data[i].data = [[1,data[i].data]];
else if (typeof(data[i].data)=='undefined' || typeof(data[i].data[0])=='undefined')
{
if (typeof(data[i].data)!='undefined' && typeof(data[i].data.label)!='undefined')
data[i].label = data[i].data.label; // fix weirdness coming from flot
data[i].data = [[1,0]];
}
}
return data;
}
function combine(data)
{
data = fixData(data);
calcTotal(data);
var combined = 0;
var numCombined = 0;
var color = options.series.pie.combine.color;
var newdata = [];
for (var i = 0; i < data.length; ++i)
{
// make sure its a number
data[i].data[0][1] = parseFloat(data[i].data[0][1]);
if (!data[i].data[0][1])
data[i].data[0][1] = 0;
if (data[i].data[0][1]/total<=options.series.pie.combine.threshold)
{
combined += data[i].data[0][1];
numCombined++;
if (!color)
color = data[i].color;
}
else
{
newdata.push({
data: [[1,data[i].data[0][1]]],
color: data[i].color,
label: data[i].label,
angle: (data[i].data[0][1]*(Math.PI*2))/total,
percent: (data[i].data[0][1]/total*100)
});
}
}
if (numCombined>0)
newdata.push({
data: [[1,combined]],
color: color,
label: options.series.pie.combine.label,
angle: (combined*(Math.PI*2))/total,
percent: (combined/total*100)
});
return newdata;
}
function draw(plot, newCtx)
{
if (!target) return; // if no series were passed
ctx = newCtx;
setupPie();
var slices = plot.getData();
var attempts = 0;
while (redraw && attempts<redrawAttempts)
{
redraw = false;
if (attempts>0)
maxRadius *= shrink;
attempts += 1;
clear();
if (options.series.pie.tilt<=0.8)
drawShadow();
drawPie();
}
if (attempts >= redrawAttempts) {
clear();
target.prepend('<div class="error">Could not draw pie with labels contained inside canvas</div>');
}
if ( plot.setSeries && plot.insertLegend )
{
plot.setSeries(slices);
plot.insertLegend();
}
// we're actually done at this point, just defining internal functions at this point
function clear()
{
ctx.clearRect(0,0,canvas.width,canvas.height);
target.children().filter('.pieLabel, .pieLabelBackground').remove();
}
function drawShadow()
{
var shadowLeft = 5;
var shadowTop = 15;
var edge = 10;
var alpha = 0.02;
// set radius
if (options.series.pie.radius>1)
var radius = options.series.pie.radius;
else
var radius = maxRadius * options.series.pie.radius;
if (radius>=(canvas.width/2)-shadowLeft || radius*options.series.pie.tilt>=(canvas.height/2)-shadowTop || radius<=edge)
return; // shadow would be outside canvas, so don't draw it
ctx.save();
ctx.translate(shadowLeft,shadowTop);
ctx.globalAlpha = alpha;
ctx.fillStyle = '#000';
// center and rotate to starting position
ctx.translate(centerLeft,centerTop);
ctx.scale(1, options.series.pie.tilt);
//radius -= edge;
for (var i=1; i<=edge; i++)
{
ctx.beginPath();
ctx.arc(0,0,radius,0,Math.PI*2,false);
ctx.fill();
radius -= i;
}
ctx.restore();
}
function drawPie()
{
startAngle = Math.PI*options.series.pie.startAngle;
// set radius
if (options.series.pie.radius>1)
var radius = options.series.pie.radius;
else
var radius = maxRadius * options.series.pie.radius;
// center and rotate to starting position
ctx.save();
ctx.translate(centerLeft,centerTop);
ctx.scale(1, options.series.pie.tilt);
//ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
// draw slices
ctx.save();
var currentAngle = startAngle;
for (var i = 0; i < slices.length; ++i)
{
slices[i].startAngle = currentAngle;
drawSlice(slices[i].angle, slices[i].color, true);
}
ctx.restore();
// draw slice outlines
ctx.save();
ctx.lineWidth = options.series.pie.stroke.width;
currentAngle = startAngle;
for (var i = 0; i < slices.length; ++i)
drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
ctx.restore();
// draw donut hole
drawDonutHole(ctx);
// draw labels
if (options.series.pie.label.show)
drawLabels();
// restore to original state
ctx.restore();
function drawSlice(angle, color, fill)
{
if (angle<=0)
return;
if (fill)
ctx.fillStyle = color;
else
{
ctx.strokeStyle = color;
ctx.lineJoin = 'round';
}
ctx.beginPath();
if (Math.abs(angle - Math.PI*2) > 0.000000001)
ctx.moveTo(0,0); // Center of the pie
else if ($.browser.msie)
angle -= 0.0001;
//ctx.arc(0,0,radius,0,angle,false); // This doesn't work properly in Opera
ctx.arc(0,0,radius,currentAngle,currentAngle+angle,false);
ctx.closePath();
//ctx.rotate(angle); // This doesn't work properly in Opera
currentAngle += angle;
if (fill)
ctx.fill();
else
ctx.stroke();
}
function drawLabels()
{
var currentAngle = startAngle;
// set radius
if (options.series.pie.label.radius>1)
var radius = options.series.pie.label.radius;
else
var radius = maxRadius * options.series.pie.label.radius;
for (var i = 0; i < slices.length; ++i)
{
if (slices[i].percent >= options.series.pie.label.threshold*100)
drawLabel(slices[i], currentAngle, i);
currentAngle += slices[i].angle;
}
function drawLabel(slice, startAngle, index)
{
if (slice.data[0][1]==0)
return;
// format label text
var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
if (lf)
text = lf(slice.label, slice);
else
text = slice.label;
if (plf)
text = plf(text, slice);
var halfAngle = ((startAngle+slice.angle) + startAngle)/2;
var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
var html = '<span class="pieLabel" id="pieLabel'+index+'" style="position:absolute;top:' + y + 'px;left:' + x + 'px;">' + text + "</span>";
target.append(html);
var label = target.children('#pieLabel'+index);
var labelTop = (y - label.height()/2);
var labelLeft = (x - label.width()/2);
label.css('top', labelTop);
label.css('left', labelLeft);
// check to make sure that the label is not outside the canvas
if (0-labelTop>0 || 0-labelLeft>0 || canvas.height-(labelTop+label.height())<0 || canvas.width-(labelLeft+label.width())<0)
redraw = true;
if (options.series.pie.label.background.opacity != 0) {
// put in the transparent background separately to avoid blended labels and label boxes
var c = options.series.pie.label.background.color;
if (c == null) {
c = slice.color;
}
var pos = 'top:'+labelTop+'px;left:'+labelLeft+'px;';
$('<div class="pieLabelBackground" style="position:absolute;width:' + label.width() + 'px;height:' + label.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').insertBefore(label).css('opacity', options.series.pie.label.background.opacity);
}
} // end individual label function
} // end drawLabels function
} // end drawPie function
} // end draw function
// Placed here because it needs to be accessed from multiple locations
function drawDonutHole(layer)
{
// draw donut hole
if(options.series.pie.innerRadius > 0)
{
// subtract the center
layer.save();
innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
layer.globalCompositeOperation = 'destination-out'; // this does not work with excanvas, but it will fall back to using the stroke color
layer.beginPath();
layer.fillStyle = options.series.pie.stroke.color;
layer.arc(0,0,innerRadius,0,Math.PI*2,false);
layer.fill();
layer.closePath();
layer.restore();
// add inner stroke
layer.save();
layer.beginPath();
layer.strokeStyle = options.series.pie.stroke.color;
layer.arc(0,0,innerRadius,0,Math.PI*2,false);
layer.stroke();
layer.closePath();
layer.restore();
// TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
}
}
//-- Additional Interactive related functions --
function isPointInPoly(poly, pt)
{
for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1]))
&& (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
&& (c = !c);
return c;
}
function findNearbySlice(mouseX, mouseY)
{
var slices = plot.getData(),
options = plot.getOptions(),
radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
for (var i = 0; i < slices.length; ++i)
{
var s = slices[i];
if(s.pie.show)
{
ctx.save();
ctx.beginPath();
ctx.moveTo(0,0); // Center of the pie
//ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here.
ctx.arc(0,0,radius,s.startAngle,s.startAngle+s.angle,false);
ctx.closePath();
x = mouseX-centerLeft;
y = mouseY-centerTop;
if(ctx.isPointInPath)
{
if (ctx.isPointInPath(mouseX-centerLeft, mouseY-centerTop))
{
//alert('found slice!');
ctx.restore();
return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i};
}
}
else
{
// excanvas for IE doesn;t support isPointInPath, this is a workaround.
p1X = (radius * Math.cos(s.startAngle));
p1Y = (radius * Math.sin(s.startAngle));
p2X = (radius * Math.cos(s.startAngle+(s.angle/4)));
p2Y = (radius * Math.sin(s.startAngle+(s.angle/4)));
p3X = (radius * Math.cos(s.startAngle+(s.angle/2)));
p3Y = (radius * Math.sin(s.startAngle+(s.angle/2)));
p4X = (radius * Math.cos(s.startAngle+(s.angle/1.5)));
p4Y = (radius * Math.sin(s.startAngle+(s.angle/1.5)));
p5X = (radius * Math.cos(s.startAngle+s.angle));
p5Y = (radius * Math.sin(s.startAngle+s.angle));
arrPoly = [[0,0],[p1X,p1Y],[p2X,p2Y],[p3X,p3Y],[p4X,p4Y],[p5X,p5Y]];
arrPoint = [x,y];
// TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
if(isPointInPoly(arrPoly, arrPoint))
{
ctx.restore();
return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i};
}
}
ctx.restore();
}
}
return null;
}
function onMouseMove(e)
{
triggerClickHoverEvent('plothover', e);
}
function onClick(e)
{
triggerClickHoverEvent('plotclick', e);
}
// trigger click or hover event (they send the same parameters so we share their code)
function triggerClickHoverEvent(eventname, e)
{
var offset = plot.offset(),
canvasX = parseInt(e.pageX - offset.left),
canvasY = parseInt(e.pageY - offset.top),
item = findNearbySlice(canvasX, canvasY);
if (options.grid.autoHighlight)
{
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i)
{
var h = highlights[i];
if (h.auto == eventname && !(item && h.series == item.series))
unhighlight(h.series);
}
}
// highlight the slice
if (item)
highlight(item.series, eventname);
// trigger any hover bind events
var pos = { pageX: e.pageX, pageY: e.pageY };
target.trigger(eventname, [ pos, item ]);
}
function highlight(s, auto)
{
if (typeof s == "number")
s = series[s];
var i = indexOfHighlight(s);
if (i == -1)
{
highlights.push({ series: s, auto: auto });
plot.triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s)
{
if (s == null)
{
highlights = [];
plot.triggerRedrawOverlay();
}
if (typeof s == "number")
s = series[s];
var i = indexOfHighlight(s);
if (i != -1)
{
highlights.splice(i, 1);
plot.triggerRedrawOverlay();
}
}
function indexOfHighlight(s)
{
for (var i = 0; i < highlights.length; ++i)
{
var h = highlights[i];
if (h.series == s)
return i;
}
return -1;
}
function drawOverlay(plot, octx)
{
//alert(options.series.pie.radius);
var options = plot.getOptions();
//alert(options.series.pie.radius);
var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
octx.save();
octx.translate(centerLeft, centerTop);
octx.scale(1, options.series.pie.tilt);
for (i = 0; i < highlights.length; ++i)
drawHighlight(highlights[i].series);
drawDonutHole(octx);
octx.restore();
function drawHighlight(series)
{
if (series.angle < 0) return;
//octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
octx.fillStyle = "rgba(255, 255, 255, "+options.series.pie.highlight.opacity+")"; // this is temporary until we have access to parseColor
octx.beginPath();
if (Math.abs(series.angle - Math.PI*2) > 0.000000001)
octx.moveTo(0,0); // Center of the pie
octx.arc(0,0,radius,series.startAngle,series.startAngle+series.angle,false);
octx.closePath();
octx.fill();
}
}
} // end init (plugin body)
// define pie specific options and their default values
var options = {
series: {
pie: {
show: false,
radius: 'auto', // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
innerRadius:0, /* for donut */
startAngle: 3/2,
tilt: 1,
offset: {
top: 0,
left: 'auto'
},
stroke: {
color: '#FFF',
width: 1
},
label: {
show: 'auto',
formatter: function(label, slice){
return '<div style="font-size:x-small;text-align:center;padding:2px;color:'+slice.color+';">'+label+'<br/>'+Math.round(slice.percent)+'%</div>';
}, // formatter function
radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
background: {
color: null,
opacity: 0
},
threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
},
combine: {
threshold: -1, // percentage at which to combine little slices into one larger slice
color: null, // color to give the new slice (auto-generated if null)
label: 'Other' // label to give the new slice
},
highlight: {
//color: '#FFF', // will add this functionality once parseColor is available
opacity: 0.5
}
}
}
};
$.plot.plugins.push({
init: init,
options: options,
name: "pie",
version: "1.0"
});
})(jQuery); | JavaScript |
/*! Javascript plotting library for jQuery, v. 0.7.
*
* Released under the MIT license by IOLA, December 2007.
*
*/
// first an inline dependency, jquery.colorhelpers.js, we inline it here
// for convenience
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={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]}})(jQuery);
// the actual Flot code
(function($) {
function Plot(placeholder, data_, options_, plugins) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
var series = [],
options = {
// the color theme used for graphs
colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#ccc", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: 5, // distance from grid edge to default legend container within plot
backgroundColor: null, // null means auto-detect
backgroundOpacity: 0.85 // set to 0 to avoid background
},
xaxis: {
show: null, // null = auto-detect, true = always, false = never
position: "bottom", // or "top"
mode: null, // null or "time"
color: null, // base color, labels, ticks
tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
transform: null, // null or f: number -> number to transform axis
inverseTransform: null, // if transform is set, this should be the inverse function
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
reserveSpace: null, // whether to reserve space even if axis isn't shown
tickLength: null, // size in pixels of ticks, or "full" for whole line
alignTicksWithAxis: null, // axis number or null for no sync
// mode specific options
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null, // number or [number, "unit"]
monthNames: null, // list of names of months
timeformat: null, // format string to use
twelveHourClock: false // 12 or 24 time in time mode
},
yaxis: {
autoscaleMargin: 0.02,
position: "left" // or "right"
},
xaxes: [],
yaxes: [],
series: {
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff",
symbol: "circle" // or callback
},
lines: {
// we don't put in show: false so we can see
// whether lines were actively disabled
lineWidth: 2, // in pixels
fill: false,
fillColor: null,
steps: false
},
bars: {
show: false,
lineWidth: 2, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: null,
align: "left", // or "center"
horizontal: false
},
shadowSize: 3
},
grid: {
show: true,
aboveData: false,
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
borderColor: null, // set if different from the grid color
tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
labelMargin: 5, // in pixels
axisMargin: 8, // in pixels
borderWidth: 2, // in pixels
minBorderMargin: null, // in pixels, null means taken from points radius
markings: null, // array of ranges or fn: axes -> array of ranges
markingsColor: "#f4f4f4",
markingsLineWidth: 2,
// interactive stuff
clickable: false,
hoverable: false,
autoHighlight: true, // highlight in case mouse is near
mouseActiveRadius: 10 // how far the mouse can be away to activate an item
},
hooks: {}
},
canvas = null, // the canvas for the plot itself
overlay = null, // canvas for interactive stuff on top of plot
eventHolder = null, // jQuery object that events should be bound to
ctx = null, octx = null,
xaxes = [], yaxes = [],
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
canvasWidth = 0, canvasHeight = 0,
plotWidth = 0, plotHeight = 0,
hooks = {
processOptions: [],
processRawData: [],
processDatapoints: [],
drawSeries: [],
draw: [],
bindEvents: [],
drawOverlay: [],
shutdown: []
},
plot = this;
// public functions
plot.setData = setData;
plot.setupGrid = setupGrid;
plot.draw = draw;
plot.getPlaceholder = function() { return placeholder; };
plot.getCanvas = function() { return canvas; };
plot.getPlotOffset = function() { return plotOffset; };
plot.width = function () { return plotWidth; };
plot.height = function () { return plotHeight; };
plot.offset = function () {
var o = eventHolder.offset();
o.left += plotOffset.left;
o.top += plotOffset.top;
return o;
};
plot.getData = function () { return series; };
plot.getAxes = function () {
var res = {}, i;
$.each(xaxes.concat(yaxes), function (_, axis) {
if (axis)
res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
});
return res;
};
plot.getXAxes = function () { return xaxes; };
plot.getYAxes = function () { return yaxes; };
plot.c2p = canvasToAxisCoords;
plot.p2c = axisToCanvasCoords;
plot.getOptions = function () { return options; };
plot.highlight = highlight;
plot.unhighlight = unhighlight;
plot.triggerRedrawOverlay = triggerRedrawOverlay;
plot.pointOffset = function(point) {
return {
left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left),
top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top)
};
};
plot.shutdown = shutdown;
plot.resize = function () {
getCanvasDimensions();
resizeCanvas(canvas);
resizeCanvas(overlay);
};
// public attributes
plot.hooks = hooks;
// initialize
initPlugins(plot);
parseOptions(options_);
setupCanvases();
setData(data_);
setupGrid();
draw();
bindEvents();
function executeHooks(hook, args) {
args = [plot].concat(args);
for (var i = 0; i < hook.length; ++i)
hook[i].apply(this, args);
}
function initPlugins() {
for (var i = 0; i < plugins.length; ++i) {
var p = plugins[i];
p.init(plot);
if (p.options)
$.extend(true, options, p.options);
}
}
function parseOptions(opts) {
var i;
$.extend(true, options, opts);
if (options.xaxis.color == null)
options.xaxis.color = options.grid.color;
if (options.yaxis.color == null)
options.yaxis.color = options.grid.color;
if (options.xaxis.tickColor == null) // backwards-compatibility
options.xaxis.tickColor = options.grid.tickColor;
if (options.yaxis.tickColor == null) // backwards-compatibility
options.yaxis.tickColor = options.grid.tickColor;
if (options.grid.borderColor == null)
options.grid.borderColor = options.grid.color;
if (options.grid.tickColor == null)
options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
// fill in defaults in axes, copy at least always the
// first as the rest of the code assumes it'll be there
for (i = 0; i < Math.max(1, options.xaxes.length); ++i)
options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]);
for (i = 0; i < Math.max(1, options.yaxes.length); ++i)
options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]);
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
if (options.x2axis) {
options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
options.xaxes[1].position = "top";
}
if (options.y2axis) {
options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
options.yaxes[1].position = "right";
}
if (options.grid.coloredAreas)
options.grid.markings = options.grid.coloredAreas;
if (options.grid.coloredAreasColor)
options.grid.markingsColor = options.grid.coloredAreasColor;
if (options.lines)
$.extend(true, options.series.lines, options.lines);
if (options.points)
$.extend(true, options.series.points, options.points);
if (options.bars)
$.extend(true, options.series.bars, options.bars);
if (options.shadowSize != null)
options.series.shadowSize = options.shadowSize;
// save options on axes for future reference
for (i = 0; i < options.xaxes.length; ++i)
getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
for (i = 0; i < options.yaxes.length; ++i)
getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
// add hooks from options
for (var n in hooks)
if (options.hooks[n] && options.hooks[n].length)
hooks[n] = hooks[n].concat(options.hooks[n]);
executeHooks(hooks.processOptions, [options]);
}
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s = $.extend(true, {}, options.series);
if (d[i].data != null) {
s.data = d[i].data; // move the data instead of deep-copy
delete d[i].data;
$.extend(true, s, d[i]);
d[i].data = s.data;
}
else
s.data = d[i];
res.push(s);
}
return res;
}
function axisNumber(obj, coord) {
var a = obj[coord + "axis"];
if (typeof a == "object") // if we got a real axis, extract number
a = a.n;
if (typeof a != "number")
a = 1; // default to first axis
return a;
}
function allAxes() {
// return flat array without annoying null entries
return $.grep(xaxes.concat(yaxes), function (a) { return a; });
}
function canvasToAxisCoords(pos) {
// return an object with x/y corresponding to all used axes
var res = {}, i, axis;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used)
res["x" + axis.n] = axis.c2p(pos.left);
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used)
res["y" + axis.n] = axis.c2p(pos.top);
}
if (res.x1 !== undefined)
res.x = res.x1;
if (res.y1 !== undefined)
res.y = res.y1;
return res;
}
function axisToCanvasCoords(pos) {
// get canvas coords from the first pair of x/y found in pos
var res = {}, i, axis, key;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used) {
key = "x" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "x";
if (pos[key] != null) {
res.left = axis.p2c(pos[key]);
break;
}
}
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used) {
key = "y" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "y";
if (pos[key] != null) {
res.top = axis.p2c(pos[key]);
break;
}
}
}
return res;
}
function getOrCreateAxis(axes, number) {
if (!axes[number - 1])
axes[number - 1] = {
n: number, // save the number for future reference
direction: axes == xaxes ? "x" : "y",
options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
};
return axes[number - 1];
}
function fillInSeriesOptions() {
var i;
// collect what we already got of colors
var neededColors = series.length,
usedColors = [],
assignedColors = [];
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
--neededColors;
if (typeof sc == "number")
assignedColors.push(sc);
else
usedColors.push($.color.parse(series[i].color));
}
}
// we might need to generate more colors if higher indices
// are assigned
for (i = 0; i < assignedColors.length; ++i) {
neededColors = Math.max(neededColors, assignedColors[i] + 1);
}
// produce colors as needed
var colors = [], variation = 0;
i = 0;
while (colors.length < neededColors) {
var c;
if (options.colors.length == i) // check degenerate case
c = $.color.make(100, 100, 100);
else
c = $.color.parse(options.colors[i]);
// vary color if needed
var sign = variation % 2 == 1 ? -1 : 1;
c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2)
// FIXME: if we're getting to close to something else,
// we should probably skip this one
colors.push(c);
++i;
if (i >= options.colors.length) {
i = 0;
++variation;
}
}
// fill in the options
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// turn on lines automatically in case nothing is set
if (s.lines.show == null) {
var v, show = true;
for (v in s)
if (s[v] && s[v].show) {
show = false;
break;
}
if (show)
s.lines.show = true;
}
// setup axes
s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
}
}
function processData() {
var topSentry = Number.POSITIVE_INFINITY,
bottomSentry = Number.NEGATIVE_INFINITY,
fakeInfinity = Number.MAX_VALUE,
i, j, k, m, length,
s, points, ps, x, y, axis, val, f, p;
function updateAxis(axis, min, max) {
if (min < axis.datamin && min != -fakeInfinity)
axis.datamin = min;
if (max > axis.datamax && max != fakeInfinity)
axis.datamax = max;
}
$.each(allAxes(), function (_, axis) {
// init axis
axis.datamin = topSentry;
axis.datamax = bottomSentry;
axis.used = false;
});
for (i = 0; i < series.length; ++i) {
s = series[i];
s.datapoints = { points: [] };
executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
}
// first pass: clean and copy data
for (i = 0; i < series.length; ++i) {
s = series[i];
var data = s.data, format = s.datapoints.format;
if (!format) {
format = [];
// find out how to copy
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
format.push({ y: true, number: true, required: false, defaultValue: 0 });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
s.datapoints.format = format;
}
if (s.datapoints.pointsize != null)
continue; // already filled in
s.datapoints.pointsize = format.length;
ps = s.datapoints.pointsize;
points = s.datapoints.points;
insertSteps = s.lines.show && s.lines.steps;
s.xaxis.used = s.yaxis.used = true;
for (j = k = 0; j < data.length; ++j, k += ps) {
p = data[j];
var nullify = p == null;
if (!nullify) {
for (m = 0; m < ps; ++m) {
val = p[m];
f = format[m];
if (f) {
if (f.number && val != null) {
val = +val; // convert to number
if (isNaN(val))
val = null;
else if (val == Infinity)
val = fakeInfinity;
else if (val == -Infinity)
val = -fakeInfinity;
}
if (val == null) {
if (f.required)
nullify = true;
if (f.defaultValue != null)
val = f.defaultValue;
}
}
points[k + m] = val;
}
}
if (nullify) {
for (m = 0; m < ps; ++m) {
val = points[k + m];
if (val != null) {
f = format[m];
// extract min/max info
if (f.x)
updateAxis(s.xaxis, val, val);
if (f.y)
updateAxis(s.yaxis, val, val);
}
points[k + m] = null;
}
}
else {
// a little bit of line specific stuff that
// perhaps shouldn't be here, but lacking
// better means...
if (insertSteps && k > 0
&& points[k - ps] != null
&& points[k - ps] != points[k]
&& points[k - ps + 1] != points[k + 1]) {
// copy the point to make room for a middle point
for (m = 0; m < ps; ++m)
points[k + ps + m] = points[k + m];
// middle point has same y
points[k + 1] = points[k - ps + 1];
// we've added a point, better reflect that
k += ps;
}
}
}
}
// give the hooks a chance to run
for (i = 0; i < series.length; ++i) {
s = series[i];
executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
}
// second pass: find datamax/datamin for auto-scaling
for (i = 0; i < series.length; ++i) {
s = series[i];
points = s.datapoints.points,
ps = s.datapoints.pointsize;
var xmin = topSentry, ymin = topSentry,
xmax = bottomSentry, ymax = bottomSentry;
for (j = 0; j < points.length; j += ps) {
if (points[j] == null)
continue;
for (m = 0; m < ps; ++m) {
val = points[j + m];
f = format[m];
if (!f || val == fakeInfinity || val == -fakeInfinity)
continue;
if (f.x) {
if (val < xmin)
xmin = val;
if (val > xmax)
xmax = val;
}
if (f.y) {
if (val < ymin)
ymin = val;
if (val > ymax)
ymax = val;
}
}
}
if (s.bars.show) {
// make sure we got room for the bar on the dancing floor
var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2;
if (s.bars.horizontal) {
ymin += delta;
ymax += delta + s.bars.barWidth;
}
else {
xmin += delta;
xmax += delta + s.bars.barWidth;
}
}
updateAxis(s.xaxis, xmin, xmax);
updateAxis(s.yaxis, ymin, ymax);
}
$.each(allAxes(), function (_, axis) {
if (axis.datamin == topSentry)
axis.datamin = null;
if (axis.datamax == bottomSentry)
axis.datamax = null;
});
}
function makeCanvas(skipPositioning, cls) {
var c = document.createElement('canvas');
c.className = cls;
c.width = canvasWidth;
c.height = canvasHeight;
if (!skipPositioning)
$(c).css({ position: 'absolute', left: 0, top: 0 });
$(c).appendTo(placeholder);
if (!c.getContext) // excanvas hack
c = window.G_vmlCanvasManager.initElement(c);
// used for resetting in case we get replotted
c.getContext("2d").save();
return c;
}
function getCanvasDimensions() {
canvasWidth = placeholder.width();
canvasHeight = placeholder.height();
if (canvasWidth <= 0 || canvasHeight <= 0)
throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
}
function resizeCanvas(c) {
// resizing should reset the state (excanvas seems to be
// buggy though)
if (c.width != canvasWidth)
c.width = canvasWidth;
if (c.height != canvasHeight)
c.height = canvasHeight;
// so try to get back to the initial state (even if it's
// gone now, this should be safe according to the spec)
var cctx = c.getContext("2d");
cctx.restore();
// and save again
cctx.save();
}
function setupCanvases() {
var reused,
existingCanvas = placeholder.children("canvas.base"),
existingOverlay = placeholder.children("canvas.overlay");
if (existingCanvas.length == 0 || existingOverlay == 0) {
// init everything
placeholder.html(""); // make sure placeholder is clear
placeholder.css({ padding: 0 }); // padding messes up the positioning
if (placeholder.css("position") == 'static')
placeholder.css("position", "relative"); // for positioning labels and overlay
getCanvasDimensions();
canvas = makeCanvas(true, "base");
overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features
reused = false;
}
else {
// reuse existing elements
canvas = existingCanvas.get(0);
overlay = existingOverlay.get(0);
reused = true;
}
ctx = canvas.getContext("2d");
octx = overlay.getContext("2d");
// we include the canvas in the event holder too, because IE 7
// sometimes has trouble with the stacking order
eventHolder = $([overlay, canvas]);
if (reused) {
// run shutdown in the old plot object
placeholder.data("plot").shutdown();
// reset reused canvases
plot.resize();
// make sure overlay pixels are cleared (canvas is cleared when we redraw)
octx.clearRect(0, 0, canvasWidth, canvasHeight);
// then whack any remaining obvious garbage left
eventHolder.unbind();
placeholder.children().not([canvas, overlay]).remove();
}
// save in case we get replotted
placeholder.data("plot", plot);
}
function bindEvents() {
// bind events
if (options.grid.hoverable) {
eventHolder.mousemove(onMouseMove);
eventHolder.mouseleave(onMouseLeave);
}
if (options.grid.clickable)
eventHolder.click(onClick);
executeHooks(hooks.bindEvents, [eventHolder]);
}
function shutdown() {
if (redrawTimeout)
clearTimeout(redrawTimeout);
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mouseleave", onMouseLeave);
eventHolder.unbind("click", onClick);
executeHooks(hooks.shutdown, [eventHolder]);
}
function setTransformationHelpers(axis) {
// set helper functions on the axis, assumes plot area
// has been computed already
function identity(x) { return x; }
var s, m, t = axis.options.transform || identity,
it = axis.options.inverseTransform;
// precompute how much the axis is scaling a point
// in canvas space
if (axis.direction == "x") {
s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
m = Math.min(t(axis.max), t(axis.min));
}
else {
s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
s = -s;
m = Math.max(t(axis.max), t(axis.min));
}
// data point to canvas coordinate
if (t == identity) // slight optimization
axis.p2c = function (p) { return (p - m) * s; };
else
axis.p2c = function (p) { return (t(p) - m) * s; };
// canvas coordinate to data point
if (!it)
axis.c2p = function (c) { return m + c / s; };
else
axis.c2p = function (c) { return it(m + c / s); };
}
function measureTickLabels(axis) {
var opts = axis.options, i, ticks = axis.ticks || [], labels = [],
l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv;
function makeDummyDiv(labels, width) {
return $('<div style="position:absolute;top:-10000px;' + width + 'font-size:smaller">' +
'<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis">'
+ labels.join("") + '</div></div>')
.appendTo(placeholder);
}
if (axis.direction == "x") {
// to avoid measuring the widths of the labels (it's slow), we
// construct fixed-size boxes and put the labels inside
// them, we don't need the exact figures and the
// fixed-size box content is easy to center
if (w == null)
w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1));
// measure x label heights
if (h == null) {
labels = [];
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel" style="float:left;width:' + w + 'px">' + l + '</div>');
}
if (labels.length > 0) {
// stick them all in the same div and measure
// collective height
labels.push('<div style="clear:left"></div>');
dummyDiv = makeDummyDiv(labels, "width:10000px;");
h = dummyDiv.height();
dummyDiv.remove();
}
}
}
else if (w == null || h == null) {
// calculate y label dimensions
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel">' + l + '</div>');
}
if (labels.length > 0) {
dummyDiv = makeDummyDiv(labels, "");
if (w == null)
w = dummyDiv.children().width();
if (h == null)
h = dummyDiv.find("div.tickLabel").height();
dummyDiv.remove();
}
}
if (w == null)
w = 0;
if (h == null)
h = 0;
axis.labelWidth = w;
axis.labelHeight = h;
}
function allocateAxisBoxFirstPhase(axis) {
// find the bounding box of the axis by looking at label
// widths/heights and ticks, make room by diminishing the
// plotOffset
var lw = axis.labelWidth,
lh = axis.labelHeight,
pos = axis.options.position,
tickLength = axis.options.tickLength,
axismargin = options.grid.axisMargin,
padding = options.grid.labelMargin,
all = axis.direction == "x" ? xaxes : yaxes,
index;
// determine axis margin
var samePosition = $.grep(all, function (a) {
return a && a.options.position == pos && a.reserveSpace;
});
if ($.inArray(axis, samePosition) == samePosition.length - 1)
axismargin = 0; // outermost
// determine tick length - if we're innermost, we can use "full"
if (tickLength == null)
tickLength = "full";
var sameDirection = $.grep(all, function (a) {
return a && a.reserveSpace;
});
var innermost = $.inArray(axis, sameDirection) == 0;
if (!innermost && tickLength == "full")
tickLength = 5;
if (!isNaN(+tickLength))
padding += +tickLength;
// compute box
if (axis.direction == "x") {
lh += padding;
if (pos == "bottom") {
plotOffset.bottom += lh + axismargin;
axis.box = { top: canvasHeight - plotOffset.bottom, height: lh };
}
else {
axis.box = { top: plotOffset.top + axismargin, height: lh };
plotOffset.top += lh + axismargin;
}
}
else {
lw += padding;
if (pos == "left") {
axis.box = { left: plotOffset.left + axismargin, width: lw };
plotOffset.left += lw + axismargin;
}
else {
plotOffset.right += lw + axismargin;
axis.box = { left: canvasWidth - plotOffset.right, width: lw };
}
}
// save for future reference
axis.position = pos;
axis.tickLength = tickLength;
axis.box.padding = padding;
axis.innermost = innermost;
}
function allocateAxisBoxSecondPhase(axis) {
// set remaining bounding box coordinates
if (axis.direction == "x") {
axis.box.left = plotOffset.left;
axis.box.width = plotWidth;
}
else {
axis.box.top = plotOffset.top;
axis.box.height = plotHeight;
}
}
function setupGrid() {
var i, axes = allAxes();
// first calculate the plot and axis box dimensions
$.each(axes, function (_, axis) {
axis.show = axis.options.show;
if (axis.show == null)
axis.show = axis.used; // by default an axis is visible if it's got data
axis.reserveSpace = axis.show || axis.options.reserveSpace;
setRange(axis);
});
allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0;
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
// make the ticks
setupTickGeneration(axis);
setTicks(axis);
snapRangeToTicks(axis, axis.ticks);
// find labelWidth/Height for axis
measureTickLabels(axis);
});
// with all dimensions in house, we can compute the
// axis boxes, start from the outside (reverse order)
for (i = allocatedAxes.length - 1; i >= 0; --i)
allocateAxisBoxFirstPhase(allocatedAxes[i]);
// make sure we've got enough space for things that
// might stick out
var minMargin = options.grid.minBorderMargin;
if (minMargin == null) {
minMargin = 0;
for (i = 0; i < series.length; ++i)
minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2);
}
for (var a in plotOffset) {
plotOffset[a] += options.grid.borderWidth;
plotOffset[a] = Math.max(minMargin, plotOffset[a]);
}
}
plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
// now we got the proper plotWidth/Height, we can compute the scaling
$.each(axes, function (_, axis) {
setTransformationHelpers(axis);
});
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
allocateAxisBoxSecondPhase(axis);
});
insertAxisLabels();
}
insertLegend();
}
function setRange(axis) {
var opts = axis.options,
min = +(opts.min != null ? opts.min : axis.datamin),
max = +(opts.max != null ? opts.max : axis.datamax),
delta = max - min;
if (delta == 0.0) {
// degenerate case
var widen = max == 0 ? 1 : 0.01;
if (opts.min == null)
min -= widen;
// always widen max if we couldn't widen min to ensure we
// don't fall into min == max which doesn't work
if (opts.max == null || opts.min != null)
max += widen;
}
else {
// consider autoscaling
var margin = opts.autoscaleMargin;
if (margin != null) {
if (opts.min == null) {
min -= delta * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin != null && axis.datamin >= 0)
min = 0;
}
if (opts.max == null) {
max += delta * margin;
if (max > 0 && axis.datamax != null && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function setupTickGeneration(axis) {
var opts = axis.options;
// estimate number of ticks
var noTicks;
if (typeof opts.ticks == "number" && opts.ticks > 0)
noTicks = opts.ticks;
else
// heuristic based on the model a*sqrt(x) fitted to
// some data points that seemed reasonable
noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight);
var delta = (axis.max - axis.min) / noTicks,
size, generator, unit, formatter, i, magn, norm;
if (opts.mode == "time") {
// pretty handling of time
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var spec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"], [3, "month"], [6, "month"],
[1, "year"]
];
var minSize = 0;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number")
minSize = opts.tickSize;
else
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
for (var i = 0; i < spec.length - 1; ++i)
if (delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize)
break;
size = spec[i][0];
unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10));
norm = (delta / timeUnitSize.year) / magn;
if (norm < 1.5)
size = 1;
else if (norm < 3)
size = 2;
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
}
axis.tickSize = opts.tickSize || [size, unit];
generator = function(axis) {
var ticks = [],
tickSize = axis.tickSize[0], unit = axis.tickSize[1],
d = new Date(axis.min);
var step = tickSize * timeUnitSize[unit];
if (unit == "second")
d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
if (unit == "minute")
d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
if (unit == "hour")
d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
if (unit == "month")
d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
if (unit == "year")
d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
// reset smaller components
d.setUTCMilliseconds(0);
if (step >= timeUnitSize.minute)
d.setUTCSeconds(0);
if (step >= timeUnitSize.hour)
d.setUTCMinutes(0);
if (step >= timeUnitSize.day)
d.setUTCHours(0);
if (step >= timeUnitSize.day * 4)
d.setUTCDate(1);
if (step >= timeUnitSize.year)
d.setUTCMonth(0);
var carry = 0, v = Number.NaN, prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month") {
if (tickSize < 1) {
// a bit complicated - we'll divide the month
// up but we need to take care of fractions
// so we don't end up in the middle of a day
d.setUTCDate(1);
var start = d.getTime();
d.setUTCMonth(d.getUTCMonth() + 1);
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getUTCHours();
d.setUTCHours(0);
}
else
d.setUTCMonth(d.getUTCMonth() + tickSize);
}
else if (unit == "year") {
d.setUTCFullYear(d.getUTCFullYear() + tickSize);
}
else
d.setTime(v + step);
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
var d = new Date(v);
// first check global format
if (opts.timeformat != null)
return $.plot.formatDate(d, opts.timeformat, opts.monthNames);
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
if (t < timeUnitSize.minute)
fmt = "%h:%M:%S" + suffix;
else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day)
fmt = "%h:%M" + suffix;
else
fmt = "%b %d %h:%M" + suffix;
}
else if (t < timeUnitSize.month)
fmt = "%b %d";
else if (t < timeUnitSize.year) {
if (span < timeUnitSize.year)
fmt = "%b";
else
fmt = "%b %y";
}
else
fmt = "%y";
return $.plot.formatDate(d, fmt, opts.monthNames);
};
}
else {
// pretty rounding of base-10 numbers
var maxDec = opts.tickDecimals;
var dec = -Math.floor(Math.log(delta) / Math.LN10);
if (maxDec != null && dec > maxDec)
dec = maxDec;
magn = Math.pow(10, -dec);
norm = delta / magn; // norm is between 1.0 and 10.0
if (norm < 1.5)
size = 1;
else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
}
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
if (opts.minTickSize != null && size < opts.minTickSize)
size = opts.minTickSize;
axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
axis.tickSize = opts.tickSize || size;
generator = function (axis) {
var ticks = [];
// spew out all possible ticks
var start = floorInBase(axis.min, axis.tickSize),
i = 0, v = Number.NaN, prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
return v.toFixed(axis.tickDecimals);
};
}
if (opts.alignTicksWithAxis != null) {
var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
if (otherAxis && otherAxis.used && otherAxis != axis) {
// consider snapping min/max to outermost nice ticks
var niceTicks = generator(axis);
if (niceTicks.length > 0) {
if (opts.min == null)
axis.min = Math.min(axis.min, niceTicks[0]);
if (opts.max == null && niceTicks.length > 1)
axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
}
generator = function (axis) {
// copy ticks, scaled to this axis
var ticks = [], v, i;
for (i = 0; i < otherAxis.ticks.length; ++i) {
v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
v = axis.min + v * (axis.max - axis.min);
ticks.push(v);
}
return ticks;
};
// we might need an extra decimal since forced
// ticks don't necessarily fit naturally
if (axis.mode != "time" && opts.tickDecimals == null) {
var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1),
ts = generator(axis);
// only proceed if the tick interval rounded
// with an extra decimal doesn't give us a
// zero at end
if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
axis.tickDecimals = extraDec;
}
}
}
axis.tickGenerator = generator;
if ($.isFunction(opts.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
else
axis.tickFormatter = formatter;
}
function setTicks(axis) {
var oticks = axis.options.ticks, ticks = [];
if (oticks == null || (typeof oticks == "number" && oticks > 0))
ticks = axis.tickGenerator(axis);
else if (oticks) {
if ($.isFunction(oticks))
// generate the ticks
ticks = oticks({ min: axis.min, max: axis.max });
else
ticks = oticks;
}
// clean up/labelify the supplied ticks, copy them over
var i, v;
axis.ticks = [];
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = +t[0];
if (t.length > 1)
label = t[1];
}
else
v = +t;
if (label == null)
label = axis.tickFormatter(v, axis);
if (!isNaN(v))
axis.ticks.push({ v: v, label: label });
}
}
function snapRangeToTicks(axis, ticks) {
if (axis.options.autoscaleMargin && ticks.length > 0) {
// snap to ticks
if (axis.options.min == null)
axis.min = Math.min(axis.min, ticks[0].v);
if (axis.options.max == null && ticks.length > 1)
axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
}
}
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
var grid = options.grid;
// draw background, if any
if (grid.show && grid.backgroundColor)
drawBackground();
if (grid.show && !grid.aboveData)
drawGrid();
for (var i = 0; i < series.length; ++i) {
executeHooks(hooks.drawSeries, [ctx, series[i]]);
drawSeries(series[i]);
}
executeHooks(hooks.draw, [ctx]);
if (grid.show && grid.aboveData)
drawGrid();
}
function extractRange(ranges, coord) {
var axis, from, to, key, axes = allAxes();
for (i = 0; i < axes.length; ++i) {
axis = axes[i];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? xaxes[0] : yaxes[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function drawBackground() {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
ctx.fillRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
function drawGrid() {
var i;
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// draw markings
var markings = options.grid.markings;
if (markings) {
if ($.isFunction(markings)) {
var axes = plot.getAxes();
// xmin etc. is backwards compatibility, to be
// removed in the future
axes.xmin = axes.xaxis.min;
axes.xmax = axes.xaxis.max;
axes.ymin = axes.yaxis.min;
axes.ymax = axes.yaxis.max;
markings = markings(axes);
}
for (i = 0; i < markings.length; ++i) {
var m = markings[i],
xrange = extractRange(m, "x"),
yrange = extractRange(m, "y");
// fill in missing
if (xrange.from == null)
xrange.from = xrange.axis.min;
if (xrange.to == null)
xrange.to = xrange.axis.max;
if (yrange.from == null)
yrange.from = yrange.axis.min;
if (yrange.to == null)
yrange.to = yrange.axis.max;
// clip
if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
continue;
xrange.from = Math.max(xrange.from, xrange.axis.min);
xrange.to = Math.min(xrange.to, xrange.axis.max);
yrange.from = Math.max(yrange.from, yrange.axis.min);
yrange.to = Math.min(yrange.to, yrange.axis.max);
if (xrange.from == xrange.to && yrange.from == yrange.to)
continue;
// then draw
xrange.from = xrange.axis.p2c(xrange.from);
xrange.to = xrange.axis.p2c(xrange.to);
yrange.from = yrange.axis.p2c(yrange.from);
yrange.to = yrange.axis.p2c(yrange.to);
if (xrange.from == xrange.to || yrange.from == yrange.to) {
// draw line
ctx.beginPath();
ctx.strokeStyle = m.color || options.grid.markingsColor;
ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
ctx.moveTo(xrange.from, yrange.from);
ctx.lineTo(xrange.to, yrange.to);
ctx.stroke();
}
else {
// fill area
ctx.fillStyle = m.color || options.grid.markingsColor;
ctx.fillRect(xrange.from, yrange.to,
xrange.to - xrange.from,
yrange.from - yrange.to);
}
}
}
// draw the ticks
var axes = allAxes(), bw = options.grid.borderWidth;
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box,
t = axis.tickLength, x, y, xoff, yoff;
if (!axis.show || axis.ticks.length == 0)
continue
ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString();
ctx.lineWidth = 1;
// find the edges
if (axis.direction == "x") {
x = 0;
if (t == "full")
y = (axis.position == "top" ? 0 : plotHeight);
else
y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
}
else {
y = 0;
if (t == "full")
x = (axis.position == "left" ? 0 : plotWidth);
else
x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
}
// draw tick bar
if (!axis.innermost) {
ctx.beginPath();
xoff = yoff = 0;
if (axis.direction == "x")
xoff = plotWidth;
else
yoff = plotHeight;
if (ctx.lineWidth == 1) {
x = Math.floor(x) + 0.5;
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
ctx.stroke();
}
// draw ticks
ctx.beginPath();
for (i = 0; i < axis.ticks.length; ++i) {
var v = axis.ticks[i].v;
xoff = yoff = 0;
if (v < axis.min || v > axis.max
// skip those lying on the axes if we got a border
|| (t == "full" && bw > 0
&& (v == axis.min || v == axis.max)))
continue;
if (axis.direction == "x") {
x = axis.p2c(v);
yoff = t == "full" ? -plotHeight : t;
if (axis.position == "top")
yoff = -yoff;
}
else {
y = axis.p2c(v);
xoff = t == "full" ? -plotWidth : t;
if (axis.position == "left")
xoff = -xoff;
}
if (ctx.lineWidth == 1) {
if (axis.direction == "x")
x = Math.floor(x) + 0.5;
else
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
}
ctx.stroke();
}
// draw border
if (bw) {
ctx.lineWidth = bw;
ctx.strokeStyle = options.grid.borderColor;
ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
}
ctx.restore();
}
function insertAxisLabels() {
placeholder.find(".tickLabels").remove();
var html = ['<div class="tickLabels" style="font-size:smaller">'];
var axes = allAxes();
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box;
if (!axis.show)
continue;
//debug: html.push('<div style="position:absolute;opacity:0.10;background-color:red;left:' + box.left + 'px;top:' + box.top + 'px;width:' + box.width + 'px;height:' + box.height + 'px"></div>')
html.push('<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis" style="color:' + axis.options.color + '">');
for (var i = 0; i < axis.ticks.length; ++i) {
var tick = axis.ticks[i];
if (!tick.label || tick.v < axis.min || tick.v > axis.max)
continue;
var pos = {}, align;
if (axis.direction == "x") {
align = "center";
pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2);
if (axis.position == "bottom")
pos.top = box.top + box.padding;
else
pos.bottom = canvasHeight - (box.top + box.height - box.padding);
}
else {
pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2);
if (axis.position == "left") {
pos.right = canvasWidth - (box.left + box.width - box.padding)
align = "right";
}
else {
pos.left = box.left + box.padding;
align = "left";
}
}
pos.width = axis.labelWidth;
var style = ["position:absolute", "text-align:" + align ];
for (var a in pos)
style.push(a + ":" + pos[a] + "px")
html.push('<div class="tickLabel" style="' + style.join(';') + '">' + tick.label + '</div>');
}
html.push('</div>');
}
html.push('</div>');
placeholder.append(html.join(""));
}
function drawSeries(series) {
if (series.lines.show)
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
prevx = null, prevy = null;
ctx.beginPath();
for (var i = ps; i < points.length; i += ps) {
var x1 = points[i - ps], y1 = points[i - ps + 1],
x2 = points[i], y2 = points[i + 1];
if (x1 == null || x2 == null)
continue;
// clip with ymin
if (y1 <= y2 && y1 < axisy.min) {
if (y2 < axisy.min)
continue; // line segment is outside
// compute new intersection point
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min) {
if (y1 < axisy.min)
continue;
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max) {
if (y2 > axisy.max)
continue;
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max) {
if (y1 > axisy.max)
continue;
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (x1 != prevx || y1 != prevy)
ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
prevx = x2;
prevy = y2;
ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
}
ctx.stroke();
}
function plotLineArea(datapoints, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
bottom = Math.min(Math.max(0, axisy.min), axisy.max),
i = 0, top, areaOpen = false,
ypos = 1, segmentStart = 0, segmentEnd = 0;
// we process each segment in two turns, first forward
// direction to sketch out top, then once we hit the
// end we go backwards to sketch the bottom
while (true) {
if (ps > 0 && i > points.length + ps)
break;
i += ps; // ps is negative if going backwards
var x1 = points[i - ps],
y1 = points[i - ps + ypos],
x2 = points[i], y2 = points[i + ypos];
if (areaOpen) {
if (ps > 0 && x1 != null && x2 == null) {
// at turning point
segmentEnd = i;
ps = -ps;
ypos = 2;
continue;
}
if (ps < 0 && i == segmentStart + ps) {
// done with the reverse sweep
ctx.fill();
areaOpen = false;
ps = -ps;
ypos = 1;
i = segmentStart = segmentEnd + ps;
continue;
}
}
if (x1 == null || x2 == null)
continue;
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= axisy.max && y2 >= axisy.max) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
continue;
}
else if (y1 <= axisy.min && y2 <= axisy.min) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
continue;
}
// else it's a bit more complicated, there might
// be a flat maxed out rectangle first, then a
// triangular cutout or reverse; to find these
// keep track of the current x values
var x1old = x1, x2old = x2;
// clip the y values, without shortcutting, we
// go through all cases in turn
// clip with ymin
if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
// it goes to (x1, y1), but we fill that below
}
// fill triangular section, this sometimes result
// in redundant points if (x1, y1) hasn't changed
// from previous line to, but we just ignore that
ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth,
sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (lw > 0 && sw > 0) {
// draw shadow as a thick and thin line with transparency
ctx.lineWidth = sw;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
// position shadow at angle from the mid of line
var angle = Math.PI/18;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
ctx.lineWidth = sw/2;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
if (fillStyle) {
ctx.fillStyle = fillStyle;
plotLineArea(series.datapoints, series.xaxis, series.yaxis);
}
if (lw > 0)
plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var x = points[i], y = points[i + 1];
if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
continue;
ctx.beginPath();
x = axisx.p2c(x);
y = axisy.p2c(y) + offset;
if (symbol == "circle")
ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
else
symbol(ctx, x, y, radius, shadow);
ctx.closePath();
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.points.lineWidth,
sw = series.shadowSize,
radius = series.points.radius,
symbol = series.points.symbol;
if (lw > 0 && sw > 0) {
// draw shadow in two steps
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPoints(series.datapoints, radius, null, w + w/2, true,
series.xaxis, series.yaxis, symbol);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPoints(series.datapoints, radius, null, w/2, true,
series.xaxis, series.yaxis, symbol);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
plotPoints(series.datapoints, radius,
getFillStyle(series.points, series.color), 0, false,
series.xaxis, series.yaxis, symbol);
ctx.restore();
}
function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
var left, right, bottom, top,
drawLeft, drawRight, drawTop, drawBottom,
tmp;
// in horizontal mode, we start the bar from the left
// instead of from the bottom so it appears to be
// horizontal rather than vertical
if (horizontal) {
drawBottom = drawRight = drawTop = true;
drawLeft = false;
left = b;
right = x;
top = y + barLeft;
bottom = y + barRight;
// account for negative bars
if (right < left) {
tmp = right;
right = left;
left = tmp;
drawLeft = true;
drawRight = false;
}
}
else {
drawLeft = drawRight = drawTop = true;
drawBottom = false;
left = x + barLeft;
right = x + barRight;
bottom = b;
top = y;
// account for negative bars
if (top < bottom) {
tmp = top;
top = bottom;
bottom = tmp;
drawBottom = true;
drawTop = false;
}
}
// clip
if (right < axisx.min || left > axisx.max ||
top < axisy.min || bottom > axisy.max)
return;
if (left < axisx.min) {
left = axisx.min;
drawLeft = false;
}
if (right > axisx.max) {
right = axisx.max;
drawRight = false;
}
if (bottom < axisy.min) {
bottom = axisy.min;
drawBottom = false;
}
if (top > axisy.max) {
top = axisy.max;
drawTop = false;
}
left = axisx.p2c(left);
bottom = axisy.p2c(bottom);
right = axisx.p2c(right);
top = axisy.p2c(top);
// fill the bar
if (fillStyleCallback) {
c.beginPath();
c.moveTo(left, bottom);
c.lineTo(left, top);
c.lineTo(right, top);
c.lineTo(right, bottom);
c.fillStyle = fillStyleCallback(bottom, top);
c.fill();
}
// draw outline
if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
c.beginPath();
// FIXME: inline moveTo is buggy with excanvas
c.moveTo(left, bottom + offset);
if (drawLeft)
c.lineTo(left, top + offset);
else
c.moveTo(left, top + offset);
if (drawTop)
c.lineTo(right, top + offset);
else
c.moveTo(right, top + offset);
if (drawRight)
c.lineTo(right, bottom + offset);
else
c.moveTo(right, bottom + offset);
if (drawBottom)
c.lineTo(left, bottom + offset);
else
c.moveTo(left, bottom + offset);
c.stroke();
}
}
function drawSeriesBars(series) {
function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// FIXME: figure out a way to add shadows (for instance along the right edge)
ctx.lineWidth = series.bars.lineWidth;
ctx.strokeStyle = series.color;
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis);
ctx.restore();
}
function getFillStyle(filloptions, seriesColor, bottom, top) {
var fill = filloptions.fill;
if (!fill)
return null;
if (filloptions.fillColor)
return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
var c = $.color.parse(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
return c.toString();
}
function insertLegend() {
placeholder.find(".legend").remove();
if (!options.legend.show)
return;
var fragments = [], rowStarted = false,
lf = options.legend.labelFormatter, s, label;
for (var i = 0; i < series.length; ++i) {
s = series[i];
label = s.label;
if (!label)
continue;
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
if (lf)
label = lf(label, s);
fragments.push(
'<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + s.color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel">' + label + '</td>');
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length == 0)
return;
var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
$(options.legend.container).html(table);
else {
var pos = "",
p = options.legend.position,
m = options.legend.margin;
if (m[0] == null)
m = [m, m];
if (p.charAt(0) == "n")
pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
c = options.grid.backgroundColor;
if (c && typeof c == "string")
c = $.color.parse(c);
else
c = $.color.extract(legend, 'background-color');
c.a = 1;
c = c.toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
// interactive features
var highlights = [],
redrawTimeout = null;
// returns the data item the mouse is over, or null if none is found
function findNearbyItem(mouseX, mouseY, seriesFilter) {
var maxDistance = options.grid.mouseActiveRadius,
smallestDistance = maxDistance * maxDistance + 1,
item = null, foundPoint = false, i, j;
for (i = series.length - 1; i >= 0; --i) {
if (!seriesFilter(series[i]))
continue;
var s = series[i],
axisx = s.xaxis,
axisy = s.yaxis,
points = s.datapoints.points,
ps = s.datapoints.pointsize,
mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
my = axisy.c2p(mouseY),
maxx = maxDistance / axisx.scale,
maxy = maxDistance / axisy.scale;
// with inverse transforms, we can't use the maxx/maxy
// optimization, sadly
if (axisx.options.inverseTransform)
maxx = Number.MAX_VALUE;
if (axisy.options.inverseTransform)
maxy = Number.MAX_VALUE;
if (s.lines.show || s.points.show) {
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1];
if (x == null)
continue;
// For points and lines, the cursor must be within a
// certain distance to the data point
if (x - mx > maxx || x - mx < -maxx ||
y - my > maxy || y - my < -maxy)
continue;
// We have to calculate distances in pixels, not in
// data units, because the scales of the axes may be different
var dx = Math.abs(axisx.p2c(x) - mouseX),
dy = Math.abs(axisy.p2c(y) - mouseY),
dist = dx * dx + dy * dy; // we save the sqrt
// use <= to ensure last point takes precedence
// (last generally means on top of)
if (dist < smallestDistance) {
smallestDistance = dist;
item = [i, j / ps];
}
}
}
if (s.bars.show && !item) { // no other point can be nearby
var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2,
barRight = barLeft + s.bars.barWidth;
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1], b = points[j + 2];
if (x == null)
continue;
// for a bar graph, the cursor must be inside the bar
if (series[i].bars.horizontal ?
(mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
my >= y + barLeft && my <= y + barRight) :
(mx >= x + barLeft && mx <= x + barRight &&
my >= Math.min(b, y) && my <= Math.max(b, y)))
item = [i, j / ps];
}
}
}
if (item) {
i = item[0];
j = item[1];
ps = series[i].datapoints.pointsize;
return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
dataIndex: j,
series: series[i],
seriesIndex: i };
}
return null;
}
function onMouseMove(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return s["hoverable"] != false; });
}
function onMouseLeave(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return false; });
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters
// so we share their code)
function triggerClickHoverEvent(eventname, event, seriesFilter) {
var offset = eventHolder.offset(),
canvasX = event.pageX - offset.left - plotOffset.left,
canvasY = event.pageY - offset.top - plotOffset.top,
pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
pos.pageX = event.pageX;
pos.pageY = event.pageY;
var item = findNearbyItem(canvasX, canvasY, seriesFilter);
if (item) {
// fill in mouse pos for any listeners out there
item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left);
item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top);
}
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname &&
!(item && h.series == item.series &&
h.point[0] == item.datapoint[0] &&
h.point[1] == item.datapoint[1]))
unhighlight(h.series, h.point);
}
if (item)
highlight(item.series, item.datapoint, eventname);
}
placeholder.trigger(eventname, [ pos, item ]);
}
function triggerRedrawOverlay() {
if (!redrawTimeout)
redrawTimeout = setTimeout(drawOverlay, 30);
}
function drawOverlay() {
redrawTimeout = null;
// draw highlights
octx.save();
octx.clearRect(0, 0, canvasWidth, canvasHeight);
octx.translate(plotOffset.left, plotOffset.top);
var i, hi;
for (i = 0; i < highlights.length; ++i) {
hi = highlights[i];
if (hi.series.bars.show)
drawBarHighlight(hi.series, hi.point);
else
drawPointHighlight(hi.series, hi.point);
}
octx.restore();
executeHooks(hooks.drawOverlay, [octx]);
}
function highlight(s, point, auto) {
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i == -1) {
highlights.push({ series: s, point: point, auto: auto });
triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s, point) {
if (s == null && point == null) {
highlights = [];
triggerRedrawOverlay();
}
if (typeof s == "number")
s = series[s];
if (typeof point == "number")
point = s.data[point];
var i = indexOfHighlight(s, point);
if (i != -1) {
highlights.splice(i, 1);
triggerRedrawOverlay();
}
}
function indexOfHighlight(s, p) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s && h.point[0] == p[0]
&& h.point[1] == p[1])
return i;
}
return -1;
}
function drawPointHighlight(series, point) {
var x = point[0], y = point[1],
axisx = series.xaxis, axisy = series.yaxis;
if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
return;
var pointRadius = series.points.radius + series.points.lineWidth / 2;
octx.lineWidth = pointRadius;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var radius = 1.5 * pointRadius,
x = axisx.p2c(x),
y = axisy.p2c(y);
octx.beginPath();
if (series.points.symbol == "circle")
octx.arc(x, y, radius, 0, 2 * Math.PI, false);
else
series.points.symbol(octx, x, y, radius, false);
octx.closePath();
octx.stroke();
}
function drawBarHighlight(series, point) {
octx.lineWidth = series.bars.lineWidth;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
}
function getColorOrGradient(spec, bottom, top, defaultColor) {
if (typeof spec == "string")
return spec;
else {
// assume this is a gradient spec; IE currently only
// supports a simple vertical gradient properly, so that's
// what we support too
var gradient = ctx.createLinearGradient(0, top, 0, bottom);
for (var i = 0, l = spec.colors.length; i < l; ++i) {
var c = spec.colors[i];
if (typeof c != "string") {
var co = $.color.parse(defaultColor);
if (c.brightness != null)
co = co.scale('rgb', c.brightness)
if (c.opacity != null)
co.a *= c.opacity;
c = co.toString();
}
gradient.addColorStop(i / (l - 1), c);
}
return gradient;
}
}
}
$.plot = function(placeholder, data, options) {
//var t0 = new Date();
var plot = new Plot($(placeholder), data, options, $.plot.plugins);
//(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
return plot;
};
$.plot.version = "0.7";
$.plot.plugins = [];
// returns a string with the date d formatted according to fmt
$.plot.formatDate = function(d, fmt, monthNames) {
var leftPad = function(n) {
n = "" + n;
return n.length == 1 ? "0" + n : n;
};
var r = [];
var escape = false, padNext = false;
var hours = d.getUTCHours();
var isAM = hours < 12;
if (monthNames == null)
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
if (fmt.search(/%p|%P/) != -1) {
if (hours > 12) {
hours = hours - 12;
} else if (hours == 0) {
hours = 12;
}
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'h': c = "" + hours; break;
case 'H': c = leftPad(hours); break;
case 'M': c = leftPad(d.getUTCMinutes()); break;
case 'S': c = leftPad(d.getUTCSeconds()); break;
case 'd': c = "" + d.getUTCDate(); break;
case 'm': c = "" + (d.getUTCMonth() + 1); break;
case 'y': c = "" + d.getUTCFullYear(); break;
case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case '0': c = ""; padNext = true; break;
}
if (c && padNext) {
c = leftPad(c);
padNext = false;
}
r.push(c);
if (!padNext)
escape = false;
}
else {
if (c == "%")
escape = true;
else
r.push(c);
}
}
return r.join("");
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
})(jQuery); | JavaScript |
(function($) {
$.msgGrowl = function(config) {
var defaults, options, container, msgGrowl, content, title, text, close;
defaults = {
type: ''
, title: ''
, text: ''
, lifetime: 6500
, sticky: false
, position: 'bottom-right'
, closeTrigger: true
, onOpen: function () {}
, onClose: function () {}
};
options = $.extend(defaults, config);
container = $('.msgGrowl-container.' + options.position);
if (!container.length) {
container = $('<div>', {
'class': 'msgGrowl-container ' + options.position
}).appendTo ('body');
}
msgGrowl = $('<div>', {
'class': 'msgGrowl ' + options.type
});
content = $('<div>', {
'class': 'msgGrowl-content'
}).appendTo (msgGrowl);
text = $('<span>', {
text: options.text
}).appendTo (content);
if (options.closeTrigger) {
close = $('<div>', {
'class': 'msgGrowl-close'
, 'click': function (e) {
e.preventDefault ();
$(this).parent ().fadeOut ('medium', function () {
$(this).remove ();
if (typeof options.onClose === 'function') {
options.onClose ();
}
});
}
}).appendTo (msgGrowl);
}
if (options.title != '') {
title = $('<h4>', {
text: options.title
}).prependTo (content);
}
if (options.lifetime > 0 && !options.sticky) {
setTimeout (function () {
if (typeof options.onClose === 'function') {
options.onClose ();
}
msgGrowl.fadeOut ('medium', function () { $(this).remove (); });
}, options.lifetime);
}
container.addClass (options.position);
if (options.position.split ('-')[0] == 'top') {
msgGrowl.prependTo (container).hide ().fadeIn ('slow');
} else {
msgGrowl.appendTo (container).hide ().fadeIn ('slow');
}
if (typeof options.onOpen === 'function') {
options.onOpen ();
}
}
})(jQuery); | JavaScript |
(function($) {
$.msgAlert = function(config) {
var defaults, options, msgAlert, popup, header, close, content, footer, overlay;
defaults = {
type: ''
, title: ''
, text: ''
, callback: function () {}
, closeTrigger: true
, escClose: true
, overlay: true
, overlayClose: false
, buttons: [{
text: 'Ok'
, callback: function () {
$.msgAlert.close ();
options.callback ();
}
}]
};
options = $.extend(defaults, config);
msgAlert = $('<div>', {
'class' : 'msgAlert ' + options.type
}).appendTo ('body');
popup = $('<div>', {
'class' : 'msgAlert_popup'
}).appendTo (msgAlert);
if (options.title != '') {
header = $('<div/>', {
'class' : 'msgAlert_header', 'html': '<h4>' + options.title + '</h4>'
}).appendTo (popup);
}
if (options.closeTrigger) {
close = $('<a>', {
'href': 'javascript:;'
, 'class': 'msgAlert_close'
, 'click': close
}).appendTo (header);
}
content = $('<div/>', {
'class': 'msgAlert_content'
, 'text': options.text
}).appendTo (popup);
footer = $('<div/>', {
'class': 'msgAlert_footer'
}).appendTo (msgAlert);
if (options.overlay) {
overlay = $('<div/>', {
'class': 'msgAlert_overlay'
}).appendTo ('body');
if (options.overlay && options.overlayClose) {
overlay.bind ('click', close);
}
}
if (options.type == 'warning') {
options.buttons = [{
text: 'Yes'
, callback: function () {
options.callback ();
$.msgAlert.close ();
}
}, {
text: 'No'
, callback: function () { $.msgAlert.close (); }
}, {
text: 'Cancel'
, callback: function () { $.msgAlert.close (); }
}];
}
if (options.buttons.length > 0) {
for (key in options.buttons) {
$('<button>', { 'text': options.buttons[key].text })
.bind ('click', options.buttons[key].callback)
.appendTo (footer);
}
}
msgAlert.appendTo ('body');
msgAlert.find ('button:first').focus ();
if (options.escClose) {
$(document).bind ('keyup.msgAlert', function (e) {
if (e.keyCode == 27) {
$.msgAlert.close ();
}
});
}
function close (e)
{
e.preventDefault ();
$.msgAlert.close ();
}
};
$.msgAlert.close = function () {
$('.msgAlert').fadeOut ('fast', function () { $(this).remove (); });
$('.msgAlert_overlay').fadeOut ('fast', function () { $(this).remove (); });
$(document).unbind ('keyup.msgAlert');
}
})(jQuery); | JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
config.filebrowserBrowseUrl = '/3ghot/kcfinder/browse.php?type=files';
config.filebrowserImageBrowseUrl = '/3ghot/kcfinder/browse.php?type=images';
config.filebrowserFlashBrowseUrl = '/3ghot/kcfinder/browse.php?type=flash';
config.filebrowserUploadUrl = '/3ghot/kcfinder/upload.php?type=files';
config.filebrowserImageUploadUrl = '/3ghot/kcfinder/upload.php?type=images';
config.filebrowserFlashUploadUrl = '/3ghot/kcfinder/upload.php?type=flash';
};
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','nl',{placeholder:{title:'Eigenschappen placeholder',toolbar:'Placeholder aanmaken',text:'Placeholder tekst',edit:'Placeholder wijzigen',textMissing:'De placeholder moet tekst bevatten.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','ug',{placeholder:{title:'ئورۇن بەلگە خاسلىقى',toolbar:'ئورۇن بەلگە قۇر',text:'ئورۇن بەلگە تېكىستى',edit:'ئورۇن بەلگە تەھرىر',textMissing:'ئورۇن بەلگىسىدە چوقۇم تېكىست بولۇشى لازىم'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','it',{placeholder:{title:'Proprietà segnaposto',toolbar:'Crea segnaposto',text:'Testo segnaposto',edit:'Modifica segnaposto',textMissing:'Il segnaposto deve contenere del testo.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','de',{placeholder:{title:'Platzhalter Einstellungen',toolbar:'Platzhalter erstellen',text:'Platzhalter Text',edit:'Platzhalter bearbeiten',textMissing:'Der Platzhalter muss einen Text beinhalten.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','pl',{placeholder:{title:'Właściwości wypełniacza',toolbar:'Utwórz wypełniacz',text:'Tekst wypełnienia',edit:'Edytuj wypełnienie',textMissing:'Wypełnienie musi posiadać jakiś tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','vi',{placeholder:{title:'Thuộc tính đặt chỗ',toolbar:'Tạo đặt chỗ',text:'Văn bản đặt chỗ',edit:'Chỉnh sửa ',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','hr',{placeholder:{title:'Svojstva rezerviranog mjesta',toolbar:'Napravi rezervirano mjesto',text:'Tekst rezerviranog mjesta',edit:'Uredi rezervirano mjesto',textMissing:'Rezervirano mjesto mora sadržavati tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','tr',{placeholder:{title:'Yer tutucu özellikleri',toolbar:'Yer tutucu oluşturun',text:'Yer tutucu metini',edit:'Yer tutucuyu düzenle',textMissing:'Yer tutucu metin içermelidir.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fr',{placeholder:{title:"Propriétés de l'Espace réservé",toolbar:"Créer l'Espace réservé",text:"Texte de l'Espace réservé",edit:"Modifier l'Espace réservé",textMissing:"L'Espace réservé doit contenir du texte."}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','zh-cn',{placeholder:{title:'占位符属性',toolbar:'创建占位符',text:'占位符文字',edit:'编辑占位符',textMissing:'占位符必需包含有文字'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','eo',{placeholder:{title:'Atributoj de la rezervita spaco',toolbar:'Krei la rezervitan spacon',text:'Texto de la rezervita spaco',edit:'Modifi la rezervitan spacon',textMissing:'La rezervita spaco devas enteni tekston.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','da',{placeholder:{title:'Egenskaber for pladsholder',toolbar:'Opret pladsholder',text:'Tekst til pladsholder',edit:'Redigér pladsholder',textMissing:'Pladsholder skal indeholde tekst'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','nb',{placeholder:{title:'Egenskaper for plassholder',toolbar:'Opprett plassholder',text:'Tekst for plassholder',edit:'Rediger plassholder',textMissing:'Plassholderen må inneholde tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','bg',{placeholder:{title:'Настройки на контейнера',toolbar:'Нов контейнер',text:'Текст за контейнера',edit:'Промяна на контейнер',textMissing:'Контейнера трябва да съдържа текст.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','el',{placeholder:{title:'Ιδιότητες Υποκατάστατου Κειμένου',toolbar:'Δημιουργία Υποκατάσταστου Κειμένου',text:'Υποκαθιστόμενο Κείμενο',edit:'Επεξεργασία Υποκατάσταστου Κειμένου',textMissing:'Πρέπει να υπάρχει υποκαθιστόμενο κείμενο.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fi',{placeholder:{title:'Paikkamerkin ominaisuudet',toolbar:'Luo paikkamerkki',text:'Paikkamerkin teksti',edit:'Muokkaa paikkamerkkiä',textMissing:'Paikkamerkin täytyy sisältää tekstiä'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','cy',{placeholder:{title:"Priodweddau'r Daliwr Geiriau",toolbar:'Creu Daliwr Geiriau',text:'Testun y Daliwr Geiriau',edit:"Golygu'r Dailwr Geiriau",textMissing:"Mae'n rhaid i'r daliwr geiriau gynnwys testun."}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','no',{placeholder:{title:'Egenskaper for plassholder',toolbar:'Opprett plassholder',text:'Tekst for plassholder',edit:'Rediger plassholder',textMissing:'Plassholderen må inneholde tekst.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fa',{placeholder:{title:'ویژگیهای محل نگهداری',toolbar:'ایجاد یک محل نگهداری',text:'متن محل نگهداری',edit:'ویرایش محل نگهداری',textMissing:'محل نگهداری باید محتوی متن باشد.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','et',{placeholder:{title:'Kohahoidja omadused',toolbar:'Kohahoidja loomine',text:'Kohahoidja tekst',edit:'Kohahoidja muutmine',textMissing:'Kohahoidja peab sisaldama teksti.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','uk',{placeholder:{title:'Налаштування Заповнювача',toolbar:'Створити Заповнювач',text:'Текст Заповнювача',edit:'Редагувати Заповнювач',textMissing:'Заповнювач повинен містити текст.'}});
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.