﻿function rh() {
    var _parent = this;
    this.divPleaseWait = null;
    this.imgLoading = null;
    this.fieldControls = {};
    this.isLoadedIFrame = (window.top==window)?false:true;
    this.errToggleOption = 1;//show errContainer for each field;




    function getDocHeight() {
        var D = document;
        return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
    }
    this.pleaseWait = function () {

        var param = arguments[0] == undefined ? { action: 'open'} : arguments[0];
        this.parent = _parent;

        if (!this.parent.divPleaseWait) {
            //alert(getDocHeight());
            //alert(document.body.clientHeight + " " + document.body.offsetHeight);
            var pageActulaHeight = getDocHeight();
            this.parent.divPleaseWait = document.createElement("div");
            this.parent.divPleaseWait.id = "divPleaseWait";

            //create the loading image
            this.parent.imgLoading = document.createElement("img");
            this.parent.imgLoading.src = "../images/ajax-loader-rh.gif";
            this.parent.imgLoading.style.cssText = "position: fixed;  top: 50%;  left: 50%; ";
            this.parent.divPleaseWait.appendChild(this.parent.imgLoading);


            this.parent.divPleaseWait.style.cssText = "position:absolute; top:0; right:0; width:100%; height: " + pageActulaHeight + "px; background-color: #000000; opacity:0.5; filter:alpha(opacity=50)";
            document.getElementsByTagName("body")[0].appendChild(this.parent.divPleaseWait);
            //window.setTimeout(function () { _parent.closePleaseWait(); }, 3000);

            function closeMe() {
            }

        }
    }   // pleaseWait end

    this.closePleaseWait = function () {
       
        this.parent = _parent;
        this.parent.divPleaseWait.removeChild(this.imgLoading);
        this.parent.divPleaseWait.parentNode.removeChild(this.parent.divPleaseWait);
        this.parent.divPleaseWait = null;
       
    }// closePleaseWait end


    this.fieldHelp = loadFieldHelp;
    function loadFieldHelp(e) {
        var eb = null;
        var curLeft = 0;
        var curTop = 0;
        var divHelpLeft = 0;
        var divHelpTop = 0;
        var marginLeft = 10;
        var divHelpId = null;
        var divHelp;
        var targetId;
        var topAdj = 0;
        var helpMessage = "<b>This field has been set to show a help description. You can alter this message by add an attribute rhHelpContent to element.</b>";
        var toggleFlagContainerId ;
        eb = (!e) ? window.event : e;

        if (eb.target) targ = eb.target;
        else if (eb.srcElement) targ = eb.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;

        targetId = $(targ).attr("id")
        divHelpId = targetId + "_" + "divHelp"; ;
        helpMessage = ($(targ).attr("rhHelpContent")) ? ($(targ).attr("rhHelpContent")) : helpMessage;

        targetCoordinates = getActualCoordinates(targ);
        divHelpLeft = marginLeft + targetCoordinates.curLeft + targ.clientWidth;
        divHelpTop = targetCoordinates.curTop;

        toggleFlagContainerId = targetId + "_" + "divToggleFlag";
        if ($('#' + toggleFlagContainerId).attr("id") != undefined) {
            if ($('#' + toggleFlagContainerId).is(":visible")) {
                topAdj = $('#' + toggleFlagContainerId).height();
                divHelpTop += 10 + topAdj;
                //alert(topAdj);
            }
        }

        if ($('#' + divHelpId).attr("id") != undefined) {

            if ($('#' + divHelpId).is(":visible")) {
                $('#' + divHelpId).hide();
            } else {
                $('#' + divHelpId).show();
            }
            $('#' + divHelpId).css("top", divHelpTop + "px");
        } else {
                   
            divHelp = document.createElement("div");
            divHelp.id = divHelpId;
            divHelp.style.cssText = "position:absolute; top:" + divHelpTop + "px; left:" + divHelpLeft + "px; min-width:100px; max-width:200px; min-height: 50px;  background-color: #000000; opacity:0.5; filter:alpha(opacity=50);color:white;border-color:yellow"; 
            document.getElementsByTagName("body")[0].appendChild(divHelp);
            $('#' + divHelpId).html(helpMessage);

        }
      

    }// loadHelp End

    function getActualCoordinates(obj) {

        var curLeft = 0;
        var curTop = 0;
        var retCoordinates = {};
        retCoordinates.curLeft = 0;
        retCoordinates.curTop = 0;
        do {
            retCoordinates.curLeft += obj.offsetLeft;
            retCoordinates.curTop += obj.offsetTop;
        } while (obj = obj.offsetParent);

        return retCoordinates;
    }

    this.hideAllToggleFlag = function () {
        this.parent = _parent;
        for (idx in this.parent.fieldControls.controls) {
            ctr = this.parent.fieldControls.controls[idx];
            this.parent.hideToggleFlag(ctr.ctrID);
           
        }
    }

    this.hideToggleFlag = function (ctrName) {
        divContainerId = ctrName + "_" + "divToggleFlag"; ;
        if (this.parent.errToggleOption == 1) {
             $('#' + ctrName + "_ErrContainer").html("");
             return;
        }        
        if ($('#' + divContainerId).attr("id") != undefined) {
            $('#' + divContainerId).hide(); 
        }
    }
    this.showToggleFlag = function (ctrName, flagImg, flagMessage) {
        this.parent = _parent;
        var eb = null;
        var curLeft = 0;
        var curTop = 0;
        var divContainerLeft = 0;
        var divContainerTop = 0;
        var marginLeft = 0;
        var divContainerId = null;
        var defaultFlagMessage = "<b>Error !</b>";
        var htmlContent ;
        if (flagImg == "default_image")
            flagImg = "<img src=\"../images/exclamation.png\" title=\"" + flagMessage + "\" style=\"cursor:hand\" />";

        htmlContent = flagImg + "<span >" + flagMessage + "</span>";
        if (this.parent.errToggleOption == 1) {
         
            $('#' + ctrName + "_ErrContainer").html(htmlContent);
           
            return;
        }

        targ = window.document.getElementById(ctrName);

        divContainerId = $(targ).attr("id") + "_" + "divToggleFlag"; ;
        //flagMessage = ($(targ).attr("flagMessage")) ? ($(targ).attr("flagMessage")) : flagMessage;
        //alert(flagMessage);
        if (flagMessage == null) {
            flagMessage = defaultFlagMessage;
            if ($(targ).attr("flagMessage"))
                flagMessage = $(targ).attr("flagMessage");
        }

        targetCoordinates = getActualCoordinates(targ);
        divContainerLeft = marginLeft + targetCoordinates.curLeft + targ.offsetWidth; //targ.clientWidth;
        divContainerTop = targetCoordinates.curTop;

        // alert($(targ).attr("id") + " " + targ.clientWidth + "," + targ.offsetWidth);

        if ($('#' + divContainerId).attr("id") != undefined) {
            $('#' + divContainerId).css("top", divContainerTop + "px");
            $('#' + divContainerId).css("left", divContainerLeft + "px");
            $('#' + divContainerId).attr("flagMessage", flagMessage);
            $('#' + divContainerId).html(flagMessage);
            $('#' + divContainerId).show();


        } else {

            var divContainer = document.createElement("div");
            divContainer.id = divContainerId;
            divContainer.style.cssText = "position:absolute; top:" + divContainerTop + "px; left:" + divContainerLeft + "px;color:red";
            document.getElementsByTagName("body")[0].appendChild(divContainer);
            $('#' + divContainerId).html(flagMessage);
            $('#' + divContainerId).attr("flagMessage", flagMessage);

        }
    }                  // load Toggle Flag End


    this.findControl = function(ctrName) {
        this.parent = _parent;
        var ctr;
        for (idx in this.parent.fieldControls.controls) {
            ctr = this.parent.fieldControls.controls[idx];
            if (ctr.ctrID == ctrName) {
                ctr.indexNo = idx;
                return ctr;
            }
        }
    }

    this.initFieldControls = function () {
        this.parent = _parent;
        for (idx in this.parent.fieldControls.controls) {
            ctr = this.parent.fieldControls.controls[idx];
       
            if (ctr.enableOnFocusHelp == "Yes") {
                $('#' + ctr.ctrID).focus(this.parent.fieldHelp);
                $('#' + ctr.ctrID).blur(this.parent.fieldHelp);
            }
        }
    }




    this.validateControls = function (ctrTovalidate) {
        this.parent = _parent;
        var realElement;
        var ctrValue;
        var idx;
        var noErrorFound = true;
        var errMessage = "";
        var boxIsUnchecked = 0;
        var alreadyShown = false;
		var errCtrId = "";
        for (idx in ctrTovalidate.controls) {

            ctr = ctrTovalidate.controls[idx];
            realElement = $('#' + ctr.ctrID);
			
            if ($(realElement).val() != null)
                ctrValue = new String($.trim($(realElement).val()));
            else
                ctrValue = "";

            errorFound = false; //reset flat

         	errCtrId = ctr.ctrID;
				
			if (ctr.errCtrId==undefined) { //check for target error control
				errCtrId = ctr.ctrID;
			}else {
				errCtrId = ctr.errCtrId;
			}
					
			
		  // check blank fields
            errMessage = null;
            this.parent.hideToggleFlag(errCtrId);
            if (ctr.noInputIndicatorx != undefined) {
                // alert(ctrValue);
                // alert($(realElement).get(0).tagName);

            }
            if ($(realElement).attr("type") == "text") {
                $(realElement).val(ctrValue);
            }

            if ($(realElement).attr("type") == "checkbox") {

                boxIsUnchecked = $(realElement).is(":checked") ? 0 : 1;
                errMessage = "You have to tick this box!";
            } else if (($(realElement).get(0).tagName == "SELECT") && (ctrValue == "null")) {
                boxIsUnchecked = 1;
                errMessage = "You have to select from the list!";
            } else {
                errMessage = "You cannot leave this field blank!";
            }

            if ((ctr.isRequired == "Yes") && ((ctrValue.length == 0) || (ctrValue == ctr.noInputIndicator) || (boxIsUnchecked == 1))) {

                noErrorFound = false;
                errorFound = true;
                boxIsUnchecked = 0;

            }


            if ((ctr.minLength != undefined) && (errorFound == false)) {
                if (ctr.minLength > ctrValue.length) {
                    noErrorFound = false;
                    errMessage = ctr.belowMinLengthMsg;
                    errMessage = errMessage.replace("{num}", ctr.minLength);
                    errorFound = true;
                }
            }



            if ((ctr.dataFormat == "email") && (errorFound == false)) {
                if (validateEmail(ctrValue) == false) {
                    noErrorFound = false;
                    errMessage = "This is an invalid email format!";
                    errorFound = true;
                }

            } else if ((ctr.dataFormat == "names") && (errorFound == false)) { //valid name format only  issue 277
                if (validateNames(ctrValue) == false) {
                    noErrorFound = false;
                    errMessage = "No Special characters and numbers allowed, except (-)hypen! ";
                    errorFound = true;
                }


            } else if ((ctr.dataFormat == "phone") && (errorFound == false)) { //valid name format only  issue 276
        
                if (validatePhoneNumber(ctrValue) == false) {
                    noErrorFound = false;
                    errMessage = "Invalid phone number! ";
                    errorFound = true;
                }

            } else if ((ctr.dataType == "numeric") && (errorFound == false) && (ctrValue.length > 0)) {
			    if (isNaN(ctrValue)) {
					errorFound = true;
					errMessage = "Only numeric value is accepted!";
					noErrorFound = false;
				}
            }

            if ((ctr.shouldMatchTo != undefined) && (errorFound == false)) {
                // alert(ctr.shouldMatchTo);
                //shouldMatchTo: "ctl00_content_txtNewPwd"

                if (ctrValue != $('#' + ctr.shouldMatchTo).val()) {
                    noErrorFound = false;
                    errorFound = true;
                    errMessage = "Does not match the value entered in " + ctr.shouldMatchToCaption;
                }

            }


            if ((noErrorFound == false) && (alreadyShown == false)) {
                alreadyShown = true;
                //errMsg = "<div id=\"errContainer\">You might probably entered an incorrect value or missed a required field to fill in.<br /> <br /><span class=\"errRed\"> A red exclamation image </span> [<img src='../images/Exclamation.png' />] appears on the right side of the field indicates an error. Move your mouse pointer over the image so read the error details.</div>";
                errMsg = "<div id=\"errContainer\"><span class= \"errRed\">You may probably entered an incorrect value or missed a required field to fill in.</span><br /> <br /><div class=\"errNote\"><span class=\"errRed\"> A red exclamation image </span> [<img src='../images/Exclamation.png' />] appears on the top left side of the field indicates an error. Errors have to be corrected before registration will be completed</div></div>";
                $('#ctl00_content_responseMessage').html(errMsg);
            }




            if (errorFound) {
               
				var exclamationbasepath = $('#__TEMPLATEPATH__').val();
		        errImg = "<img src=\"" + exclamationbasepath + "images/exclamation.png\" title=\"" + errMessage + "\" style=\"cursor:hand\" />";
			
                this.parent.showToggleFlag(errCtrId, errImg, errMessage);
            }



        }

        return noErrorFound;
    }

  

    function validatePhoneNumber(phone) {
        /* 1. 1234567890 
        2. (123)456-7890 
        3. 123-456-7890 */

        if (phone.length > 0) {
            // var phoneNumberPattern =   /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/; 
            var isvalid = false;
            var phoneNumberPattern = /^\+\d{10}$/; //(123)456-7890 
            isvalid = phoneNumberPattern.test(phone); //first check
			
			if (isvalid == false) {
				 var phoneNumberPattern = /^\d{10}$/; //(123)456-7890 
           		 isvalid = phoneNumberPattern.test(phone); //first check	
			}
			if (isvalid == false) {
                phoneNumberPattern = /^\(?(\d{3}\))\d{3}[-]\d{4}$/; //(123)456-7890 
                isvalid = phoneNumberPattern.test(phone); //first check
            }
            if (isvalid == false) {
                phoneNumberPattern = /^\d{3}[-]\d{3}[-]\d{4}$/; //(123)456-7890 
                isvalid = phoneNumberPattern.test(phone); //first check
            }
        
          
            return isvalid;
        }
    }

    function validateNames(sname) {
        if (sname.length > 0) {
            var objRegExp = /^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\-\s]*$/;
            return objRegExp.test(sname);
        }
    }

    function validateEmail(email) {
        if (email.length > 0) {
            var objRegExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            
            return objRegExp.test(email);
        }

    }

    function validateZipCode(zipCode) {
     
        if (zipCode.length > 0) {
            var pattern = /^\d{5}-\d{4}|\d{5}|[a-zA-Z]\d{1}[a-zA-Z](\-| |)\d{1}[a-zA-Z]\d{1}$/;
            return pattern.test(zipCode);
        }

    }


    function getBrowserID() {

      var browserName=navigator.appName;

      if (browserName == "Microsoft Internet Explorer")
          return 1;
      else if (browserName == "Netscape")
          return 2;
      else
          return 3;
      
    }

    return this;

}// rhFramework end

