/// <reference path="jquery-1.4.2.min-vsdoc.js" />
if (!tui3i) {
    var tui3i = {};
}

tui3i.contacForm = function ($) {
    $ = jQuery;
    var config = {
        jq: {
            $messageContainer: '#message-container',
            $messages: '.form-message',
            $messageHeading: '.heading'
        },
        todo: '/img/todo.gif',
        tick: '/img/tick.gif',
        nextButton: 'a.next-button',
        sectionDivider: 'div.section-divider',
        location: '',
        'request-for-funding': {
            currency: false,
            'amount-required': false,
            'your-location': false,
            'funding-stage': false
        },
        'details-and-request': {
            name: false,
            email: false,
            message: false
        },
        'careers': {
            name: false,
            email: false,
            'investment-area': false,
            'business-line': false,
            message: false
        },
        'supplier': {
            name: false,
            'company-name': false,
            email: false,
            phone: false,
            message: false
        },
        'recruitment-agency': {
            'recruitment-agency': false
        },
        'hr-department': {
            'hr-department': false
        },
        'hr-details': {
            name: false,
            'company-name': false,
            email: false,
            message: false
        }

    };


    /*
    * Creates the global jquery objects
    */
    function createJqueryDOMElements() {
        for (var i in config.jq) {
            config.jq[i] = $(config.jq[i]);
        }
    }


    //constructs the path that's passed to google tracker
    //var pageTracker = _gat._getTracker("UA-8712988-1");
    /*
    var pageTracker = {};
    pageTracker._trackPageview = function(path){
    console.log(path);
    }
    */
    /*
    * Logs the form element views with google analytics
    */
    function googleTracker(section, name, value) {
        //console.clear();
        name = name.toLowerCase();
        value = value.replace(/\s/g, "-").toLowerCase();
        if (name != null && value != null) {
            try {
                pageTracker._trackPageview('/enquiry.html/all/' + section + '?' + name + '=' + value);
                setTimeout(function () {
                    pageTracker._trackPageview('/enquiry.html/' + config.location + '/' + section + '?' + name + '=' + value);
                }, 200);
            }
            catch (err) {
                console.error(err);
            }
        }
        else {
            try {
                pageTracker._trackPageview('/enquiry.html/all/' + section + '/section');
                setTimeout(function () {
                    pageTracker._trackPageview('/enquiry.html/' + config.location + '/' + section + '/section');
                }, 200);
            }
            catch (err) {
                console.error(err);
            }
        }
    }



    /*
    * Retrieve URL query string value based on a name argument supplied
    */
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return results[1].toLowerCase();
    }

    /*
    * Email validation
    */
    function checkMail(email) {
        var filter = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (filter.test(email)) {
            return true;
        }
        return false;
    }

    /*
    * trim whitespace
    */
    function trim(value) {
        var temp = value;
        var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
        if (obj.test(temp)) {
            temp = temp.replace(obj, '$2');
        }
        var obj = / +/g;
        temp = temp.replace(obj, " ");
        if (temp == " ") {
            temp = "";
        }
        return temp;
    }

    /*
    *   divider: $parent,
    *   section: $parent.attr('id').replace(/-section/g, "")
    */
    function getSectionDivider($elm) {
        $parent = $elm.parents(config.sectionDivider);
        return {
            $formSection: $parent,
            sectionName: $parent.attr('id').replace(/-section/g, "")
        };
    }

    /*
    *
    */
    function extendedFormElementCheck($section, message, heading) {
        var checks = true;
        $('select', $section[0]).each(function () {
            var val = $(this).find('option:selected').attr('class');
            if (val) {
                var i = parseInt(val.replace(/value-/g, ""));

                // set the visible status of the specific message for this select list in the "funding rejected" message
                toggleMessageListItem(this.id, i);

                //if i = 0 that represents a false in javascript
                if (!i) checks = false;
            }
        })

        if (!checks) toggleMessage('show', message, $section[0], heading);       
        return checks;
    }

    /*
    *
    */
    function toggleFormSections($elm) {
        var href = $elm.attr('href');
        var info = getSectionDivider($elm);
        var checks = true;

        //Register the form values with Google when user clicks 'next' button
        if ($elm.hasClass('next-button')) {
            $('select', info.$formSection[0]).each(function () {
                googleTracker(info.sectionName, $(this).attr('id'), $(this).val());
            });

            $('input[type=text], textarea', info.$formSection[0]).each(function () {
                googleTracker(info.sectionName, $(this).attr('id'), 'true');
            });
        }

        //Run any form section checks to see if the user progesses or sees a message
        if ($elm.hasClass('next-button')) {
            switch (info.sectionName) {
                case 'request-for-funding':
                    checks = extendedFormElementCheck(info.$formSection, 'funding-message', 'Funding Enquiry');
                    break;
                case 'recruitment-agency':
                    checks = extendedFormElementCheck(info.$formSection, 'agency-message', 'Recruitment Enquiry');
                    break;
                default:
            }
        }

        //then show/hide the form section
        if (checks) {
            if (href === 'submit') {
                $elm.parents('form').submit();
            }
            else {
                $parent.hide();
                $('#' + href).fadeTo(300, 1);
            }
        }
    }

    /*
    * Changes the value of the hidden form element 'enquirytype', which is passed to mailform.php
    */
    function changeEnquiryType($elm) {
        var attr = $elm.find('option:selected').attr('alt');
        if (attr) {
            $elm.parents('form').find('input[name=formsection]').val(attr);
        }
    }

    /*
    *
    */
    function findValidationImage($elm, type) {
        return (type === 'textarea') ? $elm.parents('div.info_block').find('img.ind') : $elm.next('img.ind');
    }

    /*
    * Changes the state of the field validation images.
    * Checks to make sure all fields are valid.
    * Toggles the visibility of the next button
    */
    function validateFormField($elm) {
        //debugger;
        var info = getSectionDivider($elm);
        var $parent = info.$formSection;
        var $nextButton = $(config.nextButton, $parent[0]);
        var id = $elm.attr('id');
        var type = $elm[0].type;
        var $img = findValidationImage($elm, type);

        if (type === 'select-one') {
            changeEnquiryType($elm);
            if (id === 'investment-area' || id === 'business-line') {
                var $investment = $('#investment-area');
                var $business = $('#business-line');
                if ($investment.val() === $business.val()) {
                    //investment area
                    $img = findValidationImage($investment, type);
                    $img.attr('src', config.todo);
                    config[info.sectionName]['investment-area'] = false;
                    $investment.removeAttr('disabled');
                    //professional services
                    $img = findValidationImage($business, type);
                    $img.attr('src', config.todo);
                    config[info.sectionName]['business-line'] = false;
                    $business.removeAttr('disabled');
                }
                else {
                    //investment area
                    $img = findValidationImage($investment, type);
                    $img.attr('src', config.tick);
                    config[info.sectionName]['investment-area'] = true;
                    //professional services
                    $img = findValidationImage($business, type);
                    $img.attr('src', config.tick);
                    config[info.sectionName]['business-line'] = true;

                    if (id !== $investment.attr('id')) {
                        $investment.attr('disabled', 'disabled');
                    }
                    else {
                        $business.attr('disabled', 'disabled');
                    }
                }
            }
            else {
                if ($elm.val() === 'none') {
                    $img.attr('src', config.todo);
                    config[info.sectionName][id] = false;
                }
                else {
                    $img.attr('src', config.tick);
                    config[info.sectionName][id] = true;
                }
            }
        }
        else
            if (type === 'text' || $elm[0].type === 'textarea') {
                var val = trim($elm.val());
                var cha = parseInt($elm.attr('char'));

                if (id === 'email') {
                    if (checkMail(val)) {
                        $img.attr('src', config.tick);
                        config[info.sectionName][id] = true;
                    }
                    else {
                        $img.attr('src', config.todo);
                        config[info.sectionName][id] = false;
                    }
                }
                else {
                    if (val.length >= cha) {
                        $img.attr('src', config.tick);
                        config[info.sectionName][id] = true;
                    }
                    else {
                        $img.attr('src', config.todo);
                        config[info.sectionName][id] = false;
                    }
                }
            }
        //validate requested form fields	
        if (checkFormFieldValues(config[info.sectionName])) {
            $nextButton.fadeTo(300, 1);
        }
        else {
            $nextButton.hide();
        }
    }

    /*
    * Validate the form field items.
    * Iterate through form section object and make sure all name/values are set to true
    */
    function checkFormFieldValues(obj) {
        for (name in obj) {
            if (!obj[name]) {
                return false;
            }
        }
        return true;
    }

    /*
    *
    */
    function toggleMessage(toggle, message, section, heading) {
        if (toggle === 'show') {
            config.jq.$messages.hide();
            $('#' + message).show();
            config.jq.$messageContainer.fadeTo(200, 1);
            config.jq.$messageHeading.text(heading);
        }
        else {
            config.jq.$messages.hide();
            config.jq.$messageContainer.hide();
        }
        //if IE6 hide form elements
        if ($.browser.msie && $.browser.version.substr(0, 1) === '6') {
            (toggle === 'show') ? $('select', section).hide() : $('select', section).show();
        }
    }

    /*
    *   Hides or shows the appropriate LI in the "request for funding rejected" message. Uses the ID of the 
    *   Select box to determine the id of the LI ('fm-' + list box id).
    */
    function toggleMessageListItem(id, show) {
        var li = $('#fm-' + id);
        if (li.length > 0) {
            if (!show) {
                li.show();
            } else {
                li.hide();
            }
        }
    }

    /*
    *
    */
    var init = function () {
        createJqueryDOMElements();
        $(window).resize(function () {
            $('#shadow').css({
                'height': ($(window).height()) + 'px'
            });
        });

        $('a.right', '#close-message').click(function () {
            toggleMessage('hide');
            return false;
        });

        config.location = getParameterByName('n') || 'location-error';

        $('#request-type').change(function () {
            var $this = $(this);
            var info = getSectionDivider($this);
            googleTracker(info.sectionName, $this.attr('id'), $this.val());

            switch ($this.val()) {
                case 'investor-shareholder':
                    //window.location.href = "http://www.3igroup.com/share-info/investor-contacts.html";
                    toggleMessage('show', 'investor-message', info.$formSection[0], 'Investor/Shareholder Enquiry');
                    break;
                case 'charity':
                    toggleMessage('show', 'charity-message', info.$formSection[0], 'Charitable Donation Enquiry');
                    break;
                case 'none':
                    //nothing
                    break;
                default:
                    $this.parents('form').hide();
                    $('#' + $this.val() + '-form').fadeTo(300, 1); //this is the 'next' button
            }
        });

        $('select:not(#request-type)').live('change', function () {
            var $this = $(this);
            validateFormField($this);
        });

        $('input, textarea').live('keyup', function () {
            var $this = $(this);
            validateFormField($this);
        });

        $('a.back-button, a.next-button').click(function () {
            var $this = $(this);
            toggleFormSections($this);
            return false;
        });
    }

    return {
        init: init
    }
} (jQuery);

