﻿// author: david leghorn    13/7/07

// purpose: this script file includes generic validation functions that can be utilised by updateable pages.
//          Individual pages will define their own form/page validation functions that can utilise/call
//          the validation helper functions defined in this file

// to use:  1. import this js file in the aspx page's <head> section
//          2. initialise fields to be validated and validation messages arrays in page <head> tag 
//          <script> section

//          IMPORTANT! - do not declare the validateArray and validateMsgArray arrays in your page using 'var' as they are already declared in this script file,
//          in your page head section simply initialise the arrays e.g.
//          validateArray = new Array("txtJobcardNumber","txtPlanningActivity","ddlDiscipline");
//          validateMsgArray = new Array("valJobcardNumber","valPlanningActivity","valDllDiscipline");
        

// GLOBAL VARIABLES:
      
      // NOTE 11/3/08: FailedValBg now defined in universal.js
        
        var FailedValBg = "#ff0000";   // invalid input controls will be highlighted with this background colour
        
        // ValidationArray holds ids of all controls that are to be validated as not empty. This array is set/
        // initialised/populated within the page importing this script
        
        var ValidateArray;
        
        // ValidateMsgArray holds ids of all validation messages. IMPORTANT: the array index locations must match
        // between the ValidateArray and ValidateMsgArray for the element to be validated and its validation message,
        // e.g. if jobcard number textbox id is first array element in ValidateArray, then the jobcard number 
        // textboxe's validation message must be the first element in the ValidateMsgArray - see example below.
        
        var ValidateMsgArray;
        
        
        // NOTE:
        // Validate arrays are initialised within the pages importing this script, e.g.
        // ValidateArray = new Array("txtJobcardNumber","txtPlanningActivity","ddlDiscipline");
        // ValidateMsgArray = new Array("valJobcardNumber","valPlanningActivity","valDllDiscipline");
        
        
        // Holds any date validation error messages - utilised/populated/set by IsValidDate() function 
        var DateValidationErrorMessage = "";
     
     
        // Decimal Input Validation Messages
        var Decimal9_2validationMsg = "<b>Invalid Decimal Value!</b><br />Must be a number not larger than 9999999.99 (max 7 digits to left of decimal point, max 2 digits to right of decimal point). Decimal point is optional, but if you are using a decimal point you must include one or two digits to the right of the decimal point e.g. 33.0, 18.3, 31.01, 89.10";
        var Decimal7_2validationMsg = "<b>Invalid Decimal Value!</b><br />Must be a number not larger than 99999.99 (max 5 digits to left of decimal point, max 2 digits to right of decimal point). Decimal point is optional, but if you are using a decimal point you must include one or two digits to the right of the decimal point e.g. 12345.0, 18.3, 12345.01, 89.10";
        var Decimal5_2validationMsg = "<b>Invalid Decimal Value!</b><br />Must be a number not larger than 999.99 (max 3 digits to left of decimal point, max 2 digits to right of decimal point). Decimal point is optional, but if you are using a decimal point you must include one or two digits to the right of the decimal point e.g. 123.0, 123.3, 123.01, 89.10";

        var DecimalPercentValidationMsg = "<b>Invalid Decimal Percentage!</b><br />Must be a number not larger than 100.00 and not less than 0.00. Decimal point is optional, but if you are using a decimal point you must include one or two digits to the right of the decimal point e.g. 18.0, 33.04, 89.1, 89.10";

        // integer validation message
        var IntegerValidationMsg = "<b>Invalid Integer Value!</b><br />Must be an integer value e.g. 0, 1, -5 .. etc!";
        var IntegerOrEmptyValidationMsg = "<b>Invalid Value!</b><br />Must be an integer value e.g. 0, 1, -5 .. etc, or an empty textbox!";


        // set to true (in the page importing this script) if the page being validated as an "Add/Insert" page.
        // If false (default) - edit/update pages will include value edits highlighted in yellow as expected.
        // Add pages do not use MonitorChanges script (edited value highlighting), therefore we can set this 
        // variable to true ( IsInsertScreen = true ) and any required fields that are completed will have
        // their backgroundColor set to white (this facilitates when a user has missed a required input and then
        // completed it - next time ValidateRequiredFields() function is called, it detects the required
        // field now contains a value and sets the control's background Colour to white (indicating field 
        // is completed/valid).
        // On Edit/Update pages, setting the background colour to white if a required input 
        // control contains a value would interfere with the yellow highlight background colour
        // applied by the MonitorChanges script when a control value has been changed; hence why this 
        // variable should only be set to true in aspx pages that are insert data pages. 
        // * For edit pages you do not need to do anything as the variable is defaulted to false (see below)
        
        var IsInsertScreen = false;
        
        // note: ValidateRequiredFields() Function now takes a parameter to dictate whether or not validating
        // an insert page / insert functionality (true), or validating an update page (false)


// NOTE!!: There are more Global variables defined later in this script page just prior to the functions that
// utilise them


        var InputBoxBgColour = "#FFFFFF";   // normal input box bg colour
        
 // FUNCTIONS:
 
        // checks that all required inputs have been completed - displays validation messages/* for 
        // any incomplete/empty input fields. Returns true if all required inputs
        // are completed, or false if one or more required inputs are empty.
        
        // parameter validateAsInsertScreen added - flags whether or not we are validating data insert
        // (true) or data update (false). IsInsertScreen global variable set to validateAsInsertScreen 
        // parameter value
        
        function ValidateRequiredFields(validateAsInsertScreen)
        {
            IsInsertScreen = validateAsInsertScreen;
            var requiredCompleted = true;
            var objref;
            var objType;
            
            for(i=0; i < ValidateArray.length; i++)
            {
                objref = document.getElementById(ValidateArray[i]);
                objType = objref.type;

                if (objType == "text" || objType == "textarea" || objType == "password" || objType == "file")
                {
                    if(objref.value == "")
                    { 
                        document.getElementById(ValidateMsgArray[i]).style.display = "block";
                        objref.style.backgroundColor = FailedValBg; 
                        requiredCompleted = false;
                    }
                    else  // added 2/07/07 - set bg color to white if an Insert screen to denote required field as completed
                    {
                        if(IsInsertScreen == true) { objref.style.backgroundColor = InputBoxBgColour }
                    }
                }
                
                else if(objType == "select-one")
                {
                    if(objref.selectedIndex <= 0)
                    { 
                        document.getElementById(ValidateMsgArray[i]).style.display = "block";
                        objref.style.backgroundColor = FailedValBg; 
                        requiredCompleted = false; 
                     }
                    else  // added 2/07/07 - set bg color to white if an Insert screen to denote required field as completed
                    {
                        if (IsInsertScreen == true) { objref.style.backgroundColor = InputBoxBgColour; }
                    }
                }
                else  // assuming a radio button group - in ifa project this is only other input object validated
                {
                    var selectionMade = ValidateRadioButtonListSelectionMade(ValidateArray[i]);
                    if(selectionMade == false)
                    {
                        document.getElementById(ValidateMsgArray[i]).style.display = "block"; 
                        requiredCompleted = false; 
                    }
               }
                
            }
            
            // if one or more items failed validation
//            if(requiredCompleted == false)
//            {
//                alert("* please complete required fields!");
//            }
        
            return requiredCompleted;
        }
        

        // Resets validation messages - LOOPs required message array and sets display of message 
        // div tags to none. Called by ValidateRequiredFields() function
        
        function ClearRequiredValidationMessages()
        {
            for(indx=0; indx < ValidateMsgArray.length; indx++)
            {
               document.getElementById(ValidateMsgArray[indx]).style.display = "none";
            }
        }
        
        
        // Checks that passed string parameter is an integer - returns true (if is an integer) or false.
        // function is utilised by Date validation functions (below) but could also be utilised to validate
        // that users have entered an integer number during form input validation
                
        function IsInteger(s)
        {
	        var i;

	        for (i = 0; i < s.length; i++)
	        {   
                        var c = s.charAt(i);

		        if (((c < "0") || (c > "9"))) return false;
    	        }

            // All characters are numbers.

            return true;
        }
        
        
// ---------------------- date validation related functions ------------------------------------------
        
        
        
/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */


function stripCharsInBag(s, bag)
{
	var i;
	var returnString = "";

	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.

	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);

		if (bag.indexOf(c) == -1) returnString += c;
    	}

    return returnString;
}

function daysInFebruary (year)
{
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) 
	{
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   	}
	 
   return this
}


// checks if passed date string parameter is a valid date - returns true if valid or false if invalid.
// if an invalid date - the date validation errors are assigned to global variable DateValidationErrorMessage
// so the date validation problem can be reported to the user e.g. via alert box or div layer

function IsValidDate(dtStr)
{
    var dtCh= "/";
    var minYear=1900;
    var maxYear=3000;
        
    DateValidationErrorMessage = ""; // clear any previous stored validation errors
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}

	// NOTE FOR SELF - COULD USE month, day and year values here to re-assemble date string in
	// universal/american format before submission to server (if site hosted on us server)

	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)

	if (pos1==-1 || pos2==-1)
	{
		//alert("The date format should be : dd/mm/yyyy")
		return false
	}

	if (strMonth.length<1 || month<1 || month>12)
	{
		//alert("Please enter a valid month")
		return false
	}

	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
		//alert("Please enter a valid day")
		return false
	}

	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}

	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || IsInteger(stripCharsInBag(dtStr, dtCh))==false)
	{
		//alert("Please enter a valid date")
		return false
	}


return true

}
		
		
// Checks value is a valid decimal percentage i.e. max 3 digits to left of point and 2 digits to right
// entered value must not be greater than 100 (%).	
	
function ValidateDecimalPercentage(decimalTextboxId, validationDivId)
{
    var isvalidPercentage;
    var decPercentValue = document.getElementById(decimalTextboxId).value;
    
    if(decPercentValue == "")  // blank input can be considered valid as this will be replaced with 0.00 by update code
    {
        isvalidPercentage = true;
        document.getElementById(validationDivId).style.display = "none";
    }
    else  // not blank input string - validate input
    {
        var regExpStr = "(^[0-9]{0,3}[.][0-9]{1,2}$)|(^[0-9]{0,3}$)";
        var regexPercentage = new RegExp(regExpStr);	
        isvalidPercentage = regexPercentage.test(decPercentValue);
        
        if(isvalidPercentage == false)
        { 
            document.getElementById(validationDivId).style.display = "block"; 
        }
        else  // passed regular expression validation, now check value not > 100
        { 
            if( Number(decPercentValue) > 100 )
            { 
                isvalidPercentage = false; 
                document.getElementById(validationDivId).style.display = "block";
                document.getElementById(decimalTextboxId).style.backgroundColor = FailedValBg; // added 31/08/07 ( may mess up edited yellow bg)
            }
            else
            {
                isvalidPercentage = true; 
                document.getElementById(validationDivId).style.display = "none"; 
                document.getElementById(decimalTextboxId).style.backgroundColor = "#ffffff"; // added 31/08/07 ( may mess up edited yellow bg)
            }
           
        }
    }
    
    //alert("is valid decimal percentage = " + isvalidPercentage);
    return isvalidPercentage;
}



// ======================== DECIMAL VALIDATOR OBJECT (DL created/added 25/08/07) =========================

// AllDecimalInputValid : global variable flag set to true or false by ValidateDecimalInputTextboxes()
// function; thus after calling ValidateDecimalInputTextboxes() function, the value of 
// AllDecimalInputValid global variable will indicate (true||false) whether or not all decimal textboxes
// defined in DecimalValidationArray (via DecimalValidator objects) passed validation.

var AllDecimalInputValid = true;

// DecimalValidationArray : global array intialised by page importing this script with 
// DecimalValidator instances for each of the pages input textboxes that must contain a valid decimal value

var DecimalValidationArray = new Array();

// flag used to ensure js prototype only registers methods of object when 1st DecimalValidator object
// is instantaited/created, and not for every DEcimalValidator object created (for performance optimisation)

var DecimalValidatorPrototypeCalled = false;


// DecimalValidator Object Properties (initialised via constructor parameters):
//
// this.TextboxId = id attribute of input textbox containing decimal value to be validated
// this.ValidationMsgId = id attribute of div tag containing invalid decimal validation message
// this.ValidationMsgDisplayType = display type when showing validation message div, must be "block" or "inline"
// this.DigitsToLeftOfPoint = maximum number of digits permitted to left of the decimal point
// this.DigitsToRightOfPoint = maximum number of digits permitted to right of the decimal point

function DecimalValidator(textboxId, validationMsgId, valMsgDisplayType, digitsToLeftOfPoint, digitsToRightOfPoint)
{
    this.TextboxId = textboxId;
    this.ValidationMsgId = validationMsgId;
    this.ValidationMsgDisplayType = valMsgDisplayType;
    this.DigitsToLeftOfPoint = digitsToLeftOfPoint;
    this.DigitsToRightOfPoint = digitsToRightOfPoint;
   // this.AllowEmptyInput = allowEmptyInput;

    if( DecimalValidatorPrototypeCalled == false )     //if (typeof(_searchElement_prototype_called) == 'undefined')
    {
        // utilises js prototype property to register objects methods
        DecimalValidatorPrototypeCalled = true;
        DecimalValidator.prototype.Validate = _validateValue
        DecimalValidator.prototype.ResetDecimalValidationMessage = _resetDecimalValidationMessage
    }
    
    
    // OBJECT METHODS 
    
    // runs regular expression to validate decimal input, if input is not valid shows invalid input
    // div message and sets global variable AllDecimalInputValid = false (thus if any DecimalValidator
    // object has failed validation this variable will be set to false 
    
    function _validateValue()
    {
        var isvalid, regExpString, regex;
        var inputValue = document.getElementById(this.TextboxId).value.Trim();
        
        // V1 validates positive decimals only
        //regExpString = "(^[0-9]{0," + this.DigitsToLeftOfPoint + "}[.][0-9]{1," + this.DigitsToRightOfPoint + "}$)|(^[0-9]{0," + this.DigitsToLeftOfPoint + "}$)";
        
        // V2 also validates negative decimals
        regExpString = "(^[-]{0,1}[0-9]{0," + this.DigitsToLeftOfPoint + "}[.][0-9]{1," + this.DigitsToRightOfPoint + "}$)|(^[-]{0,1}[0-9]{0," + this.DigitsToLeftOfPoint + "}$)";
        
        regex = new RegExp(regExpString);	
        isvalid = regex.test( document.getElementById(this.TextboxId).value.Trim() );
        
        // test
        //alert(this.TextboxId + " is a valid decimal = " + isvalid);
        
        if( isvalid == false )  // set global all decimal input valid flag to false
        {   
           // AllDecimalInputValid = false; 
            document.getElementById(this.ValidationMsgId).style.display = this.ValidationMsgDisplayType;  
            document.getElementById(this.TextboxId).style.backgroundColor=FailedValBg;   //added 31/08/07 (but may mess up edited yellow highlight) 
        }
        else  // else added 31 aug
        {
             document.getElementById(this.TextboxId).style.backgroundColor="#ffffff";  // ADDED 31/08/07
             document.getElementById(this.ValidationMsgId).style.display = "none";
        }
        
        return isvalid;
    }


    function _resetDecimalValidationMessage()
    {
        document.getElementById(this.ValidationMsgId).style.display = "none";
    }

}  // end class


// 
// Loops all Decimal validator objects defined in DecimalValidationArray and calls their Validate() method.
// If any textboxes fail decimal validation, global variable AllDecimalInputValid is set to false (via decimal validator objects Validate() method)

// Step 1 : Call this function to validate all Decimal textboxes defined in the DecimalValidationArray.
// Step 2 : Check value of global variable AllDecimalInputValid (defined in this script file)
// if AllDecimalInputValid = false then 1 or more textboxes failed and do not contain valid decimals (validation message will be
// visible next to the decimal textboxes that do not contain a valid decimal).
// If AllDecimalInputValid = true then all textbox ids in the DecimalValidationArray validated successfully

function ValidateDecimalInputTextboxes()
{
    ResetDecimalValidationMessages();
    AllDecimalInputValid = true;   // set/reset flag to assume all input valid, any invalid decimals will switch value to false
    var l = DecimalValidationArray.length;
    var val;
    for(ix =0; ix < l; ix++)
    {
        val = DecimalValidationArray[ix].Validate();
        if( val == false ) { AllDecimalInputValid = false; }
    }

}


// Loops all decimal validation div ids in DecimalValidationArray and calls ResetDecimalValidationMessage()
// to hide any decimal validation messages displayed on screen

function ResetDecimalValidationMessages()
{
    var len = DecimalValidationArray.length;
    
    for(ix =0; ix < len; ix++)
    {
        DecimalValidationArray[ix].ResetDecimalValidationMessage();
        document.getElementById(DecimalValidationArray[ix].TextboxId).style.backgroundColor = "#ffffff";
    }
}



// ======================== INTEGER VALIDATOR OBJECT (added 25/08/07) =========================

var AllIntegerInputValid = true;
var IntegerValidationArray = new Array();
var IntegerValidatorPrototypeCalled = false;

function IntegerValidator(textboxId, validationMsgId, valMsgDisplayType)
{
    this.TextboxId = textboxId;
    this.ValidationMsgId = validationMsgId;
    this.ValidationMsgDisplayType = valMsgDisplayType;


    if( IntegerValidatorPrototypeCalled == false )     //if (typeof(_searchElement_prototype_called) == 'undefined')
    {
        IntegerValidatorPrototypeCalled = true;
        IntegerValidator.prototype.ValidateInt = _validateIntValue
        IntegerValidator.prototype.ResetIntegerValidationMessage = _resetIntValidationMessage
    }
    

    // ----------------------- CLASS METHODS ----------------------------
    
    function _validateIntValue()
    {
        var intIsValid;
        var inputVal = document.getElementById(this.TextboxId).value.Trim();

        //intIsValid step1 - checks for digits 0 - 9 and also permits digits 0 - 9 starting with - character denoting a -ve integer
        var regExpInt = "(^[0-9]*$)|(^-[0-9]+$)";  // original did not allow 0 in -ve strings regExpInt = "(^[0-9]*$)|(^-[1-9]+$)";
        var regexInt = new RegExp(regExpInt);	
        intIsValid  = regexInt.test( document.getElementById(this.TextboxId).value.Trim() );

        // TO DO : ? intIsValid step2 - checks user has not started string with 0 followed by digits or - followed by 0
        var regExpInt2 = "(^0[0-9]*$)|(^-0[0-9]+$)";  // original did not allow 0 in -ve strings regExpInt = "(^[0-9]*$)|(^-[1-9]+$)";
        var regexInt2 = new RegExp(regExpInt2);
        var invalidStartZero = regexInt2.test( document.getElementById(this.TextboxId).value.Trim() );
        
        if(invalidStartZero == true && inputVal != "0")
        { intIsValid = false; }
        
        if(inputVal == "-0") { intIsValid = false; }

      //  alert(this.TextboxId + " is a valid integer = " + intIsValid);
        
        if( intIsValid == false )  // set global all decimal input valid flag to false
        {   
            //AllIntegerInputValid = false; commented out 15/10/07 - AllIntegerInputValid Flag now set in ValidateIntegerInputTextboxes()
            document.getElementById(this.ValidationMsgId).style.display = this.ValidationMsgDisplayType;    
            document.getElementById(this.TextboxId).style.backgroundColor=FailedValBg;   //added 31/08/07 (but may mess up edited yellow highlight) 
        }
        else  // else added 31 aug
        {
            document.getElementById(this.ValidationMsgId).style.display = "none";
             document.getElementById(this.TextboxId).style.backgroundColor="#ffffff";  // ADDED 31/08/07
        }
        
        return intIsValid;  // added 15/10/07
    }


    function _resetIntValidationMessage()
    {
        document.getElementById(this.ValidationMsgId).style.display = "none";
    }

 }  // end class   


// Loops all IntegerValidator objects stored in IntegerValidationArray array and calls their ValidateInt method
// Object's ValidateInt() method will set global variable AllIntegerInputValid = true if any input is not a valid integer

function ValidateIntegerInputTextboxes()
{
    ResetIntegerValidationMessages();
    AllIntegerInputValid = true;   // set/reset flag to assume all input valid, any invalid decimals will switch value to false
    var l = IntegerValidationArray.length;
    var validInt;
    
    for(ix =0; ix < l; ix++)
    {
        validInt = IntegerValidationArray[ix].ValidateInt();
        if(validInt == false) { AllIntegerInputValid = false; }  // added 15/10/07
    }

}


// Loops all IntegerValidator objects stored in IntegerValidationArray array and calls their
// ResetIntegerValidationMessage() to hide any visible integer validation failure messages

function ResetIntegerValidationMessages()
{
    var len = IntegerValidationArray.length;
    
    for(ix =0; ix < len; ix++)
    {
        IntegerValidationArray[ix].ResetIntegerValidationMessage();
    }
}


// added 16/10/07 - resets background colour of any required textboxes to default white background

function ResetRequiredControlBackgroundColour()
{
    for(i=0; i < ValidateArray.length; i++)
    {
        document.getElementById(ValidateArray[i]).style.backgroundColor = "#ffffff";
    }
}
       
        
        // FormatPrecision - Trims any decimal number strings exceeding 2 decimal places precision 
        // to show only 2 decimal places precision. If value is an integer or is already formatted to
        // 1 or 2 decimal places then simply returns the value unmodified
        
        // parameter1: valueToFormat = value to be checked not exceeding 2 decimal places precision
        // parameter2: precision = decimal precision required (i.e. format value so not exceeding this number of decimal places)
        
        function FormatPrecision(valueToFormat,precision)
        {
            //alert("pre formatted value = " + valueToFormat);
            var formatValue = String(valueToFormat);
            var valueFormated;
            var isDecimal = formatValue.indexOf('.');
            if( isDecimal != -1 )
            {
                var splitDecimal = formatValue.split('.');
                if( splitDecimal.length > 1 )
                {
                    var trimmed = splitDecimal[1].substr(0,precision);
                    valueFormated = splitDecimal[0] + "." + trimmed;
                }
                else
                {
                    valueFormated = splitDecimal[0];   
                }
            }
            else
            {
                valueFormated = formatValue;
            }
            
            //alert("value formatted = " + valueFormated);
            return valueFormated;
        }
        
        
  // ----------------------------------
  // VALIDATES THAT EMAIL ENTRY IS A VALID EMAIL ADDRESS format


function IsValidEMailAddressFormat( emailStr ) 
{
	var str = emailStr;

	var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;

	if ( !str.match(re) ) 
	{
		//alert("Verify the e-mail address format.");
		//setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
		return false;
	}
	
	else 
	{
		return true;
	}


}


function ContainsQuoteCharacters(quoteStr)
{
    var regExpFindQuote = "(')|('')|(&quot;)|(\")";
    var regexQuote = new RegExp(regExpFindQuote);	
    return regexQuote.test(quoteStr);
        
}


function ContainsPotentialHtmlTags(str)
{
   // var htmlRegExp = "</?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)/?>";
   // var htmlRegExp = "/<.*>(.*)<\/\1>/";
   // var htmlIdentifyRegex = new RegExp(/<(.*)>.*<\/\1>/);
   
   //var htmlIdentifyRegex = new RegExp(/<(.*)>/);  // WORKS!
   var htmlIdentifyRegex = new RegExp(/<(.*)/);  // detects html or partial html tag
    return htmlIdentifyRegex.test(str);
}
