$(document).ready(function(){
isIE6 = /msie|MSIE 6/.test(navigator.userAgent);

	if(isIE6)
	{
		
	$(".move_kids_membership_button").css('left','260px');	
	}

    $("#r_country").removeAttr("disabled");
    $("#r_address_1").removeAttr("disabled");
    $("#r_address_2").removeAttr("disabled");
    $("#r_address_3").removeAttr("disabled");
    $("#r_city_town").removeAttr("disabled");
    $("#r_county_state").removeAttr("disabled");
    $("#r_postcode_zip").removeAttr("disabled");
	 $("#postcodejsenabled").show();
    /* Gift wrap */
    $('input.gift_wrap').click(function(){
        update_gift_wrap(this);
    });
    
    $('textarea.message').data('max_length', 250);
    $('textarea.message').prev("label").find("span.char_count").html($('textarea.message').data('max_length'));
    
    // textarea character count
    $("textarea.message").keypress(function(event){
    
        // get current count
        charCount = $(this).val().length;
        charCount += 1;
        
        if (charCount >= $(this).data('max_length')) {
            if (event.keyCode != 46 && event.keyCode != 8) {
                event.preventDefault();
            }
            else 
                if (event.keyCode >= 37 && event.keyCode <= 40) {
                    event.preventDefault();
                }
        }
        else {
            remaining = $(this).data('max_length') - (charCount);
            
            if (!remaining) {
                remaining = '0';
            }
            $(this).prev("label").find("span.char_count").html(remaining);
        }
    });
    
    /* Participant form */
    // hide participant fields
    $("#participant_form div.row div.options input#not_gift").each(function(){
    
        if ($(this).attr("checked")) {
            container = $(this).parent().parent();
            
            container.nextAll("div.row").css({
                display: "none"
            });
            container.nextAll("div.title").css({
                display: "none"
            });
            container.nextAll("div.mobile").css({
                display: "block"
            });
            container.find(".instruction span.you").html("you")
            container.find(".instruction span.your").html("your")
        }
    });
    $("#participant_form div.row div.options input#not_gift").click(function(){
    
        if ($(this).attr("checked")) {
            container = $(this).parent().parent();
            container.nextAll("div.row").css({
                display: "none"
            });
            container.nextAll("div.title").css({
                display: "none"
            });
            container.nextAll("div.mobile").css({
                display: "block"
            });
            container.find(".instruction span.you").html("you")
            container.find(".instruction span.your").html("your")
        }
    });
    
    // participant form toggle
    $("#participant_form div.row div.options #is_gift:first").click(function(){
    
        container = $(this).parent().parent();
        container.nextAll("div.row").toggle();
        container.nextAll("div.title").toggle();
        container.nextAll("div.mobile").css({
            display: "block"
        });
        
        container.parent().find("div.instruction span.you").html("the participant")
        container.parent().find("div.instruction span.your").html("their")
    });
    
    /* Payment form */
    // protx form card selection
    $("div.select_card_type label").click(function(){
    
        $(this).find("input").attr("checked", "checked");
        $(this).fadeTo(1, 1);
        $(this).siblings().fadeTo(1, 0.20);
        
        if ($(this).attr('for') == 'amex') {
            $('#cv2_length').html(4);
        }
        else {
            $('#cv2_length').html(3);
        }
        
    });
    
    /* Checkout Details Form */
    if ($("#checkout_details").length) {
    
        /* Delivery form */
        
        // set state after reloading page
        if ($('#delivery_is_different').attr("checked")) {
            $("#delivery_address").show();
            
            if ($('#use_saved_delivery_address').attr("checked")) {
                $("#blank_delivery_address").hide();
                $("#saved_delivery_addresses").show();
            };
                    };
        
        // delivery address toggles
        $("#delivery_is_different").click(function(event){
        
            if (event.target.checked) {
                $("#delivery_address").slideDown();
            }
            else {
                $("#delivery_address").slideUp();
            }
        });
        
        $("#use_saved_delivery_address").click(function(event){
        
            if (event.target.checked) {
                $("#blank_delivery_address").slideUp();
                $("#saved_delivery_addresses").slideDown();
            }
            else {
                $("#blank_delivery_address").slideDown();
                $("#saved_delivery_addresses").slideUp();
            }
        });
        
        if ($('#checkout_details').length) {
        
            //		if(!browser_is_ie6()) {
            $('#checkout_details').submit(checkout_form);
            //	}	
            // disable the continue button until the newsletter is confirmed
            //			$('#cart_continue input').attr('disabled',true).addClass('disabled');
            
            $('#close_shade').live('click', function(){
                $(this).parents('#shade_holder').hide();
                $(this).parents('#shade_holder').find('#shade_info_box_1').empty();
            });
            
            $('#checkout_newsletter_link').click(function(event){
                event.preventDefault();
                $('#shade_holder').show().fadeTo(0, .90).css({
                    background: '#ccc',
                    height: 1300
                });
                
                var shade_content = '<a id="close_shade">Close <img src="images/icon-delete.png" /></a>';
                shade_content += "<iframe src=\"" + $(this).attr('href') + "\"></iframe>";
                
                $('#shade_info_box_1').show().fadeTo(0, 100).empty();
                $('#shade_info_box_1').css({
                    width: 700,
                    height: 800,
                    overflow: 'visible',
                    border: '1px solid red',
                    background: '#FFF'
                }).append(shade_content);
                
                $('#shade_info_box_1 iframe').css({
                    height: '100%'
                })
                $.newsletter_confirmed = true;
                $('#newsletter_caution').fadeOut();
            });
        }
        
        $('#newsletter_opt_out').click(function(){
            $.newsletter_confirmed = true;
            $('#newsletter_caution').fadeOut();
        })
        
        /* Event handlers */
        $("#b_email").keyup(function(){
            check_account($(this));
        });
        $("#b_email").change(function(){
            $(this).trigger('keyup');
        });
        
        $('.lost_password').click(function(event){
        
            params = url_params_to_obj(window.location.href);
            
            if ($('#b_email').val()) {
                event.preventDefault();
                send_new_password($("#b_email").val(), params.cart_id)
            }
        });
        
        $("#claim_code").change(check_voucher_code);
        $("#claim_code").keyup(check_voucher_code);
    }
    
    /* Cart Quantity options */
    if ($('#cart_holder').length) {
    
        $('.item_quantity select').change(updateQty);
        $('.child_selector select').change(updateChild);
    }
    
    /* Fast Nav Advanced search */
    search_inputs = $("#advanced_search input[type='text']");
    search_inputs.each(function(){
        $(this).data('default', $(this).val());
    });
    
    search_inputs.focus(function(){
        if ($(this).val() == $(this).data('default')) {
            $(this).val("");
        }
    });
    
    search_inputs.blur(function(){
        if (!$(this).val().length) {
            $(this).val($(this).data('default'));
        }
    });
    
    // Order print
    $('#print_order').click(function(){
        window.print();
    });
    
    /* Fastnav voucher balance */
    $('.fast_nav_menu #claim_code').bind('keyup change blur', function(e){
        fastnav_get_voucher_balance(e, $(this).val());
    })
    
    /* Certificate printing */
    // IE doesn't like having images as labels, despite it being a valid behaviour
    // so it's time for a JS override
    $('div.certificate label').bind('click keyup change', function(e){
        $(this).parents('div:first').find('input').attr('checked', 'checked');
    });
    
    
});

function checkout_form(event){

    if ($('#anonymous_donation').attr('checked')) {
        return true;
    }
    
    form = $("#" + event.target.id);
    
    if ($("#delivery_is_different").attr("checked") && !$("#use_saved_delivery_address").attr("checked")) {
        inputs = form.find(":input.required");
    }
    else {
        inputs = form.find(":input").filter(".required:visible");
    }
    
    inputs.each(function(){
    
        if ($.trim($(this).val()).length < 2 || (this.tagName == 'SELECT' && this.value == 0)) {
            $(this).siblings("p.warning,span.warning,div.notice").fadeIn();
            $(this).siblings("img.caution_img").fadeIn();
            $(this).addClass('error');
            event.preventDefault();
            //			reset_submit_button();
        }
        else {
            $(this).siblings("span.warning,p.warning,div.notice").fadeOut();
            $(this).siblings("img.caution_img").fadeOut();
            $(this).removeClass('error');
        }
    });
    
    // loops over date of birth fields - shows error notice if any one field has the error class
    $('#r_dob_date').siblings('div.notice').fadeOut();
    $('#r_dob_date li :input').each(function(){
        if ($(this).hasClass('error')) {
            $('#r_dob_date').siblings('div.notice').fadeIn();
        }
    });
    
    if ($("#terms_yes").length) {
        if (!$("#terms_yes").attr("checked")) {
            $("#terms_yes").parents("div:first").find("span.warning").fadeIn();
            event.preventDefault();
            //			reset_submit_button()
        }
        else {
            $("#terms_yes").parents("div:first").find("span.warning").fadeOut();
        }
    }
    
    if ($('#b_first_name').length && !$('b_postcode_lookup').val() && !$('#b_address_1').val()) { // address hasnt been looked up
        $('#b_postcode_lookup_holder').find('div.notice').fadeIn();
        $('#b_postcode_lookup').addClass('error');
        event.preventDefault();
    }
    else {
        $('#b_postcode_lookup_holder').find('div.notice').fadeOut();
        $('#b_postcode_lookup').removeClass('error');
    }
    if (!$('r_postcode_lookup').val() && $('#r_first_name').length && !$('#r_address_1').val() && !$('#my_address').attr('checked')) { // recipient address hasnt been looked up
        $('#r_postcode_lookup_holder').find('div.notice').fadeIn();
        $('#r_postcode_lookup').addClass('error');
        event.preventDefault();
    }
    else {
        $('#r_postcode_lookup_holder').find('div.notice').fadeOut();
        $('#r_postcode_lookup').removeClass('error');
    }
    
    /* Added the code to check if there is any, added in the firstname
     *
     */
    $('#firstname_id').hide();
    $('#recpid').hide();
    var i = 0;
    
    if ($('#b_first_name').val() != undefined) {
    
        myString = $('#b_first_name').val().split(' ') // gets the sentence
        Chars = myString.length;
        response = "";
        
        for (i = 0; i < Chars; i++) {
            if (myString[i] == 'and' || myString[i] == ',' || myString[i] == '&') {
                response = 1;
            }
        }
        if (/&|,|.\d$/i.test($('#b_first_name').val())) {
            response = 1;
        }
        
        if (response != "") {
            $('#b_first_name').siblings("span.warning,div.notice").fadeIn(0);
            $('#b_first_name').siblings("img.caution_img").fadeIn(0);
            $('#firstname_id').html('Please enter a valid name');
            $('#firstname_id').show();
            $('#b_first_name').addClass('error');
            event.preventDefault();
            i = 1;
        }
        
    }
    
    
    if ($('#b_first_name').val() == '') {
        $('#b_first_name').siblings("p.warning,span.warning,div.notice").fadeIn(0);
        $('#b_first_name').siblings("img.caution_img").fadeIn(0);
        $('#firstname_id').html('Please enter your first name');
        $('#firstname_id').show();
        $('#b_first_name').addClass('error');
        i = 1;
        event.preventDefault();
    }
    if (i == 0) {
        $('#b_first_name').siblings("img.caution_img").fadeOut();
        $('#b_first_name').siblings("div.notice").fadeOut();
        $('#b_first_name').removeClass('error');
        $('#firstname_id').hide();
        $('#firstname_id').html('');
    }
    
    var cnt = 0;
    
    if ($('#r_first_name').val() != undefined) {
        myString = $('#r_first_name').val().split(' ') // gets the sentence
        Chars = myString.length;
        response = "";
        
        for (i = 0; i < Chars; i++) {
            if (myString[i] == 'and' || myString[i] == ',' || myString[i] == '&') {
                response = 1;
            }
        }
        if (/&|,|.\d$/i.test($('#r_first_name').val())) {
            response = 1;
        }
        
        if (response != "") {
            $('#r_first_name').siblings("span.warning,div.notice").fadeIn(0);
            $('#r_first_name').siblings("img.caution_img").fadeIn(0);
            $('#recpid').html('Please enter a valid name');
            $('#recpid').show();
            $('#r_first_name').addClass('error');
            cnt = 1;
            event.preventDefault();
        }
    }
    
    if ($('#r_first_name').val() == '') {
        $('#recpid').show();
        $('#r_first_name').siblings("p.warning,span.warning,div.notice").fadeIn(0);
        $('#r_first_name').siblings("img.caution_img").fadeIn(0);
        $('#recpid').show();
        $('#recpid').html('Please enter the recipient\'s first name');
        $('#r_first_name').addClass('error');
        cnt = 2;
        event.preventDefault();
    }
    if (cnt == 0) {
        $('#r_first_name').siblings("img.caution_img").fadeOut();
        $('#r_first_name').siblings("div.notice").fadeOut();
        $('#r_first_name').removeClass('error');
        $('#recpid').hide();
        $('#recpid').html('');
    }
    
    if ($('#under_18_holder input:checked').val()=="Yes" && $('#r_dob_year').val()!=0){
        var d = new Date();
        if (d.getFullYear()-$('#r_dob_year').val()>18){
            $('#r_dob_year').siblings("div.notice").fadeIn();
            $('#r_dob_year').addClass('error');
            event.preventDefault();
        }
        else {
            $('#r_dob_year').siblings("div.notice").fadeOut();
            $('#r_dob_year').removeClass('error');
            
        }
    }
    
    if ($('#under_18_holder input:checked').val()=="No" && $('#r_dob_year').val()!=0){
        var d = new Date();
        if (d.getFullYear()-$('#r_dob_year').val()<18){
            $('#r_dob_year').siblings("div.notice").fadeIn();
            $('#r_dob_year').addClass('error');
            event.preventDefault();
        }
        else {
            $('#r_dob_year').siblings("div.notice").fadeOut();
            $('#r_dob_year').removeClass('error');
            
        }
        
    }
     /*
     * Code ends here
     */
    //scroll to the first notice
    scrollToFirstNotice()
	
	// $('#scrolltarget').attr('id', '');
  /* notice = $('div.notice:visible:first');
    
    notice.parents('div.r1').attr('id', 'scrolltarget')
    target = document.getElementById('scrolltarget');
    
    if (target) {
	
		if (!elementInViewport(target)) {
			$.scrollTo('#scrolltarget', {
				offset: -window.innerHeight / 2
			});
		}
	}
    */
	
	
	
    
}



//function reset_submit_button() {
//	$('#cart_continue input').removeAttr('disabled');
//	$('#cart_continue input').val('Continue');
//}

function select_product(product_id){
    sku_code = document.add_to_cart.sku.options[document.add_to_cart.sku.selectedIndex].value;
    item_quantity = document.add_to_cart.qty.options[document.add_to_cart.qty.selectedIndex].value;
    
    document.location.href = '?page=shop&pid=' + product_id + '&action=add_item&sku=' + sku_code + '&qty=' + item_quantity;
}

function showHideDel(objToSwitch){
    if (document.getElementById(objToSwitch).style.display == 'none') 
        document.getElementById(objToSwitch).style.display = 'block';
    else 
        document.getElementById(objToSwitch).style.display = 'none';
}

function checkTicks(objToCheck){
    if (document.getElementById(objToCheck).checked == "true") {
        document.getElementById(objToCheck).style.display = 'block';
    }
    else {
        document.getElementById(objToCheck).style.display = 'none';
        document.getElementById(objToCheck).checked = "false";
    }
}

// onLoad="checkTicks('inTheServices'); checkTicks('deliveryAddress')";

function update_order_type(order_type){
    window.location = '?page=shop&option=cart&action=update_del&type=' + order_type;
}

function update_gift_wrap(item){
    itemID = item.id;
    splitID = itemID.split('_');
    
    sku = splitID[1];
    
    window.location = '?page=shop&option=cart&action=update_gift&sku=' + sku;
}

function check_gift_options(){
    valid = true;
    $("div.voucher div.row > :input").each(function(){
    
    
        if (this.id.indexOf('message') == -1) {
            if (this.value == "") {
                $(this).addClass("caution")
                $(this).nextAll().css({
                    display: "inline"
                });
                $(this).nextAll("span.example").css({
                    display: "none"
                });
                
                valid = false;
            }
            else {
                $(this).removeClass("caution");
                $(this).nextAll().css({
                    display: "none"
                });
                $(this).nextAll("span.example").css({
                    display: "inline"
                });
            }
        }
    });
    
    return valid;
}

function check_voucher_code(event){
    //$ = jQuery.noConflict();
    if (event.keyCode == 17) {
        return false;
    }
    
    claim_code = event.target.value;
    
    // dont check partial entries
    if (claim_code.length < 14) {
        return false;
    }
    
    // check code is not already validated
    if ($("#valid_claim_codes").val().length > 0) {
        if ($("#valid_claim_codes").attr("value").indexOf(claim_code) != -1) {
            // clear field error formatting
            $("#claim_code").css({
                border: "0px"
            })
            $("#claim_code").nextAll().css({
                display: "none"
            });
            
            return false;
        }
    }
    
    // check code on server
    $.get("ajax/index.php", {
        page: "shop",
        action: "voucher_code",
        code: claim_code
    }, function(amount){
    
        if (amount == 'redirect') {
            window.location = "index.php";
        }
        
        if (amount > 0) {
            // clear field error formatting
            $("#claim_code").css({
                border: "0px"
            })
            $("#claim_code").nextAll("img").css({
                display: "none"
            });
            $("#claim_code").nextAll("span").css({
                display: "none"
            });
            
            validCodes = $("#valid_claim_codes").val();
            
            $("#list_claim_codes").addClass('visible');
            
            //add the claim code and amount to the table;
            codeHTML = "<tr><td>" + claim_code + "</td><td align=\"center\">&pound;" + amount + '.00' + "</td></tr>";
            
            $("#list_claim_codes").append(codeHTML);
            
            //append the claim code to the valid_claim_codes hidden field
            validCodes = $("#valid_claim_codes").val();
            
            if (validCodes.length == 1) {
                validCodes = "";
            }
            validCodes += claim_code + "|";
            
            $("#valid_claim_codes").attr("value", validCodes);
            
            $("#claim_code").val('');
        }
        else {
            // mark field as invalid
            $("#claim_code").css({
                border: "2px solid #CC0033"
            })
            $("#claim_code").nextAll("img").css({
                display: "inline"
            });
            $("#claim_code").nextAll("span").css({
                display: "inline"
            });
            valid = false;
        }
    }, 'text');
}

function fastnav_get_voucher_balance(event, claim_code){
    //$ = jQuery.noConflict();
    
    if (event.keyCode == 17) {
        return false;
    }
    
    if (claim_code.length < 14) {
        $("div.balance_holder span.balance").html('�' + 0);
        return false
    }
    
    // check code on server
    $.get("ajax/index.php", {
        page: "shop",
        action: "voucher_code",
        code: claim_code
    }, function(amount){
    
        if (amount == 'redirect') {
            amount = 0;
        }
        
        $("div.balance_holder span.balance").html('�' + amount);
        
        $("#claim_code").val('');
    }, 'text');
}

function remove_claim_code(code){
    validCodes = $("#valid_claim_codes").val();
    
    return false;
}

function updateChild(event){

    el = $(event.target);
    
    item_id = el.attr('id').split('_')[1];
    new_sku = el.val();
    
    option = get_page_option();
    
    document.location.href = '?page=shop&option=' + option + '&action=update_item&sku=' + item_id + '&newsku=' + new_sku;
    
}

function updateQty(event){

    el = $(event.target);
    
    item_id = el.attr('id').split('_')[1];
    new_qty = el.val();
    
    option = get_page_option();
    
    document.location.href = '?page=shop&option=' + option + '&action=update_item&sku=' + item_id + '&qty=' + new_qty;
}

function get_page_option(){

    params = document.location.href.split('&');
    params.shift();
    
    $.each(params, function(){
        if (this.indexOf('option') != -1) {
            option = this.split('=')[1];
        }
    });
    
    return option;
}
   function scrollToFirstNotice() {
	$('#scrolltarget').attr('id','');
	notice = $('#checkout_holder div.notice:visible:first');
	notice.parents('div.r1').attr('id','scrolltarget')
	
	target = document.getElementById('scrolltarget');
			
	if(target) {
		if(!elementInViewport(target)) {
			$.scrollTo('#scrolltarget',{offset:-window.innerHeight / 2});
		}
	}
}

function elementInViewport(el){
    var top = el.offsetTop;
    var left = el.offsetLeft;
    var width = el.offsetWidth;
    var height = el.offsetHeight;
    
    while (el.offsetParent) {
        el = el.offsetParent;
        top += el.offsetTop;
        left += el.offsetLeft;
    }
    
    return (top >= window.pageYOffset &&
    left >= window.pageXOffset &&
    (top + height) <= (window.pageYOffset + window.innerHeight) &&
    (left + width) <= (window.pageXOffset + window.innerWidth));
}

