var section;
var mycarousel_itemList = [];
var regFormSubmit = 0;
var form = '';
var step = 0;
var abtest = ' Test 1 ';
var showRegistration = true;

function changeSiteSize(perc) {
    $('body').css('font-size', perc);
}

function slideloginbox() {
    $('#login_entry_box').slideToggle('fast');
}

function calculatePrices(symbol) {
    var totalCost = 0;
    var discountPercentage = 20; // percentage discount;
    var currency = '';
    $('.price-input').each(
        function () {
            var count = $(this).attr('value');
            var cost = $('#cost-' + $(this).attr('id').split('-')[1])
                .text();
            totalCost = (totalCost + (cost * count));
        });
    var discount = ((totalCost / 100) * discountPercentage).toFixed(2);
    var discountedCost = (totalCost - discount).toFixed(2);

    $('#usual_cost').html('Typical cost: <strong>' + symbol + totalCost.toFixed(2) + '</strong>');
    $('#usual_cost').css('display', 'block');
    $('#amount_saved').text(symbol + discountedCost);
}

/*
 * Hides a class of elements, and display an individual element by id
 */
function showSection(className, id) {
    if ($('#link-' + id).length) {
        $('#link-' + id).parent().parent().children().removeAttr('class');
        $('#link-' + id).parent().addClass('selected');
    } else {
        // change tab style
        $('#content_wrapper .selected').removeAttr('class');
        $('#tab-' + id).addClass('selected');
    }


    // remove all old curves
    $('#tab-' + id).siblings().children('img').each(function () {
        $(this).attr('src', $(this).attr('src').replace('-sel', ''));
    });

    // Add the new curve images to the selected tab
    var tlImg = $('#tab-' + id + ' img.corner-tl').attr('src');
    var trImg = $('#tab-' + id + ' img.corner-tr').attr('src');

    if (tlImg.indexOf('-sel') == '-1') $('#tab-' + id + ' img.corner-tl').attr('src', tlImg.replace('_tl', '_tl-sel'));
    if (trImg.indexOf('-sel') == '-1') $('#tab-' + id + ' img.corner-tr').attr('src', trImg.replace('_tr', '_tr-sel'));

    // display box
    $('.' + className).removeAttr('class').addClass(className + '-hidden');
    $('#' + id).removeAttr('class');
    $('#' + id).addClass(className);

    if (id == 'attraction_box_content-planning-your-visit') {
        initialiseMaps();
    }
}

function initialiseMaps() {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

        var geocoder = new GClientGeocoder();

        function showAddress(address, information) {
            geocoder.getLatLng(address, function (point) {
                if (!point) {
                    alert(address + " not found");
                } else {
                    map.setCenter(point, 10);
                    var marker = new GMarker(point);
                    map.addOverlay(marker);
                    marker.bindInfoWindowHtml(information);
                }
            });
        }

        var address = $('#attraction_location').text();
        // pass attraction information as the second parameter if required.
        showAddress(address, address);
    }
}

function mapOver(areaObj) {
    var areaID = areaObj.id.split('-')[1];
    $('#uk-map').attr('src', '/images/uk-map/' + areaID + '.png');
}

function mapOut() {
    $('#uk-map').attr('src', '/images/uk-map/spacer.png');
}

function regionSearch(areaObj) {
    var areaID = areaObj.id.split('-')[1];
    window.location.href = areaObj.href;
}

function clickClear(thisfield, defaulttext) {
    if (thisfield.value == defaulttext) {
        thisfield.value = "";
    }
}

function clickRecall(thisfield, defaulttext) {
    if (thisfield.value == "") {
        thisfield.value = defaulttext;
    }
}

function validateStuckForm() {
    if (hasNumber($('#postcode_box').attr('value')) == false || $('#postcode_box').attr('value') == '') {
        alert('Please enter a postcode');
        return false;
    }
    if (isNaN(parseInt($('#distance_box').attr('value')))) {
        alert('Please select a valid distance');
        return false;
    }

}

function hasNumber(t) {
    return /\d/.test(t);
}

/*
 *  Carousel configuration functions
 */
function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
    carousel.startAuto(2);
    // console.log(carousel);
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    if (mycarousel_itemList[idx - 1] != null) {
        carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
    }
}
;

function theatrecarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
    carousel.startAuto(2);
    // console.log(carousel);
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    if (mycarousel_itemList[idx - 1] != null) {
        carousel.add(i, theatrecarousel_getItemHTML(mycarousel_itemList[idx - 1]));
    }
}
;

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);
}
;

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(item) {
    // console.log(item);
    var obj = item[0];
    return '<a href="' + obj.link + '"><img src="' + obj.url
        + '" width="120" alt="' + obj.title + '" /></a>';
}
;

function theatrecarousel_getItemHTML(item) {
    // console.log(item);
    var obj = item[0];
    return '<a href="' + obj.link + '"><img src="' + obj.url
        + '" width="100" alt="' + obj.title + '" /></a>';
}
;

function geocodeSearch(fromAddress, toAddress, locale) {
    var search = fromAddress;
    geo = new GClientGeocoder();
    geo.getLocations(search, function (result) {
            map.clearOverlays();
            if (result.Status.code == G_GEO_SUCCESS) {
                if (result.Placemark.length > 1) {
                    document.getElementById("message").innerHTML = "Did you mean:";
                    for (var i = 0; i < result.Placemark.length; i++) {
                        var p = result.Placemark[i].Point.coordinates;
                        document.getElementById("message").innerHTML += "<br>" + (i + 1) + ": <a href=\"javascript:plotDirections(\'" + p[1] + "\',\'" + p[0] + "\',\'" + toAddress + "\',\'" + locale + "\')\">" + result.Placemark[i].address + "<\/a>";
                    }
                }
                else {
                    document.getElementById("message").innerHTML = "";
                    var p = result.Placemark[0].Point.coordinates;
                    plotDirections(p[1], p[0], toAddress, locale);
                    document.getElementById("message").innerHTML = "Located: " + result.Placemark[0].address;
                }
            }
            else {
                var reason = "Code " + result.Status.code;
                if (reasons[result.Status.code]) {
                    reason = reasons[result.Status.code]
                }
                alert('Could not find "' + search + '" ' + reason);
            }
        }
    );
}

function openx(zoneid) {
    document.MAX_ct0 = 'INSERT_CLICKURL_HERE';

    var m3_u = (location.protocol == 'https:' ? 'https://openx.smartsys.biz/www/delivery/ajs.php' : 'http://openx.smartsys.biz/www/delivery/ajs.php');
    var m3_r = Math.floor(Math.random() * 99999999999);
    if (!document.MAX_used) document.MAX_used = ',';
    document.write("<scr" + "ipt type='text/javascript' src='" + m3_u);
    document.write("?zoneid=" + zoneid);
    document.write('&amp;cb=' + m3_r);
    if (document.MAX_used != ',') document.write("&amp;exclude=" + document.MAX_used);
    document.write(document.charset ? '&amp;charset=' + document.charset : (document.characterSet ? '&amp;charset=' + document.characterSet : ''));
    document.write("&amp;loc=" + escape(window.location));
    if (document.referrer) document.write("&amp;referer=" + escape(document.referrer));
    if (document.context) document.write("&context=" + escape(document.context));
    if ((typeof(document.MAX_ct0) != 'undefined') && (document.MAX_ct0.substring(0, 4) == 'http')) {
        document.write("&amp;ct0=" + escape(document.MAX_ct0));
    }
    if (document.mmm_fo) document.write("&amp;mmm_fo=1");
    document.write("'><\/scr" + "ipt>");
}

function showPrintForm(overlayShow) {
    form = '#mailing-list-form';
    step = 1;

    var barcode = $.cookie('barcode');
    var registered = $.cookie('registered');
    var log = $(form).attr("action").replace('register', 'print');

    if (isNaN(parseInt(overlayShow))) {
        overlayShow = 1;
    }
    if (overlayShow == 2) {
        barcode = "53900000000";
    }
    if (null === barcode) {
        var theUrl = log.replace("print", "log/get/barcode/");
        $.get(theUrl, {}, function(data){
            barcode = data.substring(1,data.length -1);
            logPrint( overlayShow, barcode, registered );
        });
    }
    else {
        logPrint( overlayShow, barcode, registered );
    }
}

function processUrl( url, barcode ) {
    var url = url.replace("print", "log/print/barcode/" + barcode);
    if (url.split('?').count > 1) {
        var t = url.split('?');
        url = t[0];
    }
    return url;
}

function logPrint( overlayShow, barcode, registered ) {

    if ( registered == null) {
        _gaq.push(['_trackEvent', 'Barcode Print', 'Unregistered', barcode.substr(0, 3), 1]);
    }
    else {
        _gaq.push(['_trackEvent', 'Barcode Print', 'Registered', barcode.substr(0, 3), 1]);
    }

    var log = $(form).attr("action").replace('register', 'print');

    var url = processUrl( log, barcode);
    var url2 = processUrl( log, barcode.substr(0, 3));

    _gaq.push(['_trackPageview', url2]);
    $.get(url);

    if (overlayShow != 2) {
        showRegistration = false;
        window.print();
        showRegistration = true;
    }

    if (registered == null) {
        if (overlayShow == 1) {
            setTimeout(showOverlay, 4000);
        }
        else if (overlayShow == 2) {
            setTimeout(showOverlay, 10000);
        }
    }
}

function showPrintFormTest(overlayShow) {
    var tracked = 0;

    var barcode = $.cookie('barcode');

    if ($.cookie('registered') == null) {
        _gaq.push(['_trackEvent', 'Barcode Print', 'Unregistered', '9993', 1]);
    }
    else {
        _gaq.push(['_trackEvent', 'Barcode Print', 'Registered', '9993', 1]);
    }

    form = '#mailing-list-form';
    step = 1;

    if (isNaN(parseInt(overlayShow))) {
        overlayShow = 1;
    }

    var barcode = $.cookie('barcode');
    var log = $(form).attr("action").replace('register', 'print');
    var url = log.replace("print", "log/print/barcode/9993");

    if (url.split('?').count > 1) {
        var t = url.split('?');
        url = t[0];
    }

    var url2 = log.replace("print", "log/print/barcode/9993");
    if (url2.split('?').count > 1) {
        var t = url2.split('?');
        url2 = t[0];
    }

    _gaq.push(['_trackPageview', url2]);
    $.get(url);

    showRegistration = false;
    //window.print();
    showRegistration = true;

    if ($.cookie('registered') == null) {
        if (overlayShow == 1) {
            //setTimeout(showOverlay, 4000);
        }
    }
}


function showPrintForm2(overlayShow) {
    showPrintForm(overlayShow);
    /*form = '#mailing-list-form';
     step = 1;
     abtest = ' Test 2 ';

     if (isNaN(parseInt(overlayShow))) {
     overlayShow = 1;
     }
     var nameEQ = "registered=";

     var ca = document.cookie.split(';');
     for (var i = 0; i < ca.length; i++) {
     var c = ca[i];
     while (c.charAt(0) == ' ') c = c.substring(1, c.length);
     if (c.indexOf(nameEQ) == 0) {
     pageTracker._trackEvent('Print Test 2', 'Registered', escape(window.location.href));
     return false;
     }
     }
     pageTracker._trackEvent('Print Test 2', 'Unregistered', escape(window.location.href));
     if (overlayShow == 1) {
     showOverlay();
     }*/
}

function validate() {
    var error = 0;
    $(form + ' .step' + step + ' .required').each(function () {
        var element = $(this).attr("for");
        if (element != '') {
            if ($('#' + element).val() == '' || $('#' + element).val() == '-1') {
                $('#' + element + '-error').css("display", "block");
                $('#' + element).focus(function () {
                    $('#' + $(this).attr("id") + '-error').hide("slow");
                });
                error = 1;
            }
            else {
                if (element.match(/email/)) {
                    if (!$('#' + element).val().match(/^[a-zA-Z0-9_\.\-\+]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/)) {
                        $('#' + element + '-error').css("display", "block");
                        $('#' + element).focus(function () {
                            $('#' + $(this).attr("id") + '-error').hide("slow");
                        });
                        error = 1;
                    }
                }
            }
        }

    });
    return error;
}

function showJoinForm() {
    $('#form-thanks').hide();
    $('#merchant-join-form .step2').hide();
    $('#merchant-form-thanks').hide();
    $('#register-overlay').hide();
    $('#merchant-overlay').hide();
    form = '#mailing-list-form';
    step = 1;
    _gaq.push(['_trackEvent', 'Join', 'Registration', 'Open Step 1', 1]);
    showOverlay();
}

function showMerchantJoinForm() {
    form = '#merchant-join-form';
    step = 1;
    _gaq.push(['_trackEvent', 'Join', 'Merchant', 'Open Step 1', 1]);
    showOverlay();
    $('#merchant-join-form .step2').hide();
    $('#merchant-join-form').show();
    $('#merchant-join-form .step1').show();
    checkRecaptcha('recaptcha_div_registration');
}

function showOverlay() {
    $('#register-overlay').hide();
    $('#merchant-overlay').hide();
    $('#print-form').hide();
    $('#print-form2').hide();
    $('#form-thanks').hide();
    $('#merchant-form-thanks').hide();
    var height = parseInt($('#head_wrapper').height()) + parseInt($('#content_wrapper').height()) + parseInt($('#footer_wrapper').height());
    if (form == '#merchant-join-form') {
        $('#merchant-overlay').css('height', height + 35).show();
        $('#merchant-join-form').show();
    } else {
        $('#register-overlay').css('height', height + 35).show();
        $('#mailing-list-form').show();
    }
    if (window.location.href.match(/days-out/)) {
        section = 'days-out-form';
    }
    else if (window.location.href.match(/restaurants/)) {
        section = 'restaurants-form';
    }
    else if (window.location.href.match(/hotels/)) {
        section = 'hotels-form';
    }
    else if (window.location.href.match(/shopping/)) {
        section = 'shopping-form';
    }
    else if (window.location.href.match(/theatres/)) {
        section = 'theatres-form';
    }
    else if (window.location.href.match(/experiences/)) {
        section = 'experiences-form';
    }
    $(form).addClass(section);
    $(form).show();
    if (form == '#merchant-join-form') {
        $('#merchant-form-thanks').addClass(section);
    } else {
        $('#form-thanks').addClass(section);
    }
}

// Initialize the carousel
$(document).ready(function () {

    // $('#stars-wrapper').stars({disabled: true});
    $('.stars-wrapper').stars({
        cancelShow:false,
        disabled:true
    });

    $('.jcarousel-item a').each(function () {
        var obj = new Object();

        obj.link = $(this).attr('href');
        obj.url = $(this).children('img').attr('src');
        obj.title = $(this).children('img').attr('alt');

        var tempArray = [ obj ];
        mycarousel_itemList.push(tempArray);
    });

    $('#mycarousel').jcarousel({
        // Configuration goes here
        wrap:'circular',
        itemVisibleInCallback:{
            onBeforeAnimation:mycarousel_itemVisibleInCallback
        },
        itemVisibleOutCallback:{
            onAfterAnimation:mycarousel_itemVisibleOutCallback
        }
    });

    $('#theatrescarousel').jcarousel({
        // Configuration goes here
        wrap:'circular',
        itemVisibleInCallback:{
            onBeforeAnimation:theatrecarousel_itemVisibleInCallback
        },
        itemVisibleOutCallback:{
            onAfterAnimation:theatrecarousel_itemVisibleInCallback
        }
    });

    var ScrollLength = '150';
    $("#section-tab-left").click(function () {
        var leftPos = $(".section_box_tab_menu").css('left');
        if (parseInt(leftPos) < 0) {
            $(".section_box_tab_menu").animate({
                "left":"+=" + ScrollLength + "px"
            }, "fast");
        }
        else {
            $(".section_box_tab_menu").css('left', '0px');
        }
    });

    $("#section-tab-right").click(function () {

        var maxPos = (($('.section_box_tab_menu > *').length - 4) * ScrollLength);

        var pos = $('.section_box_tab_menu').offset();
        if ((pos.left + maxPos) > 0) {
            $(".section_box_tab_menu").animate({
                "left":"-=" + ScrollLength + "px"
            }, "fast");
        }

    });

    // Make each menu items li tag clickable
    $('.menu_item').each(function () {
        $(this).click(function () {
            window.location.href = $(this).children('a').attr('href');
        });
        $(this).mouseover(function () {
            $(this).addClass('selected');
        });
        $(this).mouseout(function () {
            $(this).removeClass('selected');
        });
    });

    $('.shopping-link').click(function (e) {
        e.preventDefault();
        window.open($(this).attr("href"), '_blank');
        return false;
    });

    // Initialise Quickfind UK map
    $('.uk_map_area').each(function () {
        $(this).mouseover(function () {
            mapOver(this);
        });
        $(this).mouseout(function () {
            mapOut();
        });
        $(this).click(function () {
            regionSearch(this);
            return false;
        });
    });

    // Initialise the tooltips
    //applyTooltips();
    /**
     * Tooltip redone with jquery
     */
    $('a.tooltip-icon').tooltip({
        bodyHandler:function () {
            return $($(this).attr('href')).html();
        },
        showURL:false
    });

    /*$("#register-link").colorbox({
     width: "740",
     height: "450",
     opacity: "0.5",
     onOpen: function(){ window.print(); setTimeout(function(){}, 10000); }
     });*/
    $('.facebook').click(function () {
        var title = escape(document.title);
        var href = escape(window.location.href);
        _gaq.push(['_trackEvent', 'Social', 'Facebook', barcode.substring(0, 3), 1]);
        window.open('http://www.facebook.com/sharer.php?u=' + href + '&t=' + title, 'facebook', "width=600,height=400,toolbar=0,statusbar=0,menubar=0");
        return false;
    });

    $('.twitter').click(function () {
        var status = 'Save 20% on major UK attractions with @Smartsave';
        if ($('meta[name="tw:title"]').length > 0) {
            status = 'Save 20% at ' + $('meta[name="tw:title"]').attr("content") + ' with @Smartsave'
        }
        _gaq.push(['_trackEvent', 'Social', 'Twitter', barcode.substring(0, 3), 1]);
        window.open('http://twitter.com/home?status=' + escape(status), '_blank');
        return false;
    });
});

function checkRegistration() {
    if (showRegistration) {
        if ($.cookie('registered') == null) {
            if ($.cookie('regrequested') == null) {
                $.cookie('regrequested', 1, {path:'/'});
            } else {
                $.cookie('regrequested', (parseInt($.cookie('regrequested')) + 1), {path:'/'});
            }
            if (parseInt($.cookie('regrequested')) <= ssRegTotal) {
                showJoinForm();
                window.clearTimeout(ssRegTimer);
                if (parseInt($.cookie('regrequested')) == 3) {
                    ssRegRepeat += 10000;
                }
                ssRegTimer = window.setTimeout("checkRegistration()", ssRegRepeat);
            }
        }
    }
}

$(document).ready(function () {

    $('#experiences-categories-results > li > ul')
        .hide()
        .click(function (e) {
            e.stopPropagation();
        }
    );
    $('#experiences-categories-results > li').toggle(function () {
            $('#experiences-categories-results > li > ul').slideUp();
            if (!$(this).find('ul').length) {
                window.location.href = $(this).find('a').attr("href");
            }
            else {
                $(this).find('ul').slideDown();
            }
        },
        function () {
            $(this).find('ul').slideUp();
        });

    $('#hotels-categories-results > li > ul')
        //.hide()
        .click(function (e) {
            e.stopPropagation();
        }
    );
    $('#hotels-categories-results > li').toggle(function () {
            //$('#hotels-categories-results > li > ul').slideUp();
            if (!$(this).find('ul').length) {
                window.location.href = $(this).find('a').attr("href");
            }
            else {
                //$(this).find('ul').slideDown();
            }
        },
        function () {
            //$(this).find('ul').slideUp();
        });

    // Registration Forms
    $('#header_mailing_list').submit(function () {
        if ($('#register_input_box_header').val().match(/^[a-zA-Z0-9_\.\-\+]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/)) {
            $.get($(this).attr("action") + '/validate-email', {email:escape($('#register_input_box_header').val())}, function (r) {
                var lines = r.split("\n");
                if (lines[lines.length - 1] > 0) {
                    $('#mailing-list-id').val(lines[lines.length - 1]);
                    $('#mailing-list-email-address').val($('#register_input_box_header').val());
                    $('#form-thanks').hide();
                    showJoinForm();
                }
                else if (lines[lines.length - 1] == 'ALREADY REGISTERED') {
                    $.cookie('registered', 1, { expires:999, path:'/' });
                    $('#mailing-list-form').hide();
                    form = '#form-thanks';
                    showOverlay();
                }
            });
        }
        return false;
    });

    // Registration Forms
    $('#merchant_feature_request').click(function () {
        showMerchantJoinForm();
        return false;
    });


    $('#footer-reg').submit(function () {
        if ($('#register_input_box').val().match(/^[a-zA-Z0-9_\.\-\+]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/)) {
            $.get($(this).attr("action") + '/validate-email', {email:escape($('#register_input_box').val())}, function (r) {
                var lines = r.split("\n");
                if (lines[lines.length - 1] > 0) {
                    $('#mailing-list-id').val(lines[lines.length - 1]);
                    $('#mailing-list-email-address').val($('#register_input_box').val());
                    $('#form-thanks').hide();
                    showJoinForm();
                }
                else if (lines[lines.length - 1] == 'ALREADY REGISTERED') {
                    $.cookie('registered', 1, { expires:999, path:'/' });
                    form = '#form-thanks';
                    showOverlay();
                }
            });
        }
        return false;
    });
    $('#mailing-list-form').submit(function (e) {
        var error = validate();

        if (error == 0) {
            $.post($(this).attr("action"), $(this).serializeArray(), function (r) {
                var lines = r.split("\n");
                if (lines[lines.length - 1] == 'REGISTERED') {
                    $.cookie('registered', 1, { expires:999, path:'/' });
                    _gaq.push(['_trackEvent', 'Join', 'Registration', 'Registered', 1]);
                    $('#mailing-list-form').hide();
                    $('#form-thanks').show();
                    step = 1;
                }
            });
        }
        return false;
    });

    // Print Forms
    $('#print-form').submit(function () {
        var error = validate();
        if (error == 0) {
            if (step == 1) {
                step = 2;
                $('#print-form .step1').hide();
                $('#print-form .step2').show();
                _gaq.push(['_trackEvent', 'Join', 'Registration', 'Open Step 2', 1]);

            }
            else {
                $.post($(this).attr("action"), $(this).serializeArray(), function (r) {
                    var lines = r.split("\n")
                    if (lines[lines.length - 1] == 'REGISTERED') {
                        _gaq.push(['_trackEvent', 'Join', 'Registration', 'Registered', 1]);
                    }
                    $('#print-form').hide();
                    $('#print-form .step2').hide();
                    $('#print-form .step1').show();
                    $('#form-thanks').show();
                    step = 1;
                });
            }
        }
        return false;
    });

    // Merchant registration
    $('#merchant-join-form').submit(function () {
        var error = validate();
        if (error == 0) {
            if (step == 1) {
                step = 2;
                $('#merchant-join-form .step1').hide();
                $('#merchant-join-form .step2').show();
                _gaq.push(['_trackEvent', 'Merchant', 'Registration', 'Open Step 2', 1]);

            }
            else {
                $.post($(this).attr("action"), $(this).serializeArray(), function (r) {
                    var lines = r.split("\n")
                    if (lines[lines.length - 1] == 'REGISTERED') {
                        _gaq.push(['_trackEvent', 'Merchant', 'Registration', 'Registered', 1]);
                    }
                    $('#merchant-join-form').hide();
                    $('#merchant-join-form .step1').hide();
                    $('#merchant-form-thanks').show();
                    step = 1;
                });
            }
        }
        return false;
    });

    $('#merchant-join-country').change(function () {
        if ($('select#merchant-join-country option:selected').val() == 232) {
            $('label[for=merchant-join-postal-code]').text($('#us-postal-code').text());
        } else {
            $('label[for=merchant-join-postal-code]').text($('#non-us-postal-code').text());
        }
    });

    $.post("/uk/ajax/selectcountry", function (data) {
        var sel = $("#merchant-join-country");
        var sel2 = $("#mailing-list-country");
        sel.empty();
        sel2.empty();
        $.each(data.aaData, function (key, val) {
            sel.append('<option value="' + val[0] + '">' + val[1] + '</option>');
            sel2.append('<option value="' + val[0] + '">' + val[1] + '</option>');
        });
    });

    $('#merchant-join-kind').change(function () {
        $('label[for=merchant-join-extra]').text($('#kind-' + $('select#merchant-join-kind option:selected').val()).text());
    });

    /*    $('#print-form2').submit(function () {
     var error = validate();
     if (error == 0) {
     $.post($(this).attr("action"), $(this).serializeArray(), function (r) {
     var lines = r.split("\n")
     if (lines[lines.length - 1] == 'REGISTERED') {
     pageTracker._trackEvent('Join', 'Registration', 'Registered');
     }
     $('#print-form2').hide();
     $('#form-thanks').show();
     step = 1;

     window.print();

     var barcode = $.cookie('barcode');

     if ($.cookie('registered') == null) {
     if (pageTracker._trackEvent('Barcode Print', 'Unregistered', barcode.substring(0,3))) {
     }
     }

     var nameEQ = "barcode=";
     var ca = document.cookie.split(';');
     var barcode = '';
     for (var i = 0; i < ca.length; i++) {
     var c = ca[i];
     while (c.charAt(0) == ' ') c = c.substring(1, c.length);
     if (c.indexOf(nameEQ) == 0) {
     barcode = c.substring(nameEQ.length, c.length);
     }
     }

     var log = $(form).attr("action");

     var url = log.replace("register", "log/print");

     pageTracker._trackPageview(url + '/' + barcode);
     url += '/barcode/' + barcode;
     $.get(url);
     });
     }
     return false;
     });
     */
    // close all overlays
    $('.close-overlay a').click(function () {
        $(form).hide("slow", function () {
            if (form == '#print-form' && step == 1) {
                _gaq.push(['_trackEvent', 'Join', 'Registration', 'Closed on Step 1', 1]);
            }
            else if (form == '#merchant-join-form' && step == 1) {
                _gaq.push(['_trackEvent', 'Join', 'Merchant', 'Closed on Step 1', 1]);
            }
            else if (form == '#print-form' && step == 2) {
                _gaq.push(['_trackEvent', 'Join', 'Registration', 'Closed on Step 2', 1]);
            }
            else if (form == '#mailing-list-form') {
                _gaq.push(['_trackEvent', 'Join', 'Registration', 'Closed on Step 1', 1]);
            }
            else if (form == '#mailing-list-form2') {
                _gaq.push(['_trackEvent', 'Join', 'Registration', 'Closed on Step 2', 1]);
            }
        });
        $('#register-overlay').hide();
        $('#merchant-overlay').hide();
        return false;
    });

});
