<commit_before>"use strict";

window.bmatFn = function() {
    var bmat = {};

    var disabledForms = [];

    var undoCallback = null;

    var searchCount = 0;

    // Error handling
    var _error = function(message) {
        $("#error .errorText").html(message);
        $("#error").slideDown();
    }

    $(document).ajaxError(function(e, xhr, settings, error) {
        if("responseJSON" in xhr && "error" in xhr.responseJSON) {
            _error(xhr.responseJSON.error);
        }else{
            _error("ERROR: "+error);
        }

        _enableAllForms();
    });

    window.addEventListener("error", function(e) {
        _error(e.message);
    });

    // Function that finds the form this element is in, and submits it
    var _submitParent = function() {
        $(this).parents("form").submit();
        _disableForm(this);
    };

    // And a function that disables a form
    var _disableForm = function(e) {
        $(e).parents(".block").addClass("disabled");
        $(e).parents(".block").find("input, select").attr("disabled", "disabled");
        $(e).find("input, select").attr("disabled", "disabled");
        disabledForms.push(e);
    };

    // And to enable all of them again
    var _enableAllForms = function() {
        for(var i = 0; i < disabledForms.length; i ++) {
            var f = disabledForms[i];

            $(f).parents(".block").removeClass("disabled");
            $(f).parents(".block").find("input, select").removeAttr("disabled");
        }
        disabledForms = [];
    };

    // And the undo thing
    var _displayUndo = function(message, url, payload, callback) {
        $("#undo .undoText").html(message);
        $("#undo").slideDown();

        $("#undoForm [name=obj]").val(JSON.stringify(payload));
        $("#undoForm").attr("action", url);
        undoCallback = callback;

        $("#undoForm").find("input, select").removeAttr("disabled");
    };

    // Resets all the listeners, used when a document has been changed or initially loaded
    var _update = function() {
        // Remove all the old listeners
        _clean();

        // Delete button
        $(".block .delete.button").on("click", _submitParent);
        $(".deleteForm").on("submit", function(e) {
            e.preventDefault();

            var elem = $(this);
            var id = elem.parents(".block").attr("data-id");

            //if(!confirm("Are you sure you want to delete this?")) return;

            $.post(elem.attr("action"), elem.serialize(), function(data) {
                if(data.deleted !== null) {
                    elem.parents(".block").slideUp();

                    _displayUndo("Object deleted", elem.attr("data-undo-url"), data.obj, function(dat) {
                        _replace(id, dat.type, false, true, dat.id);
                    });
                }
            });
        });

        // Inline untag button
        $(".inlineUntag.button").on("click", _submitParent);
        $(".inlineUntagForm").on("submit", function(e) {
            e.preventDefault();
            var elem = this;

            var bookmark = $(this).parents(".block").data("id");

            $.post(this.getAttribute("action"), $(this).serialize(), function(data) {
                _replace(bookmark, $(elem).parents(".block").data("taggable-type"), true);
            }, "json");

            _disableForm(this);
        });

        // Open/close button
        $(".expand.button").on("click", function() {
            if($(this).hasClass("open")) {
                $(this).parents(".block").children(".body").slideUp("fast");
                $(this).parents(".block").find(".inlineUntag").animate({"width":"0px"}, "fast");
                $(this).removeClass("open");
                _hideEditing($(this).parents(".block"));
            }else{
                $(this).parents(".block").children(".body").slideDown("fast");
                $(this).parents(".block").find(".inlineUntag").animate({"width":"16px"}, "fast");
                $(this).addClass("open");
            }
        });

        // "Add tag" entry, for generating suggestions
        $(".tagEntry").on("input", function(e) {
            var input = this;

            // Don't bother with text less than 3 characters
            if(e.target.value.length < 3) return;

            // Get the suggestion list, and set the option elemnt to contain it
            $.get("/tags/suggest/"+e.target.value, "", function(data) {
                var html = "";

                for(var i = 0; i < data.tags.length; i ++) {
                    html += "<option value='"+data.tags[i]+"'/>";
                }

                $(input).siblings("datalist").html(html);
            }, "json");
        });

        // Title editing; hides the "real title" and replaces it with the text box, or the opposite
        var _showEditing = function(e) {
            $(e).find(".noedit").hide();
            $(e).find(".edit").show();
            $(e).addClass("editing");
        };

        var _hideEditing = function(e) {
            $(e).find(".noedit").show();
            $(e).find(".edit").hide();
            $(e).removeClass("editing");
        };

        $(".editTitle").on("click", function(e) {
            var block = $(this).parents(".block");

            if(!block.hasClass("editing")) {
                _showEditing(block);
            }else{
                _hideEditing(block);
            }
        });

        // Rename and tag forms, both do the same thing and both result in updating the block
        $(".rename.button").on("click", function() {
            var form = $(this).parents(".block").find(".renameForm");
            form.submit();
            _disableForm(form);
        });
        $("form.tagForm, form.renameForm").on("submit", function(e) {
            e.preventDefault();
            var elem = this;
            $(this).find("input[name=url]").val(
                $(elem).parents(".block").find(".body input[name=url]").val()
            );

            $.post(this.getAttribute("action"), $(this).serialize(), function(data) {
                _replace($(elem).parents(".block").data("id"), $(elem).parents(".block").data("taggable-type"), true);
            }, "json");
        });

        // And the submit button for the add tag button
        $(".addTag.button").on("click", function(e) {
            $(this).parents(".block").find(".tagForm").submit();
        });
    };

    // Removes all listeners
    var _clean = function() {
        $(".delete.button").off();
        $(".untag.button").off();
        $(".inlineUntag.button").off();
        $(".inlineUntagForm").off();
        $(".expand.button").off();
        $(".tagEntry").off();

        $(".addTag.button").off();
        $("form.tagForm").off();

        $(".rename.button").off();
        $("form.renameForm").off();

        $(".editTitle").off();
    };

    // Downloads a bookmark by an id and adds it to the list; used when adding a new one
    var _prependBookmark = function(id) {
        $.get("/bookmarks/"+id+"/html", function(e) {
            $("#bookmark-list").prepend(e);
            _update();
        }, "text");
    };

    // Given an id and a type, downloads a new version of the specific block and replaces them
    // If expand is true, then they are expanded as if the user had clicked the expand button
    var _replace = function(id, type, expand, slide, newid) {
        if(newid == undefined) newid = id;
        var url = "";
        if(type == "tag") url = "/tags/htmlBlock/" + newid;
        if(type == "bookmark") url = "/bookmarks/" + newid + "/html";

        $.get(url, function(e) {
            $(".block[data-id="+id+"]").replaceWith(e);
            if(expand) {
                $(".block[data-id="+id+"][data-taggable-type="+type+"] > .body").show();
                $(".block[data-id="+id+"][data-taggable-type="+type+"] .expand.button").addClass("open");
                $(".block[data-id="+id+"][data-taggable-type="+type+"] .inlineUntag")
                    .css("width", "16px").css("display", "inline-block");
                $(".block[data-id="+id+"][data-taggable-type="+type+"] input")[0].focus();
            }
            if(slide) {
                $(".block[data-id="+newid+"][data-taggable-type="+type+"]").css("display", "none");
                $(".block[data-id="+newid+"][data-taggable-type="+type+"]").slideDown();
            }
            _update();
        }, "text");
    };

    // Add the listeners on initial load
    var _ready = function() {
        // Bookmark adding
        $("#add-bookmark").on("submit", function(e) {
            e.preventDefault();
            $.post("/bookmarks/add", $(this).serialize(), function(e) {
                _prependBookmark(e.id);
                $("#add-bookmark > input[name=url]")[0].value = "";
            }, "json");
        });

        // Error closing
        $("#error .close.button").on("click", function(e) {
            $(this).parents("#error").slideUp();
        });

        // Multitag expand
        $(".multiTag.button").on("click", function(e) {
            if($(this).hasClass("open")) {
                $(this).removeClass("open");
                $(".multiTagCheck").animate({width:"0px", marginRight:"0px", marginLeft:"0px"}, 350);
                $(".multiTagForm").fadeOut();
            }else{
                $(this).addClass("open");
                $(".multiTagCheck").animate({width:"16px", marginRight:"5px", marginLeft:"5px"}, 350);
                $(".multiTagForm").fadeIn();
            }
        });

        $(".multiTagForm").on("submit", function(e) {
            e.preventDefault();
            var tag = $(this).find("[name=name]").val();
            var colour = $(this).find("[name=colour]").val();

            $(".multiTagCheck:checked").parents(".block").find(".tagForm").each(function(i, node) {
                $(node).find("[name=name]").val(tag);
                $(node).find("[name=colour]").val(colour);
                $(node).submit();
            });
        });

        // And handle undo
        $("#undo").on("submit", function(e) {
            e.preventDefault();

            var elem = $(this).find("form");

            $.post(elem.attr("action"), elem.serialize(), function(data) {
                undoCallback(data);
            }, "json");

            _disableForm(elem);

            $("#undo").slideUp();
        });

        $("#undo .close.button").on("click", function(e) {
            $(this).parents("#undo").slideUp();
        });

        // And handle the pinning form
        $("#pinForm").on("submit", function(e) {
            e.preventDefault();

            var elem = $(this);

            $.post(elem.attr("action"), elem.serialize(), function(data) {
                document.location.reload();
            }, "json");

            _disableForm(elem);
        });

        // Search page
        $("#search-form input[name=q]").on("input", function(e) {
            var query = e.originalEvent.target.value;

            searchCount ++;
            var localSearchCount = searchCount;

            if("replaceState" in history) {
                history.replaceState({}, "", "?q="+encodeURIComponent(query).replace(/%20/gi, "+"));
            }

            $.get($("#search-form").attr("data-results"), $("#search-form").serialize(), function(results) {
                if(searchCount == localSearchCount) {
                    $("#search-results").html(results);
                    _update();
                }
            }, "html");
        });
    };

    // These two are ran on page load
    $(_ready);
    $(_update);

    return bmat;
};

window.bmatCheckReady = function() {
    if("$" in window) {
        window.bmat = window.bmatFn();
    }else{
        setTimeout(window.bmatCheckReady, 100);
    }
}

bmatCheckReady();
<commit_msg>_replace now reads the apperance of the old block<commit_after>"use strict";

window.bmatFn = function() {
    var bmat = {};

    var disabledForms = [];

    var undoCallback = null;

    var searchCount = 0;

    // Error handling
    var _error = function(message) {
        $("#error .errorText").html(message);
        $("#error").slideDown();
    }

    $(document).ajaxError(function(e, xhr, settings, error) {
        if("responseJSON" in xhr && "error" in xhr.responseJSON) {
            _error(xhr.responseJSON.error);
        }else{
            _error("ERROR: "+error);
        }

        _enableAllForms();
    });

    window.addEventListener("error", function(e) {
        _error(e.message);
    });

    // Function that finds the form this element is in, and submits it
    var _submitParent = function() {
        $(this).parents("form").submit();
        _disableForm(this);
    };

    // And a function that disables a form
    var _disableForm = function(e) {
        $(e).parents(".block").addClass("disabled");
        $(e).parents(".block").find("input, select").attr("disabled", "disabled");
        $(e).find("input, select").attr("disabled", "disabled");
        disabledForms.push(e);
    };

    // And to enable all of them again
    var _enableAllForms = function() {
        for(var i = 0; i < disabledForms.length; i ++) {
            var f = disabledForms[i];

            $(f).parents(".block").removeClass("disabled");
            $(f).parents(".block").find("input, select").removeAttr("disabled");
        }
        disabledForms = [];
    };

    // And the undo thing
    var _displayUndo = function(message, url, payload, callback) {
        $("#undo .undoText").html(message);
        $("#undo").slideDown();

        $("#undoForm [name=obj]").val(JSON.stringify(payload));
        $("#undoForm").attr("action", url);
        undoCallback = callback;

        $("#undoForm").find("input, select").removeAttr("disabled");
    };

    // Resets all the listeners, used when a document has been changed or initially loaded
    var _update = function() {
        // Remove all the old listeners
        _clean();

        // Delete button
        $(".block .delete.button").on("click", _submitParent);
        $(".deleteForm").on("submit", function(e) {
            e.preventDefault();

            var elem = $(this);
            var id = elem.parents(".block").attr("data-id");

            //if(!confirm("Are you sure you want to delete this?")) return;

            $.post(elem.attr("action"), elem.serialize(), function(data) {
                if(data.deleted !== null) {
                    elem.parents(".block").slideUp();

                    _displayUndo("Object deleted", elem.attr("data-undo-url"), data.obj, function(dat) {
                        _replace(id, dat.type, false, true, dat.id);
                    });
                }
            });
        });

        // Inline untag button
        $(".inlineUntag.button").on("click", _submitParent);
        $(".inlineUntagForm").on("submit", function(e) {
            e.preventDefault();
            var elem = this;

            var bookmark = $(this).parents(".block").data("id");

            $.post(this.getAttribute("action"), $(this).serialize(), function(data) {
                _replace(bookmark, $(elem).parents(".block").data("taggable-type"), true);
            }, "json");

            _disableForm(this);
        });

        // Open/close button
        $(".expand.button").on("click", function() {
            if($(this).hasClass("open")) {
                $(this).parents(".block").children(".body").slideUp("fast");
                $(this).parents(".block").find(".inlineUntag").animate({"width":"0px"}, "fast");
                $(this).removeClass("open");
                _hideEditing($(this).parents(".block"));
            }else{
                $(this).parents(".block").children(".body").slideDown("fast");
                $(this).parents(".block").find(".inlineUntag").animate({"width":"16px"}, "fast");
                $(this).addClass("open");
            }
        });

        // "Add tag" entry, for generating suggestions
        $(".tagEntry").on("input", function(e) {
            var input = this;

            // Don't bother with text less than 3 characters
            if(e.target.value.length < 3) return;

            // Get the suggestion list, and set the option elemnt to contain it
            $.get("/tags/suggest/"+e.target.value, "", function(data) {
                var html = "";

                for(var i = 0; i < data.tags.length; i ++) {
                    html += "<option value='"+data.tags[i]+"'/>";
                }

                $(input).siblings("datalist").html(html);
            }, "json");
        });

        // Title editing; hides the "real title" and replaces it with the text box, or the opposite
        var _showEditing = function(e) {
            $(e).find(".noedit").hide();
            $(e).find(".edit").show();
            $(e).addClass("editing");
        };

        var _hideEditing = function(e) {
            $(e).find(".noedit").show();
            $(e).find(".edit").hide();
            $(e).removeClass("editing");
        };

        $(".editTitle").on("click", function(e) {
            var block = $(this).parents(".block");

            if(!block.hasClass("editing")) {
                _showEditing(block);
            }else{
                _hideEditing(block);
            }
        });

        // Rename and tag forms, both do the same thing and both result in updating the block
        $(".rename.button").on("click", function() {
            var form = $(this).parents(".block").find(".renameForm");
            form.submit();
            _disableForm(form);
        });
        $("form.tagForm, form.renameForm").on("submit", function(e) {
            e.preventDefault();
            var elem = this;
            $(this).find("input[name=url]").val(
                $(elem).parents(".block").find(".body input[name=url]").val()
            );

            $.post(this.getAttribute("action"), $(this).serialize(), function(data) {
                _replace($(elem).parents(".block").data("id"), $(elem).parents(".block").data("taggable-type"), true);
            }, "json");
        });

        // And the submit button for the add tag button
        $(".addTag.button").on("click", function(e) {
            $(this).parents(".block").find(".tagForm").submit();
        });
    };

    // Removes all listeners
    var _clean = function() {
        $(".delete.button").off();
        $(".untag.button").off();
        $(".inlineUntag.button").off();
        $(".inlineUntagForm").off();
        $(".expand.button").off();
        $(".tagEntry").off();

        $(".addTag.button").off();
        $("form.tagForm").off();

        $(".rename.button").off();
        $("form.renameForm").off();

        $(".editTitle").off();
    };

    // Downloads a bookmark by an id and adds it to the list; used when adding a new one
    var _prependBookmark = function(id) {
        $.get("/bookmarks/"+id+"/html", function(e) {
            $("#bookmark-list").prepend(e);
            _update();
        }, "text");
    };

    // Given an id and a type, downloads a new version of the specific block and replaces them
    var _replace = function(id, type, unused, slide, newid) {
        if(newid == undefined) newid = id;
        var url = "";
        if(type == "tag") url = "/tags/htmlBlock/" + newid;
        if(type == "bookmark") url = "/bookmarks/" + newid + "/html";

        var displayMultiCheck = $(".block[data-id="+id+"] .multiTagCheck").css("width") == "16px";
        var multiChecked = $(".block[data-id="+id+"] .multiTagCheck:checked").length > 0;
        var expand = $(".block[data-id="+id+"] .expand.open").length > 0;

        $.get(url, function(e) {
            $(".block[data-id="+id+"]").replaceWith(e);
            if(expand) {
                $(".block[data-id="+id+"][data-taggable-type="+type+"] > .body").show();
                $(".block[data-id="+id+"][data-taggable-type="+type+"] .expand.button").addClass("open");
                $(".block[data-id="+id+"][data-taggable-type="+type+"] .inlineUntag")
                    .css("width", "16px").css("display", "inline-block");
                $(".block[data-id="+id+"][data-taggable-type="+type+"] input")[0].focus();
            }
            if(slide) {
                $(".block[data-id="+newid+"][data-taggable-type="+type+"]").css("display", "none");
                $(".block[data-id="+newid+"][data-taggable-type="+type+"]").slideDown();
            }

            if(displayMultiCheck) {
                $(".block[data-id="+newid+"] .multiTagCheck")
                    .css("width", "16px").css("margin-left", "5px").css("margin-right", "5px");
            }
            if(multiChecked) {
                $(".block[data-id="+newid+"] .multiTagCheck").prop("checked", true);
            }
            _update();
        }, "text");
    };

    // Add the listeners on initial load
    var _ready = function() {
        // Bookmark adding
        $("#add-bookmark").on("submit", function(e) {
            e.preventDefault();
            $.post("/bookmarks/add", $(this).serialize(), function(e) {
                _prependBookmark(e.id);
                $("#add-bookmark > input[name=url]")[0].value = "";
            }, "json");
        });

        // Error closing
        $("#error .close.button").on("click", function(e) {
            $(this).parents("#error").slideUp();
        });

        // Multitag expand
        $(".multiTag.button").on("click", function(e) {
            if($(this).hasClass("open")) {
                $(this).removeClass("open");
                $(".multiTagCheck").animate({width:"0px", marginRight:"0px", marginLeft:"0px"}, 350);
                $(".multiTagForm").fadeOut();
            }else{
                $(this).addClass("open");
                $(".multiTagCheck").animate({width:"16px", marginRight:"5px", marginLeft:"5px"}, 350);
                $(".multiTagForm").fadeIn();
            }
        });

        $(".multiTagForm").on("submit", function(e) {
            e.preventDefault();
            var tag = $(this).find("[name=name]").val();
            var colour = $(this).find("[name=colour]").val();

            $(".multiTagCheck:checked").parents(".block").find(".tagForm").each(function(i, node) {
                $(node).find("[name=name]").val(tag);
                $(node).find("[name=colour]").val(colour);
                $(node).submit();
            });
        });

        // And handle undo
        $("#undo").on("submit", function(e) {
            e.preventDefault();

            var elem = $(this).find("form");

            $.post(elem.attr("action"), elem.serialize(), function(data) {
                undoCallback(data);
            }, "json");

            _disableForm(elem);

            $("#undo").slideUp();
        });

        $("#undo .close.button").on("click", function(e) {
            $(this).parents("#undo").slideUp();
        });

        // And handle the pinning form
        $("#pinForm").on("submit", function(e) {
            e.preventDefault();

            var elem = $(this);

            $.post(elem.attr("action"), elem.serialize(), function(data) {
                document.location.reload();
            }, "json");

            _disableForm(elem);
        });

        // Search page
        $("#search-form input[name=q]").on("input", function(e) {
            var query = e.originalEvent.target.value;

            searchCount ++;
            var localSearchCount = searchCount;

            if("replaceState" in history) {
                history.replaceState({}, "", "?q="+encodeURIComponent(query).replace(/%20/gi, "+"));
            }

            $.get($("#search-form").attr("data-results"), $("#search-form").serialize(), function(results) {
                if(searchCount == localSearchCount) {
                    $("#search-results").html(results);
                    _update();
                }
            }, "html");
        });
    };

    // These two are ran on page load
    $(_ready);
    $(_update);

    return bmat;
};

window.bmatCheckReady = function() {
    if("$" in window) {
        window.bmat = window.bmatFn();
    }else{
        setTimeout(window.bmatCheckReady, 100);
    }
}

bmatCheckReady();
<|endoftext|>


<commit_before>/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

Event.observe(window, 'load', initialize, false);
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		this.content = ctrl.href;
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
	},

	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
	},

	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;

		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow;
	},

	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},

	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop;
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},

	setScroll: function(x, y){
		window.scrollTo(x, y);
	},

	displayLightbox: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none') this.loadInfo();
	},

	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);

	},

	// Display Ajax response
	processInfo: function(response){
		info = "
" + response.responseText + "
";
		new Insertion.Before($('lbLoadMessage'), info)
		$('lightbox').className = "done";
		this.actions();
	},

	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},

	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
	   link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));

	   var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );

	},

	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		Element.remove($('lbContent'));

		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}

		this.displayLightbox("none");
	}
}

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i]);
	}
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	lb.className 	= 'loading';
	lb.innerHTML	= '
' +
						  '
Loading
' +
						  '
';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}<commit_msg>Pasted in official version from site.<commit_after>/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

Event.observe(window, 'load', initialize, false);
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		this.content = ctrl.href;
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
	},

	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
	},

	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;

		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow;
	},

	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},

	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop;
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},

	setScroll: function(x, y){
		window.scrollTo(x, y);
	},

	displayLightbox: function(display){
        $('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none') this.loadInfo();
	},

	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);

	},

	// Display Ajax response
	processInfo: function(response){
		info = "
" + response.responseText + "
";
		new Insertion.Before($('lbLoadMessage'), info)
		$('lightbox').className = "done";
		this.actions();
	},

	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},

	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
	   link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));

	   var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );

	},

	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		Element.remove($('lbContent'));

		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}

		this.displayLightbox("none");
	}
}

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i]);
	}
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	lb.className 	= 'loading';
	lb.innerHTML	= '
' +
						  '
Loading
' +
						  '
';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import Const from './Const';
import Util from './util';
import classSet from 'classnames';
import SelectRowHeaderColumn from './SelectRowHeaderColumn';

class Checkbox extends React.Component{
  componentDidMount() { this.update(this.props.checked); }
  componentWillReceiveProps(props) { this.update(props.checked); }
  update(checked) {
    ReactDOM.findDOMNode(this).indeterminate = checked === 'indeterminate';
  }

  render() {
    return <input type="checkbox" checked={this.props.checked} onChange={this.props.onChange} />
  }
}

class TableHeader extends React.Component{

  constructor(props) {
    super(props);
    this.selectRowColumnWidth = null;
  }

  render(){
    var containerClasses = classSet("table-header");
    var tableClasses = classSet("table", "table-hover", {
        "table-bordered": this.props.bordered,
        "table-condensed": this.props.condensed
    });
    var selectRowHeaderCol = this.props.hideSelectColumn?null:this.renderSelectRowHeader();
    this._attachClearSortCaretFunc();

    return(

                {selectRowHeaderCol}
                {this.props.children}

    )
  }

  renderSelectRowHeader(){
    if(this.props.rowSelectType == Const.ROW_SELECT_SINGLE) {
      return (<SelectRowHeaderColumn width={this.selectRowColumnWidth}></SelectRowHeaderColumn>);
    }else if(this.props.rowSelectType == Const.ROW_SELECT_MULTI){
      return (<SelectRowHeaderColumn width={this.selectRowColumnWidth}>
          <Checkbox onChange={this.props.onSelectAllRow} checked={this.props.isSelectAll}/>
        </SelectRowHeaderColumn>
      );
    }else{
      return null;
    }
  }

  _attachClearSortCaretFunc(){
    if(Array.isArray(this.props.children)){
      for(let i=0;i<this.props.children.length;i++){
        const field = this.props.children[i].props.dataField;
        const sort = field === this.props.sortName ? this.props.sortOrder : undefined;
        this.props.children[i] =
          React.cloneElement(this.props.children[i],
            { key: i, onSort: this.props.onSort, sort });
      }
    } else {
      const field = this.props.children.props.dataField;
      const sort = field === this.props.sortName ? this.props.sortOrder : undefined;
      this.props.children =
        React.cloneElement(this.props.children, {key: 0, onSort: this.props.onSort, sort});
    }
  }

  fitHeader(headerProps, isVerticalScrollBar){
    if(Array.isArray(this.props.children)){
      let startPosition = (this.props.rowSelectType == Const.ROW_SELECT_SINGLE ||
                              this.props.rowSelectType == Const.ROW_SELECT_MULTI) && !this.props.hideSelectColumn ? 1:0;
      if(startPosition == 1)
        this.selectRowColumnWidth = headerProps[0].width;
      for(let i=0;i<this.props.children.length;i++){
        this.props.children[i] =
          React.cloneElement(this.props.children[i], {width: headerProps[i+startPosition].width+"px"});
      }
    } else {
      this.props.children =
        React.cloneElement(this.props.children, {width: headerProps[0].width+"px"});
    }
    if(this.props.condensed) {
      this.refs.container.style.height = "36px";
    }
    this.forceUpdate();
    if(isVerticalScrollBar)
      this.refs.container.style.marginRight = Util.getScrollBarWidth() + "px";
  }
}
TableHeader.propTypes = {
  rowSelectType: React.PropTypes.string,
  onSort: React.PropTypes.func,
  onSelectAllRow: React.PropTypes.func,
  sortName: React.PropTypes.string,
  sortOrder: React.PropTypes.string,
  hideSelectColumn: React.PropTypes.bool,
  bordered: React.PropTypes.bool,
  condensed: React.PropTypes.bool,
  isSelectAll: React.PropTypes.oneOf([true, 'indeterminate', false])
};

TableHeader.defaultProps = {
};
export default TableHeader;
<commit_msg>fix #230<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import Const from './Const';
import Util from './util';
import classSet from 'classnames';
import SelectRowHeaderColumn from './SelectRowHeaderColumn';

class Checkbox extends React.Component{
  componentDidMount() { this.update(this.props.checked); }
  componentWillReceiveProps(props) { this.update(props.checked); }
  update(checked) {
    ReactDOM.findDOMNode(this).indeterminate = checked === 'indeterminate';
  }

  render() {
    return <input className='react-bs-select-all' type="checkbox" checked={this.props.checked} onChange={this.props.onChange} />
  }
}

class TableHeader extends React.Component{

  constructor(props) {
    super(props);
    this.selectRowColumnWidth = null;
  }

  render(){
    var containerClasses = classSet("table-header");
    var tableClasses = classSet("table", "table-hover", {
        "table-bordered": this.props.bordered,
        "table-condensed": this.props.condensed
    });
    var selectRowHeaderCol = this.props.hideSelectColumn?null:this.renderSelectRowHeader();
    this._attachClearSortCaretFunc();

    return(

                {selectRowHeaderCol}
                {this.props.children}

    )
  }

  renderSelectRowHeader(){
    if(this.props.rowSelectType == Const.ROW_SELECT_SINGLE) {
      return (<SelectRowHeaderColumn width={this.selectRowColumnWidth}></SelectRowHeaderColumn>);
    }else if(this.props.rowSelectType == Const.ROW_SELECT_MULTI){
      return (<SelectRowHeaderColumn width={this.selectRowColumnWidth}>
          <Checkbox onChange={this.props.onSelectAllRow} checked={this.props.isSelectAll}/>
        </SelectRowHeaderColumn>
      );
    }else{
      return null;
    }
  }

  _attachClearSortCaretFunc(){
    if(Array.isArray(this.props.children)){
      for(let i=0;i<this.props.children.length;i++){
        const field = this.props.children[i].props.dataField;
        const sort = field === this.props.sortName ? this.props.sortOrder : undefined;
        this.props.children[i] =
          React.cloneElement(this.props.children[i],
            { key: i, onSort: this.props.onSort, sort });
      }
    } else {
      const field = this.props.children.props.dataField;
      const sort = field === this.props.sortName ? this.props.sortOrder : undefined;
      this.props.children =
        React.cloneElement(this.props.children, {key: 0, onSort: this.props.onSort, sort});
    }
  }

  fitHeader(headerProps, isVerticalScrollBar){
    if(Array.isArray(this.props.children)){
      let startPosition = (this.props.rowSelectType == Const.ROW_SELECT_SINGLE ||
                              this.props.rowSelectType == Const.ROW_SELECT_MULTI) && !this.props.hideSelectColumn ? 1:0;
      if(startPosition == 1)
        this.selectRowColumnWidth = headerProps[0].width;
      for(let i=0;i<this.props.children.length;i++){
        this.props.children[i] =
          React.cloneElement(this.props.children[i], {width: headerProps[i+startPosition].width+"px"});
      }
    } else {
      this.props.children =
        React.cloneElement(this.props.children, {width: headerProps[0].width+"px"});
    }
    if(this.props.condensed) {
      this.refs.container.style.height = "36px";
    }
    this.forceUpdate();
    if(isVerticalScrollBar)
      this.refs.container.style.marginRight = Util.getScrollBarWidth() + "px";
  }
}
TableHeader.propTypes = {
  rowSelectType: React.PropTypes.string,
  onSort: React.PropTypes.func,
  onSelectAllRow: React.PropTypes.func,
  sortName: React.PropTypes.string,
  sortOrder: React.PropTypes.string,
  hideSelectColumn: React.PropTypes.bool,
  bordered: React.PropTypes.bool,
  condensed: React.PropTypes.bool,
  isSelectAll: React.PropTypes.oneOf([true, 'indeterminate', false])
};

TableHeader.defaultProps = {
};
export default TableHeader;
<|endoftext|>


<commit_before>;(function ( $, window, document, undefined ) {
$.widget( "figgy.filemanager", {
    options: {
        images: [],
        selected: [],
        blank: {
          'id': '',
          'label': '',
          'url': '',
          'pageType': 'single',
          'isThumb': null,
          'isStart': null
        }
    },
    _create: function() {
        this.changeList = []
        this._createGallery()
        this._createDetailSidebar()
        this._createForm()
        this._createControls()

        var _this = this;

        // add event handlers
        this._on(this.document, {
  				'click.thumbnail': function(event) {
            _this.handleSelectPage(event)
  				}
  			});

        this._on(this.document, {
          'click#save_btn': function(event) {
            this.save()
  				}
        });

        this._on(this.document, {
          'input#label': function(event) {
            this.options.selected[0].label = $( '#label' ).val()
            this.applyChanges()
  				}
        });

        // Note: this relies on jQuery UI Sortable widget
        // Since jQuery UI is a dependency, we can lean on it
        // and look into optimizing with HTML5 native DnD if needed
        this.element.find( "#sortable" ).sortable({
          update: function( event, ui ) {
            var sortedIDs = $( "#sortable" ).sortable( "toArray" );
            _this._saveSort(sortedIDs);
          }
        });

        // paint the img_collection here
        this.refresh()
    },
    applyChanges: function() {
      // TODO: Keep a list of all changed ids so we can mark them as changed
      // or perhaps add a property to images
      for (i = 0; i < this.options.selected.length; i++) {
        var index = this.options.images.map(function(img) {
          return img.id;
        }).indexOf(this.options.selected[i].id);
        this.options.images[index] = this.options.selected[i]
        if (this.changeList.indexOf(this.options.selected[i].id) == -1) {
          this.changeList.push(this.options.selected[i].id)
        }
      }

      this.refresh()
    },
    _createGallery: function() {
      var $content = $('

')
      var $gallery = $('

')
      $content.append( $gallery )
      this.element.append( $content )
    },
    _createDetailSidebar: function() {
      var $sidebar = $('

')
      var $detail = $('

')
      var $img_detail = $('')
      $detail.append( $img_detail )
      $sidebar.append( $detail )
      this.element.append( $sidebar )
    },
    _createForm: function() {
      var $form_panel = $('

')
      var $noneSelected = $('
No items selected.
')
      var $multiSelected = $('
Multiple items are selected.
')
      var singleSelected = '<form id="singleSelected" class="formContent form-horizontal">'+
                   '
' +
                      'Label' +
                      '<input type="text" name="label" id="label" value="1" class="form-control">' +
                   '
' +
                   '
' +
                   'Page Type' +
                      '<select id="pageType" class="form-control">' +
                      '<option value="single">Single Page (Default)</option>' +
                      '<option value="non-paged">Non-Paged</option>' +
                      '<option value="facing">Facing Pages</option>' +
                    '</select>' +
                  '
' +
                  '
' +
                    '
' +
                      '' +
                        '<input id="isThumb" type="checkbox" value="">' +
                        'Set as Thumbnail (?)' +
                      '' +
                  '
' +
                    '
' +
                      '' +
                        '<input id="isStart" type="checkbox" value="">' +
                        'Set as Start Page (?)' +
                      '' +
                    '
' +
                  '
' +
                  '<input id="canvas_id" type="hidden" name="canvas_id"></form>'

      $form_panel.append( $noneSelected, $multiSelected, singleSelected )
      this.element.append( $form_panel )
    },
    _createControls: function() {
      var $controls = $('

')
      var $button = $('<button id="save_btn" name="button" type="button" class="btn btn-primary">Save</button>')
      $controls.append( $button )
      this.element.append( $controls )
    },
    deselectAll: function() {
      this.options.selected = []
    },
    _paintSelected: function() {
      // loop through and add class to all the ids
      $('.thumbnail img').removeClass('selected')
      for (i = 0; i < this.options.selected.length; i++) {
        var element = document.getElementById(this.options.selected[i].id)
        element.className += " selected";
      }
    },
    getImageById: function( id ) {
      var elementPos = this.options.images.map(function(image) {
        return image.id
      }).indexOf(id)
      return this.options.images[elementPos]
    },
    handleSelectPage: function( event ) {
      if (event.metaKey) {
        console.log("CMD")
        if(this.isSelected(event.target.id)){

        }else{
          this.options.selected.push(this.getImageById(event.target.id))
        }
      } else if (event.shiftKey) {
        console.log("Shift")
      } else {
        this.deselectAll()
        this.options.selected.push(this.getImageById(event.target.id))
      }

      // update form panel
      $( '.formContent' ).hide()
      switch (this.options.selected.length) {
        case 0:
          $( '#noneSelected' ).show()
          break
        case 1:
          var selected = this.options.selected[0]
          $( '#label' ).val(selected.label)
          $( '#pageType option[value="'+ selected.pageType +'"]' ).prop('selected', true)
          $( '#isThumb' ).prop( "checked", selected.isThumb )
          $( '#isStart' ).prop( "checked", selected.isStart )
          $( '#canvas_id' ).val(selected.id)
          $( '#detail_img' ).attr("src",selected.url)
          $( '#singleSelected' ).show()
          break
        default:
          $( '#multiSelected' ).show()
      }
      this._paintSelected()
    },
    hasChanged: function(id) {
      if (this.changeList.indexOf(id) == -1) {
        return false
      } else {
        return true
      }
    },
    isSelected: function(select_id) {
      // true or false
    },
    paintPage: function( page, index, array ) {
      console.log(this.images)
      $( "

" )
      .appendTo( "#sortable" )
      .html( "
" + page.label + "
" );
    },
    _saveSort: function( sortedIDs ) {
      var new_imgArr = [];
      var arrayLength = sortedIDs.length;
      for (var i = 0; i < arrayLength; i++) {
        new_imgArr[i] = this.options.images[sortedIDs[i]];
      }
      this.options.images = new_imgArr;
    },
    _setOption: function( key, value ) {
        this._super( key, value );
    },
    _setOptions: function( options ) {
        this._super( options );
    },
    refresh: function() {
      $( "#sortable" ).empty();
      this.options.images.forEach(this.paintPage);
    },
    reset: function() {
      this._destroy();
      this._create();
    },
    save: function() {
      this.applyChanges()
      //  This could save it to a server if we want
      //  but for now just emit an event
      this.element.trigger( "objectSaved", [this.options.images] );
    },
    _destroy: function() {
        this.element
            .removeClass( "filemanager" )
            .text( "" );
    }
});
})( jQuery, window, document );
<commit_msg>adds deselect and change indicators<commit_after>;(function ( $, window, document, undefined ) {
$.widget( "figgy.filemanager", {
    options: {
        images: [],
        selected: [],
        blank: {
          'id': '',
          'label': '',
          'url': '',
          'pageType': 'single',
          'isThumb': null,
          'isStart': null
        }
    },
    _create: function() {
        this.changeList = []
        this._createGallery()
        this._createDetailSidebar()
        this._createForm()
        this._createControls()

        var _this = this;

        // add event handlers
        this._on(this.document, {
  				'click.thumbnail': function(event) {
            _this.handleSelectPage(event)
  				}
  			});

        this._on(this.document, {
          'click#save_btn': function(event) {
            this.save()
  				}
        });

        this._on(this.document, {
          'input#label': function(event) {
            this.options.selected[0].label = $( '#label' ).val()
            this.applyChanges()
  				}
        });

        // Note: this relies on jQuery UI Sortable widget
        // Since jQuery UI is a dependency, we can lean on it
        // and look into optimizing with HTML5 native DnD if needed
        this.element.find( "#sortable" ).sortable({
          update: function( event, ui ) {
            var sortedIDs = $( "#sortable" ).sortable( "toArray" );
            _this._saveSort(sortedIDs);
          }
        });

        // paint the img_collection here
        this.refresh()
    },
    applyChanges: function() {
      // TODO: Keep a list of all changed ids so we can mark them as changed
      // or perhaps add a property to images
      for (i = 0; i < this.options.selected.length; i++) {
        var index = this.options.images.map(function(img) {
          return img.id;
        }).indexOf(this.options.selected[i].id);
        this.options.images[index] = this.options.selected[i]
        if (this.changeList.indexOf(this.options.selected[i].id) == -1) {
          this.changeList.push(this.options.selected[i].id)
        }
      }

      this.refresh()
    },
    _createGallery: function() {
      var $content = $('

')
      var $gallery = $('

')
      $content.append( $gallery )
      this.element.append( $content )
    },
    _createDetailSidebar: function() {
      var $sidebar = $('

')
      var $detail = $('

')
      var $img_detail = $('')
      $detail.append( $img_detail )
      $sidebar.append( $detail )
      this.element.append( $sidebar )
    },
    _createForm: function() {
      var $form_panel = $('

')
      var $noneSelected = $('
No items selected.
')
      var $multiSelected = $('
Multiple items are selected.
')
      var singleSelected = '<form id="singleSelected" class="formContent form-horizontal">'+
                   '
' +
                      'Label' +
                      '<input type="text" name="label" id="label" value="1" class="form-control">' +
                   '
' +
                   '
' +
                   'Page Type' +
                      '<select id="pageType" class="form-control">' +
                      '<option value="single">Single Page (Default)</option>' +
                      '<option value="non-paged">Non-Paged</option>' +
                      '<option value="facing">Facing Pages</option>' +
                    '</select>' +
                  '
' +
                  '
' +
                    '
' +
                      '' +
                        '<input id="isThumb" type="checkbox" value="">' +
                        'Set as Thumbnail (?)' +
                      '' +
                  '
' +
                    '
' +
                      '' +
                        '<input id="isStart" type="checkbox" value="">' +
                        'Set as Start Page (?)' +
                      '' +
                    '
' +
                  '
' +
                  '<input id="canvas_id" type="hidden" name="canvas_id"></form>'

      $form_panel.append( $noneSelected, $multiSelected, singleSelected )
      this.element.append( $form_panel )
    },
    _createControls: function() {
      var $controls = $('

')
      var $button = $('<button id="save_btn" name="button" type="button" class="btn btn-lg btn-primary">Save</button>')
      $controls.append( $button )
      this.element.append( $controls )
    },
    deselectAll: function() {
      this.options.selected = []
    },
    deselectOne: function() {
      this.options.selected.splice(this.getImageById(event.target.id), 1)
    },
    getImageIndexById: function( id ) {
      return this.options.images.map(function(image) {
        return image.id
      }).indexOf(id)
    },
    getImageById: function( id ) {
      var elementPos = this.getImageIndexById(id)
      return this.options.images[elementPos]
    },
    getSelectedIndexById: function( id ) {
      return this.options.selected.map(function(image) {
        return image.id
      }).indexOf(id)
    },
    handleSelectPage: function( event ) {
      if (event.metaKey) {
        if(this.isSelected(event.target.id)){
          this.options.selected.splice(this.getSelectedIndexById(event.target.id), 1)
          console.log(this.options.selected)
        }else{
          this.options.selected.push(this.getImageById(event.target.id))
        }
      } else if (event.shiftKey) {
        console.log("Shift + Click")
      } else {
        this.deselectAll()
        this.options.selected.push(this.getImageById(event.target.id))
      }

      // update form panel
      $( '.formContent' ).hide()
      switch (this.options.selected.length) {
        case 0:
          $( '#noneSelected' ).show()
          break
        case 1:
          var selected = this.options.selected[0]
          $( '#label' ).val(selected.label)
          $( '#pageType option[value="'+ selected.pageType +'"]' ).prop('selected', true)
          $( '#isThumb' ).prop( "checked", selected.isThumb )
          $( '#isStart' ).prop( "checked", selected.isStart )
          $( '#canvas_id' ).val(selected.id)
          $( '#detail_img' ).attr("src",selected.url)
          $( '#singleSelected' ).show()
          break
        default:
          $( '#multiSelected' ).show()
      }
      this._paintSelected()
    },
    hasChanged: function(id) {
      if (this.changeList.indexOf(id) == -1) {
        return false
      } else {
        return true
      }
    },
    isSelected: function(select_id) {
      var index = this.options.selected.map(function(img) {
        return img.id;
      }).indexOf(select_id);
      if( index == -1) {
        return false
      } else {
        return true
      }
    },
    _paintPages: function() {
      var totalImages = this.options.images.length
      _this = this
      for (var i = 0; i < totalImages; i++) {
        var item_state = _this.hasChanged(_this.options.images[i].id) ? 'hasChanged' : ''
        var $thumbnail = $( "

" )
        img_markup = "
" + _this.options.images[i].label + "
"
        $thumbnail.append(img_markup)
        $( '#sortable' ).append($thumbnail)
      }
    },
    _paintSelected: function() {
      // loop through and add class to all the ids
      $('.thumbnail img').removeClass('selected')
      for (i = 0; i < this.options.selected.length; i++) {
        var element = document.getElementById(this.options.selected[i].id)
        element.className += " selected";
      }
    },
    _saveSort: function( sortedIDs ) {
      var new_imgArr = [];
      var arrayLength = sortedIDs.length;
      for (var i = 0; i < arrayLength; i++) {
        new_imgArr[i] = this.options.images[sortedIDs[i]];
      }
      this.options.images = new_imgArr;
    },
    _setOption: function( key, value ) {
        this._super( key, value );
    },
    _setOptions: function( options ) {
        this._super( options );
    },
    refresh: function() {
      $( "#sortable" ).empty();
      this._paintPages()
    },
    reset: function() {
      this._destroy();
      this._create();
    },
    save: function() {
      this.applyChanges()
      //  This could save it to a server if we want
      //  but for now just emit an event
      this.element.trigger( "objectSaved", [this.options.images] )
      // TODO: investigate why reset seems to prevent us from listening for the 'metaKey'
      // Implementing "softReset()"" now as a workaround.
      // this.reset()
      this.softReset()
      alert('Changes saved!')
    },
    softReset: function() {
      this.deselectAll()
      this.changeList = []
      this.refresh()
    },
    _destroy: function() {
        this.element
            .removeClass( "filemanager" )
            .text( "" );
    }
});
})( jQuery, window, document );
<|endoftext|>


<commit_before>var FormDeliveryServiceController = function(deliveryService, $scope, formUtils, locationUtils, cdnService, profileService, typeService) {

    var getTypes = function() {
        typeService.getTypes('deliveryservice')
            .then(function(result) {
                $scope.types = result;
            });
    };

    var getCDNs = function() {
        cdnService.getCDNs()
            .then(function(result) {
                $scope.cdns = result;
            });
    };

    var getProfiles = function() {
        profileService.getProfiles()
            .then(function(result) {
                $scope.profiles = result;
            });
    };

    $scope.deliveryService = deliveryService;

    $scope.falseTrue = [
        { value: false, label: 'false' },
        { value: true, label: 'true' }
    ];

    $scope.protocols = [
        { value: "0", label: '0 - HTTP' },
        { value: "1", label: '1 - HTTPS' },
        { value: "2", label: '2 - HTTP AND HTTPS' },
        { value: "3", label: '3 - HTTP TO HTTPS' }
    ];

    $scope.qStrings = [
        { value: "0", label: '0 - use qstring in cache key, and pass up' },
        { value: "1", label: '1 - ignore in cache key, and pass up' },
        { value: "2", label: '2 - drop at edge' }
    ];

    $scope.geoLimits = [
        { value: "0", label: '0 - None' },
        { value: "1", label: '1 - CZF only' },
        { value: "2", label: '2 - CZF + Country Code(s)' }
    ];

    $scope.geoProviders = [
        { value: "0", label: '0 - Maxmind (Default)' },
        { value: "1", label: '1 - Neustar' }
    ];

    $scope.dscps = [
        { value: "0", label: '0  - Best Effort' },
        { value: "10", label: '10 - AF11' },
        { value: "12", label: '12 - AF12' },
        { value: "14", label: '14 - AF13' },
        { value: "18", label: '18  - AF21' },
        { value: "20", label: '20  - AF22' },
        { value: "22", label: '22  - AF23' },
        { value: "26", label: '26  - AF31' },
        { value: "28", label: '28  - AF32' },
        { value: "30", label: '30  - AF33' },
        { value: "34", label: '34  - AF41' },
        { value: "36", label: '36  - AF42' },
        { value: "37", label: '37  - ' },
        { value: "38", label: '38  - AF43' },
        { value: "8", label: '8  - CS1' },
        { value: "16", label: '16  - CS2' },
        { value: "24", label: '24  - CS3' },
        { value: "32", label: '32  - CS4' },
        { value: "40", label: '40  - CS5' },
        { value: "48", label: '48  - CS6' },
        { value: "56", label: '56  - CS7' }
    ];

    $scope.dispersions = [
        { value: "1", label: '1 - OFF' },
        { value: "2", label: '2' },
        { value: "3", label: '3' },
        { value: "4", label: '4' },
        { value: "5", label: '5' },
        { value: "6", label: '6' },
        { value: "7", label: '7' },
        { value: "8", label: '8' },
        { value: "9", label: '9' },
        { value: "10", label: '10' }
    ];

    $scope.rrhs = [
        { value: "0", label: "0 - Don't cache" },
        { value: "1", label: "1 - Use background_fetch plugin" },
        { value: "2", label: "2 - Use cache_range_requests plugin" }
    ];

    $scope.msoAlgos = [
        { value: "0", label: "0 - Consistent Hash" },
        { value: "1", label: "1 - Primary/Backup" },
        { value: "2", label: "2 - Strict Round Robin" },
        { value: "3", label: "3 - IP-based Round Robin" },
        { value: "4", label: "4 - Latch on Failover" }
    ];

    $scope.navigateToPath = locationUtils.navigateToPath;

    $scope.hasError = formUtils.hasError;

    $scope.hasPropertyError = formUtils.hasPropertyError;

    var init = function () {
        getTypes();
        getCDNs();
        getProfiles();
    };
    init();

};

FormDeliveryServiceController.$inject = ['deliveryService', '$scope', 'formUtils', 'locationUtils', 'cdnService', 'profileService', 'typeService'];
module.exports = FormDeliveryServiceController;<commit_msg>changes to handle ints (postgres) instead of strings<commit_after>var FormDeliveryServiceController = function(deliveryService, $scope, formUtils, locationUtils, cdnService, profileService, typeService) {

    var getTypes = function() {
        typeService.getTypes('deliveryservice')
            .then(function(result) {
                $scope.types = result;
            });
    };

    var getCDNs = function() {
        cdnService.getCDNs()
            .then(function(result) {
                $scope.cdns = result;
            });
    };

    var getProfiles = function() {
        profileService.getProfiles()
            .then(function(result) {
                $scope.profiles = result;
            });
    };

    $scope.deliveryService = deliveryService;

    $scope.falseTrue = [
        { value: false, label: 'false' },
        { value: true, label: 'true' }
    ];

    $scope.protocols = [
        { value: 0, label: '0 - HTTP' },
        { value: 1, label: '1 - HTTPS' },
        { value: 2, label: '2 - HTTP AND HTTPS' },
        { value: 3, label: '3 - HTTP TO HTTPS' }
    ];

    $scope.qStrings = [
        { value: 0, label: '0 - use qstring in cache key, and pass up' },
        { value: 1, label: '1 - ignore in cache key, and pass up' },
        { value: 2, label: '2 - drop at edge' }
    ];

    $scope.geoLimits = [
        { value: 0, label: '0 - None' },
        { value: 1, label: '1 - CZF only' },
        { value: 2, label: '2 - CZF + Country Code(s)' }
    ];

    $scope.geoProviders = [
        { value: 0, label: '0 - Maxmind (Default)' },
        { value: 1, label: '1 - Neustar' }
    ];

    $scope.dscps = [
        { value: 0, label: '0  - Best Effort' },
        { value: 10, label: '10 - AF11' },
        { value: 12, label: '12 - AF12' },
        { value: 14, label: '14 - AF13' },
        { value: 18, label: '18  - AF21' },
        { value: 20, label: '20  - AF22' },
        { value: 22, label: '22  - AF23' },
        { value: 26, label: '26  - AF31' },
        { value: 28, label: '28  - AF32' },
        { value: 30, label: '30  - AF33' },
        { value: 34, label: '34  - AF41' },
        { value: 36, label: '36  - AF42' },
        { value: 37, label: '37  - ' },
        { value: 38, label: '38  - AF43' },
        { value: 8, label: '8  - CS1' },
        { value: 16, label: '16  - CS2' },
        { value: 24, label: '24  - CS3' },
        { value: 32, label: '32  - CS4' },
        { value: 40, label: '40  - CS5' },
        { value: 48, label: '48  - CS6' },
        { value: 56, label: '56  - CS7' }
    ];

    $scope.dispersions = [
        { value: 1, label: '1 - OFF' },
        { value: 2, label: '2' },
        { value: 3, label: '3' },
        { value: 4, label: '4' },
        { value: 5, label: '5' },
        { value: 6, label: '6' },
        { value: 7, label: '7' },
        { value: 8, label: '8' },
        { value: 9, label: '9' },
        { value: 10, label: '10' }
    ];

    $scope.rrhs = [
        { value: 0, label: "0 - Don't cache" },
        { value: 1, label: "1 - Use background_fetch plugin" },
        { value: 2, label: "2 - Use cache_range_requests plugin" }
    ];

    $scope.msoAlgos = [
        { value: 0, label: "0 - Consistent Hash" },
        { value: 1, label: "1 - Primary/Backup" },
        { value: 2, label: "2 - Strict Round Robin" },
        { value: 3, label: "3 - IP-based Round Robin" },
        { value: 4, label: "4 - Latch on Failover" }
    ];

    $scope.navigateToPath = locationUtils.navigateToPath;

    $scope.hasError = formUtils.hasError;

    $scope.hasPropertyError = formUtils.hasPropertyError;

    var init = function () {
        getTypes();
        getCDNs();
        getProfiles();
    };
    init();

};

FormDeliveryServiceController.$inject = ['deliveryService', '$scope', 'formUtils', 'locationUtils', 'cdnService', 'profileService', 'typeService'];
module.exports = FormDeliveryServiceController;<|endoftext|>


<commit_before>'use strict';

angular.module('vlui')
  .service('FilterManager', function (_, vl, Dataset) {
    var self = this;

    /** local object for this object */
    self.filterIndex = {};

    this.toggle = function(field) {
      if (!self.filterIndex[field]) {
        self.filterIndex[field] = initFilter(field);
      } else {
        self.filterIndex[field].enabled = !self.filterIndex[field].enabled;
      }
    };

    this.reset = function(oldFilter, hard) {
      if (hard) {
        self.filterIndex = {};
      } else {
        _.forEach(self.filterIndex, function(value, field) {
          delete self.filterIndex[field];
        });
      }

      if (oldFilter) {
        console.error('We do not support loading filter yet!');
      }

      return self.filterIndex;
    }

    this.getVlFilter = function() {
      var vlFilter = _.reduce(self.filterIndex, function (filters, filter, field) {
        if (filter.enabled) {
          filters.push(_.omit(filter, 'enabled'));
        }
        return filters;
      }, []);

      return vlFilter.length ? vlFilter : undefined;
    }

    function initFilter(field) {
      var type = Dataset.schema.type(field);

      switch (type) {
        case vl.type.NOMINAL:
        case vl.type.ORDINAL:
          return {
            enabled: true,
            field: field,
            in: Dataset.domain(field)
          };
        case vl.type.QUANTITATIVE:
          return {
            enabled: true,
            field: field,
            range: [
              Dataset.schema.stats({field: field}).min,
              Dataset.schema.stats({field: field}).max
            ]
          };
        case vl.type.TEMPORAL:
          return {
            enabled: true,
            field: field,
            range: [
              Dataset.schema.stats({field: field}).min,
              Dataset.schema.stats({field: field}).max
            ]
          };
      }
    }
  });
<commit_msg>Implement loading filter<commit_after>'use strict';

angular.module('vlui')
  .service('FilterManager', function (_, vl, Dataset) {
    var self = this;

    /** local object for this object */
    self.filterIndex = {};

    this.toggle = function(field) {
      if (!self.filterIndex[field]) {
        self.filterIndex[field] = initFilter(field);
      } else {
        self.filterIndex[field].enabled = !self.filterIndex[field].enabled;
      }
    };

    this.reset = function(oldFilter, hard) {
      if (hard) {
        self.filterIndex = {};
      } else {
        _.forEach(self.filterIndex, function(value, field) {
          delete self.filterIndex[field];
        });
      }

      if (oldFilter) {
        oldFilter.forEach(function(filter) {
          self.filterIndex[filter.field] = vl.util.extend({enabled: true}, filter);
        });
      }

      return self.filterIndex;
    }

    this.getVlFilter = function() {
      var vlFilter = _.reduce(self.filterIndex, function (filters, filter, field) {
        if (filter.enabled) {
          filters.push(_.omit(filter, 'enabled'));
        }
        return filters;
      }, []);

      return vlFilter.length ? vlFilter : undefined;
    }

    function initFilter(field) {
      var type = Dataset.schema.type(field);

      switch (type) {
        case vl.type.NOMINAL:
        case vl.type.ORDINAL:
          return {
            enabled: true,
            field: field,
            in: Dataset.domain(field)
          };
        case vl.type.QUANTITATIVE:
          return {
            enabled: true,
            field: field,
            range: [
              Dataset.schema.stats({field: field}).min,
              Dataset.schema.stats({field: field}).max
            ]
          };
        case vl.type.TEMPORAL:
          return {
            enabled: true,
            field: field,
            range: [
              Dataset.schema.stats({field: field}).min,
              Dataset.schema.stats({field: field}).max
            ]
          };
      }
    }
  });
<|endoftext|>


<commit_before>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * The query toolbar, and associated actions
 */
var QueryToolbar = Backbone.View.extend({

    events: {
        'click .options a.button': 'call',
        'click .renderer a.button' : 'switch_render_button'
    },

    table: {
        sparkType: null
    },
    chart: {},

    render_mode: "table",

    initialize: function(args) {
        // Keep track of parent workspace
        this.workspace = args.workspace;

        // Maintain `this` in callbacks
        _.bindAll(this, "call","activate_buttons", "spark_bar", "spark_line", "render_row_viz", "run_row_viz", "switch_render_button");

        // Activate buttons when a new query is created or run
        this.workspace.bind('query:new', this.activate_buttons);
        this.workspace.bind('query:result', this.activate_buttons);
        this.workspace.bind('table:rendered', this.run_row_viz);

    },

    activate_buttons: function(args) {
        if (typeof args != "undefined" && args != null ) {
            $(this.el).find('a').removeClass('disabled_toolbar');
            if (!args.data) {
                $(this.el).find('a.export_button, a.stats').addClass('disabled_toolbar');
            }
        }

    },

    template: function() {
        var template = $("#template-query-toolbar").html() || "";
        return _.template(template)();
    },

    render: function() {
        $(this.el).html(this.template());

        $(this.el).find('render_table').addClass('on');
        $(this.el).find('ul.table').show();
        var self = this;
         $.contextMenu({
                selector: '.export_button',
                trigger: 'left',
                ignoreRightClick: true,
                callback: function(key, options) {
                    var m = "clicked: " + key;
                    window.console && console.log(m) || alert(m);
                    self.workspace.chart.exportChart(key);
                },
                items: {
                    "png": {name: "PNG"},
                    "pdf": {name: "PDF"},
                    "jpg": {name: "JPEG"},
                    "svg": {name: "SVG"}
                }
            });

        return this;
    },

    switch_render_button: function(event) {
        $target = $(event.target);
        event.preventDefault();
        if ($(event.target).hasClass('disabled_toolbar')) {
            return false;
        }
        $target.parent().siblings().find('.on').removeClass('on');
        if ($target.hasClass('render_chart')) {
            this.switch_render('chart');
            this.workspace.query.setProperty('saiku.ui.render.mode', 'chart');
            var c = $(this.el).find('ul.chart li a.on:first').size() > 0 ?
                        $(this.el).find('ul.chart li a.on:first').attr('href').replace('#', '')
                        : null;
            if (c != null) {
                this.workspace.query.setProperty('saiku.ui.render.type', c);
            }
        } else {
            this.switch_render('table');
            this.workspace.query.setProperty('saiku.ui.render.mode', 'table');
            this.workspace.query.setProperty('saiku.ui.render.type', this.table.sparkType);

        }

    },
    switch_render: function(render_type) {
        render_type = (typeof render_type != "undefined" ? render_type.toLowerCase() : "table");
        $(this.el).find('ul.renderer a.on').removeClass('on');
        $(this.el).find('ul.renderer a.render_' + render_type).addClass('on');
        if ("chart" == render_type) {
            $(this.el).find('ul.chart').show();
            $(this.el).find('ul.table').hide();
            this.render_mode = "chart";
            $(this.workspace.el).find('.workspace_results').children().hide();
            this.workspace.chart.show();
        } else {
            $(this.el).find('ul.chart').hide();
            $(this.el).find('ul.table').show();
            $(this.el).find('ul.table .stats').removeClass('on');
            $(this.workspace.el).find('.workspace_results table').show();
            $(this.workspace.chart.el).hide();
            $(this.workspace.chart.nav).hide();
            this.render_mode = "table";
            var hasRun = this.workspace.query.result.hasRun();
            if (hasRun) {
                this.workspace.table.render({ data: this.workspace.query.result.lastresult() });
            }

        }
        return false;
    },

    call: function(event) {
        event.preventDefault();
        $target = $(event.target).hasClass('button') ? $(event.target) : $(event.target).parent();
        if (! $target.hasClass('disabled_toolbar')) {
            // Determine callback
            var callback = $target.attr('href').replace('#', '');

            // Attempt to call callback
            if (this.render_mode == "table" && this[callback]) {
                this[callback](event);
            } else if (this.render_mode == "chart" && this.workspace.chart[callback]) {
                this.workspace.chart.button(event);
                this.workspace.chart[callback](event);
            }
        }
        return false;
    },

    spark_bar: function() {
        $(this.el).find('ul.table .spark_bar').toggleClass('on');
        $(this.el).find('ul.table .spark_line').removeClass('on');

        $(this.workspace.table.el).find('td.spark').remove();
        if ($(this.el).find('ul.table .spark_bar').hasClass('on')) {
            this.table.sparkType = "spark_bar";
            this.workspace.query.setProperty('saiku.ui.render.type', 'spark_bar');
            _.delay(this.render_row_viz, 10, "spark_bar");
        } else {
            this.table.sparkType = null;
        }
    },

    spark_line: function() {
        $(this.el).find('ul.table .spark_line').toggleClass('on');
        $(this.el).find('ul.table .spark_bar').removeClass('on');

        $(this.workspace.table.el).find('td.spark').remove();
        if ($(this.el).find('ul.table .spark_line').hasClass('on')) {
            this.table.sparkType = "spark_line";
            this.workspace.query.setProperty('saiku.ui.render.type', 'spark_line');
            _.delay(this.render_row_viz, 10, "spark_line");
        } else {
            this.table.sparkType = null;
        }
    },

    run_row_viz: function(args) {
        if (this.render_mode == "table" && this.table.sparkType != null) {
            this.render_row_viz(this.table.sparkType);
        }

    },

    render_row_viz: function(type) {
        $(this.workspace.table.el).find('tr').each(function(index, element) {
            var rowData = [];
            $(element).find('td.data div').each(function(i,data) {
                var val = $(data).attr('alt');
                val = (typeof val != "undefined" && val != "" && val != null && val  != "undefined") ? parseFloat(val) : 0;
                rowData.push(val);
            });

            $("

	").appendTo($(element));

            var width = rowData.length * 9;

                if (rowData.length > 0) {
                    var vis = new pv.Panel()
                        .canvas('chart' + index)
                        .height(12)
                        .width(width)
                        .margin(0);

                    if (type == "spark_bar") {
                        vis.add(pv.Bar)
                            .data(rowData)
                            .left(pv.Scale.linear(0, rowData.length).range(0, width).by(pv.index))
                            .height(pv.Scale.linear(0,_.max(rowData)).range(0, 12))
                            .width(6)
                            .bottom(0);
                    } else if (type == "spark_line") {
                        width = width / 2;
                        vis.width(width);
                        vis.add(pv.Line)
                            .data(rowData)
                            .left(pv.Scale.linear(0, rowData.length - 1).range(0, width).by(pv.index))
                            .bottom(pv.Scale.linear(rowData).range(0, 12))
                            .strokeStyle("#000")
                            .lineWidth(1);
                    }
                    vis.render();
                }
        });
    }
});
<commit_msg>remove console<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * The query toolbar, and associated actions
 */
var QueryToolbar = Backbone.View.extend({

    events: {
        'click .options a.button': 'call',
        'click .renderer a.button' : 'switch_render_button'
    },

    table: {
        sparkType: null
    },
    chart: {},

    render_mode: "table",

    initialize: function(args) {
        // Keep track of parent workspace
        this.workspace = args.workspace;

        // Maintain `this` in callbacks
        _.bindAll(this, "call","activate_buttons", "spark_bar", "spark_line", "render_row_viz", "run_row_viz", "switch_render_button");

        // Activate buttons when a new query is created or run
        this.workspace.bind('query:new', this.activate_buttons);
        this.workspace.bind('query:result', this.activate_buttons);
        this.workspace.bind('table:rendered', this.run_row_viz);

    },

    activate_buttons: function(args) {
        if (typeof args != "undefined" && args != null ) {
            $(this.el).find('a').removeClass('disabled_toolbar');
            if (!args.data) {
                $(this.el).find('a.export_button, a.stats').addClass('disabled_toolbar');
            }
        }

    },

    template: function() {
        var template = $("#template-query-toolbar").html() || "";
        return _.template(template)();
    },

    render: function() {
        $(this.el).html(this.template());

        $(this.el).find('render_table').addClass('on');
        $(this.el).find('ul.table').show();
        var self = this;
         $.contextMenu({
                selector: '.export_button',
                trigger: 'left',
                ignoreRightClick: true,
                callback: function(key, options) {
                    self.workspace.chart.exportChart(key);
                },
                items: {
                    "png": {name: "PNG"},
                    "pdf": {name: "PDF"},
                    "jpg": {name: "JPEG"},
                    "svg": {name: "SVG"}
                }
            });

        return this;
    },

    switch_render_button: function(event) {
        $target = $(event.target);
        event.preventDefault();
        if ($(event.target).hasClass('disabled_toolbar')) {
            return false;
        }
        $target.parent().siblings().find('.on').removeClass('on');
        if ($target.hasClass('render_chart')) {
            this.switch_render('chart');
            this.workspace.query.setProperty('saiku.ui.render.mode', 'chart');
            var c = $(this.el).find('ul.chart li a.on:first').size() > 0 ?
                        $(this.el).find('ul.chart li a.on:first').attr('href').replace('#', '')
                        : null;
            if (c != null) {
                this.workspace.query.setProperty('saiku.ui.render.type', c);
            }
        } else {
            this.switch_render('table');
            this.workspace.query.setProperty('saiku.ui.render.mode', 'table');
            this.workspace.query.setProperty('saiku.ui.render.type', this.table.sparkType);

        }

    },
    switch_render: function(render_type) {
        render_type = (typeof render_type != "undefined" ? render_type.toLowerCase() : "table");
        $(this.el).find('ul.renderer a.on').removeClass('on');
        $(this.el).find('ul.renderer a.render_' + render_type).addClass('on');
        if ("chart" == render_type) {
            $(this.el).find('ul.chart').show();
            $(this.el).find('ul.table').hide();
            this.render_mode = "chart";
            $(this.workspace.el).find('.workspace_results').children().hide();
            this.workspace.chart.show();
        } else {
            $(this.el).find('ul.chart').hide();
            $(this.el).find('ul.table').show();
            $(this.el).find('ul.table .stats').removeClass('on');
            $(this.workspace.el).find('.workspace_results table').show();
            $(this.workspace.chart.el).hide();
            $(this.workspace.chart.nav).hide();
            this.render_mode = "table";
            var hasRun = this.workspace.query.result.hasRun();
            if (hasRun) {
                this.workspace.table.render({ data: this.workspace.query.result.lastresult() });
            }

        }
        return false;
    },

    call: function(event) {
        event.preventDefault();
        $target = $(event.target).hasClass('button') ? $(event.target) : $(event.target).parent();
        if (! $target.hasClass('disabled_toolbar')) {
            // Determine callback
            var callback = $target.attr('href').replace('#', '');

            // Attempt to call callback
            if (this.render_mode == "table" && this[callback]) {
                this[callback](event);
            } else if (this.render_mode == "chart" && this.workspace.chart[callback]) {
                this.workspace.chart.button(event);
                this.workspace.chart[callback](event);
            }
        }
        return false;
    },

    spark_bar: function() {
        $(this.el).find('ul.table .spark_bar').toggleClass('on');
        $(this.el).find('ul.table .spark_line').removeClass('on');

        $(this.workspace.table.el).find('td.spark').remove();
        if ($(this.el).find('ul.table .spark_bar').hasClass('on')) {
            this.table.sparkType = "spark_bar";
            this.workspace.query.setProperty('saiku.ui.render.type', 'spark_bar');
            _.delay(this.render_row_viz, 10, "spark_bar");
        } else {
            this.table.sparkType = null;
        }
    },

    spark_line: function() {
        $(this.el).find('ul.table .spark_line').toggleClass('on');
        $(this.el).find('ul.table .spark_bar').removeClass('on');

        $(this.workspace.table.el).find('td.spark').remove();
        if ($(this.el).find('ul.table .spark_line').hasClass('on')) {
            this.table.sparkType = "spark_line";
            this.workspace.query.setProperty('saiku.ui.render.type', 'spark_line');
            _.delay(this.render_row_viz, 10, "spark_line");
        } else {
            this.table.sparkType = null;
        }
    },

    run_row_viz: function(args) {
        if (this.render_mode == "table" && this.table.sparkType != null) {
            this.render_row_viz(this.table.sparkType);
        }

    },

    render_row_viz: function(type) {
        $(this.workspace.table.el).find('tr').each(function(index, element) {
            var rowData = [];
            $(element).find('td.data div').each(function(i,data) {
                var val = $(data).attr('alt');
                val = (typeof val != "undefined" && val != "" && val != null && val  != "undefined") ? parseFloat(val) : 0;
                rowData.push(val);
            });

            $("

	").appendTo($(element));

            var width = rowData.length * 9;

                if (rowData.length > 0) {
                    var vis = new pv.Panel()
                        .canvas('chart' + index)
                        .height(12)
                        .width(width)
                        .margin(0);

                    if (type == "spark_bar") {
                        vis.add(pv.Bar)
                            .data(rowData)
                            .left(pv.Scale.linear(0, rowData.length).range(0, width).by(pv.index))
                            .height(pv.Scale.linear(0,_.max(rowData)).range(0, 12))
                            .width(6)
                            .bottom(0);
                    } else if (type == "spark_line") {
                        width = width / 2;
                        vis.width(width);
                        vis.add(pv.Line)
                            .data(rowData)
                            .left(pv.Scale.linear(0, rowData.length - 1).range(0, width).by(pv.index))
                            .bottom(pv.Scale.linear(rowData).range(0, 12))
                            .strokeStyle("#000")
                            .lineWidth(1);
                    }
                    vis.render();
                }
        });
    }
});
<|endoftext|>


<commit_before>/*global angular */
(function () {
    'use strict';

    function WizardTestController(bbModal) {
        var self = this;

        self.openForm = function () {
            bbModal.open({
                templateUrl: 'demo/wizard/wizardform.html'
            });
        };
    }

    function WizardTestModalController($window, bbWizardNavigator) {
        var self = this,
            steps,
            wizardNav;

        steps = [
            {
                heading: '1. Step 1',
                heading_xs: '1',
                templateUrl: 'demo/wizard/step1.html',
                complete: function () {
                    return !!self.requiredValue1;
                },
                active: true
            },
            {
                heading: '2. Step 2',
                heading_xs: '2',
                templateUrl: 'demo/wizard/step2.html',
                complete: function () {
                    return !!self.requiredValue2;
                },
                disabled: function () {
                    return !self.requiredValue1;
                }
            },
            {
                heading: '3. Step 3',
                heading_xs: '3',
                templateUrl: 'demo/wizard/step3.html',
                complete: function () {
                    return !!self.requiredValue3;
                },
                disabled: function () {
                    return !self.requiredValue1 || !self.requiredValue2;
                }
            },
            {
                heading: '4. Step 4',
                heading_xs: '4',
                templateUrl: 'demo/wizard/step4.html',
                complete: function () {
                    return !!self.requiredValue1;
                }
            },
            {
                heading: '5. Step 5',
                heading_xs: '5',
                templateUrl: 'demo/wizard/step5.html',
                complete: function () {
                    return !!self.requiredValue2;
                },
                disabled: function () {
                    return !self.requiredValue1;
                }
            },
            {
                heading: '6. Step 6',
                heading_xs: '6',
                templateUrl: 'demo/wizard/step3.html',
                complete: function () {
                    return !!self.requiredValue3;
                },
                disabled: function () {
                    return !self.requiredValue1 || !self.requiredValue2;
                }
            }
        ];

        wizardNav = bbWizardNavigator.init(
            {
                steps: steps,
                finish: function () {
                    $window.alert('Finished!');
                }
            }
        );

        self.steps = steps;

        self.wizardNav = wizardNav;

        self.firstStepComplete = function () {
            return !!self.requiredValue1;
        };

        self.secondStepComplete = function () {
            return !!self.requiredValue2;
        };
    }

    WizardTestController.$inject = ['bbModal'];

    WizardTestModalController.$inject = ['$window', 'bbWizardNavigator'];

    angular.module('stache')
        .controller('WizardTestController', WizardTestController)
        .controller('WizardTestModalController', WizardTestModalController);

}());
<commit_msg>remove extra wizard steps<commit_after>/*global angular */
(function () {
    'use strict';

    function WizardTestController(bbModal) {
        var self = this;

        self.openForm = function () {
            bbModal.open({
                templateUrl: 'demo/wizard/wizardform.html'
            });
        };
    }

    function WizardTestModalController($window, bbWizardNavigator) {
        var self = this,
            steps,
            wizardNav;

        steps = [
            {
                heading: '1. Step 1',
                heading_xs: '1',
                templateUrl: 'demo/wizard/step1.html',
                complete: function () {
                    return !!self.requiredValue1;
                },
                active: true
            },
            {
                heading: '2. Step 2',
                heading_xs: '2',
                templateUrl: 'demo/wizard/step2.html',
                complete: function () {
                    return !!self.requiredValue2;
                },
                disabled: function () {
                    return !self.requiredValue1;
                }
            },
            {
                heading: '3. Step 3',
                heading_xs: '3',
                templateUrl: 'demo/wizard/step3.html',
                complete: function () {
                    return !!self.requiredValue3;
                },
                disabled: function () {
                    return !self.requiredValue1 || !self.requiredValue2;
                }
            }
        ];

        wizardNav = bbWizardNavigator.init(
            {
                steps: steps,
                finish: function () {
                    $window.alert('Finished!');
                }
            }
        );

        self.steps = steps;

        self.wizardNav = wizardNav;

        self.firstStepComplete = function () {
            return !!self.requiredValue1;
        };

        self.secondStepComplete = function () {
            return !!self.requiredValue2;
        };
    }

    WizardTestController.$inject = ['bbModal'];

    WizardTestModalController.$inject = ['$window', 'bbWizardNavigator'];

    angular.module('stache')
        .controller('WizardTestController', WizardTestController)
        .controller('WizardTestModalController', WizardTestModalController);

}());
<|endoftext|>