Browse Source

Added blog post creation/editing/delete

tags/2.0.3
Teknikode 4 years ago
parent
commit
c295897088

Teknik/GitVersionConfig.yaml → GitVersionConfig.yaml View File

@@ -1,2 +1,2 @@
assembly-versioning-scheme: MajorMinorPatch
next-version: 3.1.0
next-version: 2.0.0

+ 6
- 1
Teknik.sln View File

@@ -1,10 +1,15 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.22823.1
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Teknik", "Teknik\Teknik.csproj", "{B20317CD-76C6-4A7B-BCE1-E4BEF8E4F964}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{725ABF52-FD44-4682-81BB-D93598787643}"
ProjectSection(SolutionItems) = preProject
GitVersionConfig.yaml = GitVersionConfig.yaml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU

+ 6
- 1
Teknik/Areas/Blog/BlogAreaRegistration.cs View File

@@ -58,10 +58,15 @@ namespace Teknik.Areas.Blog
new[] { typeof(Controllers.BlogController).Namespace }
);

// Register Bundles
// Register Script Bundles
BundleTable.Bundles.Add(new ScriptBundle("~/bundles/blog").Include(
"~/Scripts/ocupload/1.1.2/ocupload.js",
"~/Scripts/bootstrap/markdown/bootstrap-markdown.js",
"~/Scripts/bootbox/bootbox.min.js",
"~/Areas/Blog/Scripts/Blog.js"));
// Register Style Bundles
BundleTable.Bundles.Add(new StyleBundle("~/Content/blog").Include(
"~/Content/bootstrap-markdown.min.css"));
}
}
}

+ 62
- 79
Teknik/Areas/Blog/Controllers/BlogController.cs View File

@@ -19,26 +19,6 @@ namespace Teknik.Areas.Blog.Controllers
{
private TeknikEntities db = new TeknikEntities();

// GET: Blogs
[AllowAnonymous]
public ActionResult Index()
{
ViewBag.Title = "Teknik Blog - " + Config.Title;

// by default, view the teknik blog
Models.Blog blog = db.Blogs.Find(Constants.SERVERBLOGID);
BlogViewModel model = new BlogViewModel();
model.BlogId = Constants.SERVERBLOGID;
if (blog != null)
{
model.UserId = blog.UserId;
model.User = blog.User;
model.Posts = blog.Posts;
}

return View(model);
}

// GET: Blogs/Details/5
[AllowAnonymous]
public ActionResult Blog(string username)
@@ -64,7 +44,7 @@ namespace Teknik.Areas.Blog.Controllers
{
var foundPosts = db.Posts.Include("Blog").Include("Blog.User").Where(p => (p.Blog.BlogId == blog.BlogId) &&
(p.Published || p.Blog.User.Username == User.Identity.Name)
);
).OrderByDescending(p => p.DatePosted);
model = new BlogViewModel();
model.BlogId = blog.BlogId;
model.UserId = blog.UserId;
@@ -87,13 +67,12 @@ namespace Teknik.Areas.Blog.Controllers
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// find the post specified
var post = db.Posts.Include("Blog").Include("Blog.User").Where(p => (p.Blog.User.Username == username && p.PostId == id) &&
Post post = db.Posts.Include("Blog").Include("Blog.User").Where(p => (p.Blog.User.Username == username && p.PostId == id) &&
(p.Published || p.Blog.User.Username == User.Identity.Name)
);
if (post != null && post.Any())
).First();
if (post != null)
{
Post curPost = post.First();
PostViewModel model = new PostViewModel(curPost);
PostViewModel model = new PostViewModel(post);

ViewBag.Title = model.Title + " - " + username + "'s Blog - " + Config.Title;
return View("~/Areas/Blog/Views/Blog/ViewPost.cshtml", model);
@@ -107,7 +86,7 @@ namespace Teknik.Areas.Blog.Controllers
{
var posts = db.Posts.Include("Blog").Include("Blog.User").Where(p => (p.BlogId == blogID && p.PostId > startPostID) &&
(p.Published || p.Blog.User.Username == User.Identity.Name)
).Take(count);
).OrderByDescending(p => p.DatePosted).Skip(startPostID).Take(count).ToList();
List<PostViewModel> postViews = new List<PostViewModel>();
if (posts != null)
{
@@ -119,84 +98,88 @@ namespace Teknik.Areas.Blog.Controllers
return PartialView("~/Areas/Blog/Views/Blog/Posts.cshtml", postViews);
}

// GET: Blogs/Create
public ActionResult Create()
{
return View();
}

// POST: Blogs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "BlogId,UserId")] Models.Blog blog)
[AllowAnonymous]
public ActionResult GetPostTitle(int postID)
{
if (ModelState.IsValid)
string title = string.Empty;
Post post = (User.IsInRole("Admin")) ? db.Posts.Find(postID) : db.Posts.Include("Blog").Include("Blog.User").Where(p => (p.PostId == postID) &&
(p.Published || p.Blog.User.Username == User.Identity.Name)).First();
if (post != null)
{
db.Blogs.Add(blog);
db.SaveChanges();
return RedirectToAction("Index");
return Json(new { result = post.Title });
}

return View(blog);
return Json(new { error = "No title found" });
}

// GET: Blogs/Edit/5
public ActionResult Edit(int? id)
[HttpPost]
[AllowAnonymous]
public ActionResult GetPostArticle(int postID)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Models.Blog blog = db.Blogs.Find(id);
if (blog == null)
string title = string.Empty;
Post post = (User.IsInRole("Admin")) ? db.Posts.Find(postID) : db.Posts.Include("Blog").Include("Blog.User").Where(p => (p.PostId == postID) &&
(p.Published || p.Blog.User.Username == User.Identity.Name)).First();
if (post != null)
{
return HttpNotFound();
return Json(new { result = post.Article });
}
return View(blog);
return Json(new { error = "No article found" });
}

// POST: Blogs/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "BlogId,UserId")] Models.Blog blog)
public ActionResult CreatePost(int blogID, string title, string article)
{
if (ModelState.IsValid)
{
db.Entry(blog).State = EntityState.Modified;
Post post = db.Posts.Create();
post.BlogId = blogID;
post.Title = title;
post.Article = article;
post.DatePosted = DateTime.Now;
post.DatePublished = DateTime.Now;

db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
return Json(new { result = true });
}
return View(blog);
return Json(new { error = "No post found" });
}

// GET: Blogs/Delete/5
public ActionResult Delete(int? id)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int postID, string title, string article)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Models.Blog blog = db.Blogs.Find(id);
if (blog == null)
if (ModelState.IsValid)
{
return HttpNotFound();
Post post = db.Posts.Find(postID);
if (post != null)
{
post.Title = title;
post.Article = article;
db.Entry(post).State = EntityState.Modified;
db.SaveChanges();
return Json(new { result = true });
}
}
return View(blog);
return Json(new { error = "No post found" });
}

// POST: Blogs/Delete/5
[HttpPost, ActionName("Delete")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
public ActionResult DeletePost(int postID)
{
Models.Blog blog = db.Blogs.Find(id);
db.Blogs.Remove(blog);
db.SaveChanges();
return RedirectToAction("Index");
if (ModelState.IsValid)
{
Post post = db.Posts.Find(postID);
if (post != null)
{
db.Posts.Remove(post);
db.SaveChanges();
return Json(new { result = true });
}
}
return Json(new { error = "No post found" });
}
}
}

+ 35
- 34
Teknik/Areas/Blog/Scripts/Blog.js View File

@@ -1,19 +1,20 @@
$(document).ready(function () {
$("#blog_submit").click(function () {
$('#newPost').modal('hide');
title = encodeURIComponent($("#blog_title").val());
post = encodeURIComponent($("#blog_post").val());
blogID = $("#blog_blogid").val();
title = $("#blog_title").val();
post = $("#blog_post").val();
$.ajax({
type: "POST",
url: addPostURL,
data: { title: title, post: post },
data: AddAntiForgeryToken({ blogID: blogID, title: title, article: post }),
success: function (html) {
if (html == 'true') {
if (html.result) {
window.location.reload();
}
else {
$("#top_msg").css('display', 'inline', 'important');
$("#top_msg").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + html + '</div>');
$("#top_msg").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + html.error + '</div>');
}
}
});
@@ -22,25 +23,25 @@

$('#editPost').on('show.bs.modal', function (e) {
$("#edit_blog_post").val("");
postID = encodeURIComponent($(e.relatedTarget).attr("id"));
postID = $(e.relatedTarget).attr("id");
$("#edit_blog_postid").val(postID);
$.ajax({
type: "POST",
url: getPostTitleURL,
data: { id: postID },
data: { postID: postID },
success: function (html) {
if (html) {
$("#edit_blog_title").val(html);
if (html.result) {
$("#edit_blog_title").val(html.result);
}
}
});
$.ajax({
type: "POST",
url: getPostArticleURL,
data: { id: postID },
data: { postID: postID },
success: function (html) {
if (html) {
$("#edit_blog_post").val(html);
if (html.result) {
$("#edit_blog_post").val(html.result);
}
}
});
@@ -48,20 +49,20 @@

$("#edit_submit").click(function () {
$('#editPost').modal('hide');
postID = encodeURIComponent($("#edit_blog_postid").val());
title = encodeURIComponent($("#edit_blog_title").val());
post = encodeURIComponent($("#edit_blog_post").val());
postID = $("#edit_blog_postid").val();
title = $("#edit_blog_title").val();
post = $("#edit_blog_post").val();
$.ajax({
type: "POST",
url: editPostURL,
data: { postID: postID, title: title, post: post },
data: AddAntiForgeryToken({ postID: postID, title: title, article: post }),
success: function (html) {
if (html == 'true') {
if (html.result) {
window.location.reload();
}
else {
$("#top_msg").css('display', 'inline', 'important');
$("#top_msg").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + html + '</div>');
$("#top_msg").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + html.error + '</div>');
}
}
});
@@ -70,12 +71,12 @@

$("#comment_submit").click(function () {
$('#newComment').modal('hide');
postID = encodeURIComponent($("#post_id").val());
post = encodeURIComponent($("#comment_post").val());
postID = $("#post_id").val();
post = $("#comment_post").val();
$.ajax({
type: "POST",
url: addCommentURL,
data: { postID: postID, service: 'blog', comment: post },
data: AddAntiForgeryToken({ postID: postID, service: 'blog', comment: post }),
success: function (html) {
if (html == 'true') {
window.location.reload();
@@ -112,7 +113,7 @@
$.ajax({
type: "POST",
url: editCommentURL,
data: { commentID: postID, post: post },
data: AddAntiForgeryToken({ commentID: postID, post: post }),
success: function (html) {
if (html == 'true') {
window.location.reload();
@@ -148,7 +149,7 @@
});

function loadMorePosts(start, count) {
blog_id = encodeURIComponent($(".blog-main").attr("id"));
blog_id = $(".blog-main").attr("id");
$.ajax({
type: "POST",
url: getPostsURL,
@@ -166,7 +167,7 @@ function loadMorePosts(start, count) {
}

function loadMoreComments(start, count) {
post_id = encodeURIComponent($(".post-comments").attr("id"));
post_id = $(".post-comments").attr("id");
$.ajax({
type: "POST",
url: getCommentsURL,
@@ -200,11 +201,11 @@ function bindScrollComments() {
function linkPostUnpublish(selector) {
$(selector).click(function () {
var object = $(this);
post_id = encodeURIComponent(object.attr("id"));
post_id = object.attr("id");
$.ajax({
type: "POST",
url: publishPostURL,
data: { publish: false, id: post_id },
data: AddAntiForgeryToken({ publish: false, postID: post_id }),
success: function (html) {
if (html == 'true') {
window.location.reload();
@@ -221,11 +222,11 @@ function linkPostUnpublish(selector) {
function linkPostPublish(selector) {
$(selector).click(function () {
var object = $(this);
post_id = encodeURIComponent(object.attr("id"));
post_id = object.attr("id");
$.ajax({
type: "POST",
url: publishPostURL,
data: { publish: true, id: post_id },
data: AddAntiForgeryToken({ publish: true, postID: post_id }),
success: function (html) {
if (html == 'true') {
window.location.reload();
@@ -242,20 +243,20 @@ function linkPostPublish(selector) {
function linkPostDelete(selector) {
$(selector).click(function () {
var object = $(this);
post_id = encodeURIComponent(object.attr("id"));
post_id = object.attr("id");
bootbox.confirm("Are you sure you want to delete your post?", function (result) {
if (result) {
$.ajax({
type: "POST",
url: deletePostURL,
data: { id: post_id },
data: AddAntiForgeryToken({ postID: post_id }),
success: function (html) {
if (html == 'true') {
if (html.result) {
window.location.reload();
}
else {
$("#top_msg").css('display', 'inline', 'important');
$("#top_msg").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + html + '</div>');
$("#top_msg").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + html.error + '</div>');
}
}
});
@@ -267,13 +268,13 @@ function linkPostDelete(selector) {
function linkCommentDelete(selector) {
$(selector).click(function () {
var object = $(this);
post_id = encodeURIComponent(object.attr("id"));
post_id = object.attr("id");
bootbox.confirm("Are you sure you want to delete your comment?", function (result) {
if (result) {
$.ajax({
type: "POST",
url: deleteCommentURL,
data: { id: post_id },
data: AddAntiForgeryToken({ postID: post_id }),
success: function (html) {
if (html == 'true') {
window.location.reload();

+ 2
- 0
Teknik/Areas/Blog/Views/Blog/Blog.cshtml View File

@@ -22,6 +22,7 @@
var deleteCommentURL = '@Url.Action("DeleteComment", "Blog", new { area = "Blog" })';
</script>

@Styles.Render("~/Content/blog")
@Scripts.Render("~/bundles/blog")

<div class="container">
@@ -59,6 +60,7 @@
<h4 class="modal-title" id="newPostLabel">Create a New Post</h4>
</div>
<div class="modal-body">
<input name="blog_blogid" id="blog_blogid" type="hidden" value="@Model.BlogId" />
<div class="row">
<div class="form-group col-sm-12">
<label for="blog_title"><h4>Title</h4></label>

+ 1
- 0
Teknik/Areas/Blog/Views/Blog/ViewPost.cshtml View File

@@ -22,6 +22,7 @@
var deleteCommentURL = '@Url.Action("DeleteComment", "Blog", new { area = "Blog" })';
</script>

@Styles.Render("~/Content/blog")
@Scripts.Render("~/bundles/blog")

<div class="container">

+ 1
- 0
Teknik/Content/bootstrap-markdown.min.css View File

@@ -0,0 +1 @@
.md-editor{display:block;border:1px solid #ddd}.md-editor>.md-header,.md-editor .md-footer{display:block;padding:6px 4px;background:#fff}.md-editor>.md-header{margin: 0;}.md-editor>.md-preview{background:#fff;min-height:10px;padding:4px;overflow:auto}.md-editor>textarea{font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:14px;outline:0;outline:thin dotted \9;margin:0;display:block;padding:4px;width:100%;border:0;border-top:1px dashed #ddd;border-radius:0;box-shadow:none;}.md-editor>textarea:focus{box-shadow:none;background:#fff}.md-editor.active{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,0.6)}

+ 14
- 21
Teknik/Global.asax.cs View File

@@ -32,36 +32,29 @@ namespace Teknik
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
List<string> roles = new List<string>();

using (TeknikEntities entities = new TeknikEntities())
{
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
List<string> roles = new List<string>();
User user = entities.Users.Include("Groups").Include("Groups.Roles").SingleOrDefault(u => u.Username == username);

using (TeknikEntities entities = new TeknikEntities())
foreach (Group grp in user.Groups)
{
User user = entities.Users.SingleOrDefault(u => u.Username == username);

foreach (Group grp in user.Groups)
foreach (Role role in grp.Roles)
{
foreach (Role role in grp.Roles)
if (!roles.Contains(role.Name))
{
if (!roles.Contains(role.Name))
{
roles.Add(role.Name);
}
roles.Add(role.Name);
}
}
}

//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.ToArray());
}
catch (Exception)
{
//somehting went wrong
}

//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.ToArray());
}
}
}

+ 5
- 0
Teknik/Scripts/Common.js View File

@@ -1,4 +1,9 @@
$(document).ready(function () {
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};

$("#top_msg").css('display', 'none', 'important');

$("#login_dropdown").click(function () {

BIN
Teknik/Scripts/_references.js View File


+ 6
- 0
Teknik/Scripts/bootbox/bootbox.min.js
File diff suppressed because it is too large
View File


+ 6
- 0
Teknik/Scripts/bootstrap/bootstrap.min.js
File diff suppressed because it is too large
View File


+ 1
- 0
Teknik/Scripts/bootstrap/image-gallery/bootstrap-image-gallery.min.js View File

@@ -0,0 +1 @@
!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery","./blueimp-gallery"],a):a(window.jQuery,window.blueimp.Gallery)}(function(a,b){"use strict";a.extend(b.prototype.options,{useBootstrapModal:!0});var c=b.prototype.close,d=b.prototype.imageFactory,e=b.prototype.videoFactory,f=b.prototype.textFactory;a.extend(b.prototype,{modalFactory:function(a,b,c,d){if(!this.options.useBootstrapModal||c)return d.call(this,a,b,c);var e=this,f=this.container.children(".modal"),g=f.clone().show().on("click",function(a){(a.target===g[0]||a.target===g.children()[0])&&(a.preventDefault(),a.stopPropagation(),e.close())}),h=d.call(this,a,function(a){b({type:a.type,target:g[0]}),g.addClass("in")},c);return g.find(".modal-title").text(h.title||String.fromCharCode(160)),g.find(".modal-body").append(h),g[0]},imageFactory:function(a,b,c){return this.modalFactory(a,b,c,d)},videoFactory:function(a,b,c){return this.modalFactory(a,b,c,e)},textFactory:function(a,b,c){return this.modalFactory(a,b,c,f)},close:function(){this.container.find(".modal").removeClass("in"),c.call(this)}})});

+ 1302
- 0
Teknik/Scripts/bootstrap/markdown/bootstrap-markdown.js
File diff suppressed because it is too large
View File


+ 379
- 0
Teknik/Scripts/bootstrap/modal/bootstrap-modal.js View File

@@ -0,0 +1,379 @@
/* ===========================================================
* bootstrap-modal.js v2.2.0
* ===========================================================
* Copyright 2012 Jordan Schroter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */


!function ($) {

"use strict"; // jshint ;_;

/* MODAL CLASS DEFINITION
* ====================== */

var Modal = function (element, options) {
this.init(element, options);
};

Modal.prototype = {

constructor: Modal,

init: function (element, options) {
var that = this;

this.options = options;

this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));

this.options.remote && this.$element.find('.modal-body').load(this.options.remote, function () {
var e = $.Event('loaded');
that.$element.trigger(e);
});

var manager = typeof this.options.manager === 'function' ?
this.options.manager.call(this) : this.options.manager;

manager = manager.appendModal ?
manager : $(manager).modalmanager().data('modalmanager');

manager.appendModal(this);
},

toggle: function () {
return this[!this.isShown ? 'show' : 'hide']();
},

show: function () {
var e = $.Event('show');

if (this.isShown) return;

this.$element.trigger(e);

if (e.isDefaultPrevented()) return;

this.escape();

this.tab();

this.options.loading && this.loading();
},

hide: function (e) {
e && e.preventDefault();

e = $.Event('hide');

this.$element.trigger(e);

if (!this.isShown || e.isDefaultPrevented()) return (this.isShown = false);

this.isShown = false;

this.escape();

this.tab();

this.isLoading && this.loading();

$(document).off('focusin.modal');

this.$element
.removeClass('in')
.removeClass('animated')
.removeClass(this.options.attentionAnimation)
.removeClass('modal-overflow')
.attr('aria-hidden', true);

$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal();
},

layout: function () {
var prop = this.options.height ? 'height' : 'max-height',
value = this.options.height || this.options.maxHeight;

if (this.options.width){
this.$element.css('width', this.options.width);

var that = this;
this.$element.css('margin-left', function () {
if (/%/ig.test(that.options.width)){
return -(parseInt(that.options.width) / 2) + '%';
} else {
return -($(this).width() / 2) + 'px';
}
});
} else {
this.$element.css('width', '');
this.$element.css('margin-left', '');
}

this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');

if (value){
this.$element.find('.modal-body')
.css('overflow', 'auto')
.css(prop, value);
}

var modalOverflow = $(window).height() - 10 < this.$element.height();
if (modalOverflow || this.options.modalOverflow) {
this.$element
.css('margin-top', 0)
.addClass('modal-overflow');
} else {
this.$element
.css('margin-top', 0 - this.$element.height() / 2)
.removeClass('modal-overflow');
}
},

tab: function () {
var that = this;

if (this.isShown && this.options.consumeTab) {
this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
if (e.keyCode && e.keyCode == 9){
var $next = $(this),
$rollover = $(this);

that.$element.find('[data-tabindex]:enabled:not([readonly])').each(function (e) {
if (!e.shiftKey){
$next = $next.data('tabindex') < $(this).data('tabindex') ?
$next = $(this) :
$rollover = $(this);
} else {
$next = $next.data('tabindex') > $(this).data('tabindex') ?
$next = $(this) :
$rollover = $(this);
}
});

$next[0] !== $(this)[0] ?
$next.focus() : $rollover.focus();

e.preventDefault();
}
});
} else if (!this.isShown) {
this.$element.off('keydown.tabindex.modal');
}
},

escape: function () {
var that = this;
if (this.isShown && this.options.keyboard) {
if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1);

this.$element.on('keyup.dismiss.modal', function (e) {
e.which == 27 && that.hide();
});
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
},

hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end);
that.hideModal();
}, 500);

this.$element.one($.support.transition.end, function () {
clearTimeout(timeout);
that.hideModal();
});
},

hideModal: function () {
var prop = this.options.height ? 'height' : 'max-height';
var value = this.options.height || this.options.maxHeight;

if (value){
this.$element.find('.modal-body')
.css('overflow', '')
.css(prop, '');
}

this.$element
.hide()
.trigger('hidden');
},

removeLoading: function () {
this.$loading.remove();
this.$loading = null;
this.isLoading = false;
},

loading: function (callback) {
callback = callback || function () {};

var animate = this.$element.hasClass('fade') ? 'fade' : '';

if (!this.isLoading) {
var doAnimate = $.support.transition && animate;

this.$loading = $('<div class="loading-mask ' + animate + '">')
.append(this.options.spinner)
.appendTo(this.$element);

if (doAnimate) this.$loading[0].offsetWidth; // force reflow

this.$loading.addClass('in');

this.isLoading = true;

doAnimate ?
this.$loading.one($.support.transition.end, callback) :
callback();

} else if (this.isLoading && this.$loading) {
this.$loading.removeClass('in');

var that = this;
$.support.transition && this.$element.hasClass('fade')?
this.$loading.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();

} else if (callback) {
callback(this.isLoading);
}
},

focus: function () {
var $focusElem = this.$element.find(this.options.focusOn);

$focusElem = $focusElem.length ? $focusElem : this.$element;

$focusElem.focus();
},

attention: function (){
// NOTE: transitionEnd with keyframes causes odd behaviour

if (this.options.attentionAnimation){
this.$element
.removeClass('animated')
.removeClass(this.options.attentionAnimation);

var that = this;

setTimeout(function () {
that.$element
.addClass('animated')
.addClass(that.options.attentionAnimation);
}, 0);
}


this.focus();
},


destroy: function () {
var e = $.Event('destroy');
this.$element.trigger(e);
if (e.isDefaultPrevented()) return;

this.teardown();
},

teardown: function () {
if (!this.$parent.length){
this.$element.remove();
this.$element = null;
return;
}

if (this.$parent !== this.$element.parent()){
this.$element.appendTo(this.$parent);
}

this.$element.off('.modal');
this.$element.removeData('modal');
this.$element
.removeClass('in')
.attr('aria-hidden', true);
}
};


/* MODAL PLUGIN DEFINITION
* ======================= */

$.fn.modal = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modal'),
options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option);

if (!data) $this.data('modal', (data = new Modal(this, options)));
if (typeof option == 'string') data[option].apply(data, [].concat(args));
else if (options.show) data.show()
})
};

$.fn.modal.defaults = {
keyboard: true,
backdrop: true,
loading: false,
show: true,
width: null,
height: null,
maxHeight: null,
modalOverflow: false,
consumeTab: true,
focusOn: null,
replace: false,
resize: false,
attentionAnimation: 'shake',
manager: 'body',
spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};

$.fn.modal.Constructor = Modal;


/* MODAL DATA-API
* ============== */

$(function () {
$(document).off('click.modal').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
var $this = $(this),
href = $this.attr('href'),
$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7
option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data());

e.preventDefault();
$target
.modal(option)
.one('hide', function () {
$this.focus();
})
});
});

}(window.jQuery);

+ 422
- 0
Teknik/Scripts/bootstrap/modal/bootstrap-modalmanager.js View File

@@ -0,0 +1,422 @@
/* ===========================================================
* bootstrap-modalmanager.js v2.2.0
* ===========================================================
* Copyright 2012 Jordan Schroter.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */

!function ($) {

"use strict"; // jshint ;_;

/* MODAL MANAGER CLASS DEFINITION
* ====================== */

var ModalManager = function (element, options) {
this.init(element, options);
};

ModalManager.prototype = {

constructor: ModalManager,

init: function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
this.stack = [];
this.backdropCount = 0;

if (this.options.resize) {
var resizeTimeout,
that = this;

$(window).on('resize.modal', function(){
resizeTimeout && clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function(){
for (var i = 0; i < that.stack.length; i++){
that.stack[i].isShown && that.stack[i].layout();
}
}, 10);
});
}
},

createModal: function (element, options) {
$(element).modal($.extend({ manager: this }, options));
},

appendModal: function (modal) {
this.stack.push(modal);

var that = this;

modal.$element.on('show.modalmanager', targetIsSelf(function (e) {

var showModal = function(){
modal.isShown = true;

var transition = $.support.transition && modal.$element.hasClass('fade');

that.$element
.toggleClass('modal-open', that.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < that.$element.height());

modal.$parent = modal.$element.parent();

modal.$container = that.createContainer(modal);

modal.$element.appendTo(modal.$container);

that.backdrop(modal, function () {
modal.$element.show();

if (transition) {
//modal.$element[0].style.display = 'run-in';
modal.$element[0].offsetWidth;
//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
}
modal.layout();

modal.$element
.addClass('in')
.attr('aria-hidden', false);

var complete = function () {
that.setFocus();
modal.$element.trigger('shown');
};

transition ?
modal.$element.one($.support.transition.end, complete) :
complete();
});
};

modal.options.replace ?
that.replace(showModal) :
showModal();
}));

modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {

that.backdrop(modal);
if (modal.$backdrop){
var transition = $.support.transition && modal.$element.hasClass('fade');

// trigger a relayout due to firebox's buggy transition end event
if (transition) { modal.$element[0].offsetWidth; }

$.support.transition && modal.$element.hasClass('fade') ?
modal.$backdrop.one($.support.transition.end, function () { that.destroyModal(modal) }) :
that.destroyModal(modal);
} else {
that.destroyModal(modal);
}

}));

modal.$element.on('destroy.modalmanager', targetIsSelf(function (e) {
that.removeModal(modal);
}));

},

destroyModal: function (modal) {
modal.destroy();

var hasOpenModal = this.hasOpenModal();

this.$element.toggleClass('modal-open', hasOpenModal);

if (!hasOpenModal){
this.$element.removeClass('page-overflow');
}

this.removeContainer(modal);

this.setFocus();
},

getOpenModals: function () {
var openModals = [];
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) openModals.push(this.stack[i]);
}

return openModals;
},

hasOpenModal: function () {
return this.getOpenModals().length > 0;
},

setFocus: function () {
var topModal;

for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}

if (!topModal) return;

topModal.focus();

},

removeModal: function (modal) {
modal.$element.off('.modalmanager');
if (modal.$backdrop) this.removeBackdrop(modal);
this.stack.splice(this.getIndexOfModal(modal), 1);
},

getModalAt: function (index) {
return this.stack[index];
},

getIndexOfModal: function (modal) {
for (var i = 0; i < this.stack.length; i++){
if (modal === this.stack[i]) return i;
}
},

replace: function (callback) {
var topModal;

for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}

if (topModal) {
this.$backdropHandle = topModal.$backdrop;
topModal.$backdrop = null;

callback && topModal.$element.one('hidden',
targetIsSelf( $.proxy(callback, this) ));

topModal.hide();
} else if (callback) {
callback();
}
},

removeBackdrop: function (modal) {
modal.$backdrop.remove();
modal.$backdrop = null;
},

createBackdrop: function (animate, tmpl) {
var $backdrop;

if (!this.$backdropHandle) {
$backdrop = $(tmpl)
.addClass(animate)
.appendTo(this.$element);
} else {
$backdrop = this.$backdropHandle;
$backdrop.off('.modalmanager');
this.$backdropHandle = null;
this.isLoading && this.removeSpinner();
}

return $backdrop;
},

removeContainer: function (modal) {
modal.$container.remove();
modal.$container = null;
},

createContainer: function (modal) {
var $container;

$container = $('<div class="modal-scrollable">')
.css('z-index', getzIndex('modal', this.getOpenModals().length))
.appendTo(this.$element);

if (modal && modal.options.backdrop != 'static') {
$container.on('click.modal', targetIsSelf(function (e) {
modal.hide();
}));
} else if (modal) {
$container.on('click.modal', targetIsSelf(function (e) {
modal.attention();
}));
}

return $container;

},

backdrop: function (modal, callback) {
var animate = modal.$element.hasClass('fade') ? 'fade' : '',
showBackdrop = modal.options.backdrop &&
this.backdropCount < this.options.backdropLimit;

if (modal.isShown && showBackdrop) {
var doAnimate = $.support.transition && animate && !this.$backdropHandle;

modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);

modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));

if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow

modal.$backdrop.addClass('in');

this.backdropCount += 1;

doAnimate ?
modal.$backdrop.one($.support.transition.end, callback) :
callback();

} else if (!modal.isShown && modal.$backdrop) {
modal.$backdrop.removeClass('in');

this.backdropCount -= 1;

var that = this;

$.support.transition && modal.$element.hasClass('fade')?
modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
that.removeBackdrop(modal);

} else if (callback) {
callback();
}
},

removeSpinner: function(){
this.$spinner && this.$spinner.remove();
this.$spinner = null;
this.isLoading = false;
},

removeLoading: function () {
this.$backdropHandle && this.$backdropHandle.remove();
this.$backdropHandle = null;
this.removeSpinner();
},

loading: function (callback) {
callback = callback || function () { };

this.$element
.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < this.$element.height());

if (!this.isLoading) {

this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);

this.$backdropHandle[0].offsetWidth; // force reflow

var openModals = this.getOpenModals();

this.$backdropHandle
.css('z-index', getzIndex('backdrop', openModals.length + 1))
.addClass('in');

var $spinner = $(this.options.spinner)
.css('z-index', getzIndex('modal', openModals.length + 1))
.appendTo(this.$element)
.addClass('in');

this.$spinner = $(this.createContainer())
.append($spinner)
.on('click.modalmanager', $.proxy(this.loading, this));

this.isLoading = true;

$.support.transition ?
this.$backdropHandle.one($.support.transition.end, callback) :
callback();

} else if (this.isLoading && this.$backdropHandle) {
this.$backdropHandle.removeClass('in');

var that = this;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();

} else if (callback) {
callback(this.isLoading);
}
}
};

/* PRIVATE METHODS
* ======================= */

// computes and caches the zindexes
var getzIndex = (function () {
var zIndexFactor,
baseIndex = {};

return function (type, pos) {

if (typeof zIndexFactor === 'undefined'){
var $baseModal = $('<div class="modal hide" />').appendTo('body'),
$baseBackdrop = $('<div class="modal-backdrop hide" />').appendTo('body');

baseIndex['modal'] = +$baseModal.css('z-index');
baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];

$baseModal.remove();
$baseBackdrop.remove();
$baseBackdrop = $baseModal = null;
}

return baseIndex[type] + (zIndexFactor * pos);

}
}());

// make sure the event target is the modal itself in order to prevent
// other components such as tabsfrom triggering the modal manager.
// if Boostsrap namespaced events, this would not be needed.
function targetIsSelf(callback){
return function (e) {
if (this === e.target){
return callback.apply(this, arguments);
}
}
}


/* MODAL MANAGER PLUGIN DEFINITION
* ======================= */

$.fn.modalmanager = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modalmanager');

if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
if (typeof option === 'string') data[option].apply(data, [].concat(args))
})
};

$.fn.modalmanager.defaults = {
backdropLimit: 999,
resize: true,
spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};

$.fn.modalmanager.Constructor = ModalManager

}(jQuery);

+ 467
- 0
Teknik/Scripts/bootstrap/select/bootstrap-select.js View File

@@ -0,0 +1,467 @@
!function($) {
var Selectpicker = function(element, options, e) {
if (e ) {
e.stopPropagation();
e.preventDefault();
}
this.$element = $(element);
this.$newElement = null;
this.button = null;
//Merge defaults, options and data-attributes to make our options
this.options = $.extend({}, $.fn.selectpicker.defaults, this.$element.data(), typeof options == 'object' && options);
//If we have no title yet, check the attribute 'title' (this is missed by jq as its not a data-attribute
if(this.options.title==null)
this.options.title = this.$element.attr('title');
//Expose public methods
this.val = Selectpicker.prototype.val;
this.render = Selectpicker.prototype.render;
this.refresh = Selectpicker.prototype.refresh;
this.selectAll = Selectpicker.prototype.selectAll;
this.deselectAll = Selectpicker.prototype.deselectAll;
this.init();
};

Selectpicker.prototype = {

constructor: Selectpicker,

init: function (e) {
if (!this.options.container) {
this.$element.hide();
} else {
this.$element.css('visibility','hidden');
};
this.multiple = this.$element.prop('multiple');
var classList = this.$element.attr('class') !== undefined ? this.$element.attr('class').split(/\s+/) : '';
var id = this.$element.attr('id');
this.$element.after( this.createView() );
this.$newElement = this.$element.next('.bootstrap-select');
if (this.options.container) {
this.selectPosition();
}
this.button = this.$newElement.find('> button');
if (id !== undefined) {
this.button.attr('id', id);
$('label[for="' + id + '"]').click( $.proxy(this, function(){ this.$newElement.find('button#'+id).focus(); }))
}
for (var i = 0; i < classList.length; i++) {
if(classList[i] != 'selectpicker') {
this.$newElement.addClass(classList[i]);
}
}
//If we are multiple, then add the show-tick class by default
if(this.multiple) {
this.$newElement.addClass('show-tick');
}
this.button.addClass(this.options.style);
this.checkDisabled();
this.checkTabIndex();
this.clickListener();
//Listen for updates to the DOM and re render...
this.$element.bind('DOMNodeInserted DOMNodeRemoved', $.proxy(this.refresh, this));
this.render();
this.setSize();
},

createDropdown: function() {
var drop =
"<div class='btn-group bootstrap-select'>" +
"<button type='button' class='btn dropdown-toggle clearfix' data-toggle='dropdown'>" +
"<span class='filter-option pull-left'></span>&nbsp;" +
"<span class='caret'></span>" +
"</button>" +
"<ul class='dropdown-menu' role='menu'>" +
"</ul>" +
"</div>";

return $(drop);
},

createView: function() {
var $drop = this.createDropdown();
var $li = this.createLi();
$drop.find('ul').append($li);
return $drop;
},
reloadLi: function() {
//Remove all children.
this.destroyLi();
//Re build
$li = this.createLi();
this.$newElement.find('ul').append( $li );
},
destroyLi:function() {
this.$newElement.find('li').remove();
},

createLi: function() {

var _this = this;
var _li = [];
var _liA = [];
var _liHtml = '';
this.$element.find('option').each(function(){
_li.push($(this).text());
});

this.$element.find('option').each(function(index) {
//Get the class and text for the option
var optionClass = $(this).attr("class") !== undefined ? $(this).attr("class") : '';
var text = $(this).text();
var subtext = $(this).data('subtext') !== undefined ? '<small class="muted">'+$(this).data('subtext')+'</small>' : '';
var icon = $(this).data('icon') !== undefined ? '<i class="'+$(this).data('icon')+'"></i> ' : '';
if ($(this).is(':disabled') || $(this).parent().is(':disabled')) {
icon = '<span>'+icon+'</span>';
}
//Prepend any icon and append any subtext to the main text.
text = icon + '<span class="text">' + text + subtext + '</span>';

if ($(this).parent().is('optgroup') && $(this).data('divider') != true) {
if ($(this).index() == 0) {
//Get the opt group label
var label = $(this).parent().attr('label');
var labelSubtext = $(this).parent().data('subtext') !== undefined ? '<small class="muted">'+$(this).parent().data('subtext')+'</small>' : '';
var labelIcon = $(this).parent().data('icon') ? '<i class="'+$(this).parent().data('icon')+'"></i> ' : '';
label = labelIcon + '<span class="text">' + label + labelSubtext + '</span>';
if ($(this)[0].index != 0) {
_liA.push(
'<div class="div-contain"><div class="divider"></div></div>'+
'<dt>'+label+'</dt>'+
_this.createA(text, "opt " + optionClass )
);
} else {
_liA.push(
'<dt>'+label+'</dt>'+
_this.createA(text, "opt " + optionClass ));
}
} else {
_liA.push( _this.createA(text, "opt " + optionClass ) );
}
} else if ($(this).data('divider') == true) {
_liA.push('<div class="div-contain"><div class="divider"></div></div>');
} else if ($(this).data('hidden') == true) {
_liA.push('');
} else {
_liA.push( _this.createA(text, optionClass ) );
}
});
if (_li.length > 0) {
for (var i = 0; i < _li.length; i++) {
var $option = this.$element.find('option').eq(i);
_liHtml += "<li rel=" + i + ">" + _liA[i] + "</li>";
}
}
//If we are not multiple, and we dont have a selected item, and we dont have a title, select the first element so something is set in the button
if(!this.multiple && this.$element.find('option:selected').length==0 && !_this.options.title) {
this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected');
}
return $(_liHtml);
},
createA:function(text, classes) {
return '<a tabindex="0" class="'+classes+'">' +
text +
'<i class="icon-ok check-mark"></i>' +
'</a>';
},
render:function() {
var _this = this;

//Update the LI to match the SELECT
this.$element.find('option').each(function(index) {
_this.setDisabled(index, $(this).is(':disabled') || $(this).parent().is(':disabled') );
_this.setSelected(index, $(this).is(':selected') );
});
var selectedItems = this.$element.find('option:selected').map(function(index,value) {
if($(this).attr('title')!=undefined) {
return $(this).attr('title');
} else {
return $(this).text();
}
}).toArray();
//Convert all the values into a comma delimited string
var title = selectedItems.join(", ");
//If this is multi select, and the selectText type is count, the show 1 of 2 selected etc..
if(_this.multiple && _this.options.selectedTextFormat.indexOf('count') > -1) {
var max = _this.options.selectedTextFormat.split(">");
if( (max.length>1 && selectedItems.length > max[1]) || (max.length==1 && selectedItems.length>=2)) {
title = selectedItems.length +' of ' + this.$element.find('option').length + ' selected';
}
}
//If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
if(!title) {
title = _this.options.title != undefined ? _this.options.title : _this.options.noneSelectedText;
}
_this.$newElement.find('.filter-option').html( title );
},
setSize:function() {
var _this = this;
var menu = this.$newElement.find('.dropdown-menu');
var menuA = menu.find('li > a');
var liHeight = this.$newElement.addClass('open').find('.dropdown-menu li > a').outerHeight();
this.$newElement.removeClass('open');
var divHeight = menu.find('li .divider').outerHeight(true);
var selectOffset_top = this.$newElement.offset().top;
var selectHeight = this.$newElement.outerHeight();
var menuPadding = parseInt(menu.css('padding-top')) + parseInt(menu.css('padding-bottom')) + parseInt(menu.css('border-top-width')) + parseInt(menu.css('border-bottom-width'));
if (this.options.size == 'auto') {
function getSize() {
var selectOffset_top_scroll = selectOffset_top - $(window).scrollTop();
var windowHeight = window.innerHeight;
var menuExtras = menuPadding + parseInt(menu.css('margin-top')) + parseInt(menu.css('margin-bottom')) + 2;
var selectOffset_bot = windowHeight - selectOffset_top_scroll - selectHeight - menuExtras;
menuHeight = selectOffset_bot;
if (_this.$newElement.hasClass('dropup')) {
menuHeight = selectOffset_top_scroll - menuExtras;
}
if ((menu.find('li').length + menu.find('dt').length) > 3) {
minHeight = liHeight*3 + menuExtras - 2;
} else {
minHeight = 0;
}
menu.css({'max-height' : menuHeight + 'px', 'overflow-y' : 'auto', 'min-height' : minHeight + 'px'});
}
getSize();
$(window).resize(getSize);
$(window).scroll(getSize);
} else if (this.options.size && this.options.size != 'auto' && menu.find('li').length > this.options.size) {
var optIndex = menu.find("li > *").filter(':not(.div-contain)').slice(0,this.options.size).last().parent().index();
var divLength = menu.find("li").slice(0,optIndex + 1).find('.div-contain').length;
menuHeight = liHeight*this.options.size + divLength*divHeight + menuPadding;
menu.css({'max-height' : menuHeight + 'px', 'overflow-y' : 'auto'});
}

//Set width of select
if (this.options.width == 'auto') {
this.$newElement.find('.dropdown-menu').css('min-width','0');
var ulWidth = this.$newElement.find('.dropdown-menu').css('width');
this.$newElement.css('width',ulWidth);
if (this.options.container) {
this.$element.css('width',ulWidth);
}
} else if (this.options.width && this.options.width != 'auto') {
this.$newElement.css('width',this.options.width);
if (this.options.container) {
this.$element.css('width',this.options.width);
}
}
},

selectPosition:function() {
var selectElementTop = this.$element.offset().top;
var selectElementLeft = this.$element.offset().left;
this.$newElement.appendTo(this.options.container);
this.$newElement.css({'position':'absolute', 'top':selectElementTop+'px', 'left':selectElementLeft+'px'});
},

refresh:function() {
this.reloadLi();
this.render();
this.setSize();
this.checkDisabled();
if (this.options.container) {
this.selectPosition();
}
},
setSelected:function(index, selected) {
if(selected) {
this.$newElement.find('li').eq(index).addClass('selected');
} else {
this.$newElement.find('li').eq(index).removeClass('selected');
}
},
setDisabled:function(index, disabled) {
if(disabled) {
this.$newElement.find('li').eq(index).addClass('disabled');
} else {
this.$newElement.find('li').eq(index).removeClass('disabled');
}
},

isDisabled: function() {
return this.$element.is(':disabled') || this.$element.attr('readonly');
},
checkDisabled: function() {
if (this.isDisabled()) {
this.button.addClass('disabled');
this.button.click(function(e) {
e.preventDefault();
});
this.button.attr('tabindex','-1');
} else if (!this.isDisabled() && this.button.hasClass('disabled')) {
this.button.removeClass('disabled');
this.button.click(function() {
return true;
});
this.button.removeAttr('tabindex');
}
},
checkTabIndex: function() {
if (this.$element.is('[tabindex]')) {
var tabindex = this.$element.attr("tabindex");
this.button.attr('tabindex', tabindex);
}
},
clickListener: function() {
var _this = this;
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });

this.$newElement.on('click', 'li a', function(e){
var clickedIndex = $(this).parent().index(),
$this = $(this).parent(),
$select = $this.parents('.bootstrap-select'),
prevValue = _this.$element.val();
//Dont close on multi choice menu
if(_this.multiple) {
e.stopPropagation();
}
e.preventDefault();
//Dont run if we have been disabled
if (_this.$element.not(':disabled') && !$(this).parent().hasClass('disabled')){
//Deselect all others if not multi select box
if (!_this.multiple) {
_this.$element.find('option').removeAttr('selected');
_this.$element.find('option').eq(clickedIndex).prop('selected', true).attr('selected', 'selected');
}
//Else toggle the one we have chosen if we are multi selet.
else {
var selected = _this.$element.find('option').eq(clickedIndex).prop('selected');
if(selected) {
_this.$element.find('option').eq(clickedIndex).removeAttr('selected');
} else {
_this.$element.find('option').eq(clickedIndex).prop('selected', true).attr('selected', 'selected');
}
}
$select.find('.filter-option').html($this.text());
$select.find('button').focus();

// Trigger select 'change'
if (prevValue != _this.$element.val()) {
_this.$element.trigger('change');
}

_this.render();
}

});
this.$newElement.on('click', 'li.disabled a, li dt, li .div-contain', function(e) {
e.preventDefault();
e.stopPropagation();
$select = $(this).parent().parents('.bootstrap-select');
$select.find('button').focus();
});

this.$element.on('change', function(e) {
_this.render();
});
},
val:function(value) {
if(value!=undefined) {
this.$element.val( value );
this.$element.trigger('change');
return this.$element;
} else {
return this.$element.val();
}
},
selectAll:function() {
this.$element.find('option').prop('selected', true).attr('selected', 'selected');
this.render();
},
deselectAll:function() {
this.$element.find('option').prop('selected', false).removeAttr('selected');
this.render();
},

};

$.fn.selectpicker = function(option, event) {
//get the args of the outer function..
var args = arguments;
var value;
var chain = this.each(function () {
if ($(this).is('select')) {
var $this = $(this),
data = $this.data('selectpicker'),
options = typeof option == 'object' && option;
if (!data) {
$this.data('selectpicker', (data = new Selectpicker(this, options, event)));
} else if(options){
for(var i in options) {
data.options[i]=options[i];
}
}
if (typeof option == 'string') {
//Copy the value of option, as once we shift the arguments
//it also shifts the value of option.
property = option;
if(data[property] instanceof Function) {
[].shift.apply(args);
value = data[property].apply(data, args);
} else {
value = data.options[property];
}
}
}
});
if(value!=undefined) {
return value;
} else {
return chain;
}
};

$.fn.selectpicker.defaults = {
style: null,
size: 'auto',
title: null,
selectedTextFormat : 'values',
noneSelectedText : 'Nothing selected',
width: null,
container: false,
icon: false
}

}(window.jQuery);

+ 622
- 0
Teknik/Scripts/bootstrap/tags/bootstrap-tags.js View File

@@ -0,0 +1,622 @@
/*!
* bootstrap-tags 1.1.5
* https://github.com/maxwells/bootstrap-tags
* Copyright 2013 Max Lahey; Licensed MIT
*/

(function($) {
(function() {
window.Tags || (window.Tags = {});
jQuery(function() {
$.tags = function(element, options) {
var key, tag, tagData, value, _i, _len, _ref, _this = this;
if (options == null) {
options = {};
}
for (key in options) {
value = options[key];
this[key] = value;
}
this.bootstrapVersion || (this.bootstrapVersion = "3");
this.readOnly || (this.readOnly = false);
this.suggestOnClick || (this.suggestOnClick = false);
this.suggestions || (this.suggestions = []);
this.restrictTo = options.restrictTo != null ? options.restrictTo.concat(this.suggestions) : false;
this.exclude || (this.exclude = false);
this.displayPopovers = options.popovers != null ? true : options.popoverData != null;
this.popoverTrigger || (this.popoverTrigger = "hover");
this.tagClass || (this.tagClass = "btn-info");
this.tagSize || (this.tagSize = "md");
this.promptText || (this.promptText = "Enter tags...");
this.caseInsensitive || (this.caseInsensitive = false);
this.readOnlyEmptyMessage || (this.readOnlyEmptyMessage = "No tags to display...");
this.maxNumTags || (this.maxNumTags = -1);
this.beforeAddingTag || (this.beforeAddingTag = function(tag) {});
this.afterAddingTag || (this.afterAddingTag = function(tag) {});
this.beforeDeletingTag || (this.beforeDeletingTag = function(tag) {});
this.afterDeletingTag || (this.afterDeletingTag = function(tag) {});
this.definePopover || (this.definePopover = function(tag) {
return 'associated content for "' + tag + '"';
});
this.excludes || (this.excludes = function() {
return false;
});
this.tagRemoved || (this.tagRemoved = function(tag) {});
this.pressedReturn || (this.pressedReturn = function(e) {});
this.pressedDelete || (this.pressedDelete = function(e) {});
this.pressedDown || (this.pressedDown = function(e) {});
this.pressedUp || (this.pressedUp = function(e) {});
this.$element = $(element);
if (options.tagData != null) {
this.tagsArray = options.tagData;
} else {
tagData = $(".tag-data", this.$element).html();
this.tagsArray = tagData != null ? tagData.split(",") : [];
}
if (options.popoverData) {
this.popoverArray = options.popoverData;
} else {
this.popoverArray = [];
_ref = this.tagsArray;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
tag = _ref[_i];
this.popoverArray.push(null);
}
}
this.getTags = function() {
return _this.tagsArray;
};
this.getTagsContent = function() {
return _this.popoverArray;
};
this.getTagsWithContent = function() {
var combined, i, _j, _ref1;
combined = [];
for (i = _j = 0, _ref1 = _this.tagsArray.length - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
combined.push({
tag: _this.tagsArray[i],
content: _this.popoverArray[i]
});
}
return combined;
};
this.getTag = function(tag) {
var index;
index = _this.tagsArray.indexOf(tag);
if (index > -1) {
return _this.tagsArray[index];
} else {
return null;
}
};
this.getTagWithContent = function(tag) {
var index;
index = _this.tagsArray.indexOf(tag);
return {
tag: _this.tagsArray[index],
content: _this.popoverArray[index]
};
};
this.hasTag = function(tag) {
return _this.tagsArray.indexOf(tag) > -1;
};
this.removeTagClicked = function(e) {
if (e.currentTarget.tagName === "A") {
_this.removeTag($("span", e.currentTarget.parentElement).html());
$(e.currentTarget.parentNode).remove();
}
return _this;
};
this.removeLastTag = function() {
if (_this.tagsArray.length > 0) {
_this.removeTag(_this.tagsArray[_this.tagsArray.length - 1]);
if (_this.canAddByMaxNum()) {
_this.enableInput();
}
}
return _this;
};
this.removeTag = function(tag) {
if (_this.tagsArray.indexOf(tag) > -1) {
if (_this.beforeDeletingTag(tag) === false) {
return;
}
_this.popoverArray.splice(_this.tagsArray.indexOf(tag), 1);
_this.tagsArray.splice(_this.tagsArray.indexOf(tag), 1);
_this.renderTags();
_this.afterDeletingTag(tag);
if (_this.canAddByMaxNum()) {
_this.enableInput();
}
}
return _this;
};
this.canAddByRestriction = function(tag) {
return this.restrictTo === false || this.restrictTo.indexOf(tag) !== -1;
};
this.canAddByExclusion = function(tag) {
return (this.exclude === false || this.exclude.indexOf(tag) === -1) && !this.excludes(tag);
};
this.canAddByMaxNum = function() {
return this.maxNumTags === -1 || this.tagsArray.length < this.maxNumTags;
};
this.addTag = function(tag) {
var associatedContent;
if (_this.canAddByRestriction(tag) && !_this.hasTag(tag) && tag.length > 0 && _this.canAddByExclusion(tag) && _this.canAddByMaxNum()) {
if (_this.beforeAddingTag(tag) === false) {
return;
}
associatedContent = _this.definePopover(tag);
_this.popoverArray.push(associatedContent || null);
_this.tagsArray.push(tag);
_this.afterAddingTag(tag);
_this.renderTags();
if (!_this.canAddByMaxNum()) {
_this.disableInput();
}
}
return _this;
};
this.addTagWithContent = function(tag, content) {
if (_this.canAddByRestriction(tag) && !_this.hasTag(tag) && tag.length > 0) {
if (_this.beforeAddingTag(tag) === false) {
return;
}
_this.tagsArray.push(tag);
_this.popoverArray.push(content);
_this.afterAddingTag(tag);
_this.renderTags();
}
return _this;
};
this.renameTag = function(name, newName) {
_this.tagsArray[_this.tagsArray.indexOf(name)] = newName;
_this.renderTags();
return _this;
};
this.setPopover = function(tag, popoverContent) {
_this.popoverArray[_this.tagsArray.indexOf(tag)] = popoverContent;
_this.renderTags();
return _this;
};
this.clickHandler = function(e) {
return _this.makeSuggestions(e, true);
};
this.keyDownHandler = function(e) {
var k, numSuggestions;
k = e.keyCode != null ? e.keyCode : e.which;
switch (k) {
case 13:
e.preventDefault();
_this.pressedReturn(e);
tag = e.target.value;
if (_this.suggestedIndex !== -1) {
tag = _this.suggestionList[_this.suggestedIndex];
}
_this.addTag(tag);
e.target.value = "";
_this.renderTags();
return _this.hideSuggestions();

case 46:
case 8:
_this.pressedDelete(e);
if (e.target.value === "") {
_this.removeLastTag();
}
if (e.target.value.length === 1) {
return _this.hideSuggestions();
}
break;

case 40:
_this.pressedDown(e);
if (_this.input.val() === "" && (_this.suggestedIndex === -1 || _this.suggestedIndex == null)) {
_this.makeSuggestions(e, true);
}
numSuggestions = _this.suggestionList.length;
_this.suggestedIndex = _this.suggestedIndex < numSuggestions - 1 ? _this.suggestedIndex + 1 : numSuggestions - 1;
_this.selectSuggested(_this.suggestedIndex);
if (_this.suggestedIndex >= 0) {
return _this.scrollSuggested(_this.suggestedIndex);
}
break;

case 38:
_this.pressedUp(e);
_this.suggestedIndex = _this.suggestedIndex > 0 ? _this.suggestedIndex - 1 : 0;
_this.selectSuggested(_this.suggestedIndex);
if (_this.suggestedIndex >= 0) {
return _this.scrollSuggested(_this.suggestedIndex);
}
break;

case 9:
case 27:
_this.hideSuggestions();
return _this.suggestedIndex = -1;
}
};
this.keyUpHandler = function(e) {
var k;
k = e.keyCode != null ? e.keyCode : e.which;
if (k !== 40 && k !== 38 && k !== 27) {
return _this.makeSuggestions(e, false);
}
};
this.getSuggestions = function(str, overrideLengthCheck) {
var _this = this;
this.suggestionList = [];
if (this.caseInsensitive) {
str = str.toLowerCase();
}
$.each(this.suggestions, function(i, suggestion) {
var suggestionVal;
suggestionVal = _this.caseInsensitive ? suggestion.substring(0, str.length).toLowerCase() : suggestion.substring(0, str.length);
if (_this.tagsArray.indexOf(suggestion) < 0 && suggestionVal === str && (str.length > 0 || overrideLengthCheck)) {
return _this.suggestionList.push(suggestion);
}
});
return this.suggestionList;
};
this.makeSuggestions = function(e, overrideLengthCheck, val) {
if (val == null) {
val = e.target.value != null ? e.target.value : e.target.textContent;
}
_this.suggestedIndex = -1;
_this.$suggestionList.html("");
$.each(_this.getSuggestions(val, overrideLengthCheck), function(i, suggestion) {
return _this.$suggestionList.append(_this.template("tags_suggestion", {
suggestion: suggestion
}));
});
_this.$(".tags-suggestion").mouseover(_this.selectSuggestedMouseOver);
_this.$(".tags-suggestion").click(_this.suggestedClicked);
if (_this.suggestionList.length > 0) {
return _this.showSuggestions();
} else {
return _this.hideSuggestions();
}
};
this.suggestedClicked = function(e) {
tag = e.target.textContent;
if (_this.suggestedIndex !== -1) {