return JSON from MVC equivalent to web forms - asp.net

I'm trying to upload files using plupload and in MVC I have code like this:
public ActionResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
and now I want to do same in web forms. I have added these code in my submit button click
protected void submitBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
}
and I need to send the success=true to my plupload javascript code to write these photos in my folder.
$(document).ready(function () {
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles',
container: document.getElementById('container'),
url: '/Admin.aspx',
flash_swf_url: '/Scripts/Moxie.swf',
silverlight_xap_url: '/Scripts/Moxie.xap',
filters: {
max_file_size: '10mb',
mime_types: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
]
},
init: {
PostInit: function () {
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
UploadProgress: function (up, file) {
_file_name = file.name;
$('#PhotoBox').val(_file_name);
console.log(file.name);
},
Error: function (up, err) {
alert("\nError #" + err.code + ": " + err.message);
}
}
});
uploader.init();
});
so Is there any equivalent of
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
for asp.net Web Forms?

simply put
if (!IsPostBack) {
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
}
in your page load event and everything will okay

Related

How to send image into a specific folder?

I have an input element that selects an image as follows:
HTML Code
<input type="file" id="uploadEditorImage" />
Javascript Code
$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
type:"POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
},
error: function (er) {
alert(er);
}
});
And Code in MVC controller
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
I want to save the selected image in a specific folder such as C\Temp. How can I go about doing that? Please help.
Thank you.
in your html:
<input type="file" id="FileUpload1" />
script:
$(document).ready(function () {
$('#FileUpload1').change(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var data = new FormData();
var files = $("#FileUpload1").get(0).files;
console.log(files);
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: data,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
and backend:
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Content/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

Kendo UI bug with jQuery versions

I have a Kendo UI grid and a Kendo UI Window on the same page. The window contains form elements for record insertion, a record being represented by a row in the grid. But for reasons not known by me, when I opened the window and closed it again and then reopened, Kendo UI scaled it to be 100x smaller. I didn't want to hack the window, so I've looked for alternative solution.
I've used jQuery 1.7.2. I've updated jQuery to version 1.8.0. and window opening, closing and reopening worked. I was very happy until I realized that now the grid filters are not working. When I click on a grid filter, nothing happens, no popup, nothing. What is the cause of this and what would be the solution?
EDIT:
This is my code (I've replaced the values of the Urls). Grid filters are working with jQuery 1.7.2. and window reopen works with new versions of jQuery. Also, if I remove the sort hack, the grid filter popup still doesn't show up.
var hshflt = {};
var addWindow;
var editWindow;
var init = false;
//Sort Hack
/*
Changes all dataSources to case insensitive sorting (client side sorting).
This snipped enable case insensitive sorting on Kendo UI grid, too.
The original case sensitive comparer is a private and can't be accessed without modifying the original source code.
tested with Kendo UI version 2012.2.710 (Q2 2012 / July 2012).
*/
var CaseInsensitiveComparer = {
getterCache: {},
getter: function (expression) {
return this.getterCache[expression] = this.getterCache[expression] || new Function("d", "return " + kendo.expr(expression));
},
selector: function (field) {
return jQuery.isFunction(field) ? field : this.getter(field);
},
asc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a > b ? 1 : (a < b ? -1 : 0);
};
},
desc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a < b ? 1 : (a > b ? -1 : 0);
};
},
create: function (descriptor) {
return this[descriptor.dir.toLowerCase()](descriptor.field);
},
combine: function (comparers) {
return function (a, b) {
var result = comparers[0](a, b),
idx,
length;
for (idx = 1, length = comparers.length; idx < length; idx++) {
result = result || comparers[idx](a, b);
}
return result;
};
}
};
kendo.data.Query.prototype.normalizeSort = function (field, dir) {
if (field) {
var descriptor = typeof field === "string" ? { field: field, dir: dir} : field,
descriptors = jQuery.isArray(descriptor) ? descriptor : (descriptor !== undefined ? [descriptor] : []);
return jQuery.grep(descriptors, function (d) { return !!d.dir; });
}
};
kendo.data.Query.prototype.sort = function (field, dir, comparer) {
var idx,
length,
descriptors = this.normalizeSort(field, dir),
comparers = [];
comparer = comparer || CaseInsensitiveComparer;
if (descriptors.length) {
for (idx = 0, length = descriptors.length; idx < length; idx++) {
comparers.push(comparer.create(descriptors[idx]));
}
return this.orderBy({ compare: comparer.combine(comparers) });
}
return this;
};
kendo.data.Query.prototype.orderBy = function (selector) {
var result = this.data.slice(0),
comparer = jQuery.isFunction(selector) || !selector ? CaseInsensitiveComparer.asc(selector) : selector.compare;
return new kendo.data.Query(result.sort(comparer));
};
kendo.data.Query.prototype.orderByDescending = function (selector) {
return new kendo.data.Query(this.data.slice(0).sort(CaseInsensitiveComparer.desc(selector)));
};
//Sort Hack
$("#refresh-btn").click(function () {
refreshGrid();
});
var grid;
function getPageIndex() {
if (!(grid)) {
return 0;
}
return grid.pager.page() - 1;
}
function getPageSize() {
if (!(grid)) {
return 10;
}
return grid.pager.pageSize();
}
function getFilters() {
if (!(grid)) {
return "";
}
return grid.dataSource.filter();
}
function getSorts() {
if (!(grid)) {
return "";
}
var arr = grid.dataSource.sort();
if ((arr) && (arr.length == 0)) {
return "";
}
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in grid.columns) {
if (grid.columns[col].field === arr[index].field) {
type = grid.columns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
function getColumns() {
if (!(grid)) {
return "";
}
var columns = "";
for (var col in grid.columns) {
if (columns.length > 0) {
columns += ";";
}
columns += grid.columns[col].field + "," + grid.columns[col].type;
}
return columns;
}
var initGrid = true;
var grid2Data;
function getDataSource() {
$.ajax({
type: 'POST',
url: 'mydsurl' + getParams(),
data: "filter=" + JSON.stringify(getFilters()) + "&columns=" + getColumns(),
success: function (param) { grid2Data = param; },
//dataType: dataType,
async: false
});
return grid2Data.Data;
}
var shouldClickOnRefresh = false;
function refreshGrid() {
shouldClickOnRefresh = false;
$.ajax({
type: 'POST',
url: 'mydsurl' + getParams(),
data: "filter=" + JSON.stringify(getFilters()) + "&columns=" + getColumns(),
success: function (param) { grid2Data = param; },
//dataType: dataType,
async: false
});
grid.dataSource.total = function () {
return grid2Data.Total;
}
for (var col in grid.columns) {
if ((grid.columns[col].type) && (grid.columns[col].type === "Date")) {
for (var row in grid2Data.Data) {
grid2Data.Data[row][grid.columns[col].field] = new Date(parseInt((grid2Data.Data[row][grid.columns[col].field] + "").replace("/Date(", "").replace(")/", "")));
}
}
}
grid.dataSource.data(grid2Data.Data);
shouldClickOnRefresh = true;
}
function getParams() {
return getPageSize() + "|" + getPageIndex() + "|" + getSorts();
}
function bindGrid() {
var editUrl = 'myediturl';
if (!(editWindow)) {
editWindow = $("#edit-window");
}
$(".k-button.k-button-icontext.k-grid-edit").each(function (index) {
$(this).click(function () {
if (!editWindow.data("kendoWindow")) {
editWindow.kendoWindow({
title: "Edit User",
width: "60%",
height: "60%",
close: onClose,
open: onEditOpen,
content: editUrl + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"]
});
}
else {
editWindow.data("kendoWindow").refresh(editUrl + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"]);
editWindow.data("kendoWindow").open();
}
editWindow.data("kendoWindow").center();
return false;
})
});
$(".k-button.k-button-icontext.k-grid-delete").each(function (index) {
$(this).click(function () {
var r = confirm("Are you sure you want to delete this user?");
if (r == true) {
$.ajax({
type: 'POST',
url: 'mydelurl' + $("#grid").data().kendoGrid.dataSource.view()[index]["ID"],
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
});
});
}
function onDataBound() {
if (!(shouldClickOnRefresh)) {
shouldClickOnRefresh = true;
bindGrid();
}
else {
refreshGrid();
}
}
$(function () {
$("#grid").kendoGrid({
dataBound: onDataBound,
dataSource: {
autoSync: true,
data: getDataSource(),
serverPaging: true,
schema: {
model: {
fields: {
Email: { type: "string" },
FullName: { type: "string" },
LogCreateDate: { type: "date" },
RoleName: { type: "string" },
UserName: { type: "string" }
}
},
total: function (response) {
return grid2Data.Total;
}
},
pageSize: 10
},
toolbar: ["create"],
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false,
pageSizes: true
},
columns: [
{
command: ["edit", "destroy"],
title: " "
},
{
field: "Email",
title: "Email",
type: "String"
},
{
field: "FullName",
title: "Full Name",
type: "String"
},
{
field: "LogCreateDate",
title: "Created",
type: "Date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
},
{
field: "RoleName",
title: "Role",
type: "Custom"
},
{
field: "UserName",
type: "String"
}
],
editable: "popup"
});
grid = $("#grid").data("kendoGrid");
function onAddOpen() {
}
addWindow = $("#add-window");
$(".k-button.k-button-icontext.k-grid-add").click(function () {
if (!addWindow.data("kendoWindow")) {
addWindow.kendoWindow({
title: "Add User",
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: 'myaddurl'
});
}
else {
addWindow.data("kendoWindow").open();
}
addWindow.data("kendoWindow").center();
addWindow.data("kendoWindow").refresh();
return false;
});
});
function onClose() {
$("#refresh-btn").click();
}
function onEditOpen() {
//editWindow.data("kendoWdinow").center();
}
I've hacked Kendo UI for the second time, this time I've solved its incompatibility with jQuery 1.8.3. using the following hack:
$(".k-grid-filter").each(function(index) {
$(this).click(function() {
$($(".k-filter-menu.k-popup.k-group.k-reset")[index]).offset({
left: $($(".k-grid-filter")[index]).offset().left - $($(".k-filter-menu.k-popup.k-group.k-reset")[index]).width(),
top: $($(".k-grid-filter")[index]).offset().top + $($(".k-grid-filter")[index]).height()})
})
});
I've put this hack into the document load event of the page an voila, it works. It surely looks ugly as hell with this hack, but after designing it will look good as new. I'm happy I found a work around, but I'm unhappy I had to hack Kendo UI twice. It is a very nice tool except the bugs.
jQuery 1.8.# is only compatible with Kendo UI - Q2 2012 SP1 (2012.2 913) or later..
If your kendo UI version is earlier, you should update it.

Adding Images to div from codebehind in Asp.Net

I am uploading some images using plupload and adding those images to div container.And after performing some options I need to upload the edited Images again to the same div from codebehind.
Is that possible to do so?If so how can I modify my code:
This is how I'm trying to upload Images and adding them to div(thumbs):
<script type="text/javascript">
$(function () {
$("#<%=uploader.ClientId%>").plupload({
runtimes: 'gears,flash,silverlight,browserplus,html5',
url: 'Editor.aspx',
max_file_size: '10mb',
max_file_count: 21,
chunk_size: '1mb',
unique_names: true,
rename: true,
dragdrop:true,
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
],
flash_swf_url: 'js/plupload.flash.swf',
silverlight_xap_url: 'js/plupload.silverlight.xap'
});
$('form').submit(function (e) {
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
if (uploader.files.length > 0) {
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
}
else
//alert('You must at least upload one file.');
return false;
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FilesAdded', function (up, files) {
var i = up.files.length,
maxCountError = false;
plupload.each(files, function (file) {
setTimeout(function () {
up.start();
}, 100);
if (uploader.settings.max_file_count && i >= uploader.settings.max_file_count) {
$.msgBox({
title: "Info",
content: "Uuh! Please don't put me any more files.<br>Maximum Upload limit is only 20 Images.<br>Rest of the Images will be removed.",
type: "info",
showButtons: true,
opacity: 0.1,
autoClose: false
});
uploader.removeFile(up.files[i - 1]);
} else {
}
});
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FileUploaded', function (up, file, res) {
$('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "><a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' rel='group1'><img class='clickImage' src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='75' height='50' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>");
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
showStickySuccessToast();
}
});
});
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (!length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
</script>
After editing operation which I am doing it in my codebehind I have saved all those Images to one folder where users can save them.So Now What I want to do Is add all those existed Images on my server folder to be displayed it in the same div(thumbs)where I am adding Images using the uploader at the beginning.
To access a control in code behind, the control must have runat="server". However, it is simpler to use a Panel control instead of a div. A Panel control renders as a div so any client JavaScript will continue to work.
Image NewImage = new Image();
NewImage.ImageUrl= MapPath(#"~\Images\april.jpg");
Panel1.Controls.Add(NewImage);

How to load images on page refresh from folder using Asp.Net

I would like to know that On Page refresh I would like to display more than 40+ images which are already existed in my server folder to be displayed in a div control which already exists and add those images to that div
As of now I can display one image using as shown below:
Preview.ImageUrl = "~/DownloadImages/" & Session("tempDir").ToString & "/" & filename
I would like to know the better solutions!
Here is how the images are generated:
<script type="text/javascript">
$(function () {
$("#<%=uploader.ClientId%>").plupload({
runtimes: 'gears,flash,silverlight,browserplus,html5',
url: 'Default.aspx',
max_file_size: '10mb',
max_file_count: 21,
chunk_size: '1mb',
unique_names: true,
rename: true,
dragdrop: true,
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
],
flash_swf_url: 'js/plupload.flash.swf',
silverlight_xap_url: 'js/plupload.silverlight.xap'
});
$('form').submit(function (e) {
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
if (uploader.files.length > 0) {
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
}
else
//alert('You must at least upload one file.');
return false;
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FilesAdded', function (up, files) {
var i = up.files.length,
maxCountError = false;
plupload.each(files, function (file) {
setTimeout(function () {
up.start();
}, 100);
if (uploader.settings.max_file_count && i >= uploader.settings.max_file_count) {
$.msgBox({
title: "Info",
content: "Max Files Reached.",
type: "info",
showButtons: true,
opacity: 0.1,
autoClose: false
});
uploader.removeFile(up.files[i - 1]);
} else {
}
});
});
var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
uploader.bind('FileUploaded', function (up, file, res) {
$('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "><a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' rel='group1'><img class='clickImage' src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='75' height='50' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>");
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
showStickySuccessToast();
}
});
});
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (!length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
</script>
If I know how many Images users can add then it's easy but It's hard to say thats the main issue.
You can use Literal or Image Controls and add them on a Panel (or even a div if you add runat="server" to it on the aspx file)
<div id="existingDiv" runat="server"></div>
I prefer Image controls... something like this: (this is a very simple example of course)
foreach(string imageURL in urlsList)
{
var img = new System.Web.UI.WebControls.Image();
img.ImageUrl=imageURL;
img.Width = 200;
img.Height = 100;
this.div1.Controls.Add(img);
}
EDIT:
Inside urlsList i load the urls like so: (VB)
Dim urls As New List(Of String) 'I dont know if you need another parenthesis here on VB...
urls.Add("imageurl1")
urls.Add("imageurl2")

JW Player playlist only loads randomly in IE, works fine in FF every time

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);
}

Resources