$(document).ready(function () {

    $('#search .advanced-link').click(function () {
        var $box = $('#advanced-box');
        if ($box.is(':visible')) $(this).animate({ height: 30 }, 100, function () { $(this).removeClass('expanded') });
        else $(this).addClass('expanded').animate({ height: 46 }, 200);
        $box.toggle(300);
        return false;
    });

    $('#our-service').click(function () {
        $('#overlay').css({ width: $(window).width(), height: $(document).height() }).animate({ opacity: 0.85 }, 300, function () { $('#service').slideDown(150) });
        return false;
    });

    $('.openModal').live('click', function () {
        if ($('#overlay').is('animated')) return false;
        var $modal = $(this).closest('tr').find('.modal').clone();
        $('#overlay').css({ width: $(window).width(), height: $(document).height() }).animate({ opacity: 0.85 }, 300, function () { $('body').append($modal); $modal.slideDown(150) });
        return false;
    });

    $('#overlay, .closeModal').live('click', function () {
        var $modal = $('.modal:visible');
        $modal.slideUp(150, function () { $('#overlay').animate({ opacity: 0 }, 300, function () { $(this).css({ width: 0, height: 0 }) }); });
        return true;
    });

    $('.productBuyNow').click(function () {
        $('.product').slideUp(100, function () { $('#buyNow').slideDown(150) });
        return true;
    });

    $('.tooltip').simpletooltip();

    $('#tbSearch').keyup(function () {
        if (checkPostCode($(this).val())) {
            $(this).addClass('valid');
        } else {
            $(this).removeClass('valid');
        }
    });

    $('#tbSearch').keypress(function (event) {
        if (enterPressed(event)) {
            $('#btnHomePageSearch').click();
        }
    });

    $('#btnHomePageSearch, #btnUpdate').click(function () {
        var valid = checkPostCode($('#tbSearch').val());
        if (checkPostCode($('#tbSearch').val())) {
            $('#tbSearch').val(valid);
            if ($('#tbSearch').val().toLowerCase().substr(0, 2) == 'hu') {
                $('body').prepend('<div id="hull" class="modal"><a href="#" class="closeModal">x</a><p>We currently cannot conduct comparisons for customers in the Hull area. For information about products and services in your area, please visit the Kingston Communications website at <a href="http://www.k-c.co.uk/home/" target="_blank">http://www.k-c.co.uk/home/</a>.</p></div>');
                $('#overlay').css({ width: $(document).width(), height: $(document).height() }).fadeIn(300, function () { $('#hull').slideDown(150) });
                return false;
            }
            $('#loader').show(0, function () { $('#tbSearch').css('background-position', 'left top'); $('img', this).attr('src', '/common/images/loader.gif'); });
            if ($('#searchbox input:checkbox:checked').length == 0) {
                $('#broadband, #homephone').prop('checked', true).change();
            }
        } else {
            return false;
        }
    });

    $('.col input').change(function () {
        var _this = $(this).closest('.col');
        if (_this.find('input:checked').length > 0) {
            $('#' + _this.attr('title')).prop('checked', true).change();
        }
    });

    $(".tb-results th a").live('click', function () {
        var col = $(this).parent().prevAll("th").length + 1;
        var table = $(this).closest('table');
        if (table.find(':animated').length > 0) return false;
        var desc = true;
        if (!$(this).data('desc')) {
            desc = false;
        }
        table.sortTable({ onCol: col, sortType: 'numeric', keepRelationships: true, sortDesc: desc, child: 'input' });
        var cssClass = (desc) ? '' : 'asc';
        $(this).attr('class', cssClass).data('desc', !desc);

        if (!$(this).parent().hasClass('sorted')) {
            $('th, td', table).removeClass('sorted');
            $('>thead>tr', table).find('>th:eq(' + (col - 1) + ')').addClass('sorted');
        }
        return false;
    });

    //Tabs
    $('#middle').tabs();

    var autoscrolling = true;
    $('#providersSlider').imageSlider().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = true;
    });

    setInterval(function () {
        if (autoscrolling) {
            $('#providersSlider').trigger('next');
        }
    }, 5000);
});

function clearText(field) {
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}

function enterPressed(e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return false;
    return (keycode == 13);
}

function checkPostCode(toCheck) {
    var alpha1 = "[abcdefghijklmnoprstuwyz]";
    var alpha2 = "[abcdefghklmnopqrstuvwxy]";
    var alpha3 = "[abcdefghjkpmnrstuvwxy]";
    var alpha4 = "[abehmnprvwxy]";
    var alpha5 = "[abdefghjlnpqrstuwxyz]";
    var pcexp = new Array();
    pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
    pcexp.push(new RegExp("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
    pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
    pcexp.push(/^(GIR)(\s*)(0AA)$/i);
    pcexp.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);
    pcexp.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
    pcexp.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);
    var postCode = toCheck;
    var valid = false;
    for (var i = 0; i < pcexp.length; i++) {
        if (pcexp[i].test(postCode)) {
            pcexp[i].exec(postCode);
            postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
            postCode = postCode.replace(/C\/O\s*/, "c/o ");
            valid = true;
            break;
        }
    }
    if (valid) { return postCode; } else return false;
}

// Buy Now Modal
function ShowBuyNowModal() {
    $('#overlay').css({ width: $(window).width(), height: $(document).height() }).animate({ opacity: 0.85 }, 300, function () { $('#buyNow').slideDown(150) });
    return false;
}

function HideProductShowBuyNow() {
    $('.product').slideUp(100, function () { $('#buyNow').slideDown(150) });
}
