var needsSave; // Detect if anything has been changed on the page

$(document).ready(function () {
    // Deal with the login colorbox
    loginShadowBox();

    // Add styled checkboxes
    $('input:radio').add("input:checkbox") && $('input:radio').add("input:checkbox").checkbox({ empty: 'http://www.iviewsurveys.com.au/Images/templates/empty.png' });
    $('table.profileQuestion_grid input:radio').checkbox({ empty: 'http://www.iviewsurveys.com.au/Images/templates/empty.png', cls: 'jquery-table-checkbox' })

    // Add dividers in the top menu
    $('div.topMenu ul.menu li:first-child a').each(function () {
        $(this).css("border-left", "none");
        $($(this).closest("li")).css("border-left", "none");
    });

    // Add Google map for the contact page
    if ($('.officeLocations').length > 0) {
        var gmap = '<div id="map_canvas"></div>';
        $('.officeLocations').after(gmap);

        $('#map_canvas').css('width', '650px');
        $('#map_canvas').css('height', '350px');
        $('#map_canvas').css('margin', 'auto');
        $('#map_canvas').css('margin-top', '20px');
        $('#map_canvas').css('margin-bottom', '20px');

        createGoogleMap();
    }

    // Set up the auto redirect in the event that the user selects "No" to the question "Are you an Australian Resident?"
    $('#IsAustralian\\~no').click(function () {
        window.location = "ineligible.aspx";
    });

    // Load all of the features/scripts for the page
    loadFeatures();

    // Display a colorbox telling IE6 users to upgrade
    ie6ShadowBox();

    // Hides the no Javascript warning in the header
    $("noscript").css({ "display": "none" });

    // do the jump to an error
    if ($("a.scrollToAnchor").length > 0) {
        location.hash = "#" + $("a.scrollToAnchor").attr("name");
    }

    $("input.StatsPrintButton").click(function (event) {
        // Show all response output rows
        $('tr.statsRespOutput').show();
        $('div.GenericWhiteboxItem').addClass('expanded');
        window.print();
        event.preventDefault();
        //printWindow.close();
    });

    $("input.PhoneSuffix").keypress(function (event) {
        $(this).val($(this).val().replace(" ", ""));
    });

    // fix for bloody ie not showing things when it's meant to.
    $("div.MainContentFooter").css("display", $("div.MainContentFooter").css("display"));

    //fix the terms and conditions links
    $("a.TandCLink").click(function (e) {
        e.stopPropagation();
    }
	);

});

// Set height after all images have been loaded
$(window).load(function () {
    if ($('div.pc_results') && $('div.pc_results').length > 0) {
        $('div.pc_results').css('height', 'auto');
        $('div.pc_results').fadeIn(1000);
    }
    // Load the rotating banner (only on the front page)
    loadFanner();
});

// Deal with unsaved changes
window.onbeforeunload = function () {
    if (needsSave && window.location.href.indexOf("profSect=") != -1) {
        return 'You have unsaved changes on this page!';
    }
};

/* $questionChanged :- the element who's value has changed
* $listener 		:- the question who's listening for the change
* idsToCheck		:- an array of HTML ids for the responses to be checked
* compareFunction 	:- the function of comparison one of (LESS_THAN, LESS_THAN_OR_EQUAL, EQUAL_TO_ALL, EQUAL_TO_ANY, GREATER_THAN_OR_EQUAL, GREATER_THAN, NOT_EQUAL_TO)
* requiredValues	:- an array of required match values
*/
function ProfileQuestionChangedHandler(eventTriggered, $questionChanged, $listener, idsToCheck, compareFunction, requiredValues, callback) {
    //	Simple code to convert a Boolean String value to a Boolean.
    var toBoolean = function (value) {
        switch (value.toLowerCase()) {
            case "true": case "yes": case "checked": case "on": return true;
            case "false": case "no": case "unchecked": case "off": return false;
            default: throw ("Error: Value is not a recognised Boolean.");
        }
    }

    /*	Compare to function. Similar to how compareTo works in Java.
    Returns -1, 0 and 1 for less than, equal to and greater than respectively.	*/
    var compareTo = function (obj, value) {
        var type = obj.attr('type'), // Find out what type of object it is - different objects require different comparators
		NaN = isNaN(value), // Find out if the value is a number or not
		compare;

        if (!NaN) {
            value = parseInt(value);
        } else {
            value = value.toLowerCase();
        }
        //console.log(obj);
        // 2011-07-08 Added check for obj.length
        if (obj.length > 0 && obj[0].nodeName !== undefined && obj[0].nodeName != null) {
            switch (obj[0].nodeName.toLowerCase()) {
                case "input":
                    switch (type) {
                        case "radio": case "checkbox":
                            /* Compare the value of the radio/checkbox to the value. Assumes that if the index of the radio/checkbox is being compared against, 
                            the 'value' attribute of the element is set to its index */
                            if (!NaN) {
                                if (isNaN(obj.attr('value'))) {
                                    throw ("Error: The element does not have a numerical value.");
                                } else {
                                    compare = parseInt(obj.attr('value'));
                                    break;
                                }
                            } else {
                                // Check if the radio/checkbox is checked. If value is not a boolean, then an exception is thrown.
                                // Return 0 for true, -1 for false
                                return ((obj.attr('checked') == toBoolean(value)) - 1);
                            }
                            break;
                        case "text":
                            if (!NaN) {
                                if (isNaN(obj.val())) {
                                    throw ("Error: Attempting to compare a non-Integer type to an Integer.");
                                } else {
                                    compare = parseInt(obj.val());
                                }
                            } else {
                                compare = obj.val().toLowerCase();
                            }
                            break;
                        default:
                            throw ("Error: The input element has an unimplemented type.");
                    }
                    break;
                case "option":
                    compare = obj.attr("selected");
                    value = toBoolean(value);
                    break;
                default:
                    throw ("Error: The element does not exist, or is not supported by compareTo.");
                    break;
            }
        }
        if (compare > value) {
            return 1;
        } else if (compare == value) {
            return 0;
        } else {
            return -1;
        }
    }

    var multiReqValues = (requiredValues.length > 1),
	multiIDs = (idsToCheck.length > 1),
	passed = true;

    switch (compareFunction) {
        case "LESS_THAN":
            if (multiReqValues || multiIDs) {
                throw ("Error: LESS_THAN comparator may only be used to compare against a single value");
            } else if (compareTo($(idsToCheck[0]), requiredValues[0]) != -1) {
                passed = false;
            }
            break;
        case "LESS_THAN_OR_EQUAL":
            if (multiReqValues || multiIDs) {
                throw ("Error: LESS_THAN_OR_EQUAL comparator may only be used to compare against a single value");
            } else if (compareTo($(idsToCheck[0]), requiredValues[0]) == 1) {
                passed = false;
            }
            break;
        case "EQUAL_TO_ALL":
            if (idsToCheck.length != requiredValues.length && multiReqValues) {
                throw ("Error: Mismatch in the number of IDs to check, and the number of required values");
            } else {
                //2011-07-08 changed for loop to negate the added function to Array.prototype
                for (var i = 0; i < idsToCheck.length; i++) {
                    if (!multiReqValues) { // Compare all the first and only element
                        if (compareTo($(idsToCheck[i]), requiredValues[0]) != 0) {
                            passed = false;
                            break;
                        }
                    } else { // Compare all elements to their corresponding requiredValue
                        if (compareTo($(idsToCheck[i]), requiredValues[i]) != 0) {
                            passed = false;
                            break;
                        }
                    }
                }
            }
            break;
        case "EQUAL_TO_ANY":
            if (idsToCheck.length != requiredValues.length && multiReqValues) {
                throw ("Error: Mismatch in the number of IDs to check, and the number of required values");
            } else {
                passed = false;
                for (var i = 0; i < idsToCheck.length; i++) {
                    if (!multiReqValues) { // Compare all the first and only element
                        if (compareTo($(idsToCheck[i]), requiredValues[0]) == 0) {
                            passed = true;
                            break;
                        }
                    } else { // Compare all elements to their corresponding requiredValue
                        if (compareTo($(idsToCheck[i]), requiredValues[i]) == 0) {
                            passed = true;
                            break;
                        }
                    }

                }
            }
            break;
        case "GREATER_THAN_OR_EQUAL":
            if (multiReqValues || multiIDs) {
                throw ("Error: GREATER_THAN_OR_EQUAL comparator may only be used to compare against a single value");
            } else if (compareTo($(idsToCheck[0]), requiredValues[0]) == -1) {
                passed = false;
            }
            break;
        case "GREATER_THAN":
            if (multiReqValues || multiIDs) {
                throw ("Error: GREATER_THAN comparator may only be used to compare against a single value");
            } else if (compareTo($(idsToCheck[0]), requiredValues[0]) != 1) {
                passed = false;
            }
            break;
        case "NOT_EQUAL_TO": // Not equal to ALL
            if (idsToCheck.length != requiredValues.length && multiReqValues) {
                throw ("Error: Mismatch in the number of IDs to check, and the number of required values");
            } else {
                for (i in idsToCheck) {
                    if (!multiReqValues) { // Compare all the first and only element
                        if (compareTo($(idsToCheck[i]), requiredValues[0]) == 0) {
                            passed = false;
                            break;
                        }
                    } else { // Compare all elements to their corresponding requiredValue
                        if (compareTo($(idsToCheck[i]), requiredValues[i]) == 0) {
                            passed = false;
                            break;
                        }
                    }
                }
            }
            break;
        default:
            throw ("Error: Comparator is not supported.");
    }

    // code to check if there is an id to check on the page
    var idToCheckOnPage = false;
    for (i = 0; i < idsToCheck.length; i++) {
        if ($(idsToCheck[i]).length > 0) {
            idToCheckOnPage = true;
            break;
        }
    }
    // Deal with callback, or else simply show/hide the elements
    if (idToCheckOnPage) {
        if (callback === undefined) {
            if (passed) {
                $listener.css('display', 'inline-block');
            } else {
                $listener.css('display', 'none');

                // Reset values!
                if (eventTriggered) {
                    $(':input', $listener).each(function () {
                        var type = $(this).attr('type');
                        var tag = $(this).attr('nodeName').toLowerCase();

                        if ((type == 'text' || type == 'password' || tag == 'textarea') && $(this).val() != "") {
                            $(this).val("");
                            $(this).change();
                        } else if ((type == 'checkbox' || type == 'radio') && $(this).attr('checked')) {
                            $(this).attr('checked', false);
                            $(this).change();
                        } else if ((tag == 'select') && $(':selected', $(this)).attr('value') != -1) {
                            $(this).attr('selectedIndex', -1);
                            $(':selected', $(this)).attr('selected', false);
                            $('span#select_val_' + $(this).attr('id')).text("-- Please Select --");
                            $(this).change();
                        }
                    });
                }
            }
        } else {
            callback($listener, passed);
        }

        // Remove the bottom border from the last element and place it on the new last element
        removeBottomBorder();
    }
}

// Create the Google Earth map
function createGoogleMap() {
    var latlng = new google.maps.LatLng(-25.641526, 134.384766);

    var offices = [
		['Sydney', -33.834741, 151.209138, 3],
		['Melbourne', -37.829143, 145.044061, 2],
		['Brisbane', -27.501538, 152.973408, 1]
	];

    var myOptions = {
        zoom: 3,
        navigationControl: true,
        mapTypeControl: true,
        scaleControl: false,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    renderMarkers(map, offices);
};

// Render the marker icons on the Google Earth map
function renderMarkers(map, locations) {
    var image = new google.maps.MarkerImage('http://www.iview.com.au/ahm/owen/myview/images/2010/world.png',
		new google.maps.Size(28, 28),
		new google.maps.Point(0, 0),
		new google.maps.Point(14, 14));

    var shape = {
        coord: [0, 0, 0, 28, 28, 28, 28, 0],
        type: 'poly'
    };

    for (var i = 0; i < locations.length; i++) {
        var office = locations[i];
        var myLatLng = new google.maps.LatLng(office[1], office[2]);

        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            icon: image,
            shape: shape,
            title: office[0],
            zIndex: office[3]
        });

        google.maps.event.addListener(marker, 'click', function () {
            map.setCenter(this.getPosition());
            map.setZoom(18);
        });
    }

    $("p.cityName").css("cursor", "pointer");

    $("p#city_syd").click(function () {
        map.setCenter(new google.maps.LatLng(locations[0][1], locations[0][2]));
        map.setZoom(18);
    });

    $("p#city_melb").click(function () {
        map.setCenter(new google.maps.LatLng(locations[1][1], locations[1][2]));
        map.setZoom(18);
    });

    $("p#city_bris").click(function () {
        map.setCenter(new google.maps.LatLng(locations[2][1], locations[2][2]));
        map.setZoom(18);
    });
};

function loadFeatures() {
    if (window.location.href.indexOf("profSect=") != -1) {
        needsSave = false;

        // Add confirmation of unsaved changes
        $(':input').change(function () {
            if (!needsSave) {
                var divUnsaved = "<div id='confirm_background' style='display: none'><div id='confirm_navigation'><div class='nav_top'><p>SAVE CHANGES?</p><div class='nav_close'></div></div><div class='nav_content'><div class='confirm_nav_msg'><p>We noticed you made some changes to your profile.<br />What would you like to do?</p></div><div class='confirm_nav_buttons'><a id='nav_cancel' class='nav_input' href='#' title='Cancel'><span>Cancel</span></a><a id='nav_continue' class='nav_input' href='#' title=\"Don't Save\"><span>Don't Save</span></a><a id='nav_save' class='nav_input' href='#' title='Save'><span>Save</span></a><input type='submit' id='ProfileOtherRedirect' name='ProfileOtherRedirect' style='display:none' /><input type='hidden' id='RedirectTarget' name='RedirectTarget' /></div></div><div class='nav_bottom'></div></div></div>";

                $('a:not(.nav_input):not(.ui-slider-handle)').click(function (e) {
                    if ($('div#confirm_background').length == 0) {
                        $('form').append(divUnsaved);

                        // Add behaviour for continue without saving button
                        $('a#nav_cancel').click(function (e) {
                            $('div#confirm_background').hide();
                            e.preventDefault();
                        });

                        // Add behaviour for the close button
                        $('div.nav_close').click(function () {
                            $('div#confirm_background').hide();
                        });
                    }

                    var redirect = $(this).attr('href');
                    // Add behaviour for cancel button
                    $('a#nav_continue').click(function (e) {
                        needsSave = false;
                        e.preventDefault();
                        window.location = redirect;
                    });

                    // Add behaviour for save and continue
                    $('a#nav_save').click(function (e) {
                        needsSave = false;
                        $('#RedirectTarget').attr('value', redirect);
                        $('#ProfileOtherRedirect').click();
                        e.preventDefault();
                    });

                    // Show the warning div
                    $('div#confirm_background').show();

                    // Center the warning
                    $('div#confirm_navigation').css('top', ($(window).height() / 2 - $('div#confirm_navigation').height() / 2));
                    $('div#confirm_navigation').css('left', ($(window).width() / 2 - $('div#confirm_navigation').width() / 2));

                    e.preventDefault();
                });

                needsSave = true;
            }
        });

        $(':submit').click(function () {
            needsSave = false;
        });
    }

    // Add close account warning
    if ($('#ctl00_ctl01_quitterSubmit').length > 0) {
        var divUnsubscribe = "<div id='confirm_background' style='display: none'><div id='confirm_unsubscribe'><div class='unsub_top'><p>WARNING!</p><div class='nav_close'></div></div><div class='unsub_content'><div class='unsub_msg'><span>You are about to unsubscribe.<br />Are you sure that you really want to leave us?</span></div><div class='unsub_buttons'><a id='unsub_cancel' class='unsub_input' href='#' title='Cancel'><span>Cancel</span></a><a id='unsub_confirm' class='unsub_input' href='#' title='Unsubscribe'><span>Unsubscribe</span></a></div></div></div>";

        $('#ctl00_ctl01_quitterSubmit').after("<a href='#' id='conf_unsub' title='Click here to close your account!'>Close Account</a>");
        $('#ctl00_ctl01_quitterSubmit').hide();

        $('#conf_unsub').click(function (evt) {
            if ($('div#confirm_background').length == 0) {
                $('div.MainContent').append(divUnsubscribe);

                $('a#unsub_confirm').click(function (e) {
                    e.preventDefault();
                    $('#ctl00_ctl01_quitterSubmit').click();
                });

                $('a#unsub_cancel').click(function (e) {
                    e.preventDefault();
                    $('div#confirm_background').hide();
                });

                $('div.nav_close').click(function () {
                    $('div#confirm_background').hide();
                });
            }

            $('div#confirm_background').show();

            // Center the warning
            $('div#confirm_unsubscribe').css('top', ($(window).height() / 2 - $('div#confirm_unsubscribe').height() / 2));
            $('div#confirm_unsubscribe').css('left', ($(window).width() / 2 - $('div#confirm_unsubscribe').width() / 2));

            evt.preventDefault();
        });
    }

    // Hide the icons on the front page if the resolution is too small
    if ($(window).width() <= 1024) {
        $('[class^=fp_copy_image]').hide();
    }

    // Add colorboxes to images
    if ($('.news_image, .results_image').length > 0) {
        $('.news_image a, .results_image a').colorbox({
            transition: 'fade',
            onComplete: function () {
                $('div#cboxContent').addClass('cBoxImage');
                $('.cBoxImage').click(function () { $.fn.colorbox.close() });
            },
            onClosed: function () {
                $('div#cboxContent').removeClass('cBoxImage');
            },
            title: true
        });
    }

    // Do not render slider bars for ie6 users
    if (ie6) {
        $('.sliderControl').each(function () {
            $('.jquery-checkbox:first', $(this)).before('<span class="checkbox_label">0</span>');
            $('.jquery-checkbox:last', $(this)).after('<span class="checkbox_label">10</span>');


        });
    } else {
        $('table').each(function () {
            attachTableHover($(this));
        });

        $('.sliderControl').each(function (index) {
            renderSliderBar($(this), index);
        });
    }

    // Auto tab once maxlength is reached
    var autoTab = function (obj, len) {
        obj.each(function () {
            $(this).keyup(function (event) {
                // edited by Owen 2010-08-13 to only work if it's not a modifier or tab
                if (event.keyCode != '13' && event.keyCode != '9' && event.keyCode != '16') {
                    if ($(this).val().length == len) {
                        $(this).parent().next('div').find(':input').focus();
                    }
                }
            });
        });
    };

    // Add maxlength attribute to inputs
    $('input[class*=maxLen_]').each(function () {
        var maxLen = $(this).attr('class').split('maxLen_');
        var len = maxLen[1].split(' ')[0];
        $(this).attr('maxlength', len);

        // Add autotabbing if required - Note: All elements with autotabbing defined in the XML are assumed to also have maxLen defined
        if ($(this).attr('class').indexOf('autoTab') != -1) {
            autoTab($(this), parseInt(len));
        }
    });

    // Add autotabbing to Date questions
    $('input[id$=_Date_day], input[id$=_Date_Month]').each(function () {
        $(this).attr('maxlength', 2);
    });

    $('input[id$=_Date_Year]').each(function () {
        $(this).attr('maxlength', 4);
    });

    autoTab($('input[id$=_Date_day], input[id$=_Date_Month]'), 2);
    autoTab($('input[id$=_Date_Year]'), 4);

    // Automatically clear the default text
    $('.defaultText').each(function () {
        $(this).focus(function () {
            $(this).unbind('focus');
            $(this).val('');
        });
    });

    // Do not display a border-bottom for the last piechart
    $('div.piechart:last').css('border-bottom', '0px');

    // Add tabbing to checkboxes
    $('span.jquery-checkbox, span.jquery-table-checkbox').each(function () {
        $(this).attr("tabindex", 0);
        $(this).keypress(function (event) {
            if (event.keyCode == '32') {
                event.preventDefault();
                $(this).click();
            }
        });
    });

    // Add the password strength tooltip
    if ($(":input.passwordInput").length > 0) {
        var $pwTooltip = $("<div id=\"password_tooltip\"><div class=\"tooltipTop\"><span class=\"toolTipClose\"></span></div><div class=\"tooltipBody\">Your password must be:<ol><li>Minimum 6 characters in length</li><li>Mix of number and characters</li></ol><div id=\"password_strength\" class=\"strength0\"></div></div><div class=\"tooltipBottom\"></div></div>");
        $("body").append($pwTooltip);
        $("#password_tooltip").hide();

        $(":input.passwordInput").click(function () {
            var $theTextboxElem = $(this);
            var topOffset = (($theTextboxElem.closest("div.myAccount_contentArea").length > 0) ? 0 : 35);
            $("#password_tooltip").css({ "top": $theTextboxElem.offset().top + topOffset, "left": $theTextboxElem.offset().left + 275 });
            $("#password_tooltip").fadeIn('slow');
        });

        $(":input.passwordInput").blur(function () { $("#password_tooltip").fadeOut('slow'); });

        $(":input.passwordInput").keyup(function () {
            password_strength($(this).val());
        });
    }

    // Hide errors when the user changes them after a validation error
    $("div.profileQuestion input, div.profileQuestion select").change(function () {
        $("div.profileError", $($(this).closest("div.profileQuestion"))).hide();
    });

    // Repeat table headers
    $('table.profileQuestion_grid').each(function () {
        repeatTableHeaders($(this), 6);
    });

    // Alternate Panel Statistic row colours
    $('table.detailedStatsTable').each(function () {
        $('tr:odd[id!=statsTableHeader]', $(this)).addClass('odd_row');
    });

    // Render the Click to Open/Close div
    if ($('tr.statsTableHeader').length > 0) {
        var tooltip = $("<div class='toggle_tooltip'></div>").appendTo($('body'));
        tooltip.css({ 'position': 'absolute', 'visibility': 'hidden' });
    }

    // Panel Statistic row toggler
    $('tr.statsTableHeader, div.counts_contentArea .whiteBox_top').each(function () {
        var parent = $(this).closest('.GenericWhiteboxItem');
        $(this).hover(function () {
            $('div.toggle_tooltip').text(parent.hasClass('expanded') ? 'Click to Close' : 'Click to Open');
            $('tr.statsTableHeader', parent).addClass('sectionTitleHover');
            $('div.toggle_tooltip').css('visibility', 'visible');
        }, function () {
            $('tr.statsTableHeader', parent).removeClass('sectionTitleHover');
            $('div.toggle_tooltip').css('visibility', 'hidden');
        });
        $(this).mousemove(function (e) {
            $('div.toggle_tooltip').css({ 'top': e.pageY - 20, 'left': e.pageX + 20 });
        });
        $(this).click(function () {
            $('tr.statsRespOutput', parent).toggle();
            parent.toggleClass('expanded');
            $('div.toggle_tooltip').text(parent.hasClass('expanded') ? 'Click to Close' : 'Click to Open');
        });
    });

    // Hide all of the expanded entries
    $('tr.statsRespOutput').hide();

    // Remove the border-bottom from the last question on the page
    removeBottomBorder();

    // Make back to news button call 'Back' using javascript
    $('a.backTonews_Button, a.backToresults_Button').click(function (e) {
        if (document.referrer.indexOf('default') == -1) {
            history.go(-1);
            e.preventDefault();
        }
    });


    $('.profileQuestion_ddl').each(function () {
        renderSelectDropdown($(this));
    });

    $('.profileQuestion_ddl_Contact').each(function () {
        renderSelectDropdown_Contact($(this));
    });

}

// Render pretty dropdown selects
function renderSelectDropdown(obj) {
    obj.wrap('<div class="dropDown_select" id="select_' + obj.attr('id') + '" />');
    obj.css('float', 'left');

    var valueSpan = $('<span class="dropDown_value" id="select_val_' + obj.attr('id') + '"></span>').insertBefore(obj);

    if ($(':selected', obj).length > 0) {
        valueSpan.text($(':selected', obj).text());
    }

    obj.change(function () {
        if ($(':selected', obj).length > 0) {
            valueSpan.text($(':selected', obj).text());
        }
    });
}

// Render pretty dropdown selects
function renderSelectDropdown_Contact(obj) {
    obj.wrap('<div class="dropDown_select_Contact" id="select_' + obj.attr('id') + '" />');
    obj.css('float', 'left');

    var valueSpan = $('<span class="dropDown_value_Contact" id="select_val_' + obj.attr('id') + '"></span>').insertBefore(obj);

    if ($(':selected', obj).length > 0) {
        valueSpan.text($(':selected', obj).text());
    }

    obj.change(function () {
        if ($(':selected', obj).length > 0) {
            valueSpan.text($(':selected', obj).text());
        }
    });
}

// Display IE6 warning, telling users to let go of the past and upgrade!
function ie6ShadowBox() {
    var c_ie6 = getCookie("ie6");
    if (c_ie6 != "seen") {

        if ($("div.ie6Warning").length > 0) {
            $("div.ie6Warning").css({ display: "none" });
            $.colorbox({
                inline: true,
                href: "#ie6Warning",
                transition: 'fade',
                onLoad: function () {
                    if ($("body > #colorbox").length > 0) {
                        $("form").append($("body > #cboxOverlay"));
                        $("form").append($("body > #colorbox"));

                    }
                    $("div.ie6Warning").css("display", "block");
                },
                onCleanup: function () {
                    $("div.ie6Warning").css("display", "none");
                },
                overlayClose: false
            });
        }
        setCookie("ie6", "seen", 365);
    }
    else {
        $("div.ie6Warning").css("display", "none");
    }
}

// Remove the border-bottom from the last question on the page
function removeBottomBorder() {
    if ($('.no_border').length == 0) {
        $('div.profileQuestion:visible:last').addClass('no_border');
    } else {
        $('div.no_border').removeClass('no_border');
        $('div.profileQuestion:visible:last').addClass('no_border');
    }
}

// Repeat the table headings on very long grid questions
function repeatTableHeaders(obj, n) {
    var repeatRow = $('tr:first', obj).clone();
    $('tr:first', obj).remove()

    // This uses the simple heuristic of requiring n * 1.5 rows before kicking in
    $('tr:nth-child(' + n + 'n+1)', obj).before(repeatRow);
}

// Display the login colorbox
function loginShadowBox() {
    if ($("#login") && $("#login").length > 0) {
        $("#login").addClass("shadowBoxed");
        $("#login").css("display", "none");

        $("div.header div.container").append("<div id=\"headerLogin\"><a href='#' id='loginShadowBox' ></a></div>");
        $("div.header a[id=loginShadowBox]").add("a.login_link").colorbox(
		{
		    inline: true,
		    href: "#login",
		    transition: 'fade',
		    onOpen: function () {
		        $('div#cboxContent').addClass('cBoxLogin');
		        $('#login *').keypress(function (event) {
		            if (event.keyCode == '13') {
		                $('#ctl00_Login_Submit').click();
		                event.preventDefault();
		            }
		        })
		        $('#ctl00_Login_pWord, #ctl00_Login_uEmail').keypress(function () {
		            $('#ctl00_Login_loginMessage').hide();
		        });
		    },
		    onLoad: function () {
		        if ($("body > #colorbox").length > 0) {
		            $("form").append($("body > #cboxOverlay"));
		            $("form").append($("body > #colorbox"));

		        }
		        $("#login").css("display", "block");
		    },
		    onCleanup: function () {
		        $('div#cboxContent').removeClass('cBoxLogin');
		        $("#login").css("display", "none");
		        $('.loginInput').val("");
		    },
		    overlayClose: true,
		    title: true
		});
    }
}

// Load the rotating banner aka "fanner"
function loadFanner() {
    if ($("#HomeBanner").length > 0) {
        var rb = new RotatingBanner($("#HomeBanner"), rbFadeIn, 10000);
        rb.addElement("<div id='banner1'><div class='banner_content'></div></div>");
        rb.addElement("<div id='banner2'><div class='banner_content'></div></div>");
        rb.addElement("<div id='banner3'><div class='banner_content'></div></div>");
        rb.addElement("<div id='banner4'><div class='banner_content'></div></div>");
        rb.start();
    }
}

// Rotating banner implementation
var Direction = { "FWD": 0, "REV": 1 };
function RotatingBanner(container, transition, delay, first) {
    // Member variables
    this.container = container; // The container where the Rotating Banner is placed
    this.transition = transition; // The function to call when transitioning
    this.delay = delay; // The delay between transitions 

    // Index of the current element
    if (first == null) {
        this.currElement = 0;
    } else {
        this.currElement = first;
    }

    // if there is a default, remove it
    $("div.default", container).remove();

    // Create an array containing the ids of all the banner elements
    this.elements = [];

    // Add another element to the rotating banner
    this.addElement = function (elem) {
        elemID = $(elem).attr("id");

        this.container.append(elem);
        this.elements.push(elemID);

        if (this.elements.length > 1) {
            $('#' + elemID).hide();
        };
    };

    this.next = function () {
        var curr, next;
        curr = this.currElement;
        next = ++this.currElement;

        // If incrementing caused the element to go out of bounds, set next to the first element of the list
        if (next > this.elements.length - 1) {
            this.currElement = 0;
            next = 0;
        }
        // Call the transition function
        this.transition(this.container, this.elements[curr], this.elements[next]);
    };

    this.prev = function () {
        var curr, next;
        curr = this.currElement;
        next = --this.currElement;

        // If decrementing caused the element to go out of bounds, set next to the last element of the list
        if (next < 0) {
            this.currElement = this.elements.length - 1;
            next = this.elements.length - 1;
        }

        // Call the transition function
        this.transition(this.container, this.elements[curr], this.elements[next]);
    };

    // Starts the banner rotating
    this.start = function (direction) {
        // Resolve the setInterval scope problem
        var me = this;
        var fn;

        if (direction == Direction.REV) { // Reversed direction
            fn = function () { me.prev(); };
        } else { // Normal forward direction
            fn = function () { me.next(); };
        }
        this.timer = setInterval(fn, this.delay);
    };

    // Stops the banner from rotating
    this.pause = function () {
        clearInterval(this.timer);
    };

    // Sets the function that will be used for transitions between one banner to the next
    this.setTransition = function (transition) {
        this.transition = transition;
    };

    // Sets the delay between transitions
    this.setDelay = function (delay) {
        this.delay = delay;
    };
}

// Fade transition for the rotating banner
function rbFadeIn(container, curr, next) {
    $('#' + curr, container).attr('z-index', '100');
    $('#' + next, container).attr('z-index', '1000');

    $('#' + next, container).fadeIn(1500);
    $('#' + curr, container).fadeOut(1500);
}

// Renders pretty looking slider bars
function renderSliderBar(obj, curr) {
    var newSliderBar = '<div id=\'slider[' + curr + ']\' class=\'slider_container\'><span class=\'slider_min\'></span><div class=\'slider_left\'></div><div class=\'slider_bar\'></div><div class=\'slider_right\'></div><span class=\'slider_max\'></span><span class=\'slider_value\'></span></div><div style=\'clear: both;\'></div>';
    var options = $(':radio', obj);

    vMax = options.length; // Get the number of objects
    $('.jquery-checkbox', obj).hide(); // Hide the original radio buttons
    obj.after(newSliderBar); // Append the new slider bar

    // Set the underlying checkbox
    var setCheckbox = function (index) {
        $(':checked', obj).click(); // Uncheck currently selected
        $(':radio:eq(' + index + ')', obj).click(); // Check the corresponding radiobutton
        displayValue();
    };

    // Set the value of the slider (used when the extremities are clicked)
    var setValue = function (index) {
        setSlider(index);
        setCheckbox(index);
    };

    // Set the position on the slider
    var setSlider = function (index) {
        $('#slider\\[' + curr + '\\] .slider_bar').slider("value", index);
    };

    // Display the value of the currently selected checkbox
    var displayValue = function () {
        $('#slider\\[' + curr + '\\] .slider_value').text($(':checked', obj).val()); // Set the text
    };

    // Create the slider
    $('#slider\\[' + curr + '\\] .slider_bar').slider({
        animate: 'slow',
        value: parseInt(vMax / 2),
        min: 0,
        max: vMax - 1,
        step: 1,
        slide: function (event, ui) {
            setCheckbox(ui.value);
        }
    });

    // Check if a value should be set
    if ($(':checked', obj).length == 1) {
        var chkIndex = $(':checked', obj).index('[name=' + $(':checked', obj).attr('name') + ']')
        setSlider(chkIndex);
        displayValue();
    }

    // Set event handlers for clicking on the ends of the bar
    $('#slider\\[' + curr + '\\] .slider_left').add($('#slider\\[' + curr + '\\] .slider_min')).click(function () { setValue(0) });
    $('#slider\\[' + curr + '\\] .slider_right').add($('#slider\\[' + curr + '\\] .slider_max')).click(function () { setValue(vMax - 1) });
}

// Attaches row hovers to tables
function attachTableHover(obj) {
    var td_rollOver = function () {
        $('tr.rowHovered', obj).removeClass('rowHovered');

        $(this).closest('tr', obj).addClass('rowHovered');
        $(this).closest('tr', obj).children('td:first').addClass('categoryHighlight');
    };

    var td_rollOut = function () {
        $('tr.rowHovered', obj).removeClass('rowHovered');
        $('td.categoryHighlight', obj).removeClass('categoryHighlight');
    };

    // Add Row Hover Effects
    $('td', obj).each(function () { $(this).hover(td_rollOver, td_rollOut) });
    $('td *', obj).each(function () { $(this).hover(td_rollOver), function () { } });
}

/* Legacy scripts from the old MyView website */
function password_strength(password) {
    var desc = new Array();
    desc[0] = "Very Weak";
    desc[1] = "Weak";
    desc[2] = "Medium";
    desc[3] = "Strong";
    desc[4] = "Excellent";

    var points = 0;

    //---- if password is bigger than 4 , give 1 point.
    if (password.length > 4) points++;

    //---- if password has both lowercase and uppercase characters , give 1 point.	
    if ((password.match(/[a-z]/)) && (password.match(/[A-Z]/))) points++;

    //---- if password has at least one number , give 1 point.
    if (password.match(/\d+/)) points++;

    //---- if password has at least one special caracther , give 1 point.
    if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) points++;

    //---- if password is bigger than 12 ,  give 1 point.
    if (password.length > 12) points++;

    //---- Changeing CSS class.
    document.getElementById("password_strength").className = "strength" + points;
}

function checkVotes(button, pos) {
    if (pos != "") {
        var theOtherPollId = "PollId" + ((pos % 2) + 1);

        if (document.getElementById(theOtherPollId)) {
            theOtherElement = document.getElementById(theOtherPollId);
        }

        if (document.getElementById(theOtherPollId)) {
            document.getElementById(theOtherPollId).value = "";
        }
    }

    var bVoted = false;
    var bExclusiveChecked = false;
    var errorMessage = "Unknown error! Please try later!";

    if (document.getElementById("optionsContainer" + pos)) {

        var pollType = document.getElementById('polltype' + pos);
        var theContainer = document.getElementById("optionsContainer" + pos);

        var theInputElements = theContainer.getElementsByTagName('input');

        for (var i = 0; i < theInputElements.length; i++) {
            theCurrentInput = theInputElements[i];
            if (pollType.value == "checkbox") {
                if (i == theInputElements.length - 1) {
                    if (theCurrentInput.checked && bVoted)
                        bExclusiveChecked = true;
                    if (theCurrentInput.checked)
                        bVoted = true;
                }
                else
                    if (theCurrentInput.checked)
                        bVoted = true;
            }
            else {
                if (theCurrentInput.checked)
                    bVoted = true;
            }
        }

        if (button.id.indexOf("voteBtn" + pos) == -1)
            bVoted = false;

        if (bVoted && !bExclusiveChecked) {
            return true;
        }
        else {
            if (bExclusiveChecked) {
                errorMessage = "Please note the last option is exclusive";
            }

            if (!bVoted) {
                errorMessage = "Please provide an answer";
            }

            alert(errorMessage);
            return false;
        }
    }
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

