function SmoothScroll() {
	$('.scroll').click(function() {
		if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
	  && location.hostname == this.hostname) {
			var $target = $(this.hash);
			$target = $target.length && $target
		|| $('[name=' + this.hash.slice(1) + ']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$('html,body')
		  .animate({ scrollTop: targetOffset }, 1000);
				return false;
			}
		}
	});
}

function AddIframeToQueryStringForTemplates() {
	AddIframeToQueryStringForTemplate('#addToReminder');
	AddIframeToQueryStringForTemplate('#addToList');
	AddIframeToQueryStringForTemplate('a.jsIframe');
}

function AddIframeToQueryStringForTemplate(selector) {
	var links = $(selector);
	links.each(function() {
		var link = $(this);
		var linkHref = link.attr('href').toString().replace('&iframe=true', '');
		if (linkHref.indexOf('?') >= 0) {
			link.attr('href', linkHref + '&iframe=true');
		}
		else {
			link.attr('href', linkHref + '?iframe=true');
		}
	});
}



function engravePen(selectedElement) {

	var guid = getBasketItemGUID(selectedElement);

	if (guid.length > 0) { guid = "_" + guid; }

	var imageInput = $('#content input[name=previewImageURI' + guid + ']');
	var textInput = $('#content input[name=engravingText' + guid + ']');
	var styleInput = $('#content input[name=engravingStyle' + guid + ']:checked');

	var $imageURL = imageInput.val();
	var $selectedFont = styleInput.val();
	var $textString = textInput.val();

	openLightbox($imageURL, $selectedFont, $textString);

}

function engravePlate(selectedElement) {

	var guid = getBasketItemGUID(selectedElement);

	if (guid.length > 0) { guid = "_" + guid; }

	var line1 = $('#plateEngravingText1' + guid).val();
	var line2 = $('#plateEngravingText2' + guid).val();
	var line3 = $('#plateEngravingText3' + guid).val();
	var style = $('#content input[name=plateEngravingStyle' + guid + ']:checked').val();

	var imageURL;
	if (style == "Style2") {
		imageURL = '/_images/plates/silver.jpg';
	} else {
		imageURL = '/_images/plates/gold-plate-flat.jpg';
	}

	openPlateEngraving(imageURL, line1, line2, line3);

}

function openLightbox($imageURI, $selectedFont, $textString) {

	$('#engravePreviewHolder').empty();
	$('#engravePreviewHolder').flash({
		src: '/_images/flash/pen-engraver.swf',
		width: 720,
		height: 150,
		flashvars: { imageURI: $imageURI, selectedFont: $selectedFont, text: $textString }
	});
	$('#engravePreviewHolder').append('<p style="padding:0; text-align:center; color:#6A6B6C; font-size:0.9em;">Actual engraving may vary slightly from visual shown.</p>');

	$("#engravePreviewHolder").show();

	$("#engravePreviewHolder").dialog({
		modal: true,
		autoOpen: true,
		width: 770,
		height: 240,
		zIndex: 9000,
		title: "Pen Engraving Preview",
		open: function() {
			$('.ui-widget-overlay').css('zIndex', '9000');
		},
		resizable: false
	});
}

function openPlateEngraving($imageURI, $line1, $line2, $line3) {

	$('#engravePreviewHolder').empty();
	$('#engravePreviewHolder').flash({
		src: '/_images/flash/plate-engraver.swf',
		width: 566,
		height: 204,
		flashvars: { imageURI: $imageURI, line1: $line1, line2: $line2, line3: $line3 }
	});
	$('#engravePreviewHolder').append('<p style="padding:0; text-align:center; color:#6A6B6C; font-size:0.9em;">Actual engraving may vary slightly from visual shown.</p>');

	$("#engravePreviewHolder").show();
	$("#engravePreviewHolder").dialog({
		modal: true,
		autoOpen: true,
		width: 590,
		height: 285,
		title: "Plate Engraving Preview",
		open: function() {
			$('.ui-widget-overlay').css('zIndex', '9000');
		},
		resizable: false
	});
}

function getBasketItemGUID(selectedElement) {
	var id = selectedElement.attr('id');
	var guid = id.substring(id.indexOf('_') + 1, id.length);

	return guid;
}

//Mail ordering times overlay
function MailOrderingTimes() {

	$(".openingTimes > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$(".openingTimes").toggleClass("openDropDown");
	});

	$(".openingTimes > a").keyup(function(e) {
		$(this).next('div').show();
		$(".openingTimes").toggleClass("openDropDown");
	});

	$(".openingTimes .mailOrdering").mouseup(function() {
		return false;
	});

	$(document).mouseup(function(e) {
		if ($(e.target).parent(".openingTimes").length == 0) {
			$(".openingTimes").removeClass("openDropDown");
			$(".openingTimes .mailOrdering").hide();
		}
	});

	$(".openingTimes > a").blur(function(e) {
		$(".openingTimes").removeClass("openDropDown");
		$(".openingTimes .mailOrdering").hide();
	});

}

function CurrencySelector() {

	$(".dropDown").click(function(e) {
		e.preventDefault();
		$(this).parent().toggleClass('active-dropdown');
	});

}

//Main nav drop down
function DropDownMenu() {

	var display_timeout = 0;
	/* http://cherne.net/brian/resources/jquery.hoverIntent.html */
	hiConfig = {
		sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
		interval: 200, // number = milliseconds for onMouseOver polling interval
		timeout: 0, // number = milliseconds delay before onMouseOut
		over: function() {
			$("li.has-subnav").removeClass('subnav-active');
			if (display_timeout != 0) { clearTimeout(display_timeout); }
			var this_element = this;
			$(this_element).addClass('subnav-active');
		}, // function = onMouseOver callback (REQUIRED)
		out: function() {
			if (display_timeout != 0) { clearTimeout(display_timeout); }
			var this_element = this;
			display_timeout = setTimeout(function() {
				display_timeout = 0;
				$(this_element).removeClass('subnav-active');
			}, 500);
		} // function = onMouseOut callback (REQUIRED)
	}
	$('li.has-subnav').hoverIntent(hiConfig);


}

//Main nav drop down
function NavDropDownMenu() {

	var display_timeout = 0;
	$("li.withDropDown").hover(function() {
		$("li.withDropDown").removeClass('openDropDown');
		if (display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;
		$(this_element).addClass('openDropDown');
	},
	function() {
		if (display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;
		display_timeout = setTimeout(function() {
			display_timeout = 0;
			$(this_element).removeClass('openDropDown');
		}, 500);
	}
	);
}

function UpdatePostageOption(postageBandID) {
	$.ajax(
	{
		url: "/ShopPurchase/Checkout/UpdatePostageAjax/",
		type: "POST",
		data: { "PostageBandID": postageBandID },
		success: function(d) {
			if (d.Success) {
				$("dl#paymentSummary").html(d.PaymentSummaryHtml);
			}
		}
	});
}

var iframeDialog;

function DisplayIframeDialog(url, title, width, height) {

	iframeDialog = $('<div id="iFrameDialog"><iframe class="externalSite" width="100%" height="100%" frameborder="0" src="' + url + '" /></div>');

	iframeDialog.dialog({
		title: title ? title : 'External Site',
		width: width + "px",
		height: height,
		close: function(event, ui) {
			$(this).dialog("destroy");
			$(".externalSite").remove();
			$(".ui-widget-overlay").remove();
		},
		resizable: false
	});

	$(".ui-dialog").has('iframe').before("<div class='ui-widget-overlay'></div>");

	function dialogOverlayResize() { $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px").css("z-index", "1001"); }

	$(window).resize(function() { dialogOverlayResize(); });
	dialogOverlayResize();

}

function setUpProductImages() {
	$("ul.additionalImages li a").click(function(e) {
		e.preventDefault();
		var anode = $(this);
		var target = $("#" + anode.attr('rel'));

		//alert(anode.html());
		//alert(target.html());
		target.attr('href', anode.attr('href'));
		target.children("img").attr('src', anode.attr('rev'));
	});


}

$(document).ready(function() {

    //Product Options Accordian

    //$('.productOptions > div:not(:first)').hide();
    $('.productOptions > div').hide();

    $('.productOptions h2 a').click(function() {
        $(this).parent().next().toggle('slow');
        return false;
    }).next().hide();

    //Basket Options

    $('.basket .editOption').hide();

    $('.basket .edit').click(function() {
        $(this).parent().next().toggle('slow');
        return false;
    }).next().hide();

    //Engraving character count
    $('.countField').keyup(function() {
        var charLimit = $(this).attr('maxlength');
        var charCount = $(this).val().length;

        var textField = $(this).next('.counter');
        textField.text((charLimit - charCount) + ' characters remaining');
    })

    //Filter Accordian

    $('.availableFilters li > ul').hide();

    $('.availableFilters ul:first > li > a').click(function() {
        $(this).next().slideToggle('slow');
        $(this).parent().toggleClass('active');
        return false;
    }).next().hide();

    $("a[rel*='external']").attr({ target: "_blank" });

    var volatile = $("input[type=text], textarea")
    volatile.focus(function(event) {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
        }
    }, volatile.blur(function(event) {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
        }
    }
    ));

    $('#search').submit(function() {
        if ($('#search input[type=text]').val() == "Search Websters Pen Shop" ||
            $('#search input[type=text]').val() == "") {
            return false;
        }
    });

    // Help Tips Dialog

    $('.dialogContent').hide();
    $('.dialogToggle').show();

    $('.dialogToggle').click(function(e) {
        e.preventDefault();

        var dialogContent = "#" + $(this).attr('rel');
        var dialogTitle = $(this).attr("title");

        $(dialogContent).dialog({
            modal: true,
            autoOpen: false,
            width: 600,
            height: 200,
            zIndex: 4000,
            title: dialogTitle,
            resizable: false
        }).dialog('open');

    });

    // Dialogs

    $(".dialogContent").dialog({
        modal: true,
        autoOpen: false,
        width: 570,
        height: 380,
        resizable: false
    });

    $(".dialog").click(function(e) {
        e.preventDefault();
        var dialogContent = $($(this).attr("href"));
        dialogContent.dialog('open');
    });

    //Lightbox

    $(".lightbox").each(function() {
        $(this).ariaLightbox({
            pos: "auto",
            em: false,
            zIndex: "9999",
            titleText: getLightboxTitle(this),
            makeHover: false,
            opacity: 0.2
        });
    });

    function getLightboxTitle(link) {
        var img = $(link).find("img");
        return (img.attr("alt")) ? img.attr("alt") : '&nbsp;';
    }

    //Iframe
    $('.iframe').click(function(e) {

        e.preventDefault();

        var $this = $(this);

        if ($this.attr('rel')) {
            var dialogDimensions = $this.attr('rel').split("x");
            var dialogWidth = dialogDimensions[0];
            var dialogHeight = dialogDimensions[1];
        } else {
            var dialogWidth = 728;
            var dialogHeight = 500;
        }

        /*if ($('.productLists').length > 0) { dialogWidth = 590; }*/

        DisplayIframeDialog(this.href, $this.attr('title'), dialogWidth, dialogHeight);

    });

    //Iframe
    $('.productImagePopup').click(function(e) {

        e.preventDefault();

        var $this = $(this);

        var dialogDimensions = $this.attr('rel').split("x");
        var dialogWidth = dialogDimensions[0];
        var dialogHeight = dialogDimensions[1];

        DisplayIframeDialog(this.href, $this.attr('title') + '  - Use your mouse wheel to zoom', dialogWidth, dialogHeight);

    });

    SmoothScroll();
    MailOrderingTimes();
    CurrencySelector();
    NavDropDownMenu();
    DropDownMenu();

    //Custom Forms

    $("input.spin-button").SpinButton({ min: 1 });
    $('input[type=checkbox], input[type=radio]').customInput();
    $('.contact .select select').selectmenu({ style: 'dropdown', width: '298px', maxHeight: 200 });
    $('.checkoutForm select').selectmenu({ style: 'dropdown', width: '380px', maxHeight: 200 });
    $('.sortBy .sortPage select').selectmenu({ style: 'dropdown', width: '180px', maxHeight: 200 });
    $('.sortBy .perPage select').selectmenu({ style: 'dropdown', width: '120px', maxHeight: 200 });
    $('.contact .dateSelect select, .searchPod .dateSelect .year').selectmenu({ style: 'dropdown', width: '75px', maxHeight: 200 });
    $('.searchPod .dateSelect .day').selectmenu({ style: 'dropdown', width: '56px', maxHeight: 200 });
    $('.buyProduct .addToBag select').selectmenu({ style: 'dropdown', width: '60px', maxHeight: 200 });

    //Product Options Tip

    $(".productOptions a > img[alt]").qtip({

        position: {
            corner: {
                target: 'bottomRight',
                tooltip: 'topLeft'
            }
        },
        style: {
            background: '#fff',
            color: '#212121',
            textAlign: 'center',
            border: {
                width: 1,
                color: '#9f9f9f'
            }
        }
    });

    //Homepage Banners

    $("#banners li:not(:first) a").attr("tabIndex", "-1");
    $("#banners").carouFredSel({
        width: 980,
        items: 1,
        scroll: {
            items: 1,
            duration: 800,
            onBefore: function(oldItems, newItems) {
                oldItems.children('a').attr("tabIndex", "-1");
                newItems.children('a').removeAttr("tabIndex");
                $("#bannerContainer.homeBanners .play").hide();
                $("#bannerContainer.homeBanners .pause").show();
            }
        },
        auto: {
            delay: 1000
        },
        prev: {
            button: "#bannerContainer.homeBanners .prev",
            key: "left"
        },
        next: {
            button: "#bannerContainer.homeBanners .next",
            key: "right"
        }
    });

    $("#bannerContainer.homeBanners .play").click(function() {
        $("#banners").trigger("play", true);
        $(this).hide().next().show();
        return false;
    }).hide();

    $("#bannerContainer.homeBanners .pause").click(function() {
        $("#banners").trigger("pause", true);
        $(this).hide().prev().show();
        return false;
    });

    //Internal Banners

    $("#internalBanners li:not(:first) a").attr("tabIndex", "-1");
    $("#internalBanners").carouFredSel({
        width: 980,
        items: 1,
        scroll: {
            items: 1,
            duration: 800,
            onBefore: function(oldItems, newItems) {
                oldItems.children('a').attr("tabIndex", "-1");
                newItems.children('a').removeAttr("tabIndex");
            }
        },
        auto: {
            delay: 1000
        },
        prev: {
            button: "#bannerContainer.internalBanners .prev",
            key: "left",
            onAfter: function(oldItems, newItems) {
                $("#internalBanners").trigger('pause');
                $("#bannerContainer.internalBanners .play").show();
                $("#bannerContainer.internalBanners .pause").hide();
            }
        },
        next: {
            button: "#bannerContainer.internalBanners .next",
            key: "right",
            onAfter: function(oldItems, newItems) {
                $("#internalBanners").trigger('pause');
                $("#bannerContainer.internalBanners .play").show();
                $("#bannerContainer.internalBanners .pause").hide();
            }
        }
    });

    $("#bannerContainer.internalBanners .play").click(function() {
        $("#internalBanners").trigger("play");
        $(this).hide().next().show();
        return false;
    });

    $("#bannerContainer.internalBanners .pause").click(function() {
        $("#internalBanners").trigger("pause");
        $(this).hide().prev().show();
        return false;
    });

    // Horizontal Carousel

    var carouselMinimum = 3

    if ($('#home').length > 0) {
        carouselMinimum = 5
    }

    $(".horizontalCarousel .controls").show();
    $(".horizontalCarousel .inner").css("height", "204px");
    $(".horizontalCarousel ul").carouFredSel({
        scroll: {
            items: 1
        },
        items: {
            minimum: carouselMinimum
        },
        auto: false,
        prev: ".horizontalCarousel .controls .prev",
        next: ".horizontalCarousel .controls .next"
    }).css("padding", "0 35px");

    // Vertical Carousel

    var realtedCount = $("#relatedProducts .verticalCarousel ul li").length;

    if (realtedCount > 3) {
        $("#relatedProducts .verticalCarousel .inner").css("padding", "30px 0");
        $("#relatedProducts .verticalCarousel .controls").show();
    };

    $("#relatedProducts .verticalCarousel ul").carouFredSel({
        direction: "up",
        width: 450,
        items: {
            visible: 3,
            minimum: 3,
            width: 440,
            height: "variable"
        },
        scroll: {
            items: 1
        },
        auto: false,
        prev: "#relatedProducts .verticalCarousel .controls .prev",
        next: "#relatedProducts .verticalCarousel .controls .next"
    });

    // Vertical Carousel

    var recentCount = $("#recentlyViewed .verticalCarousel ul li").length;

    if (recentCount > 3) {
        $("#recentlyViewed .verticalCarousel .inner").css("padding", "30px 0");
        $("#recentlyViewed .verticalCarousel .controls").show();
    };

    $("#recentlyViewed .verticalCarousel ul").carouFredSel({
        direction: "up",
        width: 450,
        items: {
            visible: 3,
            minimum: 3,
            width: 440,
            height: "variable"
        },
        scroll: {
            items: 1
        },
        auto: false,
        prev: "#recentlyViewed .verticalCarousel .controls .prev",
        next: "#recentlyViewed .verticalCarousel .controls .next"
    });

    // Vertical Carousel

    var recentCount = $("#receiptReminders .verticalCarousel ul li").length;

    if (recentCount > 3) {
        $("#receiptReminders .verticalCarousel .inner").css("padding", "30px 0");
        $("#receiptReminders .verticalCarousel .controls").show();
    };

    $("#receiptReminders .verticalCarousel ul").carouFredSel({
        direction: "up",
        width: 450,
        items: {
            visible: 4,
            minimum: 4,
            width: 440,
            height: "variable"
        },
        scroll: {
            items: 1
        },
        auto: false,
        prev: "#receiptReminders .verticalCarousel .controls .prev",
        next: "#receiptReminders .verticalCarousel .controls .next"
    });

    //Row Highlight
    $("table tr").hover(function() { $(this).addClass('highlight'); }, function() { $(this).removeClass('highlight'); });

    //Zebra striping
    $("table tr:even").addClass('even');

    //Input Highlight

    $("#content input[type=text], textarea, #content input[type=password]").hover(function() { $(this).css('border-color', '#949494'); }, function() { $(this).css('border-color', '#D3D3D3'); });

    //Pen Engraver

    $('.preview .penPreview').click(function(event) {
        event.preventDefault();
        engravePen($(this));
    });

    // Plate engraving preview

    $('.preview .platePreview').click(function(event) {
        event.preventDefault();
        engravePlate($(this));
    });

    // Delivery select
    $(".deliveryPreference").hide();

    // Google Maps
    if ($("#map").length > 0) {
        $("#map").gMap({
            markers: [{ latitude: 51.439229, longitude: 0.271289, html: "Bluewater, Kent" },
				  		{ latitude: 50.842366, longitude: -0.13959, html: "Brighton, Kent" },
				  		{ latitude: 51.400491, longitude: -0.013733, html: "Bromley, Kent" },
				  		{ latitude: 51.375468, longitude: -0.099877, html: "Croydon, Kent" },
				  		{ latitude: 51.389763, longitude: 0.072233, html: "Orpington, Kent"}],
            zoom: 8,
            icon: { image: "/_images/icons/gmap-marker.png", shadow: false, iconsize: [30, 34], shadowsize: false, iconanchor: [15, 34], infowindowanchor: [15, 17] },
            latitude: 51.19759,
            longitude: -0.138245
        });

        $(".bluewater").gMap({
            markers: [{ latitude: 51.439229, longitude: 0.271289}],
            zoom: 14
        })

        $(".brighton").gMap({
            markers: [{ latitude: 50.842366, longitude: -0.13959}],
            zoom: 14
        })

        $(".bromley").gMap({
            markers: [{ latitude: 51.400491, longitude: -0.013733}],
            zoom: 14
        })

        $(".croydon").gMap({
            markers: [{ latitude: 51.375468, longitude: -0.099877}],
            zoom: 14
        })

        $(".orpington").gMap({
            markers: [{ latitude: 51.389763, longitude: 0.072233}],
            zoom: 14
        })
    }

    //Check postage options ajax
    if ($('#PostageBandID') && $('#setPostageBand')) {
        $('#setPostageBand').hide();

        $('#PostageBandID').change(function() {
            UpdatePostageOption($(this).val())
        });
    }

    $(".productDetailsForm").submit(function(e) {

        e.preventDefault();

        $.ajax({
            url: "/ShopPurchase/Basket/BasketCommandHandler/?ajax=true",
            dataType: 'json',
            data: $(this).serialize(),
            success: function(data) {

                $(".miniBasket").html(data.MiniBasketHtml);

                if (data.ExtendedProperties.ShowCrossSell == true) {

                    var guid = data.ExtendedProperties.GUID;
                    var productId = $("#ProductID").val();
                    var skuId = $("#SkuID") ? $("#SkuID").val() : "";
                    var bundleId = $("#SkuBundleID") ? $("#SkuBundleID").val() : "";
                    var quantity = $("#Quantity").val();

                    var url = "/shops/crosssell/?guid=" + guid + "&ProductID=" + productId + "&SkuID=" + skuId + "&SkuBundleID=" + bundleId + "&Quantity=" + quantity;
                    DisplayIframeDialog(url, "Your Bag Has Been Updated", 750, 450);

                } else {

                    $("#AddedToBasket").show();

                    $('html, body').animate({
                        scrollTop: $("#browseShop").offset().top
                    }, 500);

                }

            },
            type: 'POST'
        });

    });

    //Call to set the Add to List links querystring to allow the PageTemplate to be set dynamically (i.e. for when Javascript is enabled)
    AddIframeToQueryStringForTemplates();

    $(function() {
        $("#reminderHelp").dialog({
            autoOpen: false,
            modal: true,
            open: function() {
                $('.ui-widget-overlay').css('zIndex', '9000');
            },
            zIndex: 9000,
            resizable: false
        });

        $("#reminderOpener").click(function() {
            $("#reminderHelp").dialog("open");
            return false;
        });
    });

    $(function() {
        $("#wishlistHelp").dialog({
            autoOpen: false,
            modal: true,
            open: function() {
                $('.ui-widget-overlay').css('zIndex', '9000');
            },
            zIndex: 9000,
            resizable: false
        });

        $("#wishlistOpener").click(function() {
            $("#wishlistHelp").dialog("open");
            return false;
        });
    });

    setUpProductImages();

});


