﻿
/*---------------------
jQuery functions
-----------------------*/

$(document).ready(function () {

    /*
    -----------------------------------
	
    Fix divBannerFooter column heights
	
    -----------------------------------
    */
    if (document.getElementById('divBannerFooter') != null) {
        var dbfCoordinates = $('divBannerFooter').getCoordinates();
        var dbfHeight = dbfCoordinates.height;
        $('#divBannerFooter div.colWrapper').each(function (col) {
            col.set('styles', { 'min-height': dbfHeight });
        });
    }

    /*
    -----------------------------------
	
    Open links in a new window
		
    Usage:
    Automatically opens links begining http:// or https://
    in a new window. Add a class to the anchor to open other 
    links in a new window. set class name below or leave 
    as default

			
    -----------------------------------
    */
    // Set class sttribute

    /*
    
    var newWinClass = 'newWindowNeeded';
    
    //Add class to links beginning http:// or https://
    
    $(document.body).getElements('a[href^=http://]').addClass(newWinClass);
    $(document.body).getElements('a[href^=https://]').addClass(newWinClass);
    
    //Open specific links in a new window
    
    $$('.' + newWinClass).each(function (el) {
    el.addEvent('click', function (e) {
    e.stop();
    window.open(el.href);
    });
    });

    /*
    -----------------------------------
	
    Add image roll-overs and preloaders
	
    Usage:
    assign class 'rollOver' to image
    default image name must end '-off'
    hover image name must end '-hover'
    MOOTOOLS
    -----------------------------------
    */
    //    $('img.rollOver', 'input.rollOver').each(function (img) {
    //        var src = img.getProperty('src');
    //        var extension = src.substring(src.lastIndexOf('.'), src.length);
    //        var preloadImg = new Image(100, 25);
    //        preloadImg.src = src.replace('off' + extension, 'hover' + extension);
    //        img.mouseenter(function () { img.setProperty('src', preloadImg.src); });
    //        img.mouseleave(function () { img.setProperty('src', src); });
    //        img.focus(function () { img.setProperty('src', preloadImg.src); });
    //        img.blur(function () { img.setProperty('src', src); });
    //    });


    // TM: jQuery compatible version

    $(function () {
        $(".rollOver")
        .mouseover(function () {
            var src = $(this).attr("src");
            var extension = src.substring(src.lastIndexOf('.'), src.length);
            src = src.replace('off' + extension, 'hover' + extension);
            $(this).attr("src", src);
        })
        .mouseout(function () {
            var src = $(this).attr("src");
            var extension = src.substring(src.lastIndexOf('.'), src.length);
            src = src.replace('hover' + extension, 'off' + extension);
            $(this).attr("src", src);
        });
    });

    /*-----------------------------------
    Tabbed content
    -----------------------------------*/

    $('.tabbedSection').each(function (section) {

        section.getElements('.tab').each(function (el) {
            el.addEvent('click', function (e) {
                // Do his on click
                section.getElements('.tab').each(function (el2) {
                    $(el2.get('rel')).set('styles', { 'display': 'none' });
                    el2.removeClass('selected');
                });
                $(el.get('rel')).set('styles', { 'display': 'block' });
                el.addClass('selected');
            });
            // Hide content and push to bottom
            $(el.get('rel')).set('styles', { 'display': 'none' });
            section.grab($(el.get('rel')), 'bottom');
        });
        // Show the first tab content
        $(section.getFirst('.tab').get('rel')).set('styles', { 'display': 'block' });
        $(section.getFirst('.tab')).addClass('selected');

    });


    /*-----------------------------------
    Quote popup
    -----------------------------------*/

    var elem_imgGetQuote = $('imgGetQuote');
    if (elem_imgGetQuote != null) {
        $('imgGetQuote').click(function () {
            $('divPopup').setStyle('display', 'block');
        });
        $('imgGetQuoteClose').click(function () {
            $('divPopup').setStyle('display', 'none');
        });
        $('cbPL').change(function () {
            if ($('cbPL').checked == true) {
                $('cbEL').set('disabled', false);
            } else {
                $('cbEL').set('disabled', true);
                $('cbEL').set('checked', false);
            }
        });
    };

    /*-----------------------------------
    Labels inside inputs
    -----------------------------------*/

    $(':input[label]').each(function () {
        var label = $(this).attr('label');
        if (label != '') {

            if ($.trim($(this).val()) == '') { $(this).val(label); }

            $(this).focus(function () {
                this.setSelectionRange(0, 0);
                styleInput($(this), label, true);
            });

            $(this).keyup(function () {
                styleInput($(this), label, true);
            });

            $(this).blur(function () {
                styleInput($(this), label, false);
            });

            var startsWith = function (str, swith) {
                return str.indexOf(swith) == 0;
            }

            var styleInput = function (e, label, focused) {
                if (focused && $(e).val().indexOf(label) >= 0 && $(e).val() != label) { $(e).val($(e).val().replace(label, '')); }
                else if (!focused && $.trim($(e).val()) == '') { $(e).val(label); }

                var regex = $(e).attr('regexpression');
                var isErr = (regex == undefined) ? false : regexCheck($(e), regex);

                var rem = ""; var add = "";
                if (focused) add += " focused"; else rem += " focused";
                if (focused && $(e).val() == label) add += " faint"; else rem += " faint";
                if (!focused && $(e).val() != label && !isErr) rem += " error";

                $(e).removeClass(rem).addClass(add);
            }
        }
    });



    /*
    -----------------------------------
		
    RadioButton
				
    -----------------------------------
    */

    var processRadioGroup = function (rbClass) {
        var rbs = $('input[name="' + rbClass + '"]');
        //console.log('radio group size:' + $(rbs).size());
        if ($(rbs).size() > 0) {
            var validAns = $(rbs[0]).attr('validanswer');
            if (validAns == undefined)
                validAns = $(rbs[0]).parent().attr('validanswer');

            validAns = validAns.toLowerCase();

            if (validAns == 'Either') return;

            var valid = false;
            rbs.each(function () {
                //console.log('rbs.each(function (). checked:' + $(this).is(':checked') + '. val:' + $(this).attr('val').toLowerCase());
                if ($(this).is(':checked') && $(this).attr('val').toLowerCase() == validAns)
                    valid = true;
            });
            //console.log('validAns:' + validAns + '. valid:' + valid);
            if (!valid) {
                $(rbs[0]).parent().addClass("error");
            }
        }
    }
    $('input[type=radio]').click(function () {
        //console.log('processRadioGroup:' + $(this).attr('name'));
        processRadioGroup($(this).attr('name'));
    });

    $('.questionsCellErrorIcon span:first-child').each(function () {
        var input = $(this).parent().parent().children()[0];
        var inputId = $(input).attr('id');
        if (inputId == undefined) { //drop down
            input = $(this).parent().parent().children()[1];
            inputId = $(input).attr('id');
        }
        if (inputId == undefined) { //radio
            var rb_input = $(input).children()[0];
            inputId = $(rb_input).attr('id');
            inputId = inputId.substring(0, inputId.Length - 1);
        }
        var longdesc_err = 'divTipErr' + inputId;
        var longdesc_help = 'divTipHelp' + inputId;
        var help = $(input).attr('help');

        var img_err = $(document.createElement('img')).addClass('vAlignMiddle').addClass('tooltipToggle').css('width', '16').css('height', '16').attr('title', '')
            .attr('alt', 'Error').hide().attr('src', '/_img/icon-error-info.png').attr('id', 'error' + inputId).attr('longdesc', longdesc_err).appendTo(this);

        if (help != undefined) {
            var img_help = $(document.createElement('img')).addClass('vAlignMiddle').addClass('tooltipToggle').css('width', '16').css('height', '16').attr('title', '')
            .attr('alt', 'More information').attr('src', '/_img/icon-more-info.png').attr('id', 'help' + inputId).attr('longdesc', longdesc_help).appendTo(this);
        }

        var div_err = $(document.createElement('div')).attr('id', longdesc_err).addClass('tooltip').addClass('error').css('display', 'none').appendTo(this);
        $(document.createElement('div')).addClass('tooltipInner').text('Oops! You have missed an answer here.').appendTo(div_err);

        if (help != undefined) {
            var div_help = $(document.createElement('div')).attr('id', longdesc_help).addClass('tooltip').addClass('info').css('display', 'none').appendTo(this);
            $(document.createElement('div')).addClass('tooltipInner').text(help.replace("\'", "\\'")).appendTo(div_help);
        }
        /*
        <img id="errorcp_body_txtTradingAs" class="vAlignMiddle tooltipToggle" width="16" height="16" longdesc="divTipErrorcp_body_txtTradingAs" title="" alt="Error" style="display:none;" src="/_img/icon-error-info.png">
        <img id="helpcp_body_txtTradingAs" class="vAlignMiddle tooltipToggle" width="16" height="16" longdesc="divTipInfocp_body_txtTradingAs" title="" alt="More information" src="/_img/icon-more-info.png">
        <div id="divTipErrorcp_body_txtTradingAs" class="tooltip error" style="display: none;">
        <div class="tooltipInner">Oops! You have missed an answer here. </div>
        </div>
        <div id="divTipInfocp_body_txtTradingAs" class="tooltip info" style="display: none;">
        <div class="tooltipInner">Please tell us exactly how you would like your business name to appear on your policy. If you're a sole proprietor or haven't thought of a name for your business yet, just put your first and last name here. We can change the details for you at a later date. </div>
        </div>
        */
    });

    /*
    -----------------------------------
		
    Tool tips
				
    -----------------------------------
    */
    $('.tooltipToggle').each(function () {
        var target = $(this).attr('longdesc');
        var t = $('#' + target);
        $(t).hide();

        $(this).mouseenter(function () {
            showTooltip($(this), $(t));
        });
        $(this).mouseleave(function () { t.hide(); });

        $(this).focus(function () {
            showTooltip($(this), $(t));
        });
        $(this).blur(function () { t.hide(); });

        var showTooltip = function (parent, child) {
            //console.log('showTooltip');
            //console.log(child);
            //get the position of the placeholder element
            var pos = parent.offset();
            var width = parent.width();
            child.css({ "left": (pos.left + width + 3) + "px", "top": (pos.top - 13) + "px" }).show();
        }
    });

    /*
    -----------------------------------
		
    End domready
				
    -----------------------------------
    */
});

function Dbg() { }
Dbg.Print = function (str) {
    try {
        if (window.console && console.log) {
            console.log(str);
        }
    }
    catch (err) { }
}

function pad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function inputMask(element, mask) {
    var elementValue = element.value.replace(/(\.|-)/g, '');
    var output = "";
    var label = $('#' + element.id).attr('label');
    if (elementValue.length === 0 || elementValue === label)
        return;
    for (var i = 0; i < mask.length; i++) {
        var charMask = mask.charAt(i);
        var charElem = elementValue.charAt(0);
        if (charElem == '')
            break;

        if (charMask != null && charElem != null) {
            if (charMask == "#") {
                var isNumeric = new String(Number(charElem));
                if (isNumeric != 'NaN') {
                    output += charElem;
                }
                //start at pos 1 to lose the first char since we've now used it
                if (elementValue.length > 1) {
                    elementValue = elementValue.substr(1, elementValue.length - 1);
                }
                else {
                    elementValue = "";
                    break;
                }
            }
            else {
                output += charMask;
            }
        }
        else {
            break;
        }
    }

    var phone = element.getAttribute("ID");
    if (phone == "txtPhone" || phone == "txtPhoneCb") {
        var pos = doGetCaretPosition(element);
        element.value = output;
        setCaretPosition(element, pos);
    }
    else
        element.value = output;
}

function formatAsCurrency(elem) {
    var val = elem.value;
    val = val.replace(/[^\d]/g, "");
    var isNumber = !isNaN(val);

    if (isNumber) {
        var num = new Number(val);
        num = num.toFixed(0);
        var money = num.toString();
        var chunks = [];

        var pos = 0;
        while (money.length > 0) {
            if (money.length > 3) {
                chunks.push(money.substr(money.length - 3, 3));
                money = money.substr(0, money.length - 3);
            }
            else {
                chunks.push(money);
                money = "";
            }
            pos++;
        }

        chunks.reverse();

        money = "";
        //alert(chunks.length);
        for (var i = 0; i < chunks.length; i++) {
            if (money.length > 0) {
                money += ",";
            }
            money += chunks[i];
        }

        elem.value = money;
    }
    else {
        //elem.value = "$0"; //doing this makes it impossible single backspace back from NaN
    }

}

function doGetCaretPosition(ctrl) {
    var CaretPos = 0;
    // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;

    return (CaretPos);
}

function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

function validateForm() {
    var pageValid = true;
    $('input[type=text]').each(function () {
        var valid = validateText(this);
        if (!valid) pageValid = false;
    });
    var page = $('#ajax_page').val();
    console.log('validateForm(' + page + '):' + pageValid);
    return pageValid;
}


//*******LIGHTBOX*********

/**
* iBox 2.2 (Build 1612)
* For more info & download: http://www.ibegin.com/labs/ibox/
* Created as a part of the iBegin Labs Project - http://www.ibegin.com/labs/
* For licensing please see readme.html (MIT Open Source License)
*/
var iBox = function () {
    var _pub = {
        // label for the close link
        close_label: '',

        // show iframed content in the parent window
        // this *does not* work with #containers
        inherit_frames: false,

        // how fast to fade in the overlay/ibox (this is each step in ms)
        fade_in_speed: 300,
        fade_out_speed: 300,

        // our attribute identifier for our iBox elements
        attribute_name: 'rel',

        // tags to hide when we show our box
        tags_to_hide: ['select', 'embed', 'object'],

        // default width of the box (when displaying html only)
        // height is calculated automatically
        default_width: 650,

        // public version number
        version_number: '2.2',
        // internal build number
        build_number: '1612',

        // browser checks		
        is_opera: navigator.userAgent.indexOf('Opera/9') != -1,
        is_ie: navigator.userAgent.indexOf("MSIE ") != -1,
        is_ie6: false/*@cc_on || @_jscript_version < 5.7@*/,
        is_firefox: navigator.appName == "Netscape" && navigator.userAgent.indexOf("Gecko") != -1 && navigator.userAgent.indexOf("Netscape") == -1,
        is_mac: navigator.userAgent.indexOf('Macintosh') != -1,

        // url for including images/external files
        base_url: '',

        /**
        * Updates the base_url variable.
        * @param {String} path Relative or absolute path to this file.
        */
        setPath: function (path) {
            _pub.base_url = path;
        },

        /**
        * Checks a container for specified tags containing rel="ibox"
        * @param {Object} container
        * @param {String} tag_name
        */
        checkTags: function (container, tag_name) {
            if (!container) var container = document.body;
            if (!tag_name) var tag_name = 'a';
            var els = container.getElementsByTagName(tag_name);
            for (var i = 0; i < els.length; i++) {
                if (els[i].getAttribute(_pub.attribute_name)) {
                    var t = els[i].getAttribute(_pub.attribute_name);
                    if ((t.indexOf("ibox") != -1) || t.toLowerCase() == "ibox") { // check if this element is an iBox element
                        els[i].onclick = _pub.handleTag;
                    }
                }
            }
        },

        /**
        * Binds arguments to a callback function
        */
        bind: function (fn) {
            var args = [];
            for (var n = 1; n < arguments.length; n++) args.push(arguments[n]);
            return function (e) { return fn.apply(this, [e].concat(args)); };
        },

        /**
        * Sets the content of the ibox
        * @param {String} content HTML content
        * @param {Object} params
        */
        html: function (content, params) {
            if (content === undefined) return els.content;
            if (params === undefined) var params = {};
            if (!active.is_loaded) return;
            _pub.clear();

            _pub.updateObject(els.wrapper.style, { display: 'block', visibility: 'hidden', left: 0, top: 0, height: '', width: '' });

            if (typeof (content) == 'string') els.content.innerHTML = content;
            else els.content.appendChild(content);

            var pagesize = _pub.getPageSize();

            if (params.can_resize === undefined) params.can_resize = true;
            if (params.fade_in === undefined) params.use_fade = true;

            if (params.fullscreen) {
                params.width = '100%';
                params.height = '100%';
            }

            // reset offsets
            offset.container = [els.wrapper.offsetLeft * 2, els.wrapper.offsetTop * 2];
            offset.wrapper = [els.wrapper.offsetWidth - els.content.offsetWidth, els.wrapper.offsetHeight - els.content.offsetHeight];

            // TODO: remove the +4 when issue is solved with calculations
            offset.wrapper[1] += 4;

            if (params.width) var width = params.width;
            else var width = _pub.default_width;

            if (params.height) var height = params.height;
            else {
                els.content.style.height = '100%';
                var height = els.content.offsetHeight + 12;
                els.content.style.height = '';
            }
            active.dimensions = [width, height];
            active.params = params;
            _pub.reposition();

            // XXX: Fix for inline containers which had elements that were hidden
            for (var i = 0; i < _pub.tags_to_hide.length; i++) {
                showTags(_pub.tags_to_hide[i], els.content);
            }

            els.wrapper.style.visibility = 'visible';
        },

        /**
        * Empties the content of the iBox (also hides the loading indicator)
        */
        clear: function () {
            els.loading.style.display = "none";
            while (els.content.firstChild) els.content.removeChild(els.content.firstChild);
        },

        /**
        * Loads text into the ibox
        * @param {String} text
        * @param {String} title
        * @param {Object} params
        */
        show: function (text, title, params) {
            showInit(title, params, function () {
                _pub.html(text, active.params);
            });
        },
        /**
        * Loads a url into the ibox
        * @param {String} url
        * @param {String} title
        * @param {Object} params
        */
        showURL: function (url, title, params) {
            showInit(title, params, function () {
                for (var i = 0; i < _pub.plugins.list.length; i++) {
                    var plugin = _pub.plugins.list[i];
                    if (plugin.match(url)) {
                        active.plugin = plugin;
                        plugin.render(url, active.params);
                        break;
                    }
                }
            });
        },

        /**
        * Hides the iBox
        */
        hide: function () {
            if (active.plugin) {
                // call the plugins unload method
                if (active.plugin.unload) active.plugin.unload();
            }
            active = {}
            _pub.clear();
            // restore elements that were hidden
            for (var i = 0; i < _pub.tags_to_hide.length; i++) showTags(_pub.tags_to_hide[i]);

            els.loading.style.display = 'none';
            els.wrapper.style.display = 'none';
            _pub.fade(els.overlay, _pub.getOpacity(null, els.overlay), 0, _pub.fade_out_speed, function () { els.overlay.style.display = 'none'; });
            _pub.fireEvent('hide');
        },

        /**
        * Repositions the iBox wrapper based on the params set originally.
        */
        reposition: function () {
            if (!active.is_loaded) return;

            // center loading box
            if (els.loading.style.display != 'none') _pub.center(els.loading);

            // update ibox width/height/position
            if (active.dimensions) {
                var pagesize = _pub.getPageSize();

                var width = active.dimensions[0];
                var height = active.dimensions[1];

                if (height.toString().indexOf('%') != -1) {
                    els.wrapper.style.height = (Math.max(document.documentElement.clientHeight, document.body.clientHeight, pagesize.height) - offset.container[0]) * (parseInt(height) / 100) + 'px';
                }
                else if (height) {
                    els.content.style.height = height + 'px';
                    // TODO: if we dont set wrapper height, it doesnt restrict the height and the box is fine
                    // so offset.wrapper[1] must not be correct
                    els.wrapper.style.height = els.content.offsetHeight + offset.wrapper[1] + 'px';
                }
                else {
                    els.wrapper.style.height = els.content.offsetHeight + offset.wrapper[1] + 'px';
                }
                var container_offset = (els.content.offsetHeight - els.content.firstChild.offsetHeight);
                if (width.toString().indexOf('%') != -1) {
                    els.wrapper.style.width = (Math.max(document.documentElement.clientWidth, document.body.clientWidth, pagesize.width) - offset.container[1]) * (parseInt(width) / 100) + 'px';
                    var container_offset = 0;
                }
                else {
                    els.content.style.width = width + 'px';
                    els.wrapper.style.width = els.content.offsetWidth + offset.wrapper[0] + 'px';
                }

                _pub.updateObject(els.content.style, { width: '', height: '' });

                var width = parseInt(els.wrapper.style.width);
                var height = parseInt(els.wrapper.style.height);

                // if we can resize this, make sure it fits in our page bounds
                if (active.params.can_resize) {
                    var x = pagesize.width;
                    var y = pagesize.height;

                    x -= offset.container[0];
                    y -= offset.container[1];
                    if (width > x) {
                        if (active.params.constrain) height = height * (x / width);
                        width = x;
                    }
                    if (height > y) {
                        if (active.params.constrain) width = width * (y / height);
                        height = y;
                    }
                    _pub.updateObject(els.wrapper.style, { width: width + 'px', height: height + 'px' });
                }

                //els.content.style.width = width - offset.wrapper[0] + 'px';
                // TODO: this isn't adjusting to the right height for containers that are smaller than the page height
                // resize the wrappers height based on the content boxes height
                // this needs to be height - ibox_content[margin+padding+border]
                els.content.style.height = height - offset.wrapper[1] + 'px';
                if (active.dimensions != ['100%', '100%']) _pub.center(els.wrapper);
            }

            // fix overlay width/height (cant use css fixed on ie6 or fx or any
            // browser really due to issues)
            // added scrollheight into the equation the overlay didn't size correctly for pages that scrolled MCT 
            els.overlay.style.height = Math.max(document.body.clientHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight) + 'px';
        },

        updateObject: function (obj, params) {
            for (var i in params) obj[i] = params[i];
        },

        /**
        * Centers an object
        * @param {Object} obj
        */
        center: function (obj) {
            var pageSize = _pub.getPageSize();
            var scrollPos = _pub.getScrollPos();
            var emSize = _pub.getElementSize(obj);
            var x = Math.round((pageSize.width - emSize.width) / 2 + scrollPos.scrollX);
            var y = Math.round((pageSize.height - emSize.height) / 2 + scrollPos.scrollY);
            if (obj.offsetLeft) x -= obj.offsetLeft;
            if (obj.offsetTop) y -= obj.offsetTop;
            if (obj.style.left) x += parseInt(obj.style.left);
            if (obj.style.top) y += parseInt(obj.style.top);
            // this nearly centers it due to scrollbars
            x -= 10;
            _pub.updateObject(obj.style, { top: y + 'px', left: x + 'px' });
        },

        getStyle: function (obj, styleProp) {
            if (obj.currentStyle)
                return obj.currentStyle[styleProp];
            else if (window.getComputedStyle)
                return document.defaultView.getComputedStyle(obj, null).getPropertyValue(styleProp);
        },

        /**
        * Gets the scroll positions
        */
        getScrollPos: function () {
            var docElem = document.documentElement;
            return {
                scrollX: document.body.scrollLeft || window.pageXOffset || (docElem && docElem.scrollLeft),
                scrollY: document.body.scrollTop || window.pageYOffset || (docElem && docElem.scrollTop)
            };
        },

        /**
        * Gets the page constraints
        */
        getPageSize: function () {
            return {
                width: window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth,
                height: window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight
            };
        },

        /**
        * Gets an objects offsets
        * @param {Object} obj
        */
        getElementSize: function (obj) {
            return {
                width: obj.offsetWidth || obj.style.pixelWidth,
                height: obj.offsetHeight || obj.style.pixelHeight
            };
        },

        fade: function (obj, start, end, speed, callback) {
            if (start === undefined || !(start >= 0) || !(start <= 100)) var start = 0;
            if (end === undefined || !(end >= 0) || !(end <= 100)) var end = 100;
            if (speed === undefined) var speed = 0;

            if (obj.fader) clearInterval(obj.fader);

            if (!speed) {
                _pub.setOpacity(null, obj, end);
                if (callback) callback();
            }

            var opacity_difference = end - start;
            var time_total = speed; // time is speed (jQuery compat)
            var step_size = 25; // step size in ms
            var steps = time_total / step_size; // total number of steps
            var increment = Math.ceil(opacity_difference / steps); // how much to incr per step

            obj.fader = setInterval(_pub.bind(function (e, obj, increment, end, callback) {
                var opacity = _pub.getOpacity(e, obj) + increment;
                _pub.setOpacity(e, obj, opacity);
                if ((increment < 0 && opacity <= end) || (increment > 0 && opacity >= end)) {
                    _pub.setOpacity(e, obj, end);
                    clearInterval(obj.fader);
                    if (callback) callback();
                }
            }, obj, increment, end, callback), step_size);
        },

        /**
        * Sets the opacity of an element
        * @param {Object} obj
        * @param {Integer} value
        */
        setOpacity: function (e, obj, value) {
            value = Math.round(value);
            obj.style.opacity = value / 100;
            obj.style.filter = 'alpha(opacity=' + value + ')';
        },

        /**
        * Gets the opacity of an element
        * @param {Object} obj
        * @return {Integer} value
        */
        getOpacity: function (e, obj) {
            return _pub.getStyle(obj, 'opacity') * 100;
        },

        /**
        * Creates a new XMLHttpRequest object based on browser
        */
        createXMLHttpRequest: function () {
            var http;
            if (window.XMLHttpRequest) { // Mozilla, Safari,...
                http = new XMLHttpRequest();
                if (http.overrideMimeType) {
                    // set type accordingly to anticipated content type
                    http.overrideMimeType('text/html');
                }
            }
            else if (window.ActiveXObject) { // IE
                try {
                    http = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    try {
                        http = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) { }
                }
            }
            if (!http) {
                alert('Cannot create XMLHTTP instance');
                return false;
            }
            return http;
        },

        addEvent: function (obj, evType, fn) {
            if (obj.addEventListener) {
                obj.addEventListener(evType, fn, false);
                return true;
            }
            else if (obj.attachEvent) {
                var r = obj.attachEvent("on" + evType, fn);
                return r;
            }
            else {
                return false;
            }
        },

        addEventListener: function (name, callback) {
            if (!events[name]) events[name] = new Array();
            events[name].push(callback);
        },

        /**
        * Causes all event listeners attached to `name` event to
        * execute.
        * @param {String} name Event name
        */
        fireEvent: function (name) {
            if (events[name] && events[name].length) {
                for (var i = 0; i < events[name].length; i++) {
                    var args = [];
                    for (var n = 1; n < arguments.length; n++) args.push(arguments[n]);
                    // Events returning false stop propagation
                    if (events[name][i](args) === false) break;
                }
            }
        },

        /**
        * Parses the arguments in the rel attribute
        * @param {String} query
        */
        parseQuery: function (query) {
            var params = new Object();
            if (!query) return params;
            var pairs = query.split(/[;&]/);
            var end_token;
            for (var i = 0; i < pairs.length; i++) {
                var keyval = pairs[i].split('=');
                if (!keyval || keyval.length != 2) continue;
                var key = unescape(keyval[0]);
                var val = unescape(keyval[1]);
                val = val.replace(/\+/g, ' ');
                if (val[0] == '"') var token = '"';
                else if (val[0] == "'") var token = "'";
                else var token = null;
                if (token) {
                    if (val[val.length - 1] != token) {
                        do {
                            i += 1;
                            val += '&' + pairs[i];
                        }
                        while ((end_token = pairs[i][pairs[i].length - 1]) != token)
                    }
                    val = val.substr(1, val.length - 2);
                }
                if (val == 'true') val = true;
                else if (val == 'false') val = false;
                else if (val == 'null') val = null;
                params[key] = val;
            }
            return params;
        },
        /**
        * Handles the onclick event for iBox anchors.
        * @param {Event} e
        */
        handleTag: function (e) {
            var t = this.getAttribute('rel');
            var params = _pub.parseQuery(t.substr(5, 999));
            if (params.target) var url = params.target;
            else if (this.target && !params.ignore_target) var url = this.target;
            else var url = this.href;
            var title = this.title;
            if (_pub.inherit_frames && window.parent) window.parent.iBox.showURL(url, title, params);
            else _pub.showURL(url, title, params);
            return false;
        },

        plugins: {
            list: new Array(),
            register: function (func, last) {
                if (last === undefined) var last = false;
                if (!last) {
                    _pub.plugins.list = [func].concat(_pub.plugins.list);
                }
                else {
                    _pub.plugins.list.push(func);
                }
            }
        }
    };

    // private methods and variables
    var active = {};

    // events
    var events = {};

    // some containers
    // we store these in memory instead of finding them each time
    var els = {};

    var offset = {};

    /**
    * Creates the iBox container and appends it to an element
    * @param {HTMLObject} elem Container to attach to
    * @return {HTMLObject} iBox element
    */
    var create = function (elem) {
        pagesize = _pub.getPageSize();

        // TODO: why isnt this using DOM tools
        // a trick on just creating an ibox wrapper then doing an innerHTML on our root ibox element
        els.container = document.createElement('div');
        els.container.id = 'ibox';

        els.overlay = document.createElement('div');
        els.overlay.style.display = 'none';
        _pub.setOpacity(null, els.overlay, 0);
        // firefox mac has issues with opacity and flash
        if (!_pub.is_firefox) els.overlay.style.background = '#000000';
        else els.overlay.style.backgroundImage = "url('http://www.policybee.co.uk/_img/bg.png')";
        els.overlay.id = 'ibox_overlay';
        params = { position: 'absolute', top: 0, left: 0, width: '100%' };
        _pub.updateObject(els.overlay.style, params);
        els.overlay.onclick = _pub.hide;
        els.container.appendChild(els.overlay);

        els.loading = document.createElement('div');
        els.loading.id = 'ibox_loading';
        els.loading.innerHTML = 'Loading...';
        els.loading.style.display = 'none';
        els.loading.onclick = _pub.hide
        els.container.appendChild(els.loading);

        els.wrapper = document.createElement('div')
        els.wrapper.id = 'ibox_wrapper';
        _pub.updateObject(els.wrapper.style, { position: 'absolute', top: 0, left: 0, display: 'none' });

        els.content = document.createElement('div');
        els.content.id = 'ibox_content';
        _pub.updateObject(els.content.style, { overflow: 'auto' })
        els.wrapper.appendChild(els.content);

        var child = document.createElement('div');
        child.id = 'ibox_footer_wrapper';

        var child2_img = document.createElement('img');
        child2_img.setAttribute("src", "../../_img/lightbox/closelabel.gif");
        child2_img.id = 'close_img1';

        var child2 = document.createElement('a');
        child2.innerHTML = _pub.close_label;
        child2.href = 'javascript:void(0)';
        child2.onclick = _pub.hide;
        child2.appendChild(child2_img);
        child.appendChild(child2);

        els.footer = document.createElement('div');
        els.footer.id = 'ibox_footer';
        els.footer.innerHTML = '&nbsp;';
        child.appendChild(els.footer);
        els.wrapper.appendChild(child);

        els.container.appendChild(els.wrapper);

        elem.appendChild(els.container);

        _pub.updateObject(els.wrapper.style, { right: '', bottom: '' });

        return els.container;
    };

    /**
    * Hides tags within the container
    * @param {String} tag The name of the tag (e.g. 'a')
    * @param {HTMLObject} container The container to restore tags within (defaults to document)
    */
    var hideTags = function (tag, container) {
        if (container === undefined) var container = document.body;
        var list = container.getElementsByTagName(tag);
        for (var i = 0; i < list.length; i++) {
            if (_pub.getStyle(list[i], 'visibility') != 'hidden' && list[i].style.display != 'none') {
                list[i].style.visibility = 'hidden';
                list[i].wasHidden = true;
            }
        }
    };

    /**
    * Shows all previously hidden tags in a container.
    * @param {String} tag The name of the tag (e.g. 'a')
    * @param {HTMLObject} container The container to restore tags within (defaults to document)
    */
    var showTags = function (tag, container) {
        if (container === undefined) var container = document.body;
        var list = container.getElementsByTagName(tag);
        for (var i = 0; i < list.length; i++) {
            if (list[i].wasHidden) {
                list[i].style.visibility = 'visible';
                list[i].wasHidden = null;
            }
        }
    };

    var showInit = function (title, params, callback) {
        if (!_initialized) initialize();
        if (params === undefined) var params = {};
        if (active.plugin) _pub.hide();

        active.is_loaded = true;
        active.params = params;

        els.loading.style.display = "block";

        _pub.center(els.loading);
        _pub.reposition();

        // hide tags
        for (var i = 0; i < _pub.tags_to_hide.length; i++) {
            hideTags(_pub.tags_to_hide[i]);
        }

        // set title here
        els.footer.innerHTML = title || "&nbsp;";

        // setup background
        els.overlay.style.display = "block";

        if (!_pub.is_firefox) var amount = 70;
        else var amount = 100;
        _pub.fade(els.overlay, _pub.getOpacity(null, els.overlay), amount, _pub.fade_in_speed, callback);

        _pub.fireEvent('show');
    };

    var drawCSS = function () {
        // Core CSS (positioning/etc)
        var core_styles = "#ibox {z-index:1000000;text-align:left;} #ibox_overlay {z-index:1000000;} #ibox_loading {position:absolute;z-index:1000001;} #ibox_wrapper {margin:30px;position:absolute;top:0;left:0;z-index:1000001;} #ibox_content {z-index:1000002;margin:27px 5px 5px 5px;padding:2px;} #ibox_content object {display:block;} #ibox_content .ibox_image {width:100%;height:100%;margin:0;padding:0;border:0;display:block;} #ibox_footer_wrapper a {float:right;display:block;outline:0;margin:0;padding:0;} #ibox_footer_wrapper {text-align:left;position:absolute;top:5px;right:5px;left:5px;white-space:nowrap;overflow:hidden;}";

        // Default style/theme/skin/whatever
        var default_skin = "#ibox_footer_wrapper {font-weight:bold;height:20px;line-height:20px;} #ibox_footer_wrapper a {text-decoration:none;background:#888;border:1px solid #666;line-height:16px;padding:0 5px;color:#333;font-weight:bold;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:10px;} #ibox_footer_wrapper a:hover {background-color:#bbb;color:#111;} #ibox_footer_wrapper {font-size:12px;font-family:Verdana, Arial, Helvetica, sans-serif;color:#111;} #ibox_wrapper {border:1px solid #ccc;} #ibox_wrapper {background-color:#999;}#ibox_content {background-color:#eee;border:1px solid #666;} #ibox_loading {padding:50px; background:#000;color:#fff;font-size:16px;font-weight:bold;}";

        var head = document.getElementsByTagName("head")[0];

        // tricky hack for IE
        // because IE doesn't like when you insert stuff the proper way
        // and we cant use relative paths to include this as an external
        // stylesheet
        var htmDiv = document.createElement('div');

        htmDiv.innerHTML = '<p>x</p><style type="text/css">' + default_skin + '</style>';
        head.insertBefore(htmDiv.childNodes[1], head.firstChild);

        htmDiv.innerHTML = '<p>x</p><style type="text/css">' + core_styles + '</style>';
        head.insertBefore(htmDiv.childNodes[1], head.firstChild);
    };

    var _initialized = false;
    var initialize = function () {
        // make sure we haven't already done this
        if (_initialized) return;
        _initialized = true;
        // elements here start the look up from the start non <a> tags
        drawCSS();
        var els = document.getElementsByTagName('script');
        var src;
        for (var i = 0, el = null; (el = els[i]); i++) {
            if (!(src = el.getAttribute('src'))) continue;
            src = src.split('?')[0];
            if (src.substr(src.length - 8) == '/ibox.js') {
                _pub.setPath(src.substr(0, src.length - 7));
                break;
            }
        }
        create(document.body);
        _pub.checkTags(document.body, 'a');
        _pub.http = _pub.createXMLHttpRequest();
        _pub.fireEvent('load');
    };

    _pub.addEvent(window, 'keypress', function (e) { if (e.keyCode == (window.event ? 27 : e.DOM_VK_ESCAPE)) { iBox.hide(); } });
    _pub.addEvent(window, 'resize', _pub.reposition);
    _pub.addEvent(window, 'load', initialize);
    _pub.addEvent(window, 'scroll', _pub.reposition);

    // DEFAULT PLUGINS

    /**
    * Handles embedded containers in the page based on url of #container.
    * This _ONLY_ works with hidden containers.
    */
    var iBoxPlugin_Container = function () {
        var was_error = false;
        var original_wrapper = null;
        return {
            /**
            * Matches the url and returns true if it fits this plugin.
            */
            match: function (url) {
                return url.indexOf('#') != -1;
            },
            /**
            * Called when this plugin is unloaded.
            */
            unload: function () {
                if (was_error) return;
                var elemSrc = _pub.html().firstChild;
                if (elemSrc) {
                    elemSrc.style.display = 'none';
                    original_wrapper.appendChild(elemSrc);
                }
            },
            /**
            * Handles the output
            * @param {iBox} ibox
            * @param {String} url
            * @return {iBoxContent} an instance or subclass of iBoxContent
            */
            render: function (url, params) {
                was_error = false;
                var elemSrcId = url.substr(url.indexOf("#") + 1);
                var elemSrc = document.getElementById(elemSrcId);
                // If the element doesnt exist, break the switch
                if (!elemSrc) {
                    was_error = true;
                    _pub.html(document.createTextNode('There was an error loading the document.'), params);
                }
                else {
                    original_wrapper = elemSrc.parentNode;
                    elemSrc.style.display = 'block';
                    _pub.html(elemSrc, params);
                }
            }
        }
    } ();
    _pub.plugins.register(iBoxPlugin_Container, true);

    /**
    * Handles images
    */
    var iBoxPlugin_Image = function () {
        // Image types (for auto detection of image display)
        var image_types = /\.jpg|\.jpeg|\.png|\.gif/gi;

        return {
            match: function (url) {
                return url.match(image_types);
            },

            render: function (url, params) {
                var img = document.createElement('img');
                img.onclick = _pub.hide;
                img.className = 'ibox_image'
                img.style.cursor = 'pointer';
                img.onload = function () {
                    _pub.html(img, { width: this.width, height: this.height, constrain: true })
                }
                img.onerror = function () {
                    _pub.html(document.createTextNode('There was an error loading the document.'), params);
                }
                img.src = url;
            }
        }
    } ();
    _pub.plugins.register(iBoxPlugin_Image);

    var iBoxPlugin_YouTube = function () {
        var youtube_url = /(?:http:\/\/)?(?:www\d*\.)?(youtube\.(?:[a-z]+))\/(?:v\/|(?:watch(?:\.php)?)?\?(?:.+&)?v=)([^&]+).*/;
        return {
            match: function (url) {
                return url.match(youtube_url);
            },

            render: function (url, params) {
                var _match = url.match(youtube_url);
                var domain = _match[1];
                var id = _match[2];
                params.width = 425;
                params.height = 355;
                params.constrain = true;
                var html = '<span><object width="100%" height="100%" style="overflow: hidden; display: block;"><param name="movie" value="http://www.' + domain + '/v/' + id + '"/><param name="wmode" value="transparent"/><embed src="http://www.' + domain + '/v/' + id + '" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object></span>';
                _pub.html(html, params);
            }
        }
    } ();
    _pub.plugins.register(iBoxPlugin_YouTube);

    var iBoxPlugin_Document = function () {
        return {
            match: function (url) {
                return true;
            },

            render: function (url, params) {
                _pub.http.open('get', url, true);

                _pub.http.onreadystatechange = function () {
                    if (_pub.http.readyState == 4) {
                        // XXX: why does status return 0?
                        if (_pub.http.status == 200 || _pub.http.status == 0) {
                            _pub.html(_pub.http.responseText, params);
                        }
                        else {
                            _pub.html(document.createTextNode('There was an error loading the document.'), params);
                        }
                    }
                }
                _pub.http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                try {
                    _pub.http.send(null);
                }
                catch (ex) {
                    _pub.html(document.createTextNode('There was an error loading the document.'), params);
                }
            }
        };
    } ();
    _pub.plugins.register(iBoxPlugin_Document, true);

    return _pub;
} ();



function validateDdl(control, errorOnValue, errorMessage, type) {
    value = control.value;
    var hasHelp = control.getAttribute("hasHelp");

    var isError = new Boolean(false);
    var errorValues = errorOnValue.split('|');
    for (var i = 0; i < errorValues.length; i++) {
        if (value == errorValues[i]) {
            isError = new Boolean(errorValues[i]);
            break;
        }
    }

    // Show / Hide payroll question on default page
    if (control.id == "ddlNoEmployees") {
        if (value != "0" && value != "Select") {
            document.getElementById("payrollQuestion").style.display = "block";
        }
        else {
            document.getElementById("payrollQuestion").style.display = "none";
        }
    }


    setInputAsError(control.id, isError == true);

    if (isError == false) {
        if (control.id == 'ddlCategory') {
            var occ_array = ASP.ecomms_step1_aspx.getOccupations(value).value;
            //var occ_array = activity_list.split(",");

            // Remove the existing list of options
            var eleMainAct = document.getElementById("ddlMainActivity");
            while (eleMainAct.options.length > 0) {
                eleMainAct.remove(eleMainAct.options.length - 1);
            }
            // Now add in the new ones
            for (i = 0; i < occ_array.length; i++) {
                var newOption = document.createElement('option');
                newOption.text = occ_array[i];
                newOption.value = occ_array[i];
                eleMainAct.options.add(newOption, i);
            }
        }
        if (control.id == 'ddlMainActivity') {
            ASP.ecomms_step1_aspx.setMainActivitySessionVar(value);
        }

        if (control.id == "ddlAddressSel") {
            addressSelect(control, 'ASP.ecomms_defaultb_aspx');
        }

        if (control.id == "ddlAddressSelArch") {
            addressSelect(control, 'ASP.ecomms_architects_aspx');
        }

        if (control.id == "ddlAddressSelEng") {
            addressSelect(control, 'ASP.ecomms_engineers_aspx');
        }

        if (control.id == "ddlAddressSelSurv") {
            addressSelect(control, 'ASP.ecomms_surveyors_aspx');
        }
    }
}


function setInputAsError(controlId, err) {
    setInputAsError(controlId, valid, err)
}

function setInputAsError(controlId, objValid, err) {
    if (controlId == "")
        return;

    objValid.valid = !err;

    if (err)
        console.log(controlId + ', err:' + err);

    var control = document.getElementById(controlId);
    if (control == null) {
        //maybe the control got pulled during render
        console.log('null control passed in - ' + controlId);
        return;
    }

    if (controlId.indexOf('rb') == 0) { controlId = controlId.substring(0, controlId.length - 1); }
    var labelId = controlId.replace(/(txt|ddl|rb)/i, 'lbl');

    var lbl = document.getElementById(labelId);
    var divName = "error" + controlId;
    var div = document.getElementById(divName);

    if (div != null) {
        div.style.display = err ? 'inline' : 'none';
    }

    if (err) {
        if (lbl != null) {
            if (lbl.className.indexOf(" error") < 0) {
                lbl.className += " error";
            }
        }
        if (control.className.indexOf(" error") < 0) {
            control.className += " error";
        }
    }
    else {
        if (lbl != null) {
            lbl.className = lbl.className.replace(' error', '');
        }
        if (control.className.indexOf(" error") >= 0) {
            control.className = control.className.replace(' error', '');
        }
    }
} // END : function setInputAsError(controlId, err)



function validateTxt(control, expression, errorMessage, currency) {
    var value = control.value;
    var hasHelp = control.getAttribute("hasHelp");
    var div;
    var divName;
    //(control,expression,errorMessage,currency)');

    var isErr = !value.match(expression);
    if (!isErr && currency) {
        var money = parseFloat(value.replace(/,/g, ''));
        if (control.id == "txtPayroll") {
            var employees = document.getElementById("ddlNoEmployees").value;
            if (employees != "0") {
                if (money < 1) isErr = true;
            }
        }
        else if (money < 1) isErr = true;
    }

    if (currency == "true") {
        value = value.replace("£", '');
        control.value = "£" + value;
    }
    else {
        control.value = value;
    }

    if (!isErr && (control.id == 'txtEmail' || control.id == 'txtConfirmEmail')) {
        if (document.getElementById("txtConfirmEmail") != null) {
            if (document.getElementById("txtConfirmEmail").value != "") {
                if (document.getElementById("txtEmail").value != document.getElementById("txtConfirmEmail").value) {
                    setInputAsError('txtEmail', true);
                    setInputAsError('txtConfirmEmail', true);
                    isErr = true;
                }
                else {
                    setInputAsError('txtConfirmEmail', false);
                    setInputAsError('txtEmail', false);
                    isErr = false;
                }
            }
        }
    }

    setInputAsError(control.id, isErr);
    control.value = value;
}

function regexCheck(control,regex) {
    if (regex.match("^\/(.*)\/$")) {
        if (regex.length > 2) {
            regex = regex.substring(1, regex.length - 1);
        }
    }

    var _val = $(control).val();
    var isErr = !_val.match(regex);
    if ($(control).attr('id') == "txtPhone" && _val.length > 9) {
        isErr = false;
    }
    if ($(control).attr('questionId') == "34") {
        validatePolicyStartDate();
    }
    return isErr;
}

function oValid() {
    this.valid = true;
}

function validateText(control, page) {
    if (!$(control).is(":visible")) {
        console.log('avoiding validation of control due to non-visibility: ' + control.id);
        return true;
    }

    var page = $('#ajax_page').val();
    var value = $(control).val();
    var errorColumn = control.errorColumn;
    var hasHelp = control.getAttribute("hasHelp");
    var isRequired = control.getAttribute("isRequired");
    var qid = $(control).attr('questionId');
    var label = $(control).attr('label');
    var currency = $(control).attr('currency');
    var regex = $(control).attr('regexpression');
    var div;
    var divName;
    var objValid = oValid;

    control.value = value;

    control.value = control.value.replace(/</g, "");
    control.value = control.value.replace(/>/g, "");
    control.value = control.value.replace(/\\/g, "");
    control.value = control.value.replace(/{/g, "");
    control.value = control.value.replace(/}/g, "");
    control.value = control.value.replace(/\(/g, "");
    control.value = control.value.replace(/\)/g, "");
    //control.value = control.value.replace(/\//g, ""); / must be allowed thru
    control.value = control.value.replace(/&/g, "");

    if (currency != undefined && currency.toLowerCase() === "true" && control.value === "0") {
        control.value = "";
    }

    if (regex != undefined) {
        var isErr = regexCheck(control, regex);
        setInputAsError(control.id, objValid, isErr);
    }
    else {
        setInputAsError(control.id, objValid, (($.trim(control.value) == "" || control.value == label) && isRequired == "True"));
    }    
    //if (!objValid.valid)
        //console.log(control.id + ',value:' + value);


    if (control.getAttribute("id") == "txtSecurityCode") {
        if (document.getElementById("ddlCardType").value == "American Express") {
            if (value.length != 4) {
                setInputAsError(control.id, objValid, true);
            }
            else {
                setInputAsError(control.id, objValid, false);
            }
        }
        else {
            if (value.length != 3) {
                setInputAsError(control.id, objValid, true);
            }
            else {
                setInputAsError(control.id, objValid, false);
            }
        }
    }

    if (control.getAttribute("id") == "txtPasswordRetrieve") {
        var pwordR = document.getElementById("txtPasswordRetrieve").value.length;
        if (document.getElementById("txtPasswordRetrieve").value.length < 8) {
            setInputAsError(control.id, objValid, true);
        }
        else {
            setInputAsError(control.id, objValid, false);
        }

    }

    if (control.id == "txtOccType") {
        var OccType = document.getElementById("txtOccType").value;
        if (OccType == "") {
            setInputAsError("txtOccType", objValid, true);
        }
        else {
            setInputAsError("txtOccType", objValid, false);
        }
    }


    if (control.id == "txtLargestCustomer" || control.id == "txtRevenue") {

        if (document.getElementById("txtLargestCustomer") != null) {
            var revenue = document.getElementById("txtRevenue").value.replace(/,/g, '');
            var largestCustomer = document.getElementById("txtLargestCustomer").value.replace(/,/g, '');

            if (parseInt(largestCustomer) > parseInt(revenue)) {
                setInputAsError('txtLargestCustomer', objValid, true);
                isErr = true;
                valid = false;
            }
            else {
                if (parseInt(revenue) > 0) {
                    setInputAsError('txtRevenue', objValid, false);
                }
                setInputAsError('txtLargestCustomer', objValid, false);
                isErr = false;
                valid = true;
            }
        }

    }

    if (control.id == "txtPassword") {
        var pwordset = document.getElementById("txtPassword").value;
        if (pwordset == "") {
            setInputAsError("txtPassword", objValid, true);
        }
        else {
            setInputAsError("txtPassword", objValid, false);
        }
    }

    if (control.id == "txtEmailAddress") {
        var pwordset = document.getElementById("txtEmailAddress").value;
        if (pwordset == "") {
            setInputAsError("txtEmailAddress", objValid, true);
        }
        else {
            setInputAsError("txtEmailAddress", objValid, false);
        }
    }

    if (control.id == "txtquakerPremium") {
        var prem = document.getElementById("txtquakerPremium").value;
        if (prem == "0" || prem == "") {
            setInputAsError("txtquakerPremium", objValid, true);

        }
        else {
            setInputAsError("txtquakerPremium", objValid, false);
        }
    }

    if (control.id == "txtInternetSales") {
        var prem = document.getElementById("txtInternetSales").value;
        if (parseInt(prem) > 100 || prem == "") {
            setInputAsError("txtInternetSales", objValid, true);
        }
        else {
            setInputAsError("txtInternetSales", objValid, false);
        }
    }

    if (control.id == "txtMainActivity") {
        var company = document.getElementById("txtMainActivity").value;
        if (company == "") {
            setInputAsError("txtMainActivity", objValid, true);
        }
        else {
            setInputAsError("txtMainActivity", objValid, false);
        }
    }

    if (control.id == "txtZip") {
        var zip = document.getElementById("txtZip").value;
        if (zip == "") {
            setInputAsError("txtZip", objValid, true);
        }
        else {
            setInputAsError("txtZip", objValid, false);
        }
    }

    if (control.getAttribute("questionId") == "367" || control.getAttribute("questionId") == "1210") {
        if (value.length > 0 && value != label) {
            //var validStates = ASP.quote_callback_aspx.getValidStates().toLowerCase();   // now all handled by server-side/ddl selection 
            var stateAnswer = "|" + value.toLowerCase() + "|";
            //setInputAsError(control.id, (validStates.indexOf(stateAnswer) < 0));
            control.value = value.toUpperCase();
        }
    }
    else if (control.getAttribute("questionId") == "34") {
        ddlChange();
    }
//     else {
//        ajUpdate = control.getAttribute("ajaxupdate"); // should we update via ajax?
//        //alert('do ajaxupdate ?' + ajUpdate + ' page: ' + page);

//        if (ajUpdate == "True") {
//            var code = page + '.setSession(control.id, value, qid)';
//            eval(code);
//        }
//    }

    control.className = control.className.replace(new RegExp(" sffocus\\b"), "");

    //console.log(control.getAttribute("id") + ', valid:' + objValid.valid);

    return objValid.valid;
} // END: function validateText(control, page)


function validateFormA() {

    var valid = true;
    var elem = document.forms[0].elements;
    var startdate;
    var elName;
    var elValue;
    var eleId;

    for (var i = 0; i < elem.length; i++) {
        eleId = elem[i].id;
        if (elem[i].getAttribute("type") == "radio") {
            if (elem[i].getAttribute("rbType") == "rb" || elem[i].getAttribute("rbType") == "sh") {
                if (elem[i].getAttribute("Link") != null) {
                    link = document.getElementById(elem[i].getAttribute("Link"));
                    hidden = findcontrol(eleId, true);

                    if (elem[i].getAttribute("val") == "Yes") {
                        answer = "True";
                        linkAnswer = "False";
                    }
                    else if (elem[i].getAttribute("val") == "No") {
                        answer = "False";
                        linkAnswer = "True";
                    }
                    else {
                        answer = elem[i].getAttribute("val");
                        linkAnswer = link.getAttribute("val");
                    }
                    if (hidden != null) {
                        if (!elem[i].getAttribute("checked") && !link.getAttribute("checked")) {
                            if (hidden.value != "Error") {
                                hidden.value = "Error";
                            }
                            valid = false;
                        }
                        else {
                            hidden.value = "";
                        }
                    }
                }
            } else if (elem[i].getAttribute("rbType") == "rb2") {
                if (elem[i].getAttribute("Link") != null && elem[i].getAttribute("Link2") != null) {
                    link = document.getElementById(elem[i].getAttribute("Link"));
                    link2 = document.getElementById(elem[i].getAttribute("Link2"));
                    hidden = findcontrol(eleId, true);

                    if (hidden != null) {
                        if (!elem[i].checked && !link.checked && !link2.checked) {
                            if (hidden.value != "Error") {
                                hidden.value = "Error";
                            }
                            valid = false;
                        }
                        else {
                            if (elem[i].getAttribute("validAnswer") != null && elem[i].getAttribute("validAnswer") != "") {
                                if ((elem[i].checked && answer != elem[i].getAttribute("validAnswer")) || (link.checked && linkAnswer != elem[i].getAttribute("validAnswer")) || (link2.checked && linkAnswer != elem[i].getAttribute("validAnswer"))) {
                                    if (hidden.value != "Error") {
                                        hidden.value = "Error";
                                    }
                                    valid = false;
                                }
                                else {
                                    hidden.value = "";
                                }
                            }
                            else {
                                hidden.value = "";
                            }
                        }
                    }
                }
            }
        }
        if (elem[i].getAttribute("IsRequired") != null) {
            if (elem[i].getAttribute("IsRequired") == "True") {
                elName = elem[i].id;
                elValue = elem[i].value;
                if (elem[i].value == "" || elem[i].value == "£" || elem[i].value == "%") {
                    setInputAsError(eleId, true);
                    hidden = findcontrol(eleId, true);
                    hidden.value = "Error";
                    valid = false;
                }
                else {
                    hidden = findcontrol(eleId, true);
                    hidden.value = "";
                }
            }
        }

        if (elem[i].getAttribute("ID") == "txtPayroll") {
            var employees = document.getElementById("ddlNoEmployees").value;

            elName = elem[i].id;
            elValue = elem[i].value;

            if (elem[i].value == "0" && employees != "0") {
                setInputAsError(eleId, true);
                hidden = findcontrol(eleId, true);
                hidden.value = "Error";
                valid = false;
            }
            else {
                name = "hid" + elem[i].getAttribute('ID');
                hidden = findcontrol(eleId, true);
                hidden.value = "";
            }
        }

        if (elem[i].getAttribute("ID") == "txtTotalActivities") {
            elValue = elem[i].value;

            if (elem[i].value != "100") {
                setInputAsError(eleId, true);
                hidden = findcontrol(eleId, true);
                hidden.value = "Error";
                valid = false;
            }
            else {
                name = "hid" + elem[i].getAttribute('ID');
                hidden = findcontrol(eleId, true);
                hidden.value = "";
            }
        }

        if (elem[i].getAttribute("ErrorOnValue") != null) {
            errorOn = elem[i].getAttribute("ErrorOnValue");
            if (elem[i].value == errorOn) {
                valid = false;
                hidden = findcontrol(eleId, true);
                hidden.value = "Error";
                setInputAsError(eleId, true);
            }
            else {
                name = "hid" + elem[i].getAttribute('ID');
                hidden = findcontrol(eleId, true);
                hidden.value = "";
            }
        }

        if (elem[i].getAttribute('regExpression') != null) {
            regExpr = eval(elem[i].getAttribute('regExpression'));

            if (!elem[i].value.match(regExpr)) {
                valid = false;
                error = '469/' + elem[i].getAttribute("questionId");
                hidden = findcontrol(eleId, true);
                hidden.value = "Error";
                setInputAsError(eleId, true);
            }
            else {
                name = "hid" + elem[i].getAttribute('ID');
                hidden = findcontrol(eleId, true);
                hidden.value = "";
            }
        }
        /*
        if (elem[i].getAttribute("questionID") == "?")
        {
        if (!validatePolicyStartDate())
        valid = false;
            
        }
        */
    }

    var eDiv = document.getElementById("f_form_errorDiv");

    if (document.getElementById("lblPercentageAllocationEngineers") != null) {
        var totalActivities = document.getElementById("txtTotal");

        if (totalActivities.value != "100") {
            setInputAsError("txtTotal", true);
            valid = false;
        }
        else {
            setInputAsError("txtTotal", false);
        }

        var totalBreakdown = document.getElementById("txtTotalBreakdown");

        if (totalBreakdown.value != "100") {
            setInputAsError("txtTotalBreakdown", true);
            valid = false;
        }
        else {
            setInputAsError("txtTotalBreakdown", false);
        }
    }

    if (valid == false) {
        document.getElementById('f_form_hasError').value = "true";
        if (eDiv != null) {
            eDiv.style.display = "block";
        }
    }
    else {
        document.getElementById('f_form_hasError').value = "false";
        if (eDiv != null) {
            eDiv.style.display = "none";
        }
    }

    return valid;
}

function findcontrol(text, searchHidden) {

    var allInputs = document.getElementsByTagName("input");
    var objname = "";
    var objnameHid = "";
    for (var i = 0, al = allInputs.length; i < al; i++) {
        elm = allInputs[i];
        var elmId = elm.getAttribute("ID");
        if (elmId.indexOf(text) != -1) {
            objname = elmId;    
            if (searchHidden) {
                if (objname.indexOf("hid") != -1) {
                    objnameHid = elmId; 
                }

            }
            
        }
        else {
           //alert("elmId: " + elmId + " text: " + text);
        }
    }

    if (searchHidden) {
        return objnameHid;
    } else {
        return objname;
    }
}
