﻿/**
 * Checks that all input fields with the class "decimal" only contain digits.
 * If this isn't the case, the upper sibling "p.fout" is shown.
 */
function checkDecimals() {
    var noProblemFound = true;
    $$('input.decimal').each(
        function(el) {
            var fout = el.up("div").down("p.fout");
            fout.hide();
            if (!el.value.match(/^\d*$/)) {
                fout.show();
                noProblemFound = false;
            }
        }
    );
    return noProblemFound;
}


/**
* Add tab behaviour to elements with classes "tab" and "body"
* pairs will be recognized by id as follows: "xxx-tab" -> "xxx-body"; "yyy-tab" -> "yyy-body"; ... 
* @param htmlElement
*/
function Tabified(container) {
// initialize
	var that = this;
	var container = $(container);
	var tabs = container.select(".tab");
	var bodies = container.select(".body");
	
	// add observers on tabs		
	tabs.each(function(el){
		var name = el.getAttribute("id").replace("-tab", "");
		el.body = $(name+"-body");

		el.observe("click", function(ev){
			that.open(name);
		})
	});
	
// public
	/**
	 * @param String
	 * @return Object
	 */
	this.open = function(name) {
		closeAll();
		
		var tab = $(name+"-tab");
		var body = $(name+"-body");
		tab && tab.removeClassName("closed");
		tab && tab.addClassName("open");
		body && body.removeClassName("closed");
		body && body.addClassName("open");
		
		tab.fire("tab:open");
		
		return this;
	}
	/**
	 * @return Array
	 */
	this.tabs = function() {
		return tabs;
	}
	/**
	 * @return Array
	 */
	this.bodies = function() {
		return bodies;
	}
	
// private
	var closeAll = function(){
		tabs.invoke("removeClassName", "open");
		tabs.invoke("addClassName", "closed");
		bodies.invoke("removeClassName", "open");
		bodies.invoke("addClassName", "closed");
	}
}

/**
 * A group of inputfields, who's editability is ruled by a checkbox
 * clicking a field, checks the checkbox and puts them all editable
 */
var disabledFieldsGroup = function(checkbox, fields) {
        var that = this;
		this.checkbox = $(checkbox);
		this.fields = [];
		var fieldNames = (fields.push && fields.pop ? fields : [fields]);
	    fieldNames.each(function(el){
	          if (el = $(el) )
	          {
    	          that.fields.push(el);
	          }
	    });
		
		this.checkbox.observe(
			"click",
			this.setState.bind(this)
		);

        var enable = this.enable.bind(this);
		this.fields.each(function(field){
			field.observe(
				"click",
				enable
			);
		});
		
		this.setState();
};
disabledFieldsGroup.prototype.setState = function(){
//alert("setstate "+this.checkbox.checked);
	if ( this.checkbox.checked ) {
		this.enableFields();
	} else {
		this.disableFields();
	}
};
disabledFieldsGroup.prototype.enable = function(){
	this.checkbox.checked = true;
	this.setState();
};
disabledFieldsGroup.prototype.disable = function(){
	this.checkbox.checked = false;
	this.setState();
};
disabledFieldsGroup.prototype.enableFields = function(){
	this.fields.invoke("removeClassName", "disabled");
};
disabledFieldsGroup.prototype.disableFields = function(){
	this.fields.each(function(field){
		field.addClassName("disabled");
		if ( field.hasClassName("text") ) {
		    field.value = "";
		} else if ( field.hasClassName("checkbox") ){
		    field.checked = false;
		}
	});
};


/* add modal window ovelay behaviour */
jQuery().ready(function() {
    var trim = function(txt) {
        return txt.replace(/^\s*(.*?)\s*$/, '$1')
    }
    var pageTitle = trim(document.title.match(/^[^-]+/)[0]);

    var pxToInt = function(px) {
        return Number(((px || "").match(/^\d+/) || [0])[0]);
    };

    var spaceTop = function(el) {
        var el = jQuery(el);
        return pxToInt(el.css("padding-top")) +
		pxToInt(el.css("border-top"));
    };

    var spaceBottom = function(el) {
        var el = jQuery(el);
        return pxToInt(el.css("padding-bottom")) +
		pxToInt(el.css("border-bottom"));
    };

    var spaceLeft = function(el) {
        var el = jQuery(el);
        return pxToInt(el.css("padding-left")) +
		pxToInt(el.css("border-left"));
    };

    var spaceRight = function(el) {
        var el = jQuery(el);
        return pxToInt(el.css("padding-right")) +
		pxToInt(el.css("border-right"));
    };

    var fitToWindow = function(el) {
        var verticalMinGap = 50; // combined gap in pixels between element and top and bottom of viewport
        var minSuportedWinHeight = 400;
        var horizontalMinGap = 50; // combined gap in pixels between element and left and right of viewport
        var minSuportedWinWidth = 400;

        var el = jQuery(el);
        var win = jQuery(window);

        // height
        var winHeight = win.height();
        winHeight = winHeight < minSuportedWinHeight ? minSuportedWinHeight : winHeight;
        var elHeight = el.height();
        var paddingTop = spaceTop(el);
        var paddingBottom = spaceBottom(el);
        var topGap = pxToInt(el.css("top"));

        if ((elHeight + paddingTop + paddingBottom + topGap + (verticalMinGap / 2)) > winHeight) {
            var newHeight = winHeight - paddingTop - paddingBottom - verticalMinGap;
            el.addClass("jqmWindow-toobig")
		  .css("height", newHeight + "px")
		  .css("top", (((winHeight - newHeight) / 2) - paddingTop) + "px");
        }

        // width
        var winWidth = win.width();
        winWidth = winWidth < minSuportedWinWidth ? minSuportedWinWidth : winWidth;
        var elWidth = el.width();
        var paddingLeft = spaceLeft(el);
        var paddingRight = spaceRight(el);

        if ((elWidth + paddingLeft + paddingRight + (horizontalMinGap / 2)) > winWidth) {
            var newWidth = winWidth - paddingLeft - paddingRight - horizontalMinGap;
            el.addClass("jqmWindow-toobig")
		  .css("width", newWidth + "px")
		  .css("margin-left", "-" + (newWidth / 2) + "px");
        }
    };

    jQuery.each(jQuery('.jqmWindow'), function(i, el) {
        var infoTitle = trim(jQuery(el).find('h3').first().text());

        var closeButton = document.createElement("a");
        //closeButton.setAttribute('class', 'jqmClose jqmCloseButton');
        closeButton.className = "jqmClose jqmCloseButton";
        closeButton.setAttribute('href', '#');

        var closeText = document.createTextNode("X");
        closeButton.appendChild(closeText);

        el.insertBefore(closeButton, el.firstChild);
        jQuery(el).jqm({
            modal: false,
            trigger: '.' + jQuery.attr(el, 'id') + '-open',
            onShow: function(h) {
                h.w.show();
                fitToWindow(h.w);
                try {
                    pageTracker._trackEvent(pageTitle + " - " + infoTitle + " - open", "open", pageTitle + " - " + infoTitle);
                } catch (e) { }
            },
            onHide: function(h) {
                h.w.hide();
                if (h.o) { h.o.remove() }
                try {
                    pageTracker._trackEvent(pageTitle + " - " + infoTitle + " - close", "close", pageTitle + " - " + infoTitle);
                } catch (e) { }
            }
        });
    })
});	
