var FS = FS || {};

$(document).ready(function() {

    // ensure the loading image loads early
    $.imgpreload($("#loading").css('background-image').replace(/"/g, "").replace(/url\(|\)$/ig, ""), function() { });
    $.imgpreload($("#loading #loading-bar").css('background-image').replace(/"/g, "").replace(/url\(|\)$/ig, ""), function() { });


//    function enterLounge() {
//        var axel = Math.random() + "";
//        var a = axel * 10000000000000;
//        $("body").prepend($('<iframe src="http://fls.doubleclick.net/activityi;src=2827754;type=fours769;cat=regis789;ord=1;num=' + a + '?" width="1" height="1" frameborder="0"></iframe>'));
//    }

//    function registerLounge() {
//        var axel = Math.random() + "";
//        var a = axel * 10000000000000;
//        $("body").prepend($('<iframe src="http://fls.doubleclick.net/activityi;src=2827754;type=fours769;cat=regis336;ord=1;num=' + a + '?" width="1" height="1" frameborder="0"></iframe>'));
//    }



    if ($('li.active').length === 0) {
        $('li.home').addClass('active');
        //SWFAddress.setValue('home');
    }

    // add ajax deep link events
    $("a.ajax").each(function() {
        $(this).click(function() {
            var link = $(this).attr("href");

            if (window.location.hash.slice(1) != link) {
                if (link === '/') link = '/home';
                SWFAddress.setValue(link);
            }
            return false;
        });
    });

    // promo arrow animation
    animate_arrow = function() {
        $("#promo-arrow").delay(5000).animate({ left: "-=10px" }, 400).animate({ left: "+=15px" }, 300).animate({ left: "-=5px" }, 400, animate_arrow);
    }

    animate_arrow();

    // special behaviour for news articles back button.
    $(".news-item a.back-button").click(function() {
        $("#news-list-section").hide();
        $("#pager").hide();
        var link = $(this).attr("href");
        if (window.location.hash.slice(1) != link) {
            SWFAddress.setValue(link);
        }
        return false;
    });

    // close the lightbox when the cross is clicked
    $("#content .trade-resources .wine .close").click(function() {
        $("#content .trade-resources .modal").fadeOut();
        $("#content .trade-resources .wine").hide();
        return false;
    });

    // create an anchor to close the lightbox in IE6 over the VML shape which is not clickable
    if ($.browser.msie && $.browser.version == "6.0") {
        $("#content .trade-resources .wine .ie6_close").click(function() {
            $("#content .trade-resources .modal").fadeOut();
            $("#content .trade-resources .wine").hide();
            return false;
        });
    }

    // show the lightbox when one of the wines with two choices is clicked
    $("#content .trade-resources .label a").click(function() {
        var wine = $(this).attr("class").replace(/ lightbox invisible/, "");
        var popup = $("#content .trade-resources .wine-label-" + wine);
        if (popup.length === 0) return true;

        $("#content .trade-resources .modal").css({ opacity: 0 }).show().animate({ opacity: .5 }, 1000, function() {
            $("#content .trade-resources .matrix").addClass("modal-active");
            $("#content .trade-resources .wine-label-" + wine).show();
            if ($.browser.msie) {
                $("#content .trade-resources .wine-label-" + wine).css({ opacity: 1 });
                $("#content .trade-resources .wine-label-" + wine + " .close").css({ opacity: 1 });
            }
        });
        return false;
    });


    // show the lightbox when one of the wines with two choices is clicked
    $("#content .trade-resources .bottle a").click(function() {
        var wine = $(this).attr("class").replace(/ lightbox invisible/, "");
        var popup = $("#content .trade-resources .wine-bottle-" + wine);
        if (popup.length === 0) return true;

        $("#content .trade-resources .modal").css({ opacity: 0 }).show().animate({ opacity: .5 }, 1000, function() {
            $("#content .trade-resources .matrix").addClass("modal-active");
            $("#content .trade-resources .wine-bottle-" + wine).show();
            if ($.browser.msie) {
                $("#content .trade-resources .wine-bottle-" + wine).css({ opacity: 1 });
                $("#content .trade-resources .wine-bottle-" + wine + " .close").css({ opacity: 1 });
            }
        });
        return false;
    });

    // show the lightbox when one of the wines with two choices is clicked
    $("#content .trade-resources .tasting-note a").click(function() {
        var wine = $(this).attr("class").replace(/ lightbox invisible/, "");
        var popup = $("#content .trade-resources .tasting-notes-" + wine);
        if (popup.length === 0) return true;

        $("#content .trade-resources .modal").css({ opacity: 0 }).show().animate({ opacity: .5 }, 1000, function() {
            $("#content .trade-resources .matrix").addClass("modal-active");
            $("#content .trade-resources .tasting-notes-" + wine).show();
            if ($.browser.msie) {
                $("#content .trade-resources .tasting-notes-" + wine).css({ opacity: 1 });
                $("#content .trade-resources .tasting-notes-" + wine + " .close").css({ opacity: 1 });
            }
        });
        return false;
    });

    // close the lightbox if the esc key is pressed
    $(document).keydown(function(key) {
        if (key.keyCode == 27) {
            if ($("#content .trade-resources .modal").is(":visible")) {
                $("#content .trade-resources .modal").fadeOut();
                $("#content .trade-resources .wine").hide();
            }
        }
    });

//    // conact us.
//    $("#contact-form form").submit(function() {
//        $("#contact-form .feedback").html("Sending..").fadeIn(500);
//        formData = $("#contact-form form").serialize() + "&ajax=true";
//        $.ajax({
//            type: "POST",
//            url: "/contact",
//            data: formData,
//            dataType: "html",
//            success: function(e) {
//                $("#contact-form .feedback").hide().html(e).fadeIn(500);
//                if (e.toString().indexOf("successMessage") > 0) {
//                    $("#contact-form .input").val("");
//                    $("#contact-form .textarea").val("");
//                }
//            },
//            error: function(data) {
//                $("#contact-form .feedback").fadeOut(500).html("Sorry, an error occured sending feedback.").fadeIn(500);
//            }
//        });
//        return false;
//    });




    // subscribe us.
//    $("#lounge-form form").submit(function() {
//        $("#lounge-form .feedback").html("Sending..").fadeIn(500);
//        formData = $("#lounge-form form").serialize();
//        $.ajax({
//            type: "POST",
//            url: "/register",
//            data: formData,
//            dataType: "json",
//            success: function(e) {

//                if (e.Success) {
//                    $(".lounge div").filter(function(index) { return $(this).attr("id") != "welcome" }).remove();
//                    $(".lounge #welcome").fadeIn(500);
//                    $("#content .lounge").css("background-position", "right bottom");
//                    registerLounge();
//                }
//                else {
//                    var error = "";

//                    if (e.Errors.length > 2) {
//                        error = "All fields must be completed";
//                    } else {
//                        error += "<ul>";
//                        for (var i = 0; i < e.Errors.length; i++) {
//                            error += "<li>" + e.Errors[i].Message + "</li>";
//                        }
//                        error += "</ul>"
//                    }

//                    $("#lounge-form .feedback").hide().html(error).fadeIn(500);
//                }
//            },
//            error: function(data) {
//                $("#lounge-form .feedback").fadeOut(500).html("Sorry, an error occured sending feedback.").fadeIn(500);
//            }
//        });
//        return false;
//    });


    FS.cycle = function(page) {
        var base_selectors = ["#title", "#main-left", "#content"];
        var images = [];

//        if (page === "lounge") {
//            enterLounge();
//        }

        for (index in base_selectors) {
            var base = base_selectors[index];
            $old = $(base + " li.active");
            $new = $(base + " li." + page);

            if ($old.css('background-image') == $new.css('background-image') && $old.css('background-image') != "none" && $new.css('background-image') != "none") {
                continue;
            }

            // compile a list of all of the images on the upcoming page for preloading
            $(base + " li." + page + ", " + base + " li." + page + " *").each(function() {
                if ($(this).css('background-image') != "none") {
                    images.push($(this).css('background-image').replace(/"/g, "").replace(/url\(|\)$/ig, ""));
                }
                if ($(this)[0].tagName.toLowerCase() == "img") {
                    images.push($(this).attr("src"));
                }
            });
        };

        fade = function() {
            $("#loading").hide();
            for (index in base_selectors) {
                var base = base_selectors[index];
                $old = $(base + " li.active");
                $new = $(base + " li." + page);

                if ($old.css('background-image') == $new.css('background-image') && $old.css('background-image') != "none" && $new.css('background-image') != "none") {
                    continue;
                }


                if (base == "#main-left" && $.browser.msie) {
                    //under IE7/8 this leaves a clean transiton, albeit without the fade effect
                    $new.delay(500).show(0, function() {
                        $(this).addClass("active");
                    });
                    $old.delay(500).hide(0, function() {
                        $(this).removeClass("active");
                    });
                    //under IE7/8 this leaves a dark area behind the alpha transparency while transitioning, but is normal after
                    /*$new.fadeIn(1000, function () {
                    $(this).addClass("active");
                    });
                    $old.fadeOut(1000, function () {
                    $(this).removeClass("active");
                    });*/
                } else {
                    $new.css("opacity", 0).show().animate({ opacity: 1 }, 1000, function() {
                        $(this).css({ display: "block" });
                        $(this).addClass("active");

                        // scroll bars
                        try {
                            if (page == "where-to-buy") {
                                $("#where-to-buy .inner").jScrollPane({ scrollbarWidth: 10, scrollbarMargin: 10, showArrows: true });
                            }
                            if (page == "terms-of-use") {
                                $("#terms-of-use .inner").jScrollPane({ scrollbarWidth: 10, scrollbarMargin: 10, showArrows: true });
                            }
                            if (page == "privacy-policy") {
                                $("#privacy-policy .inner").jScrollPane({ scrollbarWidth: 10, scrollbarMargin: 10, showArrows: true });
                            }
                            if (page == "news-item") {
                                $("#news-content-pane").fadeIn(500);
                                $("#news-content-pane").jScrollPane({ scrollbarWidth: 10, scrollbarMargin: 10, showArrows: true })
                            }
                            if (page == "news") {
                                $("#news-list-section").fadeIn(500);
                                $("#pager").fadeIn(500);
                            }

                        } catch (e) {
                            //suppress the exception
                        }
                    });

                    $old.animate({ opacity: 0 }, 1000, function() {
                        $(this).hide();
                        $(this).removeClass("active");
                    });
                }

                // highlight the active navigation and footer menu
                if (page.indexOf("--") > 0) {
                    pages = page.split("--");
                    $("#navigation li a").removeClass("active");
                    $("#navigation li." + pages[0] + " a").addClass("active");
                    $("#footer-menu li a").removeClass("active");
                    $("#footer-menu li." + pages[1] + " a").addClass("active");
                } else {
                    var menuPage = page;
                    if (page == "news-item") {
                        menuPage = "news";
                    }
                    $("#navigation li a").removeClass("active");
                    $("#navigation li." + menuPage + " a").addClass("active");
                    $("#footer-menu li a").removeClass("active");
                }
            }
        }

        if (images.length == 0) {
            fade();
        }
        else {
            $("#loading").show();
            $.imgpreload(images, fade);
        }

        // start preloading the images for the coming page
    }

//    show_news_item = function(page) {
//        $("#news-content-pane").html("Loading..");
//        $("#news-content-pane").hide();
//        $.ajax({
//            url: "/news-item-ajax/" + page.slice(11),
//            global: false,
//            type: "POST",
//            data: ({ ajax: true }),
//            dataType: "html",
//            success: function(msg) {
//                $("#news-content-pane").empty().append($(msg));
//                // wait to ensure display has transitioned
//                window.setTimeout(function() {
//                    try {
//                        $("#news-content-pane").jScrollPane({ scrollbarWidth: 10, scrollbarMargin: 10, showArrows: true });
//                    } catch (e) {
//                        // suppress exception
//                    };
//                }, 2000);
//            },
//            error: function(msg) {
//                $("#news-item-body .inner").html("Sorry, it seems there was an error loading your article.");
//            }
//        });
//    }

//    show_news_list = function(page) {
//        $("#news-list").remove();
//        $("#pager").hide();
//        $("#news-list-section").html("Loading..");

//        // set active page
//        $('a[href^="/news/"]').removeClass("active");
//        $('a[href="/news/' + page.slice(6) + '"]').addClass("active");

//        $.ajax({
//            url: "/news-list/" + page.slice(6),
//            global: false,
//            type: "POST",
//            data: ({ ajax: true }),
//            dataType: "html",
//            success: function(msg) {
//                $("#news-list-section").hide().html(msg).fadeIn(1000);
//                $("#pager").fadeIn(1000);
//                // rewire readmore events
//                $("a.read-more").each(function() {
//                    $(this).click(function() {
//                        var link = $(this).attr("href");
//                        // IE6-7 return full url(!). Slice off what we need.
//                        link = "news-item" + link.slice(link.lastIndexOf("/"))
//                        if (window.location.hash.slice(1) != link) {
//                            SWFAddress.setValue(link);
//                        }
//                        return false;
//                    });
//                });

//            },
//            error: function(msg) {
//                $('a[href^="news/"]').removeClass("active");
//                $("#news-list-section").html("Sorry, it seems there was an error loading news items.");
//            }
//        });
//    };

    FS.handle_change = function(event) {
        var page = event.path.slice(1).replace(/\//, "--");

        if (page == "") {
            return;
        }

        if (page.substr(0, 9) == "news-item") {
            show_news_item(page);
            page = "news-item";
        }

        if (page.substr(0, 6) == "news--") {
            show_news_list(page);
            page = "news";
        }
        FS.cycle(page);
    }

    SWFAddress.addEventListener(SWFAddressEvent.CHANGE, FS.handle_change);

});


$(function() {

    // Setup terms link click events
    $('#terms_link').click(function(e) {
        e.preventDefault();
        $('#terms_dialog').dialog('open');
        if ($.browser.msie && $.browser.version == "6.0") {
            $("select").css("display", "none");
        }
        return false;
    });

    // Setup dialog and download content
    $("#terms_link").each(
        function(link) {

            var content = $('<div />').attr("id", "terms_content").text("Loading..")
            var container = $('<div />').attr("id", "terms_dialog").attr("title", "Terms and Conditions").css("display", "none");

            $('body').append(container.append(content));

            $('#terms_dialog').dialog({
                autoOpen: false,
                width: 960,
                height: 600,
                buttons: {
                    "": function() {
                        $(this).dialog("close");
                    }
                },
                close: function() {
                    $("select").css("display", "block");
                },
                modal: true
            });

            var url = $("#terms_link").attr('href') + window.location.search.substring(0);
            $.ajax({
                type: "POST",
                url: url,
                success: function(data) {
                    //$(data).find("#terms").html()
                    //alert($(data).find("#terms").html());
                    $('#terms_content').html(data);
                },
                error: function() {
                    $('#terms_content').html("Error Loading Terms and Condititions");
                }
            });
        });
});