﻿// JScript File

function PS_Survey_SetupRealTimeDisplay(inputID,displayID,singularFormat,pluralFormat)
{
    var input = document.getElementById(inputID);
    if (input == null || input.tagName != "INPUT")
        return;

    if( input.type == "text" )
        ValidatorHookupEvent(input, "onkeyup", "_PS_Survey_RealTimeDisplayOnChange('" + inputID + "','"  + displayID + "','" + singularFormat + "','" + pluralFormat + "',event); "); //ASP.NET//
        
    _PS_Survey_DisplayNumber(inputID,displayID,singularFormat,pluralFormat);
}


function PS_Survey_SetupCurrencyRealTimeDisplay(inputID,currencyDropDownID,displayID,singularFormat,pluralFormat)
{
    var input = document.getElementById(inputID);
    var dropdown = document.getElementById(currencyDropDownID);
    if (input == null || input.tagName != "INPUT" || dropdown == null || dropdown.tagName != "SELECT")
        return;

    var func = "_PS_Survey_CurrencyRealTimeDisplayOnChange('" + inputID + "','" + currencyDropDownID + "','"  + displayID + "','" + singularFormat + "','" + pluralFormat + "',event); ";
    if( input.type == "text" )
        ValidatorHookupEvent(input, "onkeyup", func); //ASP.NET//

    func = "_PS_Survey_CurrencyRealTimeDisplayOnDropDownChange('" + inputID + "','" + currencyDropDownID + "','"  + displayID + "','" + singularFormat + "','" + pluralFormat + "',event); ";
    ValidatorHookupEvent(dropdown, "onclick", func); //ASP.NET//
    
    _PS_Survey_DisplayCurrency( inputID, currencyDropDownID, displayID, singularFormat, pluralFormat );
}

function PS_Survey_ValidateElement(inputID,evt)
{
    ValidatorOnChange(evt); //ASP.NET//
    var isvalid = true;
    for(var i=0;i<Page_Validators.length;i++)
        if( Page_Validators[i].controltovalidate == inputID ) 
            isvalid = isvalid && Page_Validators[i].isvalid;
    return isvalid;
}

function _PS_Survey_RealTimeDisplayOnChange(inputID,displayID,singularFormat,pluralFormat,evt)
{
    if( PS_Survey_ValidateElement(inputID,evt) ) 
    {
        _PS_Survey_DisplayNumber(inputID,displayID,singularFormat,pluralFormat);
    }    
}


function _PS_Survey_DisplayNumber(inputID,displayID,singularFormat,pluralFormat)
{
    var html = "";

    var targetedControl = document.getElementById(inputID);
    if (targetedControl != null && targetedControl.value != "")
    {
        var num = null;
        var temp_num = _PS_ValidatorConvert(targetedControl.value);
        if( temp_num != null )
        {
            num = _PS_Survey_FormatNumericAnswer(temp_num, false, true);
        }
        if( num != null )
            html = num == 1 ? singularFormat.replace("{#}",num) : pluralFormat.replace("{#}",num);
        else if(singularFormat.indexOf("{$}") >= 0 )
            html = singularFormat.replace("{$}",targetedControl.value);

    }
    var e = document.getElementById(displayID);
    if(!e)
        return;
    e.innerHTML = html;
}


function _PS_Survey_CurrencyRealTimeDisplayOnChange(inputID,currencyDropDownID,displayID,singularFormat,pluralFormat,evt)
{
    if( PS_Survey_ValidateElement(inputID,evt) ) 
    {
        _PS_Survey_DisplayCurrency(inputID,currencyDropDownID,displayID,singularFormat,pluralFormat);
    }
}

function _PS_Survey_CurrencyRealTimeDisplayOnDropDownChange(inputID,currencyDropDownID,displayID,singularFormat,pluralFormat,evt)
{
    _PS_Survey_DisplayCurrency(inputID,currencyDropDownID,displayID,singularFormat,pluralFormat);
}

function _PS_ValidatorConvert(op)
{
    var num, cleanInput, m, exp, tchar;
    tchar = /,/g;
    exp = new RegExp("^\\d{1,3}(,\\d{3})*(\\.\\d*)?$");
    m = op.match(exp);
    if (m == null)
    {
        tchar = /\./g;
        exp = new RegExp("^\\d{1,3}(\\.\\d{3})*(,\\d*)?$");
        m = op.match(exp);
        
        if (m == null)
        {
            tchar = null;
            //exp = new RegExp("^\\d*$");
            exp = new RegExp("^\\d*([,\.]\\d*)?$");
            m = op.match(exp);
        }
    }
    if (m == null)
        return null;
    if (tchar == null)
        cleanInput = m[0];
    else
        cleanInput = m[0].replace(tchar, "");
    // Only one possible non-numeric remains...the decimal.
    // If "," was used as a decimal place replace it here.
    cleanInput = cleanInput.replace(",",".");
    num = parseFloat(cleanInput);
    return ((isNaN(num) || num > 99999999999999) ? null : num);
}

function _PS_Survey_DisplayCurrency(inputID,currencyDropDownID,displayID,singularFormat,pluralFormat)
{
    var html = "";
    
    var input = document.getElementById(inputID);
    var dropdown = document.getElementById(currencyDropDownID);
    var num = _PS_ValidatorConvert(input.value);
    
    if( num != null )
    {
        var fmt_num = _PS_Survey_FormatNumericAnswer(num,true,true);
        if( input._currencyFormats == null )
            input._currencyFormats = eval('('+input.getAttribute("currencyFormats")+')');
        var txt = dropdown.options[dropdown.selectedIndex].text;
        var code = txt.substr(txt.lastIndexOf("(")+1,3);
        var fmt = input._currencyFormats[code];
        if( fmt != null )
            fmt_num = fmt.replace("{#}",fmt_num);
        else
            fmt_num = code + " " + fmt_num;
        html = num == 1.0 ? singularFormat.replace("{$}",fmt_num) : pluralFormat.replace("{$}",fmt_num);
    }
    
    var e = document.getElementById(displayID);
    e.innerHTML = html;
}

function PS_Survey_ValidateCurrency(source,args)
{
    PS_Survey_ValidateNumeric(source,args, function(n) { return n >= 0.0 && n < 1e18; });
}

function PS_Survey_ValidateNumeric(source,args,lambda)
{
    var num = ValidatorConvert(args.Value,"Double",{decimalchar:'.'}); //ASP.NET//
    if (num == null)
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = typeof(lambda) == "undefined" ? num != null : lambda(num);
    }
}

function PSPage_ValidatorOnLoad() {
    if (typeof(Page_Validators) == "undefined")
        return;
    
    var i, val;
    for (i = 0; i < Page_Validators.length; i++) {
        val = Page_Validators[i];
        if (typeof(val.controltovalidate) == "string")
            PSPage_ValidatorHookupControlID(val.controltovalidate, val);
        if (typeof(val.controlhookup) == "string")
            PSPage_ValidatorHookupControlID(val.controlhookup, val);
    }
}

function PSPage_ValidatorHookupControlID(controlID, val) {
    if (typeof(controlID) != "string") 
        return;

    var ctrl = document.getElementById(controlID);
    if ((typeof(ctrl) != "undefined") && (ctrl != null)) 
        PSPage_ValidatorHookupControl(ctrl, val);
}

function PSPage_ValidatorHookupControl(control, val) {
    if (typeof(control.tagName) != "string") 
       return;
 
    if (control.tagName != "INPUT" && control.tagName != "TEXTAREA" && control.tagName != "SELECT") { 
        var i;
        for (i = 0; i < control.childNodes.length; i++) 
            ValidatorHookupControl(control.childNodes[i], val); //ASP.NET//
        return;
    }
    else if (control.type == "text" )
        ValidatorHookupEvent(control, "onkeyup", "ValidatorOnChange(event); "); //ASP.NET//
}

function _PS_Survey_FormatNumericAnswer(flt, isCurrency, showSeparator)
{
	// can't just use toLocaleString because IE's implementation always shows
    // decimal places.  also it's spottily supported, apparently.
    var result = '';
    if (flt < 0) {
        flt = -flt;
        result = '-';
    }
    
    var minDecimals = 0;
    if ((flt < 100.0) && isCurrency)
        minDecimals = 2;

    var base = Math.floor(flt);
    var rest = Math.round((flt - base) * 10000);
    if (rest >= 10000)
        base++;

    rest = (rest / 10000);

    // we can get away with toString() because we know it's integral and
    // we know it's smaller than the point at which it switches to exp notation
    base = base.toString();

    if (showSeparator) {
        var i;
        var len = base.length;
        for (i = 0; i < len; i++) {
            result += base.charAt(i);
            if ((((len - i - 1) % 3) == 0) && (i != len - 1))
                result += ',';
        }
    }
    else {
        result = base;
    }

    if (rest == 0 || rest == 1) {
        if (minDecimals == 2)
            result += '.00';
    }
    else {
        rest = rest.toString();
        result += rest.substring(1);
        for (i = rest.length + 1; i < minDecimals; i++)
            result += '0';
    }
	return result;
}

function PS_Survey_ValidatorUpdateDisplay(val)
{
    var next = val.nextSibling && val.nextSibling.nodeType == 1 ? val.nextSibling : null;

    if (val.isvalid) {
        val.style.display = "none";    
        //if nextSibling contains wizError css className, then set style.display to none
        if( next && Sys.UI.DomElement.containsCssClass(next,"wizError") )
            next.style.display = "none";
    }
    else {
        var html = val.innerHTML;
        val.innerHTML = "ERROR";
        val.style.textDecoration = "underline";
        val.style.display = "inline";
        val.style.visibility = "visible";
        //if nextSibling doesn't contains wizError css className, create
        if( !next || !Sys.UI.DomElement.containsCssClass(next,"wizError") ) {
            next = document.createElement("div");
            next.className = "wizError";

            if( Sys && Sys.Browser.agent === Sys.Browser.Safari )
                delete next.innerHTML;                

            next.innerHTML = html;
            next._hovering = false;
            next.onmouseout = function() {
	            if ((this._hovering != null) && this._hovering) {   
		            this.style.display = "none";
		            this.previousSibling.style.display = "inline";
	            }
            }

            val.parentNode.insertBefore(next,val.nextSibling);
        }
        next.style.display = "none";
        val.onmouseover = function() {
            if(!this.isvalid) {
                this.nextSibling.style.display = "inline";
                this.nextSibling._hovering = true;
                this.style.display = "none";
            }
        }
    }
}

function PS_Survey_ValidationOnLoad() {
    ValidatorUpdateDisplay = PS_Survey_ValidatorUpdateDisplay;
}

if(window.addEventListener) //DOM method for binding an event
    window.addEventListener("load",PS_Survey_ValidationOnLoad, false);
else if(window.attachEvent) //IE exclusive method for binding an event
    window.attachEvent("onload",PS_Survey_ValidationOnLoad);
else if(document.getElementById) //support older modern browsers
    window.onload = PS_Survey_ValidationOnLoad;
