$(document).ready(function() {
    toggleState();
});

var StateValidationControl;

function toggleState() {
    if (57 == $("select[id$='ddlCountry']").val()) {
        $("tr[id$='StateRequiredRow']").css('display', '');
        $("tr[id$='RegionRequiredRow']").css('display', 'none');
        try {
            if (StateValidationControl) {
                Page_Validators.push(StateValidationControl);
            }
        } catch (Error) {
        }

    } else {
        $("tr[id$='StateRequiredRow']").css('display', 'none');
        $("tr[id$='RegionRequiredRow']").css('display', '');

        try {
            var temp = [];
            for (var i = 0; i < Page_Validators.length; i++) {
                if (!Page_Validators[i].id.match(/valStateRequired/)) {
                    temp.push(Page_Validators[i]);
                } else {
                    StateValidationControl = Page_Validators[i];
                }
            }
            Page_Validators = temp;
        } catch (Error) {
        }
    }
}

// unique Analytics web profile to record events
if (
    (typeof contactsEventTracker) != 'object' || // do we have a contactsEventTracker loaded OR
    (contactsEventTracker.version < 1 && contactsEventTracker.rev < 1)) // is our version newer? 
{
    var contactsEventTracker = {
        version: 1, // version number
        rev: 1,     // revision number
        started: false,
        //This is preset to the 'Event Tracking' profile in GA
        tracker_id: "UA-1001138-42",
        //This is the queue of events stored while the _gat is being downloaded/init
        queue: [],
        //This method is used to initialise the tracker
        init: function() {
            if ((typeof _gat) == 'object' && this.started != true) {
                try {
                    this.tracker = _gat._getTracker(this.tracker_id);
                    this.tracker._trackPageview();
                    // now check the queue and unload it/run the tracking events
                    while (this.queue.length > 0) {
                        var evt = this.queue.pop();
                        this._trackEvent(evt.cat, evt.act, evt.lab, evt.val);
                    }
                    this.started = true;
                }
                catch (e) {
                }
            }

        },
        //This method records a track to the web profile
        _trackEvent: function(cat, act, lab, val) {
            // cat  'Category'      used to define what category to record this event under eg. '[Forms]'       (string)
            // act  'Action'        record what sort of action took place eg. '[Submit]'                        (string)
            // lab  'Label'         a specific label eg. '[CV].[Submission]' or '[CV].[Submitted Succesfully]'  (string)
            // val  'Value'         how much value should be applied to this event eg. $5, $10 etc.             (integers only)
            if ((typeof _gat) == 'object') {
                if ((typeof this.tracker) != 'object') this.init();
                try {
                    // record to the web profile used by this webpage/site
                    if ((typeof pageTracker) == 'object') pageTracker._trackEvent(cat, act, lab, val);
                    // record to the event tracking profile and return true or false
                    this.tracker._trackEvent(cat, act, lab, val);
                }
                catch (e) {
                }
            } else {
                // we will store this event into the queue for when we do have _gat
                this.queue.push({ cat: cat, act: act, lab: lab, val: val });
            }
            //because we are storing these into a queue if the object doesnt exist yet just send back true
            return true;
        }
    };
    // Attempt to send any queued events before the page is destroyed
    $("window").unload(function() { contactsEventTracker.init(); });
}

//This object specifies the value ($) of an event
var eventValues = { phone: 0, fax: 0, email: 5, website: 0 };

// using jQuery to hook into the input button click events
$("document").ready(function() {
    // Send Request Button
    $("input[id$='btnHamSubmit']").bind("click", function(e) {
        contactsEventTracker._trackEvent('[Form]', '[Submit]', '[Web Request].[' + e.target.value + ']', 0);
    });
    // Edit Details Button
    $("input[id$='btnHamSubmitChecked']").bind("click", function(e) {
        contactsEventTracker._trackEvent('[Form]', '[Submit]', '[Web Request].[Confirmed Details]', 0);
    });
    // Confirm correct details
    $("input[id$='btnHamSubmitCancel']").bind("click", function(e) {
        contactsEventTracker._trackEvent('[Form]', '[Submit]', '[Web Request].[' + e.target.value + ']', 0);
    });
});

// this method is used when a succesful form submission is submitted and the check details box apears
recordSuccesfulSubmission = function() {
    if ((typeof contactsEventTracker) == 'object') {
        contactsEventTracker._trackEvent('[Form]', '[Submit]', '[Web Request].[Succesful Submission]', 0);
    }
};

//This method returns a string for the label of an item to send along with the event to google analytics
function makeLabel(o) {
    label = ((o.group != undefined) ? '[' + o.group + ']' : '');
    label += ((o.location != undefined) ? (label.toString().length > 0 ? '.' : '') + '[' + o.location + ']' : '');
    label += ((o.division != undefined) ? (label.toString().length > 0 ? '.' : '') + '[' + o.division + ']' : '');
    return label;
}

//At the moment these are assuming pageTracker exists and just tracks the event through that
//2009-01-09: Added a 2nd tracker call using a seperate web profile

//This method is used to record a click event on a mailto or external web link
function recordAnchorEvent(l, o) {
    // l = Object (DOM node) the anchor tag
    // o = Object (Contains JSON with information to record)
    // o.division
    // o.location
    // o.group
    // o.type

    if (l.clickRecorded != true && (typeof pageTracker) == 'object') {
        Label = makeLabel(o);
        l.clickRecorded = contactsEventTracker._trackEvent('[Contact].[Click]', '[' + o.type + ']', (Label == null ? '' : Label), eventValues[o.type]);
    }
    return true;
};

//This method is used to show a specific contact method, and also records the 1st unique click for that link
function toggleContact(o, g, l, d, t) {

    // o = Object (DOM node)
    // g = String (Group)
    // l = String (Location)
    // d = String (Division)
    // t = String (Contact Type, eg. Telephone)

    // Check if the parent element is the data list container
    if (o.parentNode.parentNode.tagName == 'dl'.toUpperCase()) {
        // check if this element has already been tracked on this page hit
        // and record this event if it has not
        if (o.clickRecorded != true && (typeof pageTracker) == 'object') {
            Label = makeLabel({ group: g, location: l, division: d });
            o.clickRecorded = contactsEventTracker._trackEvent('[Contact].[Show]', '[' + t + ']', (Label == null ? '' : Label), eventValues[t]);
        }
        // find the corrosponding DD element to this DT element
        var n = o.parentNode.parentNode;
        var sDt = o.parentNode;
        var s = sDt;
        // this needs failsafe adding to the while()
        do { s = s.nextSibling; } while (s.tagName != 'dd'.toUpperCase() && (typeof s.nextSibling) == "object");
        var c = n.getElementsByTagName('dd'.toUpperCase());
        var triggered = false;
        // go through all the DD elements of the Data List,
        // set the selected one as the active,
        // turn off all others       
        for (var i = 0; i < c.length; i++) {
            if (c[i] == s) {
                c[i].makeActive = true;
            } else {
                // turn off  (hide) any that are active and trigger the new one
                // to become active
                if (c[i].makeActive == true || c[i].currentActive == true) {
                    c[i].nextActive = s;
                    $(c[i]).fadeOut("fast", function() {
                        this.currentActive = false;
                        this.makeActive = false;
                        this.className = "";
                        this.nextActive.makeActive = true;

                        //turn off the active title
                        var ps = this;
                        do { ps = ps.previousSibling; } while (ps.tagName != 'dt'.toUpperCase() && (typeof ps.previousSibling) == "object");
                        if (ps) {
                            ps.className = ps.prevClassName;
                        }
                        $(this.nextActive).fadeIn("fast", function() {
                            this.currentActive = true;
                            this.makeActive = false;
                            //store the current className
                            sDt.prevClassName = sDt.className;
                            sDt.className = "active";
                        });
                    });
                    triggered = true;
                } else {
                    c[i].className = "";
                }
            }
        }
        // if there was not an active DD then this will make the selected active
        if (!triggered) {
            $(s).fadeIn("fast", function() {
                this.currentActive = true;
                this.makeActive = false;
                sDt.prevClassName = sDt.className;
                sDt.className = "active";
            });
        }
    }
    return false;
}

HAM = {
    getType: function(j) {
        //var type;
        if ($('div a.email', j).length > 0) {
            return 'email';
        } else if ($('div.tel span.type', j).length > 0 && $('div.tel span.type', j).text().toLowerCase() == 'work') {
            return 'phone';
        } else if ($('div.tel span.type', j).length > 0 && $('div.tel span.type', j).text().toLowerCase() == 'fax') {
            return 'fax';
        } else if ($('div.adr', j).length > 0) {
            return 'address';
        } else if ($('div a.url', j).length > 0) {
            return 'website';
        }
        return null;

        //        switch (text.toLowerCase()) {
        //            case 'telephone':
        //                type = 'phone';
        //                break;
        //            case 'fax':
        //                type = 'fax';
        //                break;
        //            case 'email':
        //                type = 'email';
        //                break;
        //            case 'website':
        //                type = 'website';
        //                break;
        //            default:
        //                type = null;
        //                break;
        //        }

    },
    getLabel: function(vcard) {
        var Label = null, Group, Location, Division;
        Group = $('.location-details .group', vcard).text();
        Location = $('.location-details .location', vcard).text();
        Division = $('.location-details .division', vcard).text();
        Label = makeLabel({ group: Group, location: Location, division: Division });
        return Label;
    },
    setAnchors: function(jq) {
        $(jq).click(function() {
            var i = $(this), vcard = i.parent().parent().parent().parent(), type = getType($('dt.dt-active', vcard).text()), label = getLabel(vcard);
            if (i[0].clickRecorded != true && (typeof pageTracker) == 'object') {
                contactsEventTracker._trackEvent('[Contact].[Click]', '[' + type + ']', (label == null ? '' : label), eventValues[type]);
            }
            return true;
        });
    },
    showActive: function($) {
        var j = $('div.vcard'), k;
        for (k = 0; k < j.length; k++) {
            var vcard = $(j[k]), d = $('div.contact-detail', vcard), l = $('dl', vcard);
            d.html($('dt.dt-active', l).next().html());
        }
        for (k = 0; k < j.length; k++) {
            var vcard = $(j[k]), d = $('div.contact-detail', vcard), l = $('dl', vcard);
            if (d.height() < l.height()) { d.height(l.height()); }
            $('.adr', d).removeClass('adr');
            $('.org', d).removeClass('org');
            $('.organization-name', d).removeClass('organization-name');
            $('.tel', d).removeClass('tel');
            $('.url', d).removeClass('url');
            $('.email', d).removeClass('email');
        }
    }
}
$('document').ready(function() {
    var j = $('div.vcard'), k;
    $('div.vcard dt').click(function() {
        var j = $(this).next(), //dd
            i = $(this), //dt
            d = i.parent().next(),
            l = i.parent(),
            type,
            label,
            vcard = i.parent().parent().parent();

        if (i[0].clickRecorded != true) {
            label = HAM.getLabel(vcard);
            t = HAM.getType(j);
            if (t != null) { i[0].clickRecorded = contactsEventTracker._trackEvent('[Contact].[Show]', '[' + t + ']', (label == null ? '' : label), eventValues[type]); }
        }

        if ($('.dt-active', l)[0] != i[0]) {
            d.fadeOut("fast", function() {
                $('.dt-active', l).removeClass('dt-active');
                i.addClass('dt-active');
                d.css({ height: 'auto', opacity: '0.01' }).html(j.html());

                $('.adr', d).removeClass('adr');
                $('.org', d).removeClass('org');
                $('.organization-name', d).removeClass('organization-name');
                $('.tel', d).removeClass('tel');
                $('.url', d).removeClass('url');
                $('.email', d).removeClass('email');

                if (d.height() < l.height()) { d.height(l.height()); }
                d.css({ opacity: '' });
                d.fadeIn("fast", function() { HAM.setAnchors($('a', d)); });
            });
        }
    });
    HAM.showActive($);
    HAM.setAnchors($('a.url, a.email', j));
});