/*
Project: 	Elaine Curtis 2011
Author:		IPAG (Ireland) Ltd. (KG)
Created:	13/07/2011
*/
$(document).ready(function() {
    if ($(".parentCategory").length > 0) {
        $(".parentCategory").click(function(e) {
            var ul = $(this).parent().children("ul");
            e.preventDefault();
            //alert(ul.html());
            ul.slideToggle();
        });
    }

    // Homepage brand scroller
    if ($("#buttonsBrands").length > 0) {
        $("#buttonsBrands").jcarousel({
            auto: 4,
            wrap: 'circular',
            scroll: 1,
            initCallback: buttonsBrands
        });
    }
    // Homepage main image scroller
    if ($("#theStoreImageCarousel").length > 0) {
        $("#theStoreImageCarousel").jcarousel({
            auto: 4,
            wrap: 'last',
            scroll: 1,
            itemVisibleInCallback: highlight,
            itemVisibleOutCallback: removehighlight,
            initCallback: mainImageCarousel,
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
    }

    if ($("#mainImageCarousel").length > 0) {
        $("#mainImageCarousel").jcarousel({
            auto: 4,
            wrap: 'last',
            scroll: 1,
            itemVisibleInCallback: highlight,
            itemVisibleOutCallback: removehighlight,
            initCallback: mainImageCarousel,
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
    }

    /* Sitemap */
    if ($("#sitemap").length > 0) {
        $(".items").hide();
        $(".itemWrapper h2 a").click(function(e) { e.preventDefault(); });
        $(".itemWrapper h2").click(function(e) {
            e.preventDefault();
            if ($(this).next().is(':hidden') == true) {
                $(this).addClass('on');
                $(this).next().slideDown('normal');
            } else {
                $(this).removeClass('on');
                $(this).next().slideUp('normal');
            }
        });
    }
    /* End Sitemap */

    if ($("#homeLogin input[type=text], #homeLogin input[type=password], input[type=password]").val() != "") $(this).addClass("nobg");
    $("#homeLogin input[type=text], #homeLogin input[type=password], input[type=password]").bind("focus", function() {
        if ($(this).val() == "") $(this).addClass("nobg");
    });
    $("#homeLogin input[type=text], #homeLogin input[type=password], input[type=password]").bind("blur", function() {
        if ($(this).val() == "") $(this).removeClass("nobg");
    });
    // Homepage Login box
    if ($("#homeLogin").hasClass("loggedOut")) {
        $("#butSubmit").click(function(e) {
            e.preventDefault();
            userLogin();
            $("#homeLoginFeedback").hide();
        });

        function userLogin() {
            $("#homeLoginForm").fadeOut("slow", function() {
                $("#homeLoginLoading").fadeIn("slow", function() {
                    var postData = {
                        username: $("#homeLogin input[type=text]").val(),
                        password: $("#homeLogin input[type=password]").val()
                    }
                    $.ajax({
                        type: "POST",
                        url: "ElaineCurtis.asmx/login",
                        data: postData,
                        contentType: "application/x-www-form-urlencoded; charset=utf-8",
                        dataType: "xml",
                        success: loginSuccess,
                        error: loginError
                    });
                });
            });
        }
        function loginSuccess(data) {
            var username = $(data).find("username").text();
            //$("#homeLoginFeedback").html("<h3>Welcome back " + firstName + "</h3>");
            $("#homeLoginLoading").fadeOut("slow", function() {
                $("#homeLogin").fadeOut("slow", function() {
                    $("#homeLogin").removeClass("loggedOut").addClass("loggedIn").fadeIn("slow", function() {
                        $("#homeLoginFeedback").css("padding-top", "20px").html(
              "<strong>" + username + "</strong>" +
              "<div style='float:left;margin-top:5px;padding-top:15px;'><a href='My_Profile.aspx' id='homeLoginButProfile' style='margin-right:10px;'>My Profile</a>" +
              "<a href='Logout.aspx' id='homeLoginButLogout'>Logout</a></div>"
            );
                        $("#topNavLogInOut").fadeOut("slow", function() {
                            $("#topNavLogInOut").html("<a href='Logout.aspx'>Logout</a>");
                        });
                        $("#topNavRegister").fadeOut("slow", function() {
                            $("#topNavRegister").html("<a href='My_Profile.aspx'>My Account</a>" +
				                                  "<ul>" +
					                                  "<li><a href='My_Profile.aspx'>Account Details</a></li>" +
					                                  "<li><a href='#'>Wishlist</a></li>" +
					                                  "<li><a href='View_Cart.aspx'>Shopping Bag</a></li>" +
					                                  "<li><a href='#'>Order History</a></li>" +
					                                "</ul>");
                        });
                        jqueryslidemenu.buildmenu("headerTopAccount", arrowimages);
                        $("#homeLoginFeedback, #topNavLogInOut, #topNavRegister").fadeIn("slow")
                    });
                });
            });
        }
        function loginError(data) {
            $("#homeLoginFeedback").html("Login failed. Try again.");
            $("#homeLoginLoading").fadeOut("slow", function() {
                $("#homeLoginForm").val("");
                $("#homeLoginForm, #homeLoginFeedback").fadeIn("slow");
            });
        }
    } // End Homepage Login box

    // Normal login page
    if ($("#login #txtPassword").length > 0) {
        $("#login #txtPassword").bind("focus", function() {
            if ($("#login #txtPassword").val().length === 0) $("#login #txtPassword").addClass("hasBackground").removeClass("hasNoBackground");
        });
        $("#login #txtPassword").bind("blur", function() {
            if ($("#login #txtPassword").val().length > 0) $("#login #txtPassword").addClass("hasNoBackground").removeClass("hasBackground");
        });
    }

    // Item details image scroller, image replacement and zoom.
    if ($("#itemSlider").length > 0) {
        jqZoomOptions = {
            zoomType: 'standard',
            lens: true,
            preloadImages: true,
            alwaysOn: false,
            zoomWidth: 330,
            zoomHeight: 400,
            xOffset: 30,
            yOffset: 0,
            position: 'right',
            title: false
        };
        $("#itemImage a").jqzoom(jqZoomOptions);
        $("#itemSlider").jcarousel({
            auto: 0,
            wrap: 'last',
            vertical: true,
            scroll: 1,
            initCallback: mainImageCarousel
        });
        $("#itemSlider li").bind("click", function(e) {
            e.preventDefault();
            newImage = $(this).html();
            newImageRel = $("a img", this).attr("rel");
            //alert("newImage: " + newImage + " newImageRel: " + newImageRel)
            $("#itemImage").fadeOut("fast", function() {
                $(this).empty();
                $("#itemImage").html(newImage);
                $("#itemImage img").attr("src", newImageRel);
                $("#itemImage img").attr("width", "300");
                $("#itemImage img").attr("height", "400");
                $("#itemImage a").jqzoom(jqZoomOptions);
                $("#itemImage").fadeIn("slow");
            });
        });
        $("#itemTextButtons a").bind("click", function(e) {
            e.preventDefault();
            $("#itemTextButtons a").removeClass("on");
            $(this).addClass("on");
            index = $("#itemTextButtons a").index(this);
            $("#itemTextWrapper div.on").fadeOut("fast", function() {
                $("#itemTextWrapper div.on").removeClass("on");
                $("#itemTextWrapper div").eq(index).addClass("on").fadeIn("slow");
            });
        });

        /* Shop Item Details page */
        $("#itemBottomButtons a").bind("click", function(e) {
            e.preventDefault();
            $("#itemBottomButtons a").removeClass("on");
            $(this).addClass("on");
            index = $("#itemBottomButtons a").index(this);
            // ughhhh ...
            if ($("#itemBottomMoreSlider").hasClass("on") && index != 0) {
                $("#itemBottomMoreSlider").removeClass("on").addClass("off");
                $("#itemBottomRecentlySlider").addClass("on").removeClass("off");
            } else if ($("#itemBottomRecentlySlider").hasClass("on") && index != 1) {
                $("#itemBottomRecentlySlider").removeClass("on").addClass("off");
                $("#itemBottomMoreSlider").addClass("on").removeClass("off");
            }
        });
        $("#bottomMoreSlider").jcarousel({
            auto: 0,
            wrap: 'last',
            scroll: 3
        });
        $("#bottomRecentSlider").jcarousel({
            auto: 0,
            wrap: 'last',
            scroll: 3
        });

        /* Size selection */
        if ($("#availableSizes").length > 0) {
            $("#quantity").change(function() {
                $("#quantity option:selected").each(function() {
                    $("#hiddenSelectedQuantity").val($(this).text());
                });
            });

            $("#availableSizes li a").each(function(index) {
                if ($(this).attr("rel") == 0) {
                    $(this).addClass("unavailable");
                    $(this).attr("title", "This size is sold out");
                }
            });

            $("#availableSizes li a").bind("click", function(e) {
                e.preventDefault();
                var size = $(this).html();
                var avaiableQuantity = $(this).attr("rel");
                var selectedProductID = $(this).attr("id");
                $("#availableSizes li a").removeClass("on");
                if (avaiableQuantity > 0) $(this).addClass("on");
                else $(this).addClass("unavailable");

                updateQuantity(avaiableQuantity);
                if (avaiableQuantity > 0) {
                    $("#hiddenSelectedSize").val(size);
                    $("#hiddenSelectedID").val(selectedProductID);
                } else {
                    $("#hiddenSelectedSize").val("0");
                }
                //alert("Size: " + size + " - Quantity: " + avaiableQuantity + " - Product ID: " + selectedProductID);
            });

            function updateQuantity(avaiableQuantity) {
                var updateString = "";
                var i = 1;
                $("#quantity").empty();
                if (avaiableQuantity > 0) {
                    while (i <= avaiableQuantity) {
                        updateString += "<option id='" + i + "'>" + i + "</option>";
                        i++;
                    }
                } else {
                    updateString += "<option id='0'>0</option>"
                }
                $("#quantity").html(updateString);
                $("#quantity")[0].selectedIndex = 0;
                $("#hiddenSelectedQuantity").val("1");
            }
        }
        /* End Size selection */

        /* Size guide */
        $("#sizeGuide a").bind("click", function(e) {
            e.preventDefault();
            $("#sizeGuideInfo").dialog({
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                },
                minHeight: 250,
                width: 640
            });
        });

        /* Email */
        $("#butEmail").bind("click", function(e) {
            e.preventDefault();
            $("#emailThis").dialog({
                buttons: {
                    "Send": function() {
                        sendProductEmail();
                    },
                    "Cancel": function() {
                        $(this).dialog('close');
                    }
                },
                minHeight: 250,
                width: 320
            });
        });
        function sendProductEmail() {
            // $("#hiddenProductID").val()
            $("#emailThisForm").fadeOut("fast", function() {
                $("#emailThis .loading").fadeIn("fast", function() {
                    var postData = {
                        name1: $("#txtName1").val(),
                        email1: $("#txtEmail1").val(),
                        name2: $("#txtName2").val(),
                        email2: $("#txtEmail2").val(),
                        PID: $("#hiddenProductID").val()
                    }
                    $.ajax({
                        type: "POST",
                        url: "sendEmail.asmx/sendProductEmail",
                        data: postData,
                        contentType: "application/x-www-form-urlencoded; charset=utf-8",
                        dataType: "xml",
                        success: emailSuccess,
                        error: emailError
                    });
                });
            });
            function emailSuccess(data) {
                $("#emailThis .loading").fadeOut("fast", function() {
                    $("#formResponse").html("<h3>Thank You</h3><p>Your email has been sent. Thank you for recommending Elaine Curtis.</p>");
                    $("#emailThis").dialog({
                        buttons: {
                            "Close": function() {
                                $("#txtName1").val("");
                                $("#txtEmail1").val("");
                                $("#txtName2").val("");
                                $("#txtEmail2").val("");
                                $("#formResponse").html("");
                                $("#emailThisForm").show();
                                $(this).dialog("close");
                            }
                        }
                    });
                });
            }
            function emailError() {
                $("#emailThis .loading").fadeOut("fast", function() {
                    $("#formResponse").html("<h3>Oh Dear!</h3><p>There was an error sending your email.<br />Sorry about that. Please try again later.</p>");
                    $("#emailThis").dialog({
                        buttons: {
                            "Close": function() {
                                $("#txtName1").val("");
                                $("#txtEmail1").val("");
                                $("#txtName2").val("");
                                $("#txtEmail2").val("");
                                $("#formResponse").html("");
                                $("#emailThisForm").show();
                                $(this).dialog("close");
                            }
                        }
                    });
                });
            }
        } //sendProductEmail()

        // The 'Back to List view' button
        if ($("#backToListView").length > 0) {
            $("#backToListView").attr("href", $("#backLink").attr("href"));
        }
        if ($("#pagingControlsPrev").length > 0) {
            $("#pagingControlsPrev").bind("click", function(e) {
                e.preventDefault();
                history.go(-1);
            });
        }
    }

    if ($(".registerPrivacyPolicy").length > 0) {
        $(".registerPrivacyPolicy").bind("click", function(e) {
            e.preventDefault();
            $("#registerPrivacyPolicy").dialog({
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                },
                //minHeight: 250,
                height: 400,
                width: 640
            });
        });
    }

    // Footer twitter feed
    $("#footerTweetLoading").show();
    $.jTwitter("ElaineCurtis", 1, function(posts) {
        $("#footerTweetLoading").fadeOut("slow", function() {
            $("#footerTweet").append(replaceURLWithHTMLLinks(posts[0].text));
        });
    });
    // Fix the FB stream box height
    $("#stream_content").height(150);

    // Fancy text swapper for input boxes
    $.each("input[type=text].replace", function(index) {
        if ($("input[type=text].replace").length > 0)
            clearInputDefaults($("input[type=text].replace").eq(index).attr("id"));
    });
    $.each("textarea", function(index) {
        if ($(".replace").length > 0) {
            clearTextareaDefaults($("textarea").eq(index).attr("id"));
        }
    });

    /* Make IE7 work properly ... */
    if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") {
        $("#headerLeft ul li, #headerTopAccount ul li a, #headerTopNav ul li a").hover(function() {
            $(this).addClass("on");
        }, function() { $(this).removeClass("on"); });
    }

    /* Fashion Show */
    if ($("#fashionShowWrapper").length > 0) {
        $("#fashionShowWrapper .image").click(function(e) {
            e.preventDefault();
            var pictureID = $(this).attr("rel");
            popup(pictureID);
        });

        $("#closeButton").click(function() {
            clearPopup();
            return false;
        });

        function clearPopup() {
            $('#dialog-box, #dialog-overlay, #emailThis').hide();
            $("#message-image, #dialog-message-right, #formResponse").html("");
            return false;
        }

        $(window).resize(function() {
            //only do it if the dialog box is not hidden
            //if (!$('#dialog-box').is(':hidden')) popup();
            return false;
        });

        function popup(pictureID) {
            $("#dialog-message, #dialog-box-wrapper").hide();
            $("#dialog-error").hide();
            $("#dialog-loading, #dialog-box-wrapper").show().fadeIn("fast");
            // get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            // calculate the values for center alignment
            var dialogTop = (maskHeight / 3) - ($('#dialog-box').height());
            var dialogLeft = (maskWidth / 2) - ($('#dialog-box').width() / 2);

            // assign values to the overlay and dialog box
            $('#dialog-overlay').css({ height: maskHeight, width: maskWidth }).show();
            $('#dialog-box').css({ top: "200px", left: dialogLeft }).show();

            // get the user's information
            $.ajax({
                type: "POST",
                url: "ElaineCurtis.asmx/getFashionInfo",
                data: { pictureID: pictureID },
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                dataType: "xml",
                success: loadSuccess,
                error: loadError
            });
        }
        function loadSuccess(data) {
            $xml = $(data);
            // Add the image to the popup
            $("#message-image").html("<img src='Fashion_Show/" + $xml.find('season').text() + "/main/" + $xml.find('image').text() + "' />");

            // Add the fashion show items to the popup
            $($xml).find("product").each(function() {
                var label = $(this).find("label").text();
                var description = $(this).find("description").text();
                var price = $(this).find("price").text();
                var productID = $(this).find("ID").text();
                $("#dialog-message-right").append("<div class='itemWrapper'>" +
                                            "<div class='itemInfo'>" +
                                              "<h4><a href='Product_Details.aspx?ID=" + productID + "'>" + label + "</a></h4>" +
                                              "<p><a href='Product_Details.aspx?ID=" + productID + "'>" + description + "</a></p>" +
                                              "<p><strong>" + price + "</strong></p>" +
                                            "</div>" +
                                            "<div class='itemBuy'><a href='Product_Details.aspx?ID=" + productID + "'>Add to Shopping Bag</a></div>" +
                                          "<!--itemWrapper--></div>");
            });

            var socialFacebook = "<div id='socialFacebook'><iframe src='https://www.facebook.com/plugins/like.php?href=http://elainecurtis.ie/Fashion_Show.aspx?ID=" + $xml.find('fsID').text() + "' scrolling='no' frameborder='0' style='border:none; width:220px; height:30px'></iframe></div>";
            //var socialGooglePlusOne = "<div id='socialGooglePlusOne'><g:plusone size='medium' annotation='inline' width='220' href='http://elainecurtis.ie/Fashion_Show.aspx?ID=" + $xml.find("fsID").text() + "'></g:plusone></div>";
            $.getScript('https://apis.google.com/js/plusone.js');
            var socialGooglePlusOne = "<div id='socialGooglePlusOne'><div class='g-plusone' data-size='medium' annotation='inline' width='220' data-count='true' href='http://elainecurtis.ie/Fashion_Show.aspx?ID=1'></div></div>";
            var socialTwitter = "<div id='socialTwitter'><a href='http://twitter.com/share' class='twitter-share-button' data-url='http://elainecurtis.ie/Fashion_Show.aspx?ID=" + $xml.find('fsID').text() + "' data-text='I found something great on the Elaine Curtis website!' data-count='horizontal' data-via='elainecurtis'>Tweet</a><script type='text/javascript' src='https://platform.twitter.com/widgets.js'></script></div>";
            var socialEmaiThis = "<a href='#' class='button emailThis' id='emailThisButton'>Email this</a>";
            $("#dialog-message-right-social").html(socialFacebook + socialGooglePlusOne + socialTwitter + socialEmaiThis);
            gapi.plusone.go();

            $("#emailThisButton").bind("click", function(e) {
                e.preventDefault();
                emailThis($xml.find('fsID').text());
            });

            // Display the popup
            $("#dialog-loading").fadeOut("fast", function() {
                $("#dialog-message, #dialog-box-wrapper").fadeIn("fast").show();
            }).hide();
        }
        function loadError(request, status, error) {
            $("#dialog-loading").fadeOut("fast", function() {
                $("#dialog-error").fadeIn("fast").show();
            });
        }

        // The user is looking for a specific Fashion Show item
        fsID = getParameterByName("id");
        if (fsID.length > 0) popup(fsID);

        // Email this function
        function emailThis(fsID) {
            alert("The following needs tweaking and does not actually send and email ...  (KG: 30/8/11)");
            $("#dialog-message, #dialog-box-wrapper").fadeOut("fast", function() {
                $("#emailThis").fadeIn("fast", function() { $("#emailThisForm").fadeIn(); });
                $("#butSendEmail").bind("click", function(e) { sendFashionShowEmail(e, fsID) });
                $("#butCancelEmail").bind("click", function(e) { cancelFashionShowEmail(e) });
            });

            function sendFashionShowEmail(e, fsID) {
                $("#emailThisForm").fadeOut("fast", function() {
                    $("#emailThis .loading-white").fadeIn("fast", function() {
                        var postData = {
                            name1: $("#txtName1").val(),
                            email1: $("#txtEmail1").val(),
                            name2: $("#txtName2").val(),
                            email2: $("#txtEmail2").val(),
                            PID: fsID
                        }
                        $.ajax({
                            type: "POST",
                            url: "sendEmail.asmx/sendFashionShowEmail",
                            data: postData,
                            contentType: "application/x-www-form-urlencoded; charset=utf-8",
                            dataType: "xml",
                            success: emailFSSuccess,
                            error: emailFSError
                        });
                    });
                });
            } // sendFashionShowEmail()
            function cancelFashionShowEmail(e) {
                e.preventDefault();
                clearPopup();
            } // cancelFashionShowEmail()
            function emailFSSuccess(data) {
                $("#emailThis .loading-white").fadeOut("fast", function() {
                    $("#formResponse").html("<h3>Thank You</h3><p>Your email has been sent. Thank you for recommending Elaine Curtis.</p>");
                    $("#formResponse").append("<a href='#' id='closeButtonFS' class='button close'>Close</a>");
                    $("#closeButtonFS").bind("click", function() { clearPopup(); });
                });
            }
            function emailFSError() {
                $("#emailThis .loading-white").fadeOut("fast", function() {
                    $("#formResponse").html("<h3>Oh Dear!</h3><p>There was an error sending your email.<br />Sorry about that. Please try again later.</p>");
                    $("#formResponse").append("<a href='#' id='closeButtonFS' class='button close'>Close</a>");
                    $("#closeButtonFS").bind("click", function() { clearPopup(); });
                });
            }
        } // emailThis()
    } // fashionShowWrapper

    /* Auto-expand any textboxes */
    if ($("textarea").length > 0) {
        $("textarea").autoResize({
            // On resize:
            onResize: function() {
                $(this).css({ opacity: 1 });
            },
            // After resize:
            animateCallback: function() {
                $(this).css({ opacity: 1 });
            },
            // Quite slow animation:
            animateDuration: 300,
            // More extra space:
            extraSpace: 40
        });
    }

    //if ($(".chzn-select").length > 0) {
    //$(".chzn-select").chosen();
    //}
    /* Shopping Cart */
    /* Size guide */
    $("#shippingInfoLink, #shippingInfoLink2").bind("click", function(e) {
        e.preventDefault();
        $("#shippingInfo").dialog({
            buttons: {
                "Close": function() {
                    $(this).dialog("close");
                }
            },
            minHeight: 250,
            width: 320
        });
    });
    /* CCV Info */
    $("#CCVInfoLink").bind("click", function(e) {
        e.preventDefault();
        $("#CCVInfo").dialog({
            buttons: {
                "Close": function() {
                    $(this).dialog("close");
                }
            },
            minHeight: 250,
            width: 320
        });
    });
    /* Terms and Conditions on final cart page */

    if ($(".chkTC").length > 0) {
        /* Terms and Conditions popup */
        $(".TCClick").bind("click", function(e) {
            e.preventDefault();
            $("#TCClick").dialog({
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                },
                maxHeight: 250,
                width: 980,
                open: function(event, ui) {
                    $(this).css({ "max-height": 400, "overflow-y": "auto" });
                },
                position: "top"
            });
        });

        $(function() { // this line makes sure this code runs on page load
            $(".chkTC").click(function() {
                $(".chkTC").attr("checked", this.checked);
            });
        });
    }

    /* Google Map */
    if ($("#map").length > 0) {
        $.getScript("include/jquery.gmap.min.js", function() {
            popupString = "<img src='images/template/mapsLogo.jpg' width='140' height='140' alt='Elaine Curtis Carlow' />" +
      "<h3>Elaine Curtis</h3>" +
      "<address>Exchequer House,<br/> Potato Market,<br/> Carlow,<br/> Ireland</address>" +
      "<p style='margin-left: 88px'><strong>T:</strong> +353 59 914 1790<br />" +
      "<a href='mailto:hello@elainecurtis.ie'>hello@elainecurtis.ie</a></p>";
            $("#map").gMap({ markers: [{ latitude: 52.835513,
                longitude: -6.92921,
                html: popupString,
                popup: true}],
                zoom: 15,
                latitude: 52.838250,
                longitude: -6.925
            });
        });
    }

    /* Newsletter signup */
    $("#butNewsletterEmail").bind("click", function(e) {
        e.preventDefault();
        emailAddress = $("#txtNewsletterEmail").val();
        phoneNumber = $("#txtPhoneNumber").val();

        // if the phone number is not a number and the email is invaild
        if ((isNaN(phoneNumber) && !isValidEmail(emailAddress))) {
            $("#newsletterFeedback").text("Invalid email adddress / phone number (numbers only)");
        }
        else { newsletterSignup(); }
        //if (isValidEmail(emailAddress)) {
        //  newsletterSignup(emailAddress);
        //} else {
        //  $("#newsletterFeedback").text("Please enter a valid email adddress.");
        //}
    });
    function newsletterSignup() {
        $("#newsletterSignupForm").fadeOut("slow", function() {
            $("#loadingNewsletter").fadeIn("slow", function() {
                emailAddress = $("#txtNewsletterEmail").val();
                phoneNumber = $("#txtPhoneNumber").val();
                if (phoneNumber == "Your mobile number") phoneNumber = "";
                if (emailAddress == "Your email address") emailAddress = "";

                var postData = {
                    emailAddress: emailAddress,
                    phoneNumber: phoneNumber
                }
                $.ajax({
                    type: "POST",
                    url: "ElaineCurtis.asmx/newsletterSignup",
                    data: postData,
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    dataType: "xml",
                    success: newslettterSignupSuccess,
                    error: newslettterSignupError
                });
            });
        });
    }

    function newslettterSignupSuccess(data) {
        $("#loadingNewsletter").fadeOut("slow", function() {
            $("#newsletterFeedback").text("You have signed up to the Elaine Curtis newsletter. Thank you.");
        });
    }
    function newslettterSignupError(data) {
        $("#loadingNewsletter").fadeOut("slow", function() {
            $("#newsletterFeedback").text("There was a problem adding your address to our mailing list, try again later. Sorry about that.");
        });
    }

    /* End Newsletter signup */

    /* Shop by Style */
    if ($("#shopStyle a").length > 0) {
        $("#shopStyle a").each(function(index) {
        });
    }

    /* Brands Info */
    /*$("#brands a").click(function(e) {
    // Prevent user from leaving the page
    e.preventDefault();
    // Get the ID of the brand
    var brandID = $(this).attr("href");
    var arrBrandID = brandID.split("=");
    brandID = arrBrandID[1];

  var postData = {
    iBrandID: brandID
    }
    $.ajax({
    type: "POST",
    url: "ElaineCurtis.asmx/getBrandInfo",
    data: postData,
    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    dataType: "xml",
    success: brandSuccess,
    error: brandFail
    });

  function brandSuccess() {
    alert("SUCCESS!");
    }
    function brandFail() {
    alert("FAIL WHALE");
    }
    });*/
    /* End Brand info */

    if ($("input[type=text].password").length > 0) {
        $("input[type=text].password").bind("blur", function() { $(this).addClass("password"); });
        $("input[type=text].password").bind("focus", function() { $(this).removeClass("password"); });
    }
});   // ready()

// Homepage brand scroller
function buttonsBrands(carousel) {
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

// Homepage main image scroller
function mainImageCarousel(carousel) {
    $(".jcarousel-control a").bind("click", function() {
        carousel.scroll(jQuery.jcarousel.intval($(this).text()));
        return false;
    });

    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};
function highlight(carousel, obejctli, liindex, listate) {
    currentHighlight = ((liindex - 1) % $(".jcarousel-control a").size());
    jQuery('.jcarousel-control a:eq(' + currentHighlight + ')').attr("class", "on");
};
function removehighlight(carousel, obejctli, liindex, listate) {
    currentHighlight = ((liindex - 1) % $(".jcarousel-control a").size());
    jQuery('.jcarousel-control a:eq(' + currentHighlight + ')').removeAttr("class", "on");
};

// Parse text and replace text with links
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
}

/* Fancy text swapper */
function clearInputDefaults(inputID) {
    if ($("#" + inputID).length > 0) {
        var ctrlID = ("#" + inputID);
        var defTxt = $(ctrlID).val();
        $(ctrlID).focus(function() { if ($(this).val() == defTxt) $(this).val(''); });
        $(ctrlID).blur(function() { if ($(this).val() == '') $(this).val(defTxt); });
    }
}
function clearTextareaDefaults(inputID) {
    if ($("#" + inputID).length > 0) {
        var ctrlID = ("#" + inputID);
        var defTxt = $(ctrlID).html();
        $(ctrlID).bind("focus", function() { if ($(this).html() == defTxt) $(this).html(""); });
        $(ctrlID).bind("blur", function() { if ($(this).val() == '') $(this).val(defTxt); });
        //$(ctrlID).focus(function() { if ($(this).val() == defTxt) $(this).val(''); });
        //$(ctrlID).blur(function() { if ($(this).val() == '') $(this).val(defTxt); });
    }
}

// Parse the query string - see: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Valid email address?
function isValidEmail(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}
