﻿function RemoveAllButAlphaNumeric(startString, replaceAmpersand) 
{
    var retval = "";
    
    if (startString == null || startString == undefined) startString = "";

    if (replaceAmpersand == true) {
        startString = startString.replace(new RegExp("&", "g"), "and");    
    }
    
    for(var i=0; i<startString.length; i++)
    {
        var cc = startString.charCodeAt(i);
        
        if (cc >= 48 && cc <= 57) retval += String.fromCharCode(cc);
        else if (cc >= 65 && cc <= 90) retval += String.fromCharCode(cc);
        else if (cc >= 97 && cc <= 122) retval += String.fromCharCode(cc);
    }
    
    return retval;
}

/*IE + Vista sometimes has a problem rendering if a very large div, hence the splitting to 2000px chunks*/
function addModalBG(depth, colour, opacity) {
    var opMS = 100 * opacity;

    var wrapstyle = "position:absolute; \
                    top:0; left:0; \
                    height:100%; \
                    width:100%; z-index:100; overflow:hidden;";

    var style = "background-color:" + colour + "; \
                 -ms-filter: progid:DXImageTransform.Microsoft.Alpha(opacity=" + opMS.toString() + "); \
                filter: progid:DXImageTransform.Microsoft.Alpha(opacity=" + opMS.toString() + ");  \
                opacity:" + opacity.toString() + "; \
                position:absolute; \
                top:0; left:0; \
                height:2000px; \
                max-height:2000px; \
                width:100%; z-index:100;";

    var height = getDocHeight();

    var mod = $("<div style='" + wrapstyle + "'></div>");

    var currRem = height;
    var currY = 0;

    while (currRem > 0) {
        var inner = $("<div style='" + style + "'></div>");

        inner.css("top", currY);
        currRem -= 2000;
        currY += 2000;
        
        mod.append(inner);
    }    
      
    var idClass = "modal" + depth;
    mod.addClass(idClass);
    mod.css("z-index", depth);
    mod.css("height", height);
    $("body").append(mod);
}

function removeModalBG(depth) {
    $(".modal" + depth).remove();
}

function GetShortDate(date) {
    var day = date.getDate().toString();
    var month = (date.getMonth() + 1).toString();

    if (day.length < 2) day = "0" + day;
    if (month.length < 2) month = "0" + month;

    //var retval = date.getDate() + "/" + (date.getMonth()+1) + "/" + date.getFullYear() + " " + date.toLocaleTimeString();
    var retval = day + "/" + month + "/" + date.getFullYear() + " " + date.toLocaleTimeString();

    return retval;
}

function IsDateType(dateObj) {
    return dateObj.constructor === (new Date).constructor;
}

function GetTextWidth(text, jqParent) {
    var tmp = "<div style='position:absolute;'>[txt]</div>";

    var e = $(tmp.replace("[txt]", text));

    jqParent.append(e);
    
    var retval = e.width();
    
    e.remove();
    
    return retval;
    


//    <div id="Test">
//    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
//</div>
// position: absolute;
//    visibility: hidden;
//    height: auto;
//    width: auto;
//var test = document.getElementById("Test");
//test.style.fontSize = fontSize;
//var height = (test.clientHeight + 1) + "px";
//var width = (test.clientWidth + 1) + "px";

}

function getDocHeight() {
    return Math.max(
        $(document).height(),
        $(window).height(),
    /* For opera: */
        document.documentElement.clientHeight
    );
};

function getDocumentHeight() {
    if ($.browser.msie) {
//        var $temp = $("<div>")
//             .css("position", "absolute")
//             .css("left", "-10000px")
//             .append($("body").html());

//        $("body").append($temp);
//        var h = $temp.height();
//        $temp.remove();
        return document.body.scrollHeight; //h;
    }
    return $("body").height();
}

function IsNumeric(input) {
    if (input == 0) return true;
    
    var retval = (input - 0) == input && input.length > 0;

    if (retval) {
        retval = (parseFloat(input) != NaN);
    }

    return retval;
}

$(document).ready(function() {
    $(".bubbX").click(toggleBubb);
});

function toggleBubb(e) {
    var ttl = $(this).children("span");
    var img = $(this).children("img")[0];
    var expander = $(this).parent().prev().children(".bubbExpand");

    var newHeight = parseInt(expander.styleAttr("min-height").replace("px", "").replace("pt", ""));

    var xT = "DETAILS";
    var cT = " CLOSE";
    var currTtl = ttl.html();

    if (currTtl == "MORE" || currTtl == xT) {
        if (currTtl == xT)
            ttl.html(cT);
        else
            ttl.html("CLOSE");
        img.src = img.src.replace("Expand", "Contract");
        newHeight = Math.max(newHeight, expander.children().eq(0).height());

    }
    else {
        if (currTtl == cT)
            ttl.html(xT);
        else
            ttl.html("MORE");

        img.src = img.src.replace("Contract", "Expand");
    }

    expander.animate({ height: newHeight }, 400, function() { if ($.scrollTo) { $.scrollTo(expander.parent().parent(), 200, { offset: -50 }); } });
}

var rxISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
var rxMsAjax = /^\/Date\((d|-|.*)\)\/$/;

function ParseJSONDate(dtString) {
    var a = rxISO.exec(dtString);
    if (a)
        return new Date(Date.UTC(+a[1], +a[2] - 1,
                       +a[3], +a[4], +a[5],
                       +a[6]));
    a = rxMsAjax.exec(dtString);
    if (a) {
        var b = a[1].split(/[-,.+]/);
        return new Date(+b[0]);
    }
    return null;
}

function ParseJSON(json) {
    var obj = eval(json);

    CleanJSON(obj);
    
    return obj;
}

function CleanJSON(obj) {
    if ($.isArray(obj)) {
        for (var ix = 0; ix < obj.length; ix++) {
            this.CleanJSON(obj[ix]);
        }
    }
    else {
        for (property in obj) {
            if (typeof (obj[property]) == "string") {
                if (obj[property].indexOf("/Date(") == 0)
                    obj[property] = ParseJSONDate(obj[property]);
            }
            else if (typeof (obj[property]) == "object")
                CleanJSON(obj[property]);
        }
    }
}
//jQuery.fn.extend({
//    validate: function(fn) {
//        if (fn) {
//            return jQuery.event.add(this[0], "validate", fn, null);
//        } else {
//            var ret = jQuery.event.trigger("validate", null, this[0], false, null);

//            // if there was no return value then the even validated correctly
//            if (ret === undefined)
//                ret = true;

//            return ret;
//        }
//    }
//});

Date.prototype.isSameDay = function(toCompare) {
    return (toCompare.getDate() == this.getDate() && toCompare.getMonth() == this.getMonth() && toCompare.getFullYear() == this.getFullYear());
}

Date.prototype.formatDate2 = function(format) {
    var date = this;
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    
    if (!format)
        format = "dd/MM/yyyy";
        
    //TODO: Redo - time replaces t of september/august!!

    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    if (format.indexOf("MMMM") > -1)
        format = format.replace("MMMM", months[date.getMonth()]);
    else if (format.indexOf("MMM") > -1)
        format = format.replace("MMM", months[date.getMonth()].substr(0, 3));
    else
        format = format.replace("MM", month.toString().padL(2, "0"));

    if (format.indexOf("yyyy") > -1)
        format = format.replace("yyyy", year.toString());
    else if (format.indexOf("yy") > -1)
        format = format.replace("yy", year.toString().substr(2, 2));

    if (format.indexOf("d") > -1)
        format = format.replace("d", date.getDate().toString());
    else
        format = format.replace("dd", date.getDate().toString().padL(2, "0"));

    var hours = date.getHours();

    if (format.indexOf("t") > -1) {
        if (hours > 11)
            format = format.replace("t", "pm")
        else
            format = format.replace("t", "am")
    }

    if (format.indexOf("HH") > -1)
        format = format.replace("HH", hours.toString().padL(2, "0"));
    if (format.indexOf("hh") > -1) {
        if (hours > 12) hours - 12;
        if (hours == 0) hours = 12;
        format = format.replace("hh", hours.toString().padL(2, "0"));
    }

    if (format.indexOf("mm") > -1)
        format = format.replace("mm", date.getMinutes().toString().padL(2, "0"));
    if (format.indexOf("ss") > -1)
        format = format.replace("ss", date.getSeconds().toString().padL(2, "0"));

    return format;
}

String.repeat = function(chr, count) {
    var str = "";
    for (var x = 0; x < count; x++) { str += chr };
    return str;
}

String.prototype.padL = function(width, pad) {
    if (!width || width < 1)
        return this;

    if (!pad) pad = " ";
    var length = width - this.length
    if (length < 1) return this.substr(0, width);

    return (String.repeat(pad, length) + this).substr(0, width);
}

String.prototype.padR = function(width, pad) {
    if (!width || width < 1)
        return this;

    if (!pad) pad = " ";
    var length = width - this.length
    if (length < 1) this.substr(0, width);

    return (this + String.repeat(pad, length)).substr(0, width);
} 
