﻿/*
String Extension Methods
*/

String.prototype.isAlpha = function()
{
    return (this.match(/[A-Za-z]/g) ? true : false);
}

String.prototype.isNumeric = function()
{
    return (this.match(/^\d+$/) ? true : false);
}

String.prototype.isSpecial = function()
{
    return (this.match(/[^A-Za-z0-9]/g) ? true : false);
}

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g, '');
}

String.prototype.ltrim = function()
{
    return this.replace(/^\s+/, "");
}

String.prototype.rtrim = function()
{
    return this.replace(/\s+$/, "");
}

String.prototype.isEmail = function()
{
    var rx = new RegExp("\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    var matches = rx.exec(this);
    return (matches != null && this == matches[0]);
}

String.prototype.isURL = function()
{
    var rx = new RegExp("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-\\+ ./?%:&=#\\[\\]]*)?");
    var matches = rx.exec(this);
    return (matches != null && this == matches[0]);
}

String.prototype.contains = function(t)
{
    return this.indexOf(t) >= 0 ? true : false;
}

String.prototype.beginsWith = function(t, i)
{
    if (i == false)
    {
        return (t == this.substring(0, t.length));
    }
    else
    {
        return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
    }
}

String.prototype.endsWith = function(t, i)
{
    if (i == false)
    {
        return (t == this.substring(this.length - t.length));
    }
    else
    {
        return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase());
    }
}

/* 
Checks a string is a valid date.  
Allowed formats are:
dd/mm/yyyy
mm/dd/yyyy
*/
String.prototype.isValidDate = function(dateFormat)
{
    var delimiter = dateFormat.substring(2, 3);
    var ddStart = dateFormat.substring(0, 2) == "dd" ? true : false;

    var datePartPattern = "^([0-9]{2})" + delimiter + "([0-9]{2})" + delimiter + "([0-9]{4})$";

    var ddPos = 1;
    var mmPos = 2;
    var yyPos = 3;

    if (!ddStart)
    {
        ddPos = 2;
        mmPos = 1;
    }

    var IsoDateRe = new RegExp(datePartPattern);
    var matches = IsoDateRe.exec(this);
    if (!matches) return false;

    var ddVal = matches[ddPos];
    var mmVal = matches[mmPos];
    var yyVal = matches[yyPos];

    var composedDate = new Date(yyVal, (mmVal - 1), ddVal);

    return (
        (composedDate.getMonth() == parseInt(mmVal - 1)) &&
        (composedDate.getDate() == parseInt(ddVal)) &&
        (composedDate.getFullYear() == parseInt(yyVal))
    );
}
