jQuery.noConflict();
var $j = jQuery;

mcafee = '<div id="footer-mcafee"><a onclick="this.target="\'_blank\'" href="https://www.mcafeesecure.com/RatingVerify?ref=bigbrownbox.com.au"><img width="94" height="54" style="border:none;" src="//images.scanalert.com/meter/bigbrownbox.com.au/23.gif" alt="McAfee Secure sites help keep you safe from identity theft, credit card fraud, spyware, spam, viruses and online scams" oncontextmenu="alert(\'Copying Prohibited by Law - McAfee Secure is a Trademark of McAfee, Inc.\'); return false;"/></a></div>';

var bbb_utils = {};

bbb_utils.width = function( tmp )
{
    return tmp.innerWidth() - (parseInt(tmp.css('padding-right')) || 0) - ( parseInt(tmp.css('padding-left')) || 0);
}

bbb_utils.height = function( tmp )
{
    return tmp.innerHeight() - (parseInt(tmp.css('padding-top')) || 0) - ( parseInt(tmp.css('padding-bottom')) || 0);
}

//function TParam()
//{
//}
//
//TParam.prototype.setTimer = function( ctrl )
//{
//    var myClass = this;
//
//    function timerRelay()
//    {
//        myClass.handleTimer( ctrl );
//    }
//
//    window.setTimeout( timerRelay, 10 );
//}
//
//TParam.prototype.handleTimer = function( el )
//{
//    if( $j( el ).val() != '' )
//    {
//        $j( el ).prev( 'label' ).addClass( 'text' );
//    }
//    else
//    {
//        $j( el ).prev( 'label' ).removeClass( 'text' );
//    }
//}

var checkObj = {};
var isProductPage = false;
var isCategoryPage = false;
var isShoppingCart = false;
var isCmsPage = false;

$j(document).ready(function() {
    var reviewToggle = $j('#review-form-status').val();
    $j('.nav-container .location-details').hide();
    $j('#review-form-toggle').click(function() {
        $j('#review-form-wrapper').toggle();
        
        if (reviewToggle == 0) {
            // add the recaptcha
            reviewRecaptcha('add');
            $j('#review-form-status').val('1');
        } else {
            reviewRecaptcha('remove');
            $j('#review-form-status').val('0');
        }
        return false;
    });

    $j('.set-location label').click(function(){
        $j(this).siblings('input.postcode').focus();
    });

    $j('#onestepcheckout-form input, #onestepcheckout-form textarea, input#coupon_code, #onestepcheckout-login-form input, #onestepcheckout-forgot-form input, .customer-account-login .form-list input, .set-location input.postcode' ).each(function() {
        var label = $j(this).siblings('label');
        var input = $j(this);

        if( input.val() != '' && input.attr( 'type' ) != "checkbox" )
        {
            label.addClass( 'text' );
        }

        // Is it a valid text input? or just a textarea?
        // Also, does it have a related label to hide?
        if ((input.attr('type') == 'text' || input.attr('tagName') == 'TEXTAREA') && label.text() != '') {
            //            label.hide();
            //            input.data('label', input.attr('title'));
            //
            //            if (input.val() == '' || input.val() == input.data('label') ) {
            //                input.val(input.data('label')).addClass('showing-label');
            //            }

            input.focus(function() {
                    $j( this ).addClass( 'active' )
                        .prev( 'label' ).addClass( 'focused' );
                }).blur(function() {
                    $j( this ).removeClass( 'active' )
                        .prev( 'label' ).removeClass( 'focused' );
                    label.show();
                }).keypress( function() {
                    checkObj = this;
                    var check = function() {
                        var el = checkObj;
                        if( $j( el ).val() != '' )
                        {
                            $j( el ).prev( 'label' ).addClass( 'text' );
                        }
                        else
                        {
                            $j( el ).prev( 'label' ).removeClass( 'text' );
                        }
                    }
                    window.setTimeout(check, 10);
                }).keydown( function() {
                    checkObj = this;
                    var check = function() {
                        var el = checkObj;
                        if( $j( el ).val() != '' )
                        {
                            $j( el ).prev( 'label' ).addClass( 'text' );
                        }
                        else
                        {
                            $j( el ).prev( 'label' ).removeClass( 'text' );
                        }
                    }
                    window.setTimeout(check, 10);
            });;
        }
    });

    $j('.customer-account-login .form-list input' ).each(function() {
        var label = $j(this).siblings('label');
        var input = $j(this);

        if( input.val() != '' && input.attr( 'type' ) != "checkbox" )
        {
            label.addClass( 'text' );
        }

        // Is it a valid text input? or just a textarea?
        // Also, does it have a related label to hide?
        if ((input.attr('type') == 'password') && label.text() != '') {
            //            label.hide();
            //            input.data('label', input.attr('title'));
            //
            //            if (input.val() == '' || input.val() == input.data('label') ) {
            //                input.val(input.data('label')).addClass('showing-label');
            //            }

            input.focus( function() {
                    $j( this ).addClass( 'active' )
                        .prev( 'label' ).addClass( 'focused' );
                }).blur( function() {
                    $j( this ).removeClass( 'active' )
                        .prev( 'label' ).removeClass( 'focused' );
                }).live( 'keypress', function() {
                    checkObj = this;
                    var check = function() {
                        var el = checkObj;
                        if( $j( el ).val() != '' )
                        {
                            $j( el ).prev( 'label' ).addClass( 'text' );
                        }
                        else
                        {
                            $j( el ).prev( 'label' ).removeClass( 'text' );
                        }
                    }
                    window.setTimeout(check, 10);
                }).keydown( function() {
                    checkObj = this;
                    var check = function() {
                        var el = checkObj;
                        if( $j( el ).val() != '' )
                        {
                            $j( el ).prev( 'label' ).addClass( 'text' );
                        }
                        else
                        {
                            $j( el ).prev( 'label' ).removeClass( 'text' );
                        }
                    }
                    window.setTimeout(check, 10);
            });
        }
    });
    $j('.postcode').autocomplete({
        source: function(request, response){
            $j('.postcode').addClass("loading-postcode");
            
            $j.ajax({
                url: '/postcode/ajax/searchLocation',
                type: 'post',
		data:
                    {
                        q: request.term
                    },
                dataType: 'json',
                success: function(data){
                    // create array to generate response objects
                    var suggestion = [];

                    $j.each(data, function (index, item){
                        suggestion.push( item.sub +', '+ item.postcode + ', '+ item.state );
                    });
                    $j('.postcode').removeClass("loading-postcode");
                   //pass array to callback
                    response(suggestion);
                }
            });
        },
        minLength:3,
        delay: 300,
        select: function (event, ui){
            var record = ui.item.label.split(", ");
            //set location
            $j.ajax({
                url : "/postcode/ajax/setLocation",
                type: "post",
                data: "postcode=" + record[1] + "&suburb=" + record[0] + "&state=" + record[2],
                dataType: "json",
                success: function(data){
                    if (data.stockid != 'error') {                        
                        if (isProductPage) {
                            if (data.candeliver) {
                                checkProductData(data.stockid,record[1],record[0]);
                                $j(".product-essential div#product-free-delivery").removeClass('product-free-delivery-question').addClass('product-free-delivery').show();
                                $j(".product-essential div.product-no-delivery, .product-essential span.product-no-delivery-text").hide();
                            } else {
                                $j('.product-main-info p#product-stock-info').removeClass('in-stock out-of-stock available').addClass('out-of-stock');
                                $j('.product-main-info p#product-stock-info').html('<span>No delivery available</span>');                                
                                $j('.product-shop .add-to-cart, .product-essential div#product-free-delivery').hide();
                                $j('.product-essential div.product-no-delivery, .product-essential span.product-no-delivery-text').show();
                            }
                        } else if (isShoppingCart) {
                            checkCartItems();
                        } else if (window.adj_nav_make_request){
                            adj_nav_make_request();
                        }else if (isCmsPage) {
                            if (data.candeliver){
                                $j("div#check-delivery-result").removeClass('product-free-delivery-question product-free-delivery no-free-delivery')
                                        .addClass('product-free-delivery').html('Free Delivery');
                                $j('span.product-no-delivery-text').hide();
                            }else{
                                $j("div#check-delivery-result").removeClass('product-free-delivery-question product-free-delivery no-free-delivery')
                                        .addClass('no-free-delivery').html('No Delivery Available');
                                $j('span.product-no-delivery-text').show();
                            }
                        }
                        // for header set-location
                        if (data.candeliver){
                            $j(".nav-container .product-free-delivery-question,.nav-container .product-free-delivery,.nav-container .no-free-delivery").removeClass('product-free-delivery-question product-free-delivery no-free-delivery')
                                        .addClass('product-free-delivery').html('Free Delivery').show();
                        }else{
                            $j(".nav-container .product-free-delivery-question,.nav-container .product-free-delivery,.nav-container .no-free-delivery").removeClass('product-free-delivery-question product-free-delivery no-free-delivery')
                                        .addClass('no-free-delivery').html('No Delivery Available').show();
                        }
                        $j(".nav-container .product-delivery-content div").append(" ("+ record[1]+")");
                    }
                }
            });
            $j(".location-details").text(record[0]+" "+record[1]+", "+ record[2]);
            $j(".show-location").show();
            $j(".set-location").hide();
        }
    });

    $j(".change-location-control").click(function(){
        if ($j(this).attr("href") == "#"){
            $j('.postcode').val('');
            $j(".show-location").hide();
            $j(".product-free-delivery,.product-free-delivery-question, .no-free-delivery").hide();
            $j(".set-location").show();
            $j(".set-location label").removeClass();
            return false;
        }
    });

    $j(".btn-proceed-checkout").click(function(){
        $j('.cart ul.messages').remove();
        $j('.cart .spinner').show();
        $j.ajax({
            url: "/postcode/ajax/checkShippingLocation",
            data:
                {
                    q: ""
                },
            type: "post",
            dataType: "json",
            success: function(data){             
                if (data.response == 'false') {
                    $j(".page-title").after("<ul class=\"messages\"><li class=\"error-msg\"><ul><li class=\"msg-content\"></li></ul></li></ul>");
                    if (data.message == 'no install') {
                        $j("li.msg-content").text("Sorry, we can\'t provide installation service for your location. Please remove it from your shopping cart.");
                    } else if (data.message == 'cannot sell') {
                        $j("li.msg-content").text("Sorry, some of your item(s) in the cart is out of stock. Please contact us for more information.");
                    } else if (data.message == 'wrong location') {
                        $j(".set-location input.postcode").css("border-color", "#ee3300");
                        $j("li.msg-content").text("Please set shipping location before checkout.");
                    } else if (data.message == 'no delivery') {
                        $j("li.msg-content").text("Sorry, we cannot deliver to your chosen location. Please contact us for more information.");
                    }
                    
                    $j('.cart .spinner').hide();
                    return false;
                } else if (data.response == 'true') {
                    //proceed to checkout
                    window.location = lnk;
                }
            }
        });
    });
});


function checkProductData(stockid,postcode,suburb) {
    $j.ajax({
        url: "/extension/ajax/checkProductData",
        type: "post",
        data: "pid=" + productId + "&stockid=" + stockid + "&postcode=" + postcode + "&suburb=" + suburb,
        dataType: "json",
        success : function(data){
            // process the stock info first
            if (data.status == 'instock') {                
                $j('.product-main-info p#product-stock-info').removeClass('in-stock out-of-stock available').addClass('in-stock');
                $j('.product-main-info p#product-stock-info').html('<span>In Stock</span>');
                $j('.product-shop .add-to-cart').show();
            } else if (data.status == 'backordered') {
                if (data.backorder_override == 'yes') {
                    $j('.product-main-info p#product-stock-info').removeClass('in-stock out-of-stock available').addClass('out-of-stock');
                    $j('.product-main-info p#product-stock-info').html('<span>Backordered</span>');
                } else {
                    $j('.product-main-info p#product-stock-info').removeClass('in-stock out-of-stock available').addClass('available');
                    $j('.product-main-info p#product-stock-info').html('<span>Available</span>');
                }
                
                $j('.product-shop .add-to-cart').show();
            } else {
                $j('.product-main-info p#product-stock-info').removeClass('in-stock out-of-stock available').addClass('out-of-stock');
                $j('.product-main-info p#product-stock-info').html('<span>Out of Stock</span>');
                $j('.product-shop .add-to-cart').hide();
            }
            
            // process the install data
            var selectInstall = $j("#select_install_"+productId);
            if (data.allowinstall == 'yes') {
                $j('.product-installs').show();
            } else {
                $j('.product-installs').hide();
                selectInstall.attr("selectedIndex", 0);
            }
        }
    });
}

function checkCartItems()
{
    $j.ajax({
        url: "/extension/ajax/checkCartItemsStock",
        type: "get",
        success : function(data){
            $j('.cart ul.messages').remove();
            $j(".item-stock").html("");
            var allInStock = true;
            
            $j.each(data,function(index,pid){
                $j("#stock-info-"+pid).html("* This product is currently out of stock.");
                allInStock = false;
            });
            
            if (!allInStock) {
                $j(".page-title").after("<ul class=\"messages\"><li class=\"error-msg\"><ul><li class=\"msg-content\"></li></ul></li></ul>");
                $j("li.msg-content").text("Sorry, some of your item(s) in the cart is out of stock. Please contact us for more information.");
                $j("ul.checkout-types").hide();
            } else {
                $j("ul.checkout-types").show();
            }
        }
    });
}

function getDivString( id, msg )
{
    if( !msg )
    {
        msg = "This is a required field.";
    }

    return '<div id="' + id + '-msg" class="validation-advice">' + msg + '</div>';
}

function CleanInputs( selector )
{
    $j( selector ).each(function() {
        var label = $j(this).prev();
        var input = $j(this);

        if( input.val() != '' && input.attr( 'type' ) != "checkbox" )
        {
            label.addClass( 'text' );
        }
        else
        {
            label.removeClass( 'text' );
        }
    });
}

function showShipping()
{
    $j('.onestepcheckout-step-title-1').removeClass('inactive');
    $j('.onestepcheckout-numbers-1').removeClass('inactive');
    $j('.onestepcheckout-step-title-1 .onestepcheckout-edit-link-container').hide();
    
    if( $j.browser.msie && jQuery.browser.version.substr(0,3)=="6.0" )
    {
        $j( '.onestepcheckout-shipping' ).show();
    }
    else
    {
        $j('.onestepcheckout-shipping-inactive').hide();
        $j('.onestepcheckout-shipping-left').show();
        $j('.onestepcheckout-shipping-right').show();
        $j('.onestepcheckout-step-title').removeClass('inactive');
    }
    
    CleanInputs( '.onestepcheckout-shipping input' );
}

function hideShipping()
{
    $j('.onestepcheckout-step-title-1').addClass('inactive');
    $j('.onestepcheckout-numbers-1').addClass('inactive');
    $j('.onestepcheckout-step-title-1 .onestepcheckout-edit-link-container').show();

    if( $j.browser.msie && jQuery.browser.version.substr(0,3)=="6.0" )
    {
        $j( '.onestepcheckout-shipping' ).hide();
    }
    else
    {
        $j('.onestepcheckout-shipping-left').hide();
        $j('.onestepcheckout-shipping-right').hide();

        var customerShippingName = "<strong>" + $j('input#shipping\\:firstname').val() + " " + $j('input#shipping\\:lastname').val() + "</strong>";
        var shippingAddress = "";
        var companyName = $j.trim($j('input#shipping\\:company').val());
        if (companyName != "Company (optional)" && companyName.length > 0){
            shippingAddress += companyName + "<br />";
        }
        shippingAddress += $j('input#shipping\\:street1').val() + "<br />";

        var address2 = $j.trim($j('input#shipping\\:street2').val());
        if (address2 != "Additional Address Info (optional)" && address2.length > 0){
            shippingAddress += address2 + "<br />";
        }
        shippingAddress += $j('input#shipping\\:city').val() + "<br />";
        shippingAddress += $j('.input-region .location-prefilled-info').text() + " " + $j('input#shipping\\:postcode').val() + "<br />";
        shippingAddress += "T: " + $j('input#shipping\\:telephone').val();

        $j('.onestepcheckout-shipping-inactive .shipping-customername-inactive').html(customerShippingName);
        $j('.onestepcheckout-shipping-inactive .shipping-customeraddress-inactive').html(shippingAddress);

        $j('.onestepcheckout-shipping-inactive .shipping-customeremail-inactive').html($j('input#billing\\:email').val());
        $j('.onestepcheckout-shipping-inactive .shipping-deliverydate-inactive').html($j('input#shipping\\:delivery_date').val());

        if ($j("#id_comments").length > 0) {
            var instructBox = $j('textarea#id_comments').val().replace(/\n\r?/g, '<br />');
            $j('.onestepcheckout-shipping-inactive .shipping-instructions-inactive').html(instructBox);
        }
        
        $j('.onestepcheckout-shipping-inactive').show();
    }
}
function showPayment()
{
    $j('.onestepcheckout-step-title-2').removeClass('inactive');
    $j('.onestepcheckout-numbers-2').removeClass('inactive');
    $j('.onestepcheckout-step-title-2 .onestepcheckout-edit-link-container').hide();

    if( $j.browser.msie && jQuery.browser.version.substr(0,3)=="6.0" )
    {
        $j( '.onestepcheckout-payment' ).show();
    }
    else
    {
        $j('.onestepcheckout-payment-inactive').hide();
        $j('.onestepcheckout-payment-left').show();
        $j('.onestepcheckout-payment-right').show();
        $j('#creditcard-payment-summary').hide();
    }

    CleanInputs( '.onestepcheckout-payment input' );
}

function hidePayment()
{
    $j('.onestepcheckout-step-title-2').addClass('inactive');
    $j('.onestepcheckout-numbers-2').addClass('inactive');
    $j('.onestepcheckout-step-title-2 .onestepcheckout-edit-link-container').show();

    if( $j.browser.msie && jQuery.browser.version.substr(0,3)=="6.0" )
    {
        $j( '.onestepcheckout-payment' ).hide();
    }
    else
    {
        $j('.onestepcheckout-payment-left').hide();
	$j('.onestepcheckout-payment-right').hide();
                
        var customerBillingName = "<strong>" + $j.trim($j('input#billing\\:firstname').val()) + " " + $j.trim($j('input#billing\\:lastname').val()) + "</strong>";
        var billingAddress = "";
        var companyName = $j.trim($j('input#billing\\:company').val());
        if (companyName != "Company (optional)" && companyName.length > 0){
            billingAddress += companyName + "<br />";
        }
        billingAddress += $j('input#billing\\:street1').val() + "<br />";

        var address2 = $j.trim($j('input#billing\\:street2').val());
        if (address2 != "Additional Address Info (optional)" && address2.length > 0){
            billingAddress += address2 + "<br />";
        }
        billingAddress += $j('input#billing\\:city').val() + "<br />";
        billingAddress += $j('select#billing\\:region_id option:selected').text() + " " + $j('input#billing\\:postcode').val() + "<br />";
        billingAddress += "T: " + $j('input#billing\\:telephone').val();
        
        $j('.onestepcheckout-payment-inactive .payment-customername-inactive').html(customerBillingName);
        $j('.onestepcheckout-payment-inactive .payment-customeraddress-inactive').html(billingAddress);
        
        $j('.onestepcheckout-payment-inactive').show();
    }
}

var invalidPostCode;
var invalidShippingPostCode;
var validPostCode;
var ccdata;

$j(document).ready(function()
{
    // only work if it's the checkout page.
    if( !$j('body').hasClass( "onestepcheckout-index-index" )) {return;}
    var shipping_set = false;
    var payment_set = false;
    var register_set = false;
    var placeable = false;
    var postcode = true;
    var block = false;

    // check for postback errors
    if( $j( '.onestepcheckout-payment .onestepcheckout-error' ).size() > 0 )
    {
        hideShipping();
        shipping_set = true;
        showPayment();
        $j('.onestepcheckout-payment').show();
    }

    $j( window ).scroll( function()
    {
        var el = $j( '.col-right.sidebar .block' )
        var offset = el.offset();

        // too low?
        var elheight = el.height();
        var docheight = $j( document ).height() - 415;
        if( (offset.top + elheight) > (docheight) )
        {
            el.css( "top", parseInt( el.css( 'top' )) - (offset.top + elheight - docheight) );
        }

        // too high?
        if( offset.top < 276 )
        {
            el.css( 'top', parseInt( el.css( 'top' )) + 276 - offset.top );
        }

    });

    $j( '#onestepcheckout-form' ).submit( function( event )
    {
        if( !placeable || !postcode )
        {
            event.preventDefault();
            return false;
        }
    });

    $j( '#onestepcheckout-forgot-form' ).submit( function( evt ) {
        evt.preventDefault();
        $j( '#onestepcheckout-forgot-button' ).click();
    });

    $j( '#onestepcheckout-login-form' ).submit( function( evt ) {
        evt.preventDefault();
        $j( '#onestepcheckout-login-button' ).click();
    });

    $j( '#id_onestepcheckout_password' ).live( 'focus', function() {
            $j( this ).addClass( 'active' )
                .prev().addClass( 'focused' );
        }).live( 'blur', function() {
            $j( this ).removeClass( 'active' )
                .prev().removeClass( 'focused' );
        }).live( 'keypress', function() {
            var el = this;
            var check = function() {
                if( $j( el ).val() != '' )
                {
                    $j( el ).prev( 'label' ).addClass( 'text' );
                }
                else
                {
                    $j( el ).prev( 'label' ).removeClass( 'text' );
                }
            }
            window.setTimeout(check, 10);
        });

    $j( '#verisign_cc_owner, #verisign_cc_number, #verisign_cc_cid' ).live( 'focus', function() {
            $j( this ).addClass( 'active' )
                .prev().addClass( 'focused' );
        }).live( 'blur', function() {
            $j( this ).removeClass( 'active' )
                .prev().removeClass( 'focused' );
        }).live( 'keypress', function() {
            var el = this;
            var check = function() {
                if( $j( el ).val() != '' )
                {
                    $j( el ).prev( 'label' ).addClass( 'text' );
                }
                else
                {
                    $j( el ).prev( 'label' ).removeClass( 'text' );
                }
            }
            window.setTimeout(check, 10);
        });

    $j( '#onestepcheckout-form select' ).each( function()
    {
    	$j(this)
	    	.focus( function()
	    	{
	    		$j( this ).addClass( 'active' );
	    	})

	    	.blur( function()
	    	{
	    		$j( this ).removeClass( 'active' );
	    	});
    });

    // clicking the edit shipping button
    $j('#onestepcheckout-edit-shipping').click(function() {
        placeable = false;
        showShipping();
        if(payment_set==false) {
            $j('.onestepcheckout-payment').hide();
        }
        $j('.onestepcheckout-step-title-2').addClass('inactive');
        $j('.onestepcheckout-numbers-2').addClass('inactive');
        return false;
    });

    // clicking the continue button in shipping section
    $j('#onestepcheckout-continue-shipping').click(function() {
        var missing_entries = 0;

        // clear errors
        $j( '.onestepcheckout-shipping .validation-advice' ).remove();
        $j( '.onestepcheckout-shipping .validation-failed' ).removeClass( 'validation-failed' );

        // first name
        var el = $j( '#shipping\\:firstname' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'shipping-firstname' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // last name
        el = $j( '#shipping\\:lastname' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'shipping-lastname' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // telephone
        el = $j( '#shipping\\:telephone' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'shipping-telephone' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // email address
        el = $j( '#billing\\:email' );
        if( el.size() > 0 )
        {
            if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
            {
                $j( getDivString( 'billing-email' )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++;
            }
            else 
            {
                // must check if email address is valid using Zend
                $j.ajax({
                    url: "/extension/ajax/validateEmail",
                    async: false,
                    type: "post",
                    data: "email=" + el.val(),
                    dataType: "json",
                    success : function(data){
                        if (data.result == "invalid") {
                            $j( getDivString( 'billing-email', 'The email address must be valid.' )).insertAfter( el );
                            el.addClass( 'validation-failed' );
                            missing_entries++;
                        }
                    }
                });
            }
        }

        // Street Address
        el = $j( '#shipping\\:street1' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0)
        {
            $j( getDivString( 'shipping-street1', 'Shipping Address must be valid.' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }else if (el.val().match( 'p\.* *o\.* *box', 'gi' ) || el.val().match('locked *bag' , 'gi')){
            $j( getDivString( 'shipping-street1' , 'Sorry, delivery to PO Box or Locked Bag are not allowed.')).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // City
        el = $j( '#shipping\\:city' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'shipping-city' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // State
        el = $j( '#shipping\\:region_id' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'shipping-region_id' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // Post Code
        el = $j( '#shipping\\:postcode' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( '#shipping-postcode' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }
        else if( !el.val().match( '^\\d*$' ) || el.val().length != 4 )
        {
            $j( getDivString( '#shipping-postcode', 'The post code must be a four digit number.' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // Delivery Date
        el = $j( '#shipping\\:delivery_date' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'shipping:delivery_date' )).insertAfter( '#shipping_delivery_date_reset' );
            el.addClass( 'validation-failed' );
            $j( '#shipping\\:delivery_date-msg').css('margin','0px 0px 0px 5px');
            missing_entries++;
        }

        if( missing_entries == 0 )
        {
            block = true;
            var save = get_save_billing_function( urls.url_save_billing, urls.url_set_methods, urls.update_payments );
            save();
        }

        return false;
    });

    invalidPostCode = function( noship, postcode )
    {
        block = false;
        placeable = false;

        if( postcode == false )
        {
            el = $j( '#shipping\\:postcode' );
            $j( getDivString( '#shipping-postcode', "This post code is invalid." )).insertAfter( el );
            el.addClass( 'validation-failed' );
            $j( '#onestepcheckout-ajax-overlay' ).remove();
        }

        else
        {
            var html = '<div id="checkout-msg-box"><p class="top">The following products can not be shipped to your postcode. (' + $j( '#shipping\\:postcode' ).val() + ')</p><ul>';

            for( var i = 0; i < noship.length; i++ )
            {
                html += "<li>" + noship[i] + "</li>";
            }

            html += '</ul><p class="bottom">Please contact Customer Support for assistance.</p><button id="checkout-msg-box-close">Close</button></div>';

            $j( '#onestepcheckout-ajax-overlay' ).html( html ).addClass( 'msg' );

            $j( '#checkout-msg-box-close' ).click( function() {
                $j( '#onestepcheckout-ajax-overlay' ).remove()
            });
        }
    }

    validPostCode = function()
    {
        block = false;
        shipping_set = true;

        // if same as billing is set
        if( $j( '#onestepcheckout-shipping-for-billing' ).attr( 'checked' ))
        {
            copyBillingData();
        }

        $j( '#verisign_cc_owner' ).val( ccdata.ccowner );
        $j( '#verisign_cc_type' ).val( ccdata.cctype );
        $j( '#verisign_cc_number' ).val( ccdata.ccnumber );
        $j( '#verisign_cc_cid' ).val( ccdata.cccid );
        $j( '#verisign_expiration' ).val( ccdata.ccexpiration );
        $j( '#verisign_expiration_yr' ).val( ccdata.ccexpirationyr );

        // JS for the CVV popup
        if($('payment-tool-tip-close')){
            Event.observe($('payment-tool-tip-close'), 'click', toggleToolTip);
        }

        $$('.cvv-what-is-this').each(function(element){
            Event.observe(element, 'click', toggleToolTip);
        });

        // IE treats the kb events differently to the way that everyone else does,
        // so we need to have different handlers for it.
        /*if( $j.browser.msie )
        {
            $j( '#verisign_cc_number, #verisign_cc_cid' ).keypress( function( evt )
            {
                // special characters, hyphen, space and the numbers are allowed.  Stop on all others
                if( !( evt.keyCode == 0 || evt.keyCode == 32 || evt.keyCode == 45 || ( evt.keyCode > 47 && evt.keyCode < 58 )))
                {
                    evt.stopImmediatePropagation();
                    evt.stopPropagation();
                    evt.preventDefault();
                    return false;
                }

            });

            $j( '#verisign_cc_cid' ).keypress( function( evt )
            {
                // special characters, hyphen, space and the numbers are allowed.  Stop on all others
                if( !( evt.keyCode == 0 || ( evt.keyCode > 47 && evt.keyCode < 58 )))
                {
                    evt.stopImmediatePropagation();
                    evt.stopPropagation();
                    evt.preventDefault();
                    return false;
                }

            });
        }

        // handlers for the rest of the browsers
        else
        {
            $j( '#verisign_cc_number, #verisign_cc_cid' ).keypress( function( evt )
            {
                // special characters, hyphen, space and the numbers are allowed.  Stop on all others
                if( !( evt.charCode == 0 || evt.charCode == 32 || evt.charCode == 45 || ( evt.charCode > 47 && evt.charCode < 58 )))
                {
                    evt.stopImmediatePropagation();
                    evt.stopPropagation();
                    evt.preventDefault();
                    return false;
                }

            });

            $j( '#verisign_cc_cid' ).keypress( function( evt )
            {
                // special characters, hyphen, space and the numbers are allowed.  Stop on all others
                if( !( evt.charCode == 0 || ( evt.charCode > 47 && evt.charCode < 58 )))
                {
                    evt.stopImmediatePropagation();
                    evt.stopPropagation();
                    evt.preventDefault();
                    return false;
                }

            });
        }*/

//        $j('#container_payment_method_verisign input, #container_payment_method_verisign textarea').each(function() {
//            var label = $j(this).siblings('label');
//            var input = $j(this);
//
//            // Is it a valid text input? or just a textarea?
//            // Also, does it have a related label to hide?
//            if ((input.attr('type') == 'text' || input.attr('tagName') == 'TEXTAREA') && label.text() != '') {
//                label.hide();
//                input.data('label', input.attr('title'));
//
//                if (input.val() == '' || input.val() == input.data('label') ) {
//                    input.val(input.data('label')).addClass('showing-label');
//                }
//
//                input.focus(function() {
//                    $j( this ).addClass( 'active' );
//                    if($j(this).data('label') == $j(this).val()) {
//                        $j( this ).addClass( 'original' );
//                    }
//                }).blur(function() {
//                    if ($j(this).val() == '' || $j(this).val() == $j(this).data('label')) {
//                        $j(this).val($j(this).data('label')).addClass('showing-label');
//                    }
//                    else
//                    {
//                        $j(this).removeClass('showing-label');
//                    }
//                    $j( this ).removeClass( 'active' ).removeClass( 'original' );
//                }).keypress( function( evt ) {
//                    if ($j(this).val() == $j(this).data('label')) {
//                        $j(this).val('').removeClass('showing-label');
//                        $j(this).removeClass( 'original' );
//                    }
//                });
//            }
//        });

        /*$j( '#verisign_cc_number' ).keypress( function( evt )
        {
            var val = $j( this ).val();

            if( evt.charCode > 47 && evt.charCode < 58 )
            {
                val = val + (evt.charCode - 48);
            }

            if( val.match( "^4.*" ))
            {
                $j( '#verisign_cc_type' ).val( "VI" ).change();
            }
            else if( val.match( "^3[47].*" ))
            {
                $j( '#verisign_cc_type' ).val( "AE" ).change();
            }
            else if( val.match( "^5[1-5].*" ))
            {
                $j( '#verisign_cc_type' ).val( "MC" ).change();
            }
            else
            {
                $j( '#verisign_cc_type' ).val( "" ).change();
            }
        });*/

        //        $j( '#container_payment_method_verisign select' ).each( function()
        //        {
        //            $j(this)
        //            .focus( function()
        //            {
        //                $j( this ).addClass( 'active' );
        //            })
        //
        //            .blur( function()
        //            {
        //                $j( this ).removeClass( 'active' );
        //            });
        //        });

        hideShipping();

        $j( '#s_method_batchserial_batchserial' ).attr( 'checked', 'checked' );

        if(payment_set==false)
        {
            placeable = false;
            $j('.onestepcheckout-step-title-2').removeClass('inactive');
            $j('.onestepcheckout-numbers-2').removeClass('inactive');
            $j('.onestepcheckout-payment').show();
        }
        else
        {
            placeable = true;
            $j('.onestepcheckout-place-order').show();
        }

        CleanInputs( '.onestepcheckout-payment input' );
        $j( '#onestepcheckout-ajax-overlay' ).remove();
    }

    $j( '#onestepcheckout-shipping-for-billing, #onestepcheckout-shipping-for-billing-label').click( function()
    {
        $j( '#onestepcheckout-shipping-for-billing-billing' ).attr( 'checked', $j( this ).is(':checked'));
        if( $j( this ).is(':checked') )
        {
            copyBillingData();
        }
        else
        {
            emptyBillingData();
        }
        CleanInputs( '.onestepcheckout-payment input' );
    });

    $j( '#onestepcheckout-shipping-for-billing-billing, #onestepcheckout-shipping-for-billing-billing-label').click( function()
    {
        $j( '#onestepcheckout-shipping-for-billing' ).attr( 'checked', $j( this ).is(':checked'));
        if( $j( this ).is(':checked') )
        {
            copyBillingData();
        }
        else
        {
            emptyBillingData();
        }
        CleanInputs( '.onestepcheckout-payment input' );
    });

    function copyBillingData()
    {
        $j( '#billing\\:firstname' ).val( $j( '#shipping\\:firstname' ).val() );
        $j( '#billing\\:lastname' ).val( $j( '#shipping\\:lastname' ).val() );
        $j( '#billing\\:telephone' ).val( $j( '#shipping\\:telephone' ).val() );
        $j( '#billing\\:company' ).val( $j( '#shipping\\:company' ).val() );
        $j( '#billing\\:street1' ).val( $j( '#shipping\\:street1' ).val() );
        $j( '#billing\\:street2' ).val( $j( '#shipping\\:street2' ).val() );
        $j( '#billing\\:city' ).val( $j( '#shipping\\:city' ).val() );
        $j( '#billing\\:region_id' ).val( $j( '#shipping\\:region_id' ).val() );
        $j( '#billing\\:postcode' ).val( $j( '#shipping\\:postcode' ).val() );
    }

    function emptyBillingData()
    {
        $j( '#billing\\:firstname' ).val( '' );
        $j( '#billing\\:lastname' ).val( '' );
        $j( '#billing\\:telephone' ).val( '' );
        $j( '#billing\\:company' ).val( '' );
        $j( '#billing\\:street1' ).val( '' );
        $j( '#billing\\:street2' ).val( '' );
        $j( '#billing\\:city' ).val( '' );
        $j( '#billing\\:region_id' ).val( '' );
        $j( '#billing\\:postcode' ).val( '' );
    }

    // clicking the edit payment button
    $j('#onestepcheckout-edit-payment').click(function()
    {
        if( block ) {
            return false;
        }
        showPayment();
        placeable = false;

        return false;
    });

    // clicking the continue button in payment section
    $j('#onestepcheckout-continue-payment').click(function() {
        var missing_entries = 0;

        /* Billing Validation */
        // clear errors
        $j( '.onestepcheckout-payment .validation-advice' ).remove();
        $j( '.onestepcheckout-payment .validation-failed' ).removeClass( 'validation-failed' );

        // first name
        var el = $j( '#billing\\:firstname' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'billing-firstname' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;            
        }

        // last name
        el = $j( '#billing\\:lastname' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'billing-lastname' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // telephone
        el = $j( '#billing\\:telephone' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'billing-telephone' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // Street Address
        el = $j( '#billing\\:street1' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'billing-street1' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // City
        el = $j( '#billing\\:city' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'billing\\:city' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // State
        el = $j( '#billing\\:region_id' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( 'billing-region_id' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // Post Code
        el = $j( '#billing\\:postcode' );
        if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
        {
            $j( getDivString( '#billing-postcode' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }
        else if( !el.val().match( '^\\d*$' ) || el.val().length != 4 )
        {
            $j( getDivString( '#billing-postcode', 'The post code must be a four digit number.' )).insertAfter( el );
            el.addClass( 'validation-failed' );
            missing_entries++;
        }

        // if using credit card payment method
        if( $j( '#checkout-payment-method-load input:checked' ).val() == 'verisign' )
        {
            // credit card owner name
            el = $j( '#verisign_cc_owner' );
            if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
            {
                $j( getDivString( 'verisign_cc_owner' )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++;
            }
            
            // credit card type
            el = $j( '#verisign_cc_type' );
            if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
            {
                el = $j( '#verisign_cc_number' );
                $j( getDivString( 'verisign_cc_number', "The card number is invalid." )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++;
            }
            else
            {
                var info = Validation.creditCartTypes.get( $j( '#verisign_cc_type' ).val() );
            }

            // credit card number
            el = $j( '#verisign_cc_number' );
            if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
            {
                $j( getDivString( 'verisign_cc_number' )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++;
            }
            else if( info )
            {
                var cardnum = removeDelimiters( el.val() );
                if( info[2] && !validateCreditCard( cardnum ))
                {
                    $j( getDivString( 'verisign_cc_number', "The card number is invalid." )).insertAfter( el );
                    el.addClass( 'validation-failed' );
                    missing_entries++;
                }
                else if( !cardnum.match( info[0] ))
                {
                    $j( getDivString( 'verisign_cc_number', "The card number is invalid." )).insertAfter( el );
                    el.addClass( 'validation-failed' );
                    missing_entries++;
                }
            }

            // credit card CVC
            el = $j( '#verisign_cc_cid' );
            if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
            {
                $j( getDivString( 'verisign_cc_cid' )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++;
            }

            else if( info && !el.val().match( info[1] ))
            {
                $j( getDivString( 'verisign_cc_cid', "The CVC does not match the card type." )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++
            }

            var monthset = true;
            var yearset = true;

            // credit card expiration year
            el = $j( '#verisign_expiration_yr' );
            var year = el.val();
            if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
            {
                $j( getDivString( 'verisign_expiration_yr' )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++;
                yearset = false;
            }

            // credit card expiration month
            el = $j( '#verisign_expiration' );
            var month = el.val();
            if( el.val() == el.attr( 'title' ) || el.val().length == 0 )
            {
                $j( getDivString( 'verisign_expiration' )).insertAfter( el );
                el.addClass( 'validation-failed' );
                missing_entries++;
                monthset = false;
            }

            // expiration date is valid
            if( monthset && yearset )
            {
                var currentTime  = new Date();
                var currentMonth = currentTime.getMonth() + 1;
                var currentYear  = currentTime.getFullYear();
                if (month < currentMonth && year == currentYear)
                {
                    $j( getDivString( 'verisign_expiration_both', 'The expiration date is invalid.' )).insertAfter( el );
                    el.addClass( 'validation-failed' );
                    $j( '#verisign_expiration_yr' ).addClass( 'validation-failed' );
                    missing_entries++;
                }
            }
        }

        // have selected a payment method
        if( $j( 'input:radio[name=payment\\[method\\]]:checked' ).size() < 1 )
        {
            el = $j( '.payment-methods' );
            $j( getDivString( 'verisign_cc_number', "Please choose a payment method." )).insertAfter( el );
            missing_entries++;
        }

        if( missing_entries == 0 )
        {
            payment_set = true;

            hidePayment();

            $j('.onestepcheckout-step-title-3').removeClass('inactive');
            $j('.onestepcheckout-numbers-3').removeClass('inactive');
            $j('.onestepcheckout-register').show();
            $j('.onestepcheckout-place-order').show();

            var paymentDetails = "<p><strong>Payment Method</strong></p>";
            
            if($j('#p_method_verisign').is(':checked')) {
                var img = "";
                var card_type = $j("#verisign_cc_type option:selected").text();
                switch(card_type)
                {
                    case 'American Express':
                        img = ccImages.amex;
                        break;
                    case 'Master Card':
                        img = ccImages.mc;
                        break;
                    case 'Visa':
                        img = ccImages.visa;
                        break;
                    default:
                        img = '';
                }
                var cardNumFormat = $j('#verisign_cc_number').val().replace(/\s/g, '').replace(/\-/g, '');
                paymentDetails += "Credit Card<br />" + img + "<br />" + $j('#verisign_cc_owner').val() + "<br />xxxx-xxxx-xxxx-" + cardNumFormat.substring(12,16) + "<br />Expires: " + $j('#verisign_expiration option:selected').text().substring(0,2) + ' / ' + $j('#verisign_expiration_yr option:selected').text();
                $j('.payment-inactive-element-right').html(paymentDetails);                
            }
            else if ($j('#p_method_paypal_standard').is(':checked'))
            {
                paymentDetails += paypalImage;
                $j('.payment-inactive-element-right').html(paymentDetails);
            }
            else
            {
                paymentDetails += "Cash on Delivery";
                $j('.payment-inactive-element-right').html(paymentDetails);
            }
            placeable = true;
        }
        return false;
    });
});

// make sure that when placing order, if any input errors are caught, that the relevant section is opened for editing
function IsNumeric(input)
{
    return (input - 0) == input && input.length > 0;
}


