i have a asp dropdownlist, which is getting generated by ajax, now my problem is, i have a jquery, now basically this jquery is for apply dropdown effect to any select element, now what this does is, once the select element have some option, it hide those option and copy those inside ul and li format, now whats happening, before my ajax call is made, this jquery is executed, and as it finds nothing in select element, it does not creates ul and li, because of which i always gets blank list, i tried placing static items inside DropDownList, it works, but with jquery it does not works, i also tried to place whole jquery code (Jquery which is adding slide effect for dropdownlist) inside document.ready below the ajax call function, but that too is not working, below is my ajax function:
function GetRegion() {
$("select[id$=ddlRegion] > option").remove();
$.ajax({
type: "POST",
url: "InteractiveMap.asmx/GetRegions",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
var Items = data.d;
ddlRegion.attr("disabled", false);
ddlCountry.append('<option value="-1">--Select Region--</option>');
$.each(Items, function (index, Item) {
ddlRegion.append('<option value="' + Item.RID + '">' + Item.Text + '</option>');
});
ddlRegion.val(RegionQueryString);
},
failure: function (msg) {
ShowErrorMessage(msg);
}
});
}
and below is my jquery which is adding slide effect, sorry but its pretty large:
(function ($) {
$.fn.jNice = function (options) {
var self = this;
var safari = $.browser.safari; /* We need to check for safari to fix the input:text problem */
/* Apply document listener */
$(document).mousedown(checkExternalClick);
/* each form */
return this.each(function () {
$('input:submit, input:reset, input:button', this).each(ButtonAdd);
$('button').focus(function () { $(this).addClass('jNiceFocus') }).blur(function () { $(this).removeClass('jNiceFocus') });
$('input:text:visible, input:password', this).each(TextAdd);
/* If this is safari we need to add an extra class */
if (safari) { $('.jNiceInputWrapper').each(function () { $(this).addClass('jNiceSafari').find('input').css('width', $(this).width() + 11); }); }
$('input:checkbox', this).each(CheckAdd);
$('input:radio', this).each(RadioAdd);
$('select', this).each(function (index) {
//$(this).attr('size')
if ($(this).attr('multiple')) {
MultipleSelectAdd(this, index);
}
else
SelectAdd(this, index);
});
/* Add a new handler for the reset action */
$(this).bind('reset', function () { var action = function () { Reset(this); }; window.setTimeout(action, 10); });
$('.jNiceHidden').css({ opacity: 0 });
});
}; /* End the Plugin */
var Reset = function (form) {
var sel;
$('.jNiceWrapper select', form).each(function () { sel = (this.selectedIndex < 0) ? 0 : this.selectedIndex; $('.jNiceSelectWrapper ul', $(this).parent()).each(function () { $('a:eq(0)', this).click(); }); });
$('.jNiceWrapper select', form).each(function () {
sel = (this.selectedIndex < 0) ? 0 : this.selectedIndex; $('.jNiceMultipleSelectWrapper ul li', $(this).parent()).each(function () {
if ($('a:first', this).hasClass('selected'))
$('a:first', this).click();
});
});
$('a.jNiceCheckbox, a.jNiceRadio', form).removeClass('jNiceChecked');
$('input:checkbox, input:radio', form).each(function () { if (this.checked) { $('a', $(this).parent()).addClass('jNiceChecked'); } });
};
var RadioAdd = function () {
var $input = $(this).addClass('jNiceHidden').wrap('<span class="jRadioWrapper jNiceWrapper"></span>');
var $wrapper = $input.parent();
var $a = $('<span class="jNiceRadio"></span>');
$wrapper.prepend($a);
/* Click Handler */
$a.click(function () {
var $input = $(this).addClass('jNiceChecked').siblings('input').attr('checked', true);
/* uncheck all others of same name */
$('input:radio[name="' + $input.attr('name') + '"]').not($input).each(function () {
$(this).attr('checked', false).siblings('.jNiceRadio').removeClass('jNiceChecked');
});
return false;
});
$input.click(function () {
if (this.checked) {
var $input = $(this).siblings('.jNiceRadio').addClass('jNiceChecked').end();
/* uncheck all others of same name */
$('input:radio[name="' + $input.attr('name') + '"]').not($input).each(function () {
$(this).attr('checked', false).siblings('.jNiceRadio').removeClass('jNiceChecked');
});
}
}).focus(function () { $a.addClass('jNiceFocus'); }).blur(function () { $a.removeClass('jNiceFocus'); });
/* set the default state */
if (this.checked) { $a.addClass('jNiceChecked'); }
};
var CheckAdd = function () {
var $input = $(this).addClass('jNiceHidden').wrap('<span class="jNiceWrapper"></span>');
var $wrapper = $input.parent().append('<span class="jNiceCheckbox"></span>');
/* Click Handler */
var $a = $wrapper.find('.jNiceCheckbox').click(function () {
var $a = $(this);
var input = $a.siblings('input')[0];
if (input.checked === true) {
input.checked = false;
$a.removeClass('jNiceChecked');
}
else {
input.checked = true;
$a.addClass('jNiceChecked');
}
return false;
});
$input.click(function () {
if (this.checked) { $a.addClass('jNiceChecked'); }
else { $a.removeClass('jNiceChecked'); }
}).focus(function () { $a.addClass('jNiceFocus'); }).blur(function () { $a.removeClass('jNiceFocus'); });
/* set the default state */
if (this.checked) { $('.jNiceCheckbox', $wrapper).addClass('jNiceChecked'); }
};
var TextAdd = function () {
var $input = $(this).addClass('jNiceInput').wrap('<div class="jNiceInputWrapper"><div class="jNiceInputInner"></div></div>');
var $wrapper = $input.parents('.jNiceInputWrapper');
$input.focus(function () {
$wrapper.addClass('jNiceInputWrapper_hover');
}).blur(function () {
$wrapper.removeClass('jNiceInputWrapper_hover');
});
};
var ButtonAdd = function () {
var value = $(this).attr('value');
$(this).replaceWith('<button id="' + this.id + '" name="' + this.name + '" type="' + this.type + '" class="' + this.className + '" value="' + value + '"><span><span>' + value + '</span></span>');
};
/* Hide all open selects */
var SelectHide = function () {
$('.jNiceSelectWrapper ul:visible').hide();
};
/* Check for an external click */
var checkExternalClick = function (event) {
if ($(event.target).parents('.jNiceSelectWrapper').length === 0) { SelectHide(); }
};
var SelectAdd = function (element, index) {
var $select = $(element);
index = index || $select.css('zIndex') * 1;
index = (index) ? index : 0;
/* First thing we do is Wrap it */
$select.wrap($('<div class="jNiceWrapper"></div>').css({ zIndex: 100 - index }));
var width = $select.width();
$select.addClass('jNiceHidden').after('<div class="jNiceSelectWrapper"><div><span class="jNiceSelectText"></span><span class="jNiceSelectOpen"></span></div><ul></ul></div>');
var $wrapper = $(element).siblings('.jNiceSelectWrapper').css({ width: width + 'px' });
$('.jNiceSelectText, .jNiceSelectWrapper ul', $wrapper).width(width - $('.jNiceSelectOpen', $wrapper).width());
/* IF IE 6 */
if ($.browser.msie && jQuery.browser.version < 7) {
$select.after($('<iframe src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" tabIndex="-1" frameborder="0"></iframe>').css({ height: $select.height() + 4 + 'px' }));
}
/* Now we add the options */
SelectUpdate(element);
/* Apply the click handler to the Open */
$('div', $wrapper).click(function () {
var $ul = $(this).siblings('ul');
if ($ul.css('display') == 'none') { SelectHide(); } /* Check if box is already open to still allow toggle, but close all other selects */
$ul.slideToggle('fast');
var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
$ul.animate({ scrollTop: offSet });
return false;
});
/* Add the key listener */
$select.keydown(function (e) {
var selectedIndex = this.selectedIndex;
switch (e.keyCode) {
case 40: /* Down */
if (selectedIndex < this.options.length - 1) { selectedIndex += 1; }
break;
case 38: /* Up */
if (selectedIndex > 0) { selectedIndex -= 1; }
break;
default:
return;
break;
}
$('ul a', $wrapper).removeClass('selected').eq(selectedIndex).addClass('selected');
$('span:eq(0)', $wrapper).html($('option:eq(' + selectedIndex + ')', $select).attr('selected', 'selected').text());
return false;
}).focus(function () { $wrapper.addClass('jNiceFocus'); }).blur(function () { $wrapper.removeClass('jNiceFocus'); });
};
var MultipleSelectAdd = function (element, index) {
var $select = $(element);
var size = parseInt($select.attr('size'));
index = index || $select.css('zIndex') * 1;
index = (index) ? index : 0;
/* First thing we do is Wrap it */
$select.wrap($('<div class="jNiceWrapper"></div>').css({ zIndex: 100 - index }));
var width = $select.width();
$select.addClass('jNiceHidden').after('<div class="jNiceMultipleSelectWrapper"><div><span class="jNiceSelectText"></span><span class="jNiceSelectOpen"></span></div><ul></ul></div>');
var $wrapper = $(element).siblings('.jNiceMultipleSelectWrapper').css({ width: width + 'px' });
$('.jNiceSelectText, .jNiceMultipleSelectWrapper ul', $wrapper).width(width - $('.jNiceSelectOpen', $wrapper).width());
//$('.jNiceMultipleSelectWrapper ul').height(($select.height()+4) +'px');
//$('.jNiceMultipleSelectWrapper ul').css({'overflow-x':'hidden','overflow-y':'auto'});
/* IF IE 6 */
if ($.browser.msie && jQuery.browser.version < 7) {
$select.after($('<iframe src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" tabIndex="-1" frameborder="0"></iframe>').css({ height: $select.height() + 4 + 'px' }));
}
/* Now we add the options */
MultipleSelectUpdate(element);
/* Add the key listener */
$select.keydown(function (e) {
var selectedIndex = this.selectedIndex;
switch (e.keyCode) {
case 40: /* Down */
if (selectedIndex < this.options.length - 1) { selectedIndex += 1; }
break;
case 38: /* Up */
if (selectedIndex > 0) { selectedIndex -= 1; }
break;
default:
return;
break;
}
$('ul a', $wrapper).removeClass('selected').eq(selectedIndex).addClass('selected');
$('span:eq(0)', $wrapper).html($('option:eq(' + selectedIndex + ')', $select).attr('selected', 'selected').text());
return false;
}).focus(function () { $wrapper.addClass('jNiceFocus'); }).blur(function () { $wrapper.removeClass('jNiceFocus'); });
};
var MultipleSelectUpdate = function (element) {
var $select = $(element);
var $wrapper = $select.siblings('.jNiceMultipleSelectWrapper');
var $ul = $wrapper.find('ul').find('li').remove().end().show();
$('option', $select).each(function (i) {
if ($('option:eq(' + i + ')', $select).attr('selected'))
$ul.append('<li>' + this.text + '</li>');
else
$ul.append('<li>' + this.text + '</li>');
});
/* Add click handler to the a */
$ul.find('a').click(function () {
//$('a.selected', $wrapper).removeClass('selected');
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else
$(this).addClass('selected');
/* Fire the onchange event */
//if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
//$select[0].selectedIndex = $(this).attr('index');
/// we make the select in the input also true
$('option:eq(' + $(this).attr('index') + ')', $select).attr('selected', true);
if ($(this).attr('index') == 0)
$('span:eq(0)', $wrapper).html($(this).html());
return false;
});
/* Set the defalut */
$('a:eq(0)', $ul).click();
};
var SelectUpdate = function (element) {
var $select = $(element);
var $wrapper = $select.siblings('.jNiceSelectWrapper');
var $ul = $wrapper.find('ul').find('li').remove().end().hide();
$('option', $select).each(function (i) {
$ul.append('<li>' + this.text + '</li>');
});
/* Add click handler to the a */
$ul.find('a').click(function () {
$('a.selected', $wrapper).removeClass('selected');
$(this).addClass('selected');
/* Fire the onchange event */
//if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
if ($select[0].selectedIndex != $(this).attr('index')) {
$select.trigger('change');
}
$select[0].selectedIndex = $(this).attr('index');
$('span:eq(0)', $wrapper).html($(this).html());
$ul.hide();
return false;
});
/* Set the defalut */
$('a:eq(' + $select[0].selectedIndex + ')', $ul).click();
};
var SelectRemove = function (element) {
var zIndex = $(element).siblings('.jNiceSelectWrapper').css('zIndex');
$(element).css({ zIndex: zIndex }).removeClass('jNiceHidden');
$(element).siblings('.jNiceSelectWrapper').remove();
};
/* Utilities */
$.jNice = {
SelectAdd: function (element, index) { SelectAdd(element, index); },
MultipleSelectAdd: function (element, index) { MultipleSelectAdd(element, index); },
MultipleSelectUpdate: function (element) { MultipleSelectUpdate(element); },
SelectRemove: function (element) { SelectRemove(element); },
SelectUpdate: function (element) { SelectUpdate(element); },
Reset: function (element) { Reset(element); }
}; /* End Utilities */
/* Automatically apply to any forms with class jNice */
$(function () { $('.content').jNice(); });
})(jQuery);
You don't need to $.parseJSON(response); on success. jQuery parses it ahead of time and passes the object (not the JSON string) to the success function. So response contains the object.
See the "dataType" section for "json" here: http://api.jquery.com/jQuery.ajax/
Related
I have added a custom draggable overlay onto a google map, which works well using a mouse, but doesn't work on touch screens.
The code I am using is from this question : Can we make custom overlays draggable on google maps V3
The code is from #Dr.Molle and shown below.
Is there anything I can do to make it work on a touch screen? The marker shows, but I cannot move it.
DraggableOverlay.prototype = new google.maps.OverlayView();
DraggableOverlay.prototype.onAdd = function () {
var container = document.createElement('div'),
that = this;
if (typeof this.get('content').nodeName !== 'undefined') {
container.appendChild(this.get('content'));
} else {
if (typeof this.get('content') === 'string') {
container.innerHTML = this.get('content');
} else {
return;
}
}
container.style.position = 'absolute';
container.draggable = true;
google.maps.event.addDomListener(this.get('map').getDiv(),
'mouseleave',
function () {
google.maps.event.trigger(container, 'mouseup');
}
);
google.maps.event.addDomListener(container,
'mousedown',
function (e) {
this.style.cursor = 'move';
that.map.set('draggable', false);
that.set('origin', e);
that.moveHandler =
google.maps.event.addDomListener(that.get('map').getDiv(),
'mousemove',
function (e) {
var origin = that.get('origin'),
left = origin.clientX - e.clientX,
top = origin.clientY - e.clientY,
pos = that.getProjection()
.fromLatLngToDivPixel(that.get('position')),
latLng = that.getProjection()
.fromDivPixelToLatLng(new google.maps.Point(pos.x - left,
pos.y - top));
that.set('origin', e);
that.set('position', latLng);
that.draw();
});
}
);
google.maps.event.addDomListener(container, 'mouseup', function () {
that.map.set('draggable', true);
this.style.cursor = 'default';
google.maps.event.removeListener(that.moveHandler);
});
this.set('container', container)
this.getPanes().floatPane.appendChild(container);
};
function DraggableOverlay(map, position, content) {
if (typeof draw === 'function') {
this.draw = draw;
}
this.setValues({
position: position,
container: null,
content: content,
map: map
});
}
DraggableOverlay.prototype.draw = function () {
var pos = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.get('container').style.left = pos.x + 'px';
this.get('container').style.top = pos.y + 'px';
};
DraggableOverlay.prototype.onRemove = function () {
this.get('container').parentNode.removeChild(this.get('container'));
this.set('container', null)
};
new DraggableOverlay(
map,//maps-instance
latLng,//google.maps.LatLng
'content',//HTML-String or DOMNode
function(){}//optional, function that ovverrides the draw-method
);
I am trying to create a custom element which wraps tinyMCE functionality.
I have the following:-
(function(xtag) {
xtag.register('x-tinymce', {
lifecycle:{
created: tinymceCreate,
removed: tinymceDestroy
},
accessors: {
disabled: {
attribute: {
boolean: true
},
get: getDisabledAttribute,
set: setDisabledAttribute
}
}
});
function tinymceCreate(){
var textarea = document.createElement('textarea');
var currentElement = this;
currentElement.textAreaId = xtag.uid();
textarea.id = currentElement.textAreaId;
currentElement.appendChild(textarea);
currentElement.currentMode = 'design';
var complexConfig = {
selector: '#' + currentElement.textAreaId,
setup: editorSetup
}
tinymce.init(complexConfig)
.then(function thenRetrieveEditor(editors) {
currentElement.currentEditor = editors[0];
currentElement.currentEditor.setMode(currentElement.currentMode ? currentElement.currentMode : 'design');
});
function editorSetup(editor) {
editor.on('blur', function blur(event) {
editor.save();
document.getElementById(editor.id).blur();
xtag.fireEvent(currentElement, 'blur', { detail: event, bubbles: false, cancellable: true });
});
editor.on('focus', function focus(event) {
xtag.fireEvent(currentElement, 'focus', { detail: event, bubbles: false, cancellable: true });
});
editor.on('BeforeSetContent', function beforeSetContent(ed) {
if (ed.content)
ed.content = ed.content.replace(/\t/ig, ' ');
});
}
}
function tinymceDestroy() {
if (this.currentEditor)
tinymce.remove(this.currentEditor);
}
function getDisabledAttribute() {
return this.currentMode === 'readonly';
}
function setDisabledAttribute(value) {
if (value) {
this.currentMode = 'readonly';
}
else {
this.currentMode = 'design';
}
if (this.currentEditor) {
this.currentEditor.setMode(this.currentMode);
}
}
})(xtag);
Now, when I register a blur event, it does get called, but so does the focus event. I think that this is because focus/blur events are captured by x-tag by default. I don't want it to do that. Instead, I want these events fired when the user focusses/blurs tinymce.
I am using xtags 1.5.11 and tinymce 4.4.3.
Update 1
OK, the problem is when I call:-
xtag.fireEvent(currentElement, 'focus', { detail: event, bubbles: false, cancellable: true });
This caused the focus to be lost on the editor and go to the containing eleemnt (x-tinymce). To counter this, I modified my editorSetup to look like this:-
function editorSetup(editor) {
// // Backspace is not detected in keypress, so need to include keyup event as well.
// editor.on('keypress change keyup focus', function(ed) {
// $j("#" + editor.id).trigger(ed.type);
// });
var isFocusFromEditor = false;
var isBlurFromEditor = false;
editor.on('blur', function blurEvent(event) {
console.log("blurred editor");
if (!isFocusFromEditor) {
editor.save();
xtag.fireEvent(currentElement, 'blur', { detail: event, bubbles: false, cancellable: false });
}
else {
console.log('refocussing');
isFocusFromEditor = false;
editor.focus();
isBlurFromEditor = true;
}
});
editor.on('focus', function focusEvent(event) {
console.log("Focus triggered");
isFocusFromEditor = true;
xtag.fireEvent(currentElement, 'focus', { detail: event, bubbles: false, cancellable: false });
});
editor.on('BeforeSetContent', function beforeSetContent(ed) {
if (ed.content) {
ed.content = ed.content.replace(/\t/ig, ' ');
}
});
}
This stops the blur event from triggering, unfortuantely, now, the blur event does not get called when you leave the editing area.
This feels like a tinyMCE problem, just not sure what.
Here is a solution that catches focus and blur events at the custom element level.
It uses the event.stopImmediatePropagation() method to stop the transmission of the blur event to other (external) event listeners when needed.
Also, it uses 2 hidden <input> (#FI and #FO) controls in order to catch the focus when the tab key is pressed.
document.registerElement('x-tinymce', {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var textarea = this.querySelector('textarea')
var output = this.querySelector('output')
output.textContent = "state"
var self = this
self.textAreaId = this.dataset.id // xtag.uid();
textarea.id = self.textAreaId
var complexConfig = {
selector: '#' + self.textAreaId,
setup: editorSetup,
}
var FI = this.querySelector('#FI')
FI.addEventListener('focus', function(ev) {
if (ev.relatedTarget) {
var ev = new FocusEvent('focus')
self.dispatchEvent(ev)
} else {
var ev = new FocusEvent('blur')
self.dispatchEvent(ev)
focusNextElement(-1)
}
})
var FO = this.querySelector('#FO')
FO.addEventListener('focus', function(ev) {
if (!ev.relatedTarget) {
var ev = new FocusEvent('blur')
self.dispatchEvent(ev)
focusNextElement(1)
} else {
var ev = new FocusEvent('focus')
self.dispatchEvent(ev)
}
})
var focused = false
this.addEventListener('focus', function(ev) {
console.log('{focus} in ', this.localName)
if (!focused) {
focused = true
output.textContent = focused
self.editor.focus()
} else {
console.error('should not be here')
ev.stopImmediatePropagation()
}
})
this.addEventListener('blur', function(ev) {
console.log('{blur} in %s', this.localName)
if (focused) {
focused = false
output.textContent = focused
} else {
console.log('=> cancel blur')
ev.stopImmediatePropagation()
}
})
tinymce.init(complexConfig).then(function(editors) {
//self.currentEditor = editors[0]
})
//private
function focusNextElement(diff) {
//add all elements we want to include in our selection
var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])'
if (document.activeElement) {
var focussable = Array.prototype.filter.call(document.querySelectorAll(focussableElements), function(element) {
//check for visibility while always include the current activeElement
return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
})
var index = focussable.indexOf(document.activeElement)
focussable[index + diff].focus()
}
}
function editorSetup(editor) {
console.warn('editor setup')
self.editor = editor
editor.on('focus', function(event) {
if (!focused) {
var ev = new FocusEvent('focus')
self.dispatchEvent(ev)
}
})
editor.on('blur', function(event) {
//if ( focused )
{
var ev = new FocusEvent('blur')
self.dispatchEvent(ev)
}
})
}
}
},
detachedCallback: {
value: function() {
if (this.editor)
tinymce.remove(this.editor)
}
}
})
})
var xElem = document.querySelector('x-tinymce')
xElem.addEventListener('focus', function(ev) {
console.info('focus!')
})
xElem.addEventListener('blur', function(ev) {
console.info('blur!')
})
<script src="http://cdn.tinymce.com/4/tinymce.min.js"></script>
<input type="text">
<x-tinymce data-id="foo">
<output id=output></output>
<input type=text id=FI style='width:0;height:0;border:none'>
<textarea>content</textarea>
<input type=text id=FO style='width:0;height:0;border:none'>
</x-tinymce>
<input type="text">
Does anyone have a sample project for lightbox2 rotate? I have applied all the javascript and css for this example http://jsfiddle.net/pootie/EBLc7/
and the rotate button never seems to show. What am I missing please help me
HTML CODE:
<img src="http://grgichtran.com/code/img/car-seat.jpg" class="img-polaroid" style="width: 100px;"/>
JS CODE:
(function () {
var $, Lightbox, LightboxOptions;
$ = jQuery;
LightboxOptions = (function () {
function LightboxOptions() {
this.fadeDuration = 500;
this.fitImagesInViewport = true;
this.resizeDuration = 700;
this.showImageNumberLabel = true;
this.wrapAround = false;
}
LightboxOptions.prototype.albumLabel = function (curImageNum, albumSize) {
return "Image " + curImageNum + " of " + albumSize;
};
return LightboxOptions;
})();
Lightbox = (function () {
function Lightbox(options) {
this.options = options;
this.album = [];
this.currentImageIndex = void 0;
this.init();
}
Lightbox.prototype.init = function () {
this.enable();
return this.build();
};
Lightbox.prototype.enable = function () {
var _this = this;
return $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function (e) {
_this.start($(e.currentTarget));
return false;
});
};
Lightbox.prototype.build = function () {
var _this = this;
$("<div id='lightboxOverlay' class='lightboxOverlay'></div><div id='lightbox' class='lightbox'><div class='lb-outerContainer'><div class='lb-container'><img class='lb-image' src='' /><div class='lb-nav'><a class='lb-prev' href='' ></a><a class='lb-next' href='' ></a></div><div class='lb-loader'><a class='lb-cancel'></a></div></div></div><div class='lb-dataContainer'><div class='lb-data'><div class='lb-details'><span class='lb-caption'></span><span class='lb-number'></span></div><div class='lb-closeContainer'><a class='lb-close'></a><a class='lb-rotate'></a></div></div></div></div>").appendTo($('body'));
this.$lightbox = $('#lightbox');
this.$overlay = $('#lightboxOverlay');
this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
this.$container = this.$lightbox.find('.lb-container');
this.containerTopPadding = parseInt(this.$container.css('padding-top'), 10);
this.containerRightPadding = parseInt(this.$container.css('padding-right'), 10);
this.containerBottomPadding = parseInt(this.$container.css('padding-bottom'), 10);
this.containerLeftPadding = parseInt(this.$container.css('padding-left'), 10);
this.$overlay.hide().on('click', function () {
_this.end();
return false;
});
this.$lightbox.hide().on('click', function (e) {
if ($(e.target).attr('id') === 'lightbox') {
_this.end();
}
return false;
});
this.$outerContainer.on('click', function (e) {
if ($(e.target).attr('id') === 'lightbox') {
_this.end();
}
return false;
});
this.$lightbox.find('.lb-prev').on('click', function () {
if (_this.currentImageIndex === 0) {
_this.changeImage(_this.album.length - 1);
} else {
_this.changeImage(_this.currentImageIndex - 1);
}
return false;
});
this.$lightbox.find('.lb-next').on('click', function () {
if (_this.currentImageIndex === _this.album.length - 1) {
_this.changeImage(0);
} else {
_this.changeImage(_this.currentImageIndex + 1);
}
return false;
});
this.$lightbox.find('.lb-rotate').on('click', function () {
$cont = _this.$lightbox.find('.lb-outerContainer');
$image = _this.$lightbox.find('.lb-image');
if ($($cont).attr('angle') == null) {
$($cont).attr('angle', 0);
}
var value = Number($($cont).attr('angle'));
value += 90;
$($cont).rotate({
animateTo: value
});
$($cont).attr('angle', value);
return false;
});
return this.$lightbox.find('.lb-loader, .lb-close').on('click', function () {
_this.end();
return false;
});
};
Lightbox.prototype.start = function ($link) {
var $window, a, dataLightboxValue, i, imageNumber, left, top, _i, _j, _len, _len1, _ref, _ref1;
$(window).on("resize", this.sizeOverlay);
$('select, object, embed').css({
visibility: "hidden"
});
this.$overlay.width($(document).width()).height($(document).height()).fadeIn(this.options.fadeDuration);
this.album = [];
imageNumber = 0;
dataLightboxValue = $link.attr('data-lightbox');
if (dataLightboxValue) {
_ref = $($link.prop("tagName") + '[data-lightbox="' + dataLightboxValue + '"]');
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
a = _ref[i];
this.album.push({
link: $(a).attr('href'),
title: $(a).attr('title')
});
if ($(a).attr('href') === $link.attr('href')) {
imageNumber = i;
}
}
} else {
if ($link.attr('rel') === 'lightbox') {
this.album.push({
link: $link.attr('href'),
title: $link.attr('title')
});
} else {
_ref1 = $($link.prop("tagName") + '[rel="' + $link.attr('rel') + '"]');
for (i = _j = 0, _len1 = _ref1.length; _j < _len1; i = ++_j) {
a = _ref1[i];
this.album.push({
link: $(a).attr('href'),
title: $(a).attr('title')
});
if ($(a).attr('href') === $link.attr('href')) {
imageNumber = i;
}
}
}
}
$window = $(window);
top = $window.scrollTop() + $window.height() / 10;
left = $window.scrollLeft();
this.$lightbox.css({
top: top + 'px',
left: left + 'px'
}).fadeIn(this.options.fadeDuration);
this.changeImage(imageNumber);
};
Lightbox.prototype.changeImage = function (imageNumber) {
var $image, preloader,
_this = this;
this.disableKeyboardNav();
$image = this.$lightbox.find('.lb-image');
this.sizeOverlay();
this.$overlay.fadeIn(this.options.fadeDuration);
$('.lb-loader').fadeIn('slow');
this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
this.$outerContainer.addClass('animating');
preloader = new Image();
preloader.onload = function () {
var $preloader, imageHeight, imageWidth, maxImageHeight, maxImageWidth, windowHeight, windowWidth;
$image.attr('src', _this.album[imageNumber].link);
$preloader = $(preloader);
$image.width(preloader.width);
$image.height(preloader.height);
if (_this.options.fitImagesInViewport) {
windowWidth = $(window).width();
windowHeight = $(window).height();
maxImageWidth = windowWidth - _this.containerLeftPadding - _this.containerRightPadding - 20;
maxImageHeight = windowHeight - _this.containerTopPadding - _this.containerBottomPadding - 110;
if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
imageWidth = maxImageWidth;
imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
$image.width(imageWidth);
$image.height(imageHeight);
} else {
imageHeight = maxImageHeight;
imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
$image.width(imageWidth);
$image.height(imageHeight);
}
}
}
return _this.sizeContainer($image.width(), $image.height());
};
preloader.src = this.album[imageNumber].link;
this.currentImageIndex = imageNumber;
};
Lightbox.prototype.sizeOverlay = function () {
return $('#lightboxOverlay').width($(document).width()).height($(document).height());
};
Lightbox.prototype.sizeContainer = function (imageWidth, imageHeight) {
var newHeight, newWidth, oldHeight, oldWidth,
_this = this;
oldWidth = this.$outerContainer.outerWidth();
oldHeight = this.$outerContainer.outerHeight();
newWidth = imageWidth + this.containerLeftPadding + this.containerRightPadding;
newHeight = imageHeight + this.containerTopPadding + this.containerBottomPadding;
this.$outerContainer.animate({
width: newWidth,
height: newHeight
}, this.options.resizeDuration, 'swing');
setTimeout(function () {
_this.$lightbox.find('.lb-dataContainer').width(newWidth);
_this.$lightbox.find('.lb-prevLink').height(newHeight);
_this.$lightbox.find('.lb-nextLink').height(newHeight);
_this.showImage();
}, this.options.resizeDuration);
};
Lightbox.prototype.showImage = function () {
this.$lightbox.find('.lb-loader').hide();
this.$lightbox.find('.lb-image').fadeIn('slow');
this.updateNav();
this.updateDetails();
this.preloadNeighboringImages();
this.enableKeyboardNav();
};
Lightbox.prototype.updateNav = function () {
this.$lightbox.find('.lb-nav').show();
if (this.album.length > 1) {
if (this.options.wrapAround) {
this.$lightbox.find('.lb-prev, .lb-next').show();
} else {
if (this.currentImageIndex > 0) {
this.$lightbox.find('.lb-prev').show();
}
if (this.currentImageIndex < this.album.length - 1) {
this.$lightbox.find('.lb-next').show();
}
}
}
};
Lightbox.prototype.updateDetails = function () {
var _this = this;
if (typeof this.album[this.currentImageIndex].title !== 'undefined' && this.album[this.currentImageIndex].title !== "") {
this.$lightbox.find('.lb-caption').html(this.album[this.currentImageIndex].title).fadeIn('fast');
}
if (this.album.length > 1 && this.options.showImageNumberLabel) {
this.$lightbox.find('.lb-number').text(this.options.albumLabel(this.currentImageIndex + 1, this.album.length)).fadeIn('fast');
} else {
this.$lightbox.find('.lb-number').hide();
}
this.$outerContainer.removeClass('animating');
this.$lightbox.find('.lb-dataContainer').fadeIn(this.resizeDuration, function () {
return _this.sizeOverlay();
});
};
Lightbox.prototype.preloadNeighboringImages = function () {
var preloadNext, preloadPrev;
if (this.album.length > this.currentImageIndex + 1) {
preloadNext = new Image();
preloadNext.src = this.album[this.currentImageIndex + 1].link;
}
if (this.currentImageIndex > 0) {
preloadPrev = new Image();
preloadPrev.src = this.album[this.currentImageIndex - 1].link;
}
};
Lightbox.prototype.enableKeyboardNav = function () {
$(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
};
Lightbox.prototype.disableKeyboardNav = function () {
$(document).off('.keyboard');
};
Lightbox.prototype.keyboardAction = function (event) {
var KEYCODE_ESC, KEYCODE_LEFTARROW, KEYCODE_RIGHTARROW, key, keycode;
KEYCODE_ESC = 27;
KEYCODE_LEFTARROW = 37;
KEYCODE_RIGHTARROW = 39;
keycode = event.keyCode;
key = String.fromCharCode(keycode).toLowerCase();
if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
this.end();
} else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
if (this.currentImageIndex !== 0) {
this.changeImage(this.currentImageIndex - 1);
}
} else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
if (this.currentImageIndex !== this.album.length - 1) {
this.changeImage(this.currentImageIndex + 1);
}
}
};
Lightbox.prototype.end = function () {
this.disableKeyboardNav();
$(window).off("resize", this.sizeOverlay);
this.$lightbox.fadeOut(this.options.fadeDuration);
this.$overlay.fadeOut(this.options.fadeDuration);
return $('select, object, embed').css({
visibility: "visible"
});
};
return Lightbox;
})();
$(function () {
var lightbox, options;
options = new LightboxOptions();
return lightbox = new Lightbox(options);
});
}).call(this);
I'm not sure what your question is; please allow me to confirm that after applying the code in your project,
the lightbox shows up properly, but rotate button doesn't
nothing special shows up. Neither lightbox, nor rotate button show up.
If your question is the first one, please check if the rotate button image (rotate.png) is placed in proper path. From the css file, this image should be put in img/ folder.
From this sample's css, rotate.png should be here:
background: url(../img/rotate.png) top right no-repeat;
On the other hand, if your question is second one, please check all files (js/css/images) exist and are in correct path, especially css and images.
I have a problem with plugin SoundManager + Slider jquery UI - this one works as volume/current position changer while playing music.
After page is loaded, sometimes (i think it depends on file size) volume and current position are works fine, but if file are too huge, slider is loading properly (no errors in console) but not changing anything.
<?php
// In page Javascript
function audio_player_javascript () {
?>
<script>
var AudioPlayerDebugMode = true;
var songPlays = 0;
function AudioPlayerConsole (message) {
if (AudioPlayerDebugMode == true)
console.log(message);
}
function convertMilliseconds (ms, p) {
var pattern = p || "hh:mm:ss",
arrayPattern = pattern.split(":"),
clock = [ ],
hours = Math.floor ( ms / 3600000 ), // 1 Hour = 36000 Milliseconds
minuets = Math.floor (( ms % 3600000) / 60000), // 1 Minutes = 60000 Milliseconds
seconds = Math.floor ((( ms % 360000) % 60000) / 1000) // 1 Second = 1000 Milliseconds
// build the clock result
function createClock(unit){
// match the pattern to the corresponding variable
if (pattern.match(unit)) {
if (unit.match(/h/)) {
addUnitToClock(hours, unit);
}
if (unit.match(/m/)) {
addUnitToClock(minuets, unit);
}
if (unit.match(/s/)) {
addUnitToClock(seconds, unit);
};
}
}
function addUnitToClock(val, unit){
if ( val < 10 && unit.length === 2) {
val = "0" + val;
}
clock.push(val); // push the values into the clock array
}
// loop over the pattern building out the clock result
for ( var i = 0, j = arrayPattern.length; i < j; i ++ ){
createClock(arrayPattern[i]);
}
return {
hours : hours,
minuets : minuets,
seconds : seconds,
clock : clock.join(":")
};
}
<?php
$detect = new Mobile_Detect();
if ($detect->isMobile())
{
?>
setTimeout(function () {jQuery(".audio-player-toggle").trigger("click");}, 1000);
<?php
}
if (get_option("audio_player_autoplay_plugin") == "yes")
{
?>
setTimeout(function () { jQuery("#play-pause-button").trigger("click"); }, 1000);
<?php
}
?>
jQuery(function() {
soundManager.url = "<?php echo plugins_url('/js/soundmanager/swf', __FILE__);?>";
// Hide audio player
jQuery(".audio-player-toggle.open").live("click", function (e) {
jQuery(".audio-player-container").animate({
bottom: '-' + jQuery(".audio-player-container").height() + 'px'
}, 300, function () {
jQuery(".audio-player-toggle").removeClass("open");
jQuery(".audio-player-toggle").addClass("closed");
});
});
// Show audio player
jQuery(".audio-player-toggle.closed").live("click", function (e) {
jQuery(".audio-player-container").animate({
bottom: '0px'
}, 300, function () {
jQuery(".audio-player-toggle").removeClass("closed");
jQuery(".audio-player-toggle").addClass("open");
});
});
jQuery( "#position-scrubber" ).slider({
range: "max",
min: 0,
max: 0,
value: 0,
slide: function( event, ui ) {
}
});
if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
{
// Set volume range if browser has Flash enabled
jQuery( "#volume-scrubber" ).slider({
range: "max",
min: 0,
max: 100,
value: 50,
slide: function( event, ui ) {
}
});
}
else
{
// Set volume range if browser doesn't have Flash enabled
jQuery( "#volume-scrubber" ).slider({
range: "max",
min: 0,
max: 1,
value: 0.5,
step: 0.01,
slide: function( event, ui ) {
}
});
}
jQuery(".audio-controls-container a").click(function (e) {
e.preventDefault();
});
var htmlSound = new Audio ();
// Set first song in playlist to be played
jQuery(".playlist_item:first").addClass("current");
var firstSong;
var mySound;
// Find playlist item with current class
firstSong = jQuery(".playlist_item:first").attr("data-song_file");
jQuery("#play-pause-button").live("click", function (e) {
AudioPlayerConsole(songPlays);
if (songPlays == 0)
{
playAudio(firstSong);
jQuery(this).addClass("playing");
}
else
{
// Pause music if it has playing class
if (jQuery(this).hasClass("playing"))
{
AudioPlayerConsole("stop playing");
jQuery(this).removeClass("playing");
if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined)
mySound.pause('audio-player');
else
htmlSound.pause();
return;
}
else
{
AudioPlayerConsole("start playing");
jQuery(this).addClass("playing");
if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
mySound.resume('audio-player');
else
htmlSound.play();
return;
}
}
});
jQuery("#next-button").live("click", function (e) {
var thisSongFile = jQuery(".playlist_item.current").next(".playlist_item").attr("data-song_file");
if(!thisSongFile)
{
jQuery(".playlist_item").removeClass("current");
jQuery(".playlist_item:first").addClass("current");
thisSongFile = jQuery(".playlist_item:first").attr("data-song_file");
playAudio(thisSongFile);
}
else
{
console.log(thisSongFile);
var foundCurrent = false;
jQuery(".playlist_item").each(function () {
if (foundCurrent == true)
{
jQuery(this).addClass("current");
foundCurrent = false;
return;
}
if (jQuery(this).hasClass("current"))
{
jQuery(this).removeClass("current");
foundCurrent = true;
}
});
playAudio(thisSongFile);
}
});
jQuery("#previous-button").live("click", function (e) {
var thisSongFile = jQuery(".playlist_item.current").prev(".playlist_item").attr("data-song_file");
if(!thisSongFile)
{
jQuery(".playlist_item").removeClass("current");
jQuery(".playlist_item:first").addClass("current");
thisSongFile = jQuery(".playlist_item:first").attr("data-song_file");
playAudio(thisSongFile);
}
else
{
var foundCurrent = false;
jQuery(".playlist_item").each(function () {
if (jQuery(this).hasClass("current"))
{
jQuery(this).removeClass("current");
jQuery(this).prev(".playlist_item").addClass("current");
}
});
playAudio(thisSongFile);
}
});
// Load album track preview into audio player
jQuery(".track-preview").live("click", function (e) {
e.preventDefault();
var thisSongFile = jQuery(this).attr("data-song_file");
var thisSongArtist = jQuery(this).attr("data-song_artist");
var thisSongTitle = jQuery(this).attr("data-song_title");
var isInPlaylist = false;
// Determine if selected song is already in playlist
jQuery(".playlist_item").each(function () {
// Get title and artist of playing song
var songTitle = jQuery(this).attr("data-song_title");
var songArtist = jQuery(this).attr("data-song_artist");
if (thisSongArtist == songArtist && thisSongTitle == songTitle)
{
jQuery(".playlist_item").removeClass("current");
jQuery(this).addClass("current");
isInPlaylist = true;
}
});
if (isInPlaylist == true)
{
playAudio(thisSongFile);
}
else
{
jQuery(".playlist_item").removeClass("current");
var newPlaylistItem = '<li class="playlist_item current" song_title="' + thisSongTitle + '" song_artwork="" song_file="' + thisSongFile + '" song_artist="' + thisSongArtist + '"></li>';
jQuery("#audio-player-playlist").append(newPlaylistItem);
playAudio(thisSongFile);
}
});
function playAudio (songFile) {
songPlays++;
AudioPlayerConsole("Loading " + songFile);
if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
{
soundManager.onready(function() {
soundManager.destroySound('audio-player');
mySound = soundManager.createSound({
id:'audio-player',
url: songFile,
onload: function() {
var duration = mySound.duration;
jQuery( "#position-scrubber" ).slider("option", "max", duration);
var durationTime = convertMilliseconds(duration, "mm:ss");
jQuery("#total-track-time").html(durationTime.clock);
jQuery( "#position-scrubber" ).bind( "slide", function(event, ui) {
mySound.setPosition(ui.value);
});
// Show pause button
jQuery("#play-pause-button").addClass("playing");
},
whileplaying: function() {
var position = mySound.position;
var positionTime = convertMilliseconds(position, "mm:ss");
jQuery("#current-track-time").html(positionTime.clock);
jQuery( "#position-scrubber" ).slider("option", "value", position/1000);
var volume = jQuery( "#volume-scrubber" ).slider("option", "value");
mySound.setVolume(volume);
},
whileloading: function() {
var duration = mySound.duration;
var durationTime = convertMilliseconds(duration, "mm:ss");
jQuery("#total-track-time").html(durationTime.clock);
},
onfinish: function() {
// Play next song in playlist
setTimeout(function () {jQuery("#next-button").trigger("click");}, 300);
}
});
// End soundManager.createSound
mySound.play();
});
jQuery("#play-pause-button").addClass("playing");
}
// End if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
else
// Player will use HTML5
{
htmlSound.src = songFile;
htmlSound.load();
jQuery( "#position-scrubber" ).bind( "slide", function(event, ui) {
htmlSound.currentTime = ui.value;
});
htmlSound.addEventListener("timeupdate", function() {
var newVolume = jQuery( "#volume-scrubber" ).slider("option", "value");
htmlSound.volume = newVolume;
var duration = htmlSound.duration * 1000;
var durationTime = convertMilliseconds(duration, "mm:ss");
jQuery("#total-track-time").html(durationTime.clock );
var position = htmlSound.currentTime * 1000;
var positionTime = convertMilliseconds(position, "mm:ss");
jQuery("#current-track-time").html(positionTime.clock );
jQuery( "#position-scrubber" ).slider("option", "max", duration/1000);
jQuery( "#position-scrubber" ).slider("option", "value", position/1000);
});
htmlSound.addEventListener("ended", function() {
setTimeout(function () {jQuery("#next-button").trigger("click");}, 300);
});
htmlSound.play();
jQuery("#play-pause-button").addClass("playing");
}
// End Player will use HTML5
jQuery(".playlist_item").each(function () {
if (jQuery(this).hasClass("current"))
{
// Set title, artist, and artwork of playing song
var songArtwork = jQuery(this).attr("data-song_artwork");
var songTitle = jQuery(this).attr("data-song_title");
var songArtist = jQuery(this).attr("data-song_artist");
if (songArtwork != "")
{
jQuery(".audio-player-artwork img").attr("src", songArtwork);
jQuery(".audio-player-artwork").show();
}
else
{
jQuery(".audio-player-artwork img").attr("src", "");
jQuery(".audio-player-artwork").hide();
}
jQuery(".audio-player-song-title").html(songTitle);
jQuery(".audio-player-song-artist").html(songArtist);
}
});
}
// End playAudio()
});
</script>
The playlist loads every time in FF but only the first time in IE (6-8), after that only randomly.
If I alert the error that's thrown I get "TypeError: playerReady is undefined".
My code looks good and obviously works since FF displays the playlist perfectly. I've got no idea how to solve this. Anyone?
<script type='text/javascript'>
var so = new SWFObject('/UI/Flash/player.swf', 'ply', '<%=FlashWidth %>', '<%=FlashHeight %>', '9', '#ffffff'),
playlistURL = '<%=PlaylistURL %>',
imageURL = '<%=GetBackgroundImageUrl() %>';
so.addParam('allowfullscreen', 'true');
so.addParam('allowscriptaccess', 'always');
if (playlistURL !== '') {
so.addVariable('playlistfile', playlistURL);
so.addVariable('playlist', 'none');
so.addVariable('enablejs', 'true');
}
else {
so.addVariable('file', '<%=FlashURL %>');
}
if (imageURL.length > 0) {
so.addVariable('image', imageURL);
}
so.write('preview<%=PlayerID %>');
</script>
The playerReady function is called by the player once it's finished it's setup process. Do you happen to define that function and then set it to undefined? That might cause an error.
Also, what version of the player are you using?
so.addVariable('enablejs', 'true');
I don't belive that's been a flashvar since the 3.X player, which is no longer supported.
Best,
Zach
Developer, LongTail Video
Not sure how I solved it, but here is the final code that actually works:
HTML PAGE:
<script type='text/javascript'>
var so = new SWFObject('/UI/Flash/player.swf', 'ply', '700', '345', '9', '#ffffff'),
playlistUrl = 'XML-PLaylist',
imageURL = '/ImageVault/Images/conversionFormat_2/id_1577/scope_0/ImageVaultHandler.aspx';
so.addParam('allowfullscreen', 'true');
so.addParam('allowscriptaccess', 'always');
so.addParam('wmode', 'opaque');
if (playlistUrl !== '') {
so.addVariable('playlistfile', playlistUrl);
so.addVariable('playlist', 'none');
so.addVariable('controlbar', 'bottom');
so.addVariable('backcolor', '0xDDE5FF');
so.addVariable('frontcolor', '0x142864');
so.addVariable('screencolor', '0xffffff');
so.addVariable('enablejs', 'true');
so.addVariable('overstretch', 'true');
}
else {
so.addVariable('file', '');
}
if (imageURL.length > 0) {
so.addVariable('image', imageURL);
}
so.write('preview');
</script>
And here's the JavaScript:
try {
var playlistReady = playerReady;
} cat
ch (err) {
//alert('1' + err);
}
playerReady = function(obj) {
setTimeout(function() { checkPlaylistLoaded(obj) }, 1);
try {
playlistReady(obj);
} catch (err) {
//alert(err);
}
}
function itemHandler(obj) {
var item = obj['index'];
var playlist = $("#" + obj['id']).next();
var currentItem = 0;
playlist.children().each(function() {
if (currentItem == item) {
$(this).addClass("playing");
} else {
$(this).removeClass("playing");
}
currentItem++;
});
}
function checkPlaylistLoaded(obj) {
//debugger;
var player = document.getElementById(obj['id']),
jsPlaylist = player.getPlaylist();
if (jsPlaylist.length > 0) {
var playlist = createPlaylist(obj);
populatePlaylist(player, jsPlaylist, playlist);
player.addControllerListener("PLAYLIST", "playlistHandler");
player.addControllerListener("ITEM", "itemHandler");
player.addControllerListener("STOP", "showPlaylist");
player.addModelListener("STATE", "stateListener");
} else {
setTimeout(function() { checkPlaylistLoaded(obj) }, 150);
}
}
function stateListener(obj) {
if (obj.newstate === 'PLAYING') {
hidePlaylist();
}
if (obj.newstate === 'PAUSED') {
showPlaylist();
}
}
function createPlaylist(obj) {
var playerDiv = $("#" + obj['id']);
playerDiv.after("<div class='jw_playlist_playlist'></div>");
return playerDiv.next();
}
function hidePlaylist() {
$('.jw_playlist_playlist').animate({ left: "-320px" }, 1000);
}
function showPlaylist() {
$('.jw_playlist_playlist').animate({ left: "-10px" }, 1000);
}
function playlistHandler(obj) {
var player = document.getElementById(obj['id']),
jsPlaylist = player.getPlaylist(),
playerDiv = $("#" + obj['id']),
playlist = playerDiv.next();
populatePlaylist(player, jsPlaylist, playlist);
}
function populatePlaylist(player, jsPlaylist, playlist) {
playlist.empty();
for (var i = 0; i < jsPlaylist.length; i++) {
var jsItem = jsPlaylist[i];
var alternate = "even";
if (i % 2) {
alternate = "odd";
}
playlist.append("<div id='" + getItemId(jsItem) + "' class='jw_playlist_item " + alternate + "'>" + dump(jsItem) + "</div>");
}
var playlistItem = 0;
playlist.children().each(function() {
var currentItem = playlistItem;
$(this).click(function() {
player.sendEvent("ITEM", currentItem);
});
playlistItem++;
});
}
function getItemId(arr) {
var output = '${link}',
variables = getVars(output),
j;
for (j = 0; j < variables.length; j++) {
var variable = variables[j],
varName = variable.replace('${', '').replace('}', ''),
value = arr[varName];
if (!value) {
value = '';
}
output = output.replace(variable, value);
}
return output;
}
function dump(arr) {
var output = "<div class='jw_playlist_title'>${title}</div><div class='jw_playlist_description'>${description}</div>",
variables = getVars(output),
j;
for (j = 0; j < variables.length; j++) {
var variable = variables[j],
varName = variable.replace('${', '').replace('}', ''),
value = arr[varName];
if (!value) {
value = '';
}
output = output.replace(variable, value);
}
return output;
}
function dumpText(arr) {
var dumped_text = "";
if (typeof (arr) == 'object') {
for (var item in arr) {
var value = arr[item];
if (typeof (value) == 'object') {
dumped_text += "<div class='" + item + "'>";
dumped_text += dump(value);
dumped_text += "</div>";
} else {
dumped_text += "<div class='" + item + "'>" + value + "</div>";
}
}
} else {
dumped_text += arr + " (" + typeof (arr) + ")";
}
return dumped_text;
}
function getVars(str) {
return str.match(/\$\{(.*?)\}/g);
}