﻿/* Copyright 2009 by 4IT Limited / Kevin Fairs www.4it.co.uk
* Licenced under: LGPL http://www.gnu.org/licenses/lgpl.html
*
*/

//Centers rows of floated elements (eg li) in a container (eg div) by adjusting the left/right margins. 
//Opera is buggered as the width returned is wrong.
(function($) {
$.fn.centerFloatedElement = function(Container, DefaultMargin) {
    
        var liWidth = parseFloat($.pxToEm(this.outerWidth(false), { 'scope': Container })) + DefaultMargin + DefaultMargin;
        var divWidth = parseFloat($.pxToEm(Container.width(), { 'scope': Container }));
        var NumberAcross = parseInt(divWidth / liWidth);
        var UsedWidth = (liWidth - DefaultMargin - DefaultMargin) * NumberAcross;
        var UnusedWidth = divWidth - UsedWidth;
        var NewMargin = (UnusedWidth / (2 * NumberAcross)).toFixed(2);
        this.css("margin-left", NewMargin + "em");
        this.css("margin-right", NewMargin + "em");
        //Last Row
        var TotalElements = this.size();
        var LastRow = TotalElements - (parseInt(TotalElements / NumberAcross) * NumberAcross);
        if (LastRow != 0) {
            //reprocess last row
            UsedWidth = (liWidth - DefaultMargin - DefaultMargin) * LastRow;
            UnusedWidth = divWidth - UsedWidth;
            NewMargin = UnusedWidth / (2 * LastRow);
            this.slice(TotalElements - LastRow).css("margin-left", NewMargin + "em");
            this.slice(TotalElements - LastRow).css("margin-right", NewMargin + "em");
        }
        return this;
    };
})(jQuery);


// finds all emements matching the ElementPattern and centers these in each element of the collection
(function($) {
    $.fn.centerElementContents = function(ElementPattern, DefaultMargin) {
    this.each(function(i) {
        $(this).find(ElementPattern).centerFloatedElement($(this), DefaultMargin)
        });
     return this;
    };
})(jQuery);


//
$.extend({ URLEncode: function(c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        } 
    } return o;
},
    URLDecode: function(s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});
    
    
    