﻿// for intellisense
/// <reference path="jquery-1.3.2.js" />
/// <reference path="jquery.jcarousel.js" />

var yuunik = yuunik || {};

// settings for the yuunik web site
yuunik.settings = {
    designsCountToDisplayOnRow: 7,
    desingsRows: 2,
    own_design_id: -1
};

yuunik.analytics = {
    track: function(url) {
        // check if the disable_analytics meta tag is not specified
        if ($("meta[name=disable_analytics]").length == 0) {
            _gaq.push(['_trackPageview', url]);
        };
    }
};

yuunik.buy = {
    add_to_shopping_cart: function(event) {
        prodProdId = $("#prodprodid").text();

        // get item count
        var count = yuunik.personalized_product.getItemCount();

        var configurations = yuunik.personalized_product.get_product_configurations();

        yuunik.shopping_cart.addOrderItem(prodProdId, configurations, count,
            function() {
                // delay the showing of shopping cart by 500ms to allow the server to generate the image
                window.setTimeout(yuunik.shopping_cart_overview_dlg.show, 500);
            }
        );

        return false;
    },

    updatePrice: function(productId, properties) {
        yuunik.ajax.load("/Product/Price/", { productId: productId, propertyValuePairs: properties }, "#product_price");
    }
}

yuunik.select_design_hint = {
    show: function() {
        $("#select_design_hint").show(500);
    },

    hide: function() {
        $("#select_design_hint").hide(500);
    }
}

yuunik.configurator_help = {
    current_timer: null,

    init: function() {
        $("#configurator_help_button")
            .bind("click", yuunik.configurator_help.on_help_button_clicked)
            .bind("mouseleave", yuunik.configurator_help.on_help_button_mouseleave);
    },

    on_help_button_clicked: function() {
        if (yuunik.configurator_help.current_timer != null) {
            window.clearTimeout(yuunik.configurator_help.current_timer);
            yuunik.configurator_help.current_timer = null;
        }

        $("#configurator_help").show();

        return false;
    },

    on_help_button_mouseleave: function() {
        yuunik.configurator_help.current_timer = window.setTimeout(
            function() {
                $("#configurator_help").hide();
                yuunik.configurator_help.current_timer = null;
            }, 5000
        );

        return false;
    }
}

yuunik.personalized_product = {
    map_property_images_to_url: null,

    // the currently selected design
    current_design_id: 0,
    current_configurator_img: "",
    current_design_author: "",
    current_design_author_url: "",
    current_user_design_id: "",
    current_design_ratio: 1.0,

    // the currently selected products
    productId: 0,

    // saves the infos about the current design to a session cookie
    saveCurrentDesignInfos: function () {
        var design_infos =
            {
                id: yuunik.personalized_product.current_design_id,
                config_img: yuunik.personalized_product.current_configurator_img,
                author: yuunik.personalized_product.current_design_author,
                author_url: yuunik.personalized_product.current_design_author_url,
                user_design_id: yuunik.personalized_product.current_user_design_id,
                ratio: yuunik.personalized_product.current_design_ratio
            };

        $.cookie("design_infos", JSON.stringify(design_infos), { path: "/Konfigurator" });
    },

    // if available retrieves the infos about the current design from the session cookie
    retrieveCurrentDesignInfos: function () {
        var str_design_infos = $.cookie("design_infos");
        if (str_design_infos != null) {
            var design_infos = JSON.parse(str_design_infos);

            yuunik.personalized_product.current_design_id = design_infos.id;
            yuunik.personalized_product.current_configurator_img = design_infos.config_img;
            yuunik.personalized_product.current_design_author = design_infos.author;
            yuunik.personalized_product.current_design_author_url = design_infos.author_url;
            yuunik.personalized_product.current_user_design_id = design_infos.user_design_id;
            yuunik.personalized_product.current_design_ratio = design_infos.ratio;

            // display the saved design
            yuunik.personalized_product.set_design_on_current_tab();
        }
    },

    getProperties: function () {
        var properties = $("#prod_properties").serializeArray();

        array_len = properties.length;

        // temp product specific fields
        if (yuunik.personalized_product.productId == 149)
            array_len = array_len - 2;
        // temp product specific fields

        // convert the properties to a string array
        // since i did not find a way to send the properties as an object array
        // the objects should be simple object with two properties name and value
        var propertiesArray = new Array(array_len);

        for (var i = 0; i < properties.length; i++) {
            // temp product specific fields
            if (properties[i].name.substring(0, 8) != "exclude_")
                propertiesArray[i] = properties[i].name + ":" + properties[i].value;
        }

        return propertiesArray;
    },

    get_product_configurations: function () {
        // creates the configurations array
        var configurations = new Array();

        var $product_views_tab = $("#prod_imgs");
        var selected_tab = yuunik.personalized_product.get_current_previews_tab_index();

        // gets the values from the html elements
        $("#prod_imgs > ul > li").each(function (index) {
            var $this = $(this);

            // select the tab in order to get the right coordinates from get_design_area
            $product_views_tab.tabs("select", index);

            // gets the display design area
            var preview_div_id = $("a", $this).attr("href");
            var $preview_div = $(preview_div_id);
            var $d_d = $(".d_d", $preview_div);

            var design_id = $d_d.attr("design_id");
            var user_design_id = $d_d.attr("user_design_id");
            var design_position = { left: 0, top: 0, width: 0, height: 0 };

            if (design_id != 0) {
                design_position = yuunik.personalized_product.get_design_position($preview_div, $d_d);
            }

            configurations[index] = {
                preview_id: $this.attr("previewid"),
                design_id: design_id,
                design_pos_left: design_position.left,
                design_pos_top: design_position.top,
                design_pos_width: design_position.width,
                design_pos_height: design_position.height,
                user_design_id: user_design_id
            }
        });

        // select the previously selected tab
        $product_views_tab.tabs("select", selected_tab);

        return JSON.stringify(configurations)
    },

    get_design_position: function ($preview_div, $d_d) {
        pos = $d_d.offset();
        pos_preview_container = $(".preview_container", $preview_div).offset();

        // returns the absolute values for left and top
        // since on FF sometimes these values are float, always convert them to int
        return {
            left: parseInt(pos.left - pos_preview_container.left + 0.5),
            top: parseInt(pos.top - pos_preview_container.top + 0.5),
            width: parseInt($d_d.width() + 0.5),
            height: parseInt($d_d.height() + 0.5)
        };
    },

    // gets the key for the map containing the detailed imgurls
    // the key consist of the values of the properties with images concatenated as string
    get_selected_props_with_img_values: function () {
        var selected_values = "";
        $("#prod_properties select[hasimg='True']").each(function () {
            var $this = $(this);

            selected_values += $this.val() + " ";
        });

        return selected_values;
    },

    getItemCount: function () {
        var count = $("#ord_item_count").val();

        return count;
    },

    onPropertyChange: function () {
        // update the producers list based on the selected properties
        var properties = yuunik.personalized_product.getProperties();

        yuunik.buy.updatePrice(yuunik.personalized_product.productId, properties);

        // also update the product image based on the selected properties
        var selected_values = yuunik.personalized_product.get_selected_props_with_img_values();

        // update the product images on all the tabs
        yuunik.personalized_product.update_product_imgs(selected_values);

        return false;
    },

    onPropertyFocus: function (event) {
        var target = (event.target) ? event.target : event.srcElement;
        var $select = $(target);

        propertyId = $select.attr("name");

        // gets the element used for positioning the values description
        var $values_descr_pos = $("#values_descr_pos_" + propertyId);

        var offset = $values_descr_pos.offset();

        var offset_parent = $select.parent().offset();

        var $valuesDescription = $("#values_descr_" + propertyId);
        if ($valuesDescription.length > 0) {
            $valuesDescription
                .css("left", (offset.left - offset_parent.left + 5) + "px")
                .css("top", (offset.top - offset_parent.top + 5) + "px")
                .show();
        }
    },

    onPropertyBlur: function (event) {
        var target = (event.target) ? event.target : event.srcElement;
        var $select = $(target);

        propertyId = $select.attr("name");

        var $valuesDescription = $("#values_descr_" + propertyId);
        $valuesDescription.hide();
    },

    init_remove_design: function () {
        $("#remove_design").bind("click", yuunik.personalized_product.on_remove_design);
    },

    on_remove_design: function () {
        var $preview_div = yuunik.personalized_product.get_current_preview_div();
        var $design_area = $(".design_area", $preview_div);

        if ($design_area.attr("inited") != undefined) {

            // remove the desing and hide the design display
            $(".d_d", $preview_div).attr("src", "").addClass("hidden").attr("design_id", "0").attr("user_design_id", "");

            // remove the reference to the design's author and url
            $(".design_author_c", $preview_div).text("");
            $(".design_author_url_c", $preview_div).attr("href", "").text("").addClass("hidden");

            // hide the design area and remove the resizable and draggable functionality
            $design_area.addClass("hidden");

            // the the resize hanle
            var $pos_resize_handle = $(".pos_resize_d_d", $design_area.siblings(".pos_resize_d_d_parent"));

            $pos_resize_handle
                .resizable("destroy")
                .draggable("destroy")
                .removeClass("cursor_pointer");

            // remove the init flag from the design area
            $design_area.removeAttr("inited");

            // show the hint to select a design
            yuunik.select_design_hint.show();
        }

        return false;
    },

    prepare_product_view: function () {
        var products_display = $("#products");

        // when the view is loaded create the images tab
        $("#prod_imgs", products_display).tabs();

        // set the events on the currently downloaded page
        $("select.update", products_display)
            .bind("change", yuunik.personalized_product.onPropertyChange)
            .bind("focus", yuunik.personalized_product.onPropertyFocus)
            .bind("blur", yuunik.personalized_product.onPropertyBlur);

        yuunik.personalized_product.init_remove_design();

        // also fire the change event, to load the price info
        yuunik.personalized_product.onPropertyChange();
    },

    // sets the design to be displayed in the product view
    set_design_on_current_tab: function () {
        if (yuunik.personalized_product.current_design_id !== 0) {
            // hide the hint to select a design
            yuunik.select_design_hint.hide();

            // get the currently selected preview
            var $preview_div = yuunik.personalized_product.get_current_preview_div();

            // display the design on the current tab's product image
            yuunik.personalized_product.set_design_display_on_tab($preview_div);

            // display the desing area and make it resizable and draggable
            yuunik.personalized_product.set_design_area($preview_div);
        }
    },

    set_design_on_all_tabs: function () {
        if (yuunik.personalized_product.current_design_id !== 0) {
            // hide the hint to select a design
            yuunik.select_design_hint.hide();

            $(".prod_preview").each(
                function () {
                    var $preview = $(this);

                    // display the design on the current tab's product image
                    yuunik.personalized_product.set_design_display_on_tab($preview);

                    // display the desing area and make it resizable and draggable
                    yuunik.personalized_product.set_design_area($preview);
                }
            );
        }
    },

    set_design_display_on_tab: function ($preview_div) {
        $(".d_d", $preview_div)
            .attr("src", yuunik.personalized_product.current_configurator_img)
            .removeClass("hidden")
            .attr("design_id", yuunik.personalized_product.current_design_id)
            .attr("user_design_id", yuunik.personalized_product.current_user_design_id);

        // if specified show the design's author
        if (yuunik.personalized_product.current_design_author != undefined && yuunik.personalized_product.current_design_author.length != 0) {
            $(".design_author_c", $preview_div).text("Design by " + yuunik.personalized_product.current_design_author);
        }
        else {
            $(".design_author_c", $preview_div).text("");
        }

        // if specified show the design's author's url
        if (yuunik.personalized_product.current_design_author_url != undefined && yuunik.personalized_product.current_design_author_url.length != 0) {
            $(".design_author_url_c", $preview_div)
                .attr("href", "http://" + yuunik.personalized_product.current_design_author_url)
                .text(yuunik.personalized_product.current_design_author_url)
                .removeClass("hidden");
        }
        else {
            $(".design_author_url_c", $preview_div).attr("href", "").text("").addClass("hidden");
        }
    },

    set_design_area: function ($preview_div) {
        // also make the design resizable and draggable
        $(".design_area", $preview_div).each(function () {
            var $design_area = $(this);

            var $pos_resize_handle = $(".pos_resize_d_d", $design_area.siblings(".pos_resize_d_d_parent"));

            if ($design_area.attr("inited") == undefined) {
                // show the design area since now there is a selected design
                $design_area.removeClass("hidden");

                $pos_resize_handle
                        .resizable({
                            handles: 'all',
                            // containment: 'parent',
                            autoHide: true,
                            aspectRatio: true,
                            resize: yuunik.personalized_product.resize_design
                        })
                        .draggable({
                            // containment: $pos_resize_handle.parents(".preview_container"),
                            drag: yuunik.personalized_product.drag_design
                        })
                        .addClass("cursor_pointer");

                // if the autoHide property is changed after init, the change of value is ignored
                // so in order to show the handles the first time call the show function on the resizable handles
                $(".ui-resizable-handle", $pos_resize_handle).show();

                // mark as initialized
                $design_area.attr("inited", "1");
            }

            // position the design according to width/height ratio
            yuunik.personalized_product.position_design($design_area, $pos_resize_handle);
        });
    },

    position_design: function ($design_area, $pos_resize_handle) {
        ratio = parseFloat(yuunik.personalized_product.current_design_ratio);

        if (ratio == NaN)
            ratio = 1.0;

        // get the width and height of the design area
        design_area_width = $design_area.width();
        design_area_height = $design_area.height();

        // try to see if the design will fit horizontally or vertically
        design_height = design_area_width / ratio;
        design_width = design_area_width;
        if (design_height > design_area_height) {
            design_width = design_area_height * ratio;
            design_height = design_area_height;
        }

        pos_left = (design_area_width - design_width) / 2;
        pos_top = (design_area_height - design_height) / 2;

        // set the position and size for the design
        $(".d_d", $design_area)
            .css("left", pos_left).css("top", pos_top)
            .css("width", design_width).css("height", design_height);

        // set the size for the resize handles
        $pos_resize_handle
            .css("left", pos_left).css("top", pos_top)
            .css("width", design_width).css("height", design_height);
    },

    show_resize_handles: function () {
        $(".ui-resizable-handle").show();
    },

    hide_resize_handles: function () {
        $(".ui-resizable-handle").hide();
    },

    get_current_previews_tab_index: function () {
        // get the current tab index
        var selected_index = $("#prod_imgs").tabs('option', 'selected');

        // when there is only one tab, the selected option always returns -1
        if (selected_index == -1)
            selected_index = 0;

        return selected_index;
    },

    get_current_preview_div: function () {
        // get the current tab index
        var selected_index = yuunik.personalized_product.get_current_previews_tab_index();

        var $selected_tab = $("#prod_imgs li")[selected_index];

        return $("a", $selected_tab).attr("href");
    },

    // function called when the design is being resized
    // it will not allow the image to be bigger than then div design_position, which is actually resized
    resize_design: function (event, ui) {
        var target = (event.target) ? event.target : event.srcElement;
        var $pos_resize_handle = $(target);

        var $design_area = $pos_resize_handle.parent().siblings(".design_area");

        // the ui.position and ui.size are not used since they do not respect the containment flag
        // specified in the call to resizable
        $(".d_d", $design_area)
            .css("left", $pos_resize_handle.position().left).css("top", $pos_resize_handle.position().top)
            .css("width", $pos_resize_handle.width()).css("height", $pos_resize_handle.height());
    },

    drag_design: function (event, ui) {
        var target = (event.target) ? event.target : event.srcElement;
        var $pos_resize_handle = $(target);

        var $design_area = $pos_resize_handle.parent().siblings(".design_area");

        // reposition the design
        $(".d_d", $design_area)
            .css("left", ui.position.left).css("top", ui.position.top);
    },

    set_design_position: function (left, top, width, height) {
        var $first_preview = $(".prod_preview:first");

        if ($first_preview.length > 0) {
            pos_design_area = $(".design_area", $first_preview).position();

            $(".d_d", $first_preview)
                .css("left", left - pos_design_area.left)
                .css("top", top - pos_design_area.top)
                .css("width", width)
                .css("height", height);

            $(".pos_resize_d_d", $first_preview)
                .css("left", left - pos_design_area.left)
                .css("top", top - pos_design_area.top)
                .css("width", width)
                .css("height", height);
        }
    },

    selectDesign: function (id, conf_src, author, author_url, user_design_id, on_all_tabs, design_ratio) {
        // saves info about the currently selected design
        yuunik.personalized_product.current_design_id = id;
        yuunik.personalized_product.current_configurator_img = conf_src;
        yuunik.personalized_product.current_design_author = author;
        yuunik.personalized_product.current_design_author_url = author_url;
        yuunik.personalized_product.current_user_design_id = user_design_id;
        yuunik.personalized_product.current_design_ratio = 1.0;

        if (design_ratio != undefined) {
            yuunik.personalized_product.current_design_ratio = design_ratio;
        }

        // saves the infos about the currently selected design to a session cookie
        yuunik.personalized_product.saveCurrentDesignInfos();

        if (on_all_tabs == undefined || on_all_tabs == false) {
            yuunik.personalized_product.set_design_on_current_tab();
        } else {
            yuunik.personalized_product.set_design_on_all_tabs();
        }

        // track the click on the design
        yuunik.analytics.track('/design_selected/' + id);
    },

    update_product_imgs: function (selected_values) {
        // first check if we have the map send from server
        if (yuunik.personalized_product.map_property_images_to_url == null)
            return;

        // iterate over the product views and update the background image
        $("#prod_imgs .preview_img").each(function (index) {
            yuunik.personalized_product.update_product_img($(this), index, selected_values, "_b");
        });

        // iterate over the product views and update the foreground image
        $("#prod_imgs .preview_img_foreground").each(function (index) {
            yuunik.personalized_product.update_product_img($(this), index, selected_values, "_f");
        });
    },

    update_product_img: function ($img, index, selected_values, image_type) {
        var key_to_default_img = index + " ";
        var key = key_to_default_img + selected_values;

        key_to_default_img += image_type;
        key += image_type;

        var img_src = yuunik.personalized_product.map_property_images_to_url[key];

        // if no image was found get the default
        if (img_src == undefined || img_src.length == 0)
            img_src = yuunik.personalized_product.map_property_images_to_url[key_to_default_img];

        // if an image url was found then set it
        if (img_src != undefined && img_src.length > 0)
            $img.attr("src", img_src);
    },

    show_configurator_elements: function () {
        // show all elements needed for the configurator
        $(".configurator_element").show(100);

        // hide the elements that are not needed
        $(".configurator_element_hide").hide();

        // change the image for the configurator's top margin
        $("#configurator_top_img").attr("src", "../../Content/images/white-top-arrow.gif");

        // initialise the designs box
        yuunik.main_page.init_designs_box();

        // also show the resize handles
        yuunik.personalized_product.show_resize_handles();

        return false;
    }
};

// class for the designs carousel
yuunik.designsCarousel = {
    // the web service call that return the designs as json result
    serverUrl: "",

    // the instance of the carousel on the page
    instance: null,

    // the init functions to save the carousel instance
    onInitCarousel: function (carousel, state) {
        if (state == 'init' && yuunik.designsCarousel.instance == null) {
            yuunik.designsCarousel.instance = carousel;
        }
    },

    onItemClick: function (event) {
        // the target element is expected to be an img
        var target = (event.target) ? event.target : event.srcElement;
        var targetWrappedElem = $(target);

        id = targetWrappedElem.attr("id");
        src = targetWrappedElem.attr("src");
        conf_src = targetWrappedElem.attr("conf_src");
        author = targetWrappedElem.attr("author");
        author_url = targetWrappedElem.attr("url");

        // mark the clicked item as the selected one
        yuunik.personalized_product.selectDesign(id, conf_src, author, author_url, "");
    },

    on_show_big_preview: function (event) {
        var target = (event.target) ? event.target : event.srcElement;
        var $target = $(target);

        // check which row does the design belong to
        row = $target.attr("row");

        // default show the big preview below the design
        offset = 90;

        // if the design is on the row below show the big preview above the design
        if (row == "1")
            offset = -197;

        // gets the image source and author
        src = $target.attr("conf_src");
        author = $target.attr("author");
        author_url = $target.attr("url");

        yuunik.designsCarousel.reset_big_preview(false);

        // set the image
        var $big_preview = $("#big_preview");
        var $img = $("img", $big_preview);

        // bind the load event. this needs to be done each time since reset_big_preview 
        // unbinds the handler for load, to allow the transparent image to be loaded
        $img.bind("load",
            function () {
                $big_preview.addClass("white_background").removeClass("loading_background");
            }
        );

        $img.attr("src", src);

        // display the author
        var $design_author = $("#design_author");
        if (author != undefined && author.length != 0) {
            // $big_preview.css("height", 161);
            design_author_text = "Design by " + author;

            // check if an url has been specified
            if (author_url != undefined && author_url.length != 0) {
                design_author_text += " " + author_url;
            }

            $design_author.text(design_author_text)
        }
        else {
            // if no author is defined, display only the design
            // $big_preview.css("height", 150);
            $design_author.text("")
        }

        var target_position = $target.offset();

        // show the preview
        $big_preview.css("top", target_position.top + offset).css("left", target_position.left - 52).show();

        // track the preview of the design
        yuunik.analytics.track('/design_preview/' + $target.attr("id"));
    },

    reset_big_preview: function (hide) {
        var $big_preview = $("#big_preview");

        $big_preview.hide().addClass("loading_background").removeClass("white_background");
        $("img", $big_preview).unbind("load").attr("src", "/Content/images/transparent.png");
    },

    // helper for creating the item's html
    getItemHTML: function (design, row) {
        return '<div class="subitem"><div class="img_holder"><img id="' + design.Id +
                '" src="' + design.ThumbViewPath +
                '" conf_src="' + design.ConfiguratorViewPath +
                '" row="' + row +
                '" author="' + design.Author +
                '" url="' + design.Url +
            '" /></div></div>';
    },

    // called to add the desings retrieved from server
    itemAddCallback: function (carousel, first, last, designs) {
        var designsCount = designs.length;

        // if we have reached the end of the designs for this category, set the size of the carousel
        var setSize = (designsCount == 0);

        // since there are 2 rows we need to add 2 designs to each item
        // todo: this should be changed to use desingsRows instead of 2
        for (var i = 0; i < designsCount; i += 2) {
            var html = yuunik.designsCarousel.getItemHTML(designs[i], 0);

            var nextIndex = i + 1;
            // check if we have enough designs for this item
            if (nextIndex < designsCount)
                html += yuunik.designsCarousel.getItemHTML(designs[nextIndex], 1);
            else
                setSize = true;

            carousel.add(first + i / 2, html);
        }

        if (setSize)
            carousel.size(first + (i - 2) / 2);
    },

    // callbak for retrieving the designs from the server
    onItemLoad: function (carousel, state) {
        // the original carousel works only with one row
        // we have to ask from the server enough images to display on required rows
        // also when adding the image to the carousel we have to add more then one to the carousel item

        // make sure always designsCountToDisplayOnRow are loaded to the left as well as too the right
        var first_to_load = Math.max(1, carousel.first - yuunik.settings.designsCountToDisplayOnRow);
        var last_to_load = carousel.last + yuunik.settings.designsCountToDisplayOnRow;

        // if the carousel already has a size then limit the last to load item to that one
        if (carousel.options.size != null && carousel.options.size != 0)
            last_to_load = Math.min(last_to_load, carousel.options.size);

        // assume the carousel contains already all items
        var carouselHasAllItems = true;

        // check which of the requested items do not exist
        if (state == 'init' || state == 'next') {
            for (var i = first_to_load; i <= last_to_load; i++) {
                if (!carousel.has(i)) {
                    // this is the first item to be loaded from the server
                    first_to_load = i;

                    carouselHasAllItems = false;
                    break;
                }
            }
        }
        else {
            for (var i = last_to_load; i >= first_to_load; i--) {
                if (!carousel.has(i)) {
                    // this is the last item to be loaded from the server
                    last_to_load = i;

                    carouselHasAllItems = false;
                    break;
                }
            }
        }

        // if the carousel already has all items, do not reload them
        if (carouselHasAllItems)
            return;

        // request the elements
        $.post(yuunik.designsCarousel.serverUrl,
            {
                // convert to indexes using desingsRows images per row
                // also, the server works with zero-based arrays
                start: (first_to_load * yuunik.settings.desingsRows - 1) - 1,
                end: last_to_load * yuunik.settings.desingsRows - 1
            },
            function (designs) {
                yuunik.designsCarousel.itemAddCallback(carousel, first_to_load, last_to_load, designs);
            }, "json");
    },

    // callback called to remove the items that are not visible anymore
    removeItem: function (carousel, item, i, state, evt) {
        // offset the item to remove outside the cached area
        if (state == 'next' && carousel.has(i - yuunik.settings.designsCountToDisplayOnRow)) {
            carousel.remove(i - yuunik.settings.designsCountToDisplayOnRow);
        }
        else if (state == 'prev' && carousel.has(i + yuunik.settings.designsCountToDisplayOnRow)) {
            carousel.remove(i + yuunik.settings.designsCountToDisplayOnRow);
        }
    },

    isInit: function () {
        return (yuunik.designsCarousel.instance != null)
    },

    init: function () {
        var carousel = $("#designs-carousel");

        // fade in the carousel
        carousel.show();

        // initialize 
        carousel.jcarousel({
            scroll: yuunik.settings.designsCountToDisplayOnRow,
            initCallback: yuunik.designsCarousel.onInitCarousel,
            itemVisibleOutCallback: { onAfterAnimation: yuunik.designsCarousel.removeItem },
            itemLoadCallback: yuunik.designsCarousel.onItemLoad
        });

        // please check jquery.jcarousel.js line 184 at the end of the constructor
        if ($.browser.safari) {
            yuunik.designsCarousel.instance.setup();
        }

        // set up the click event for any carousel item
        $("#designs-carousel ul li .subitem img").live("click", yuunik.designsCarousel.onItemClick);

        // set up handling of the big preview for designs
        $("#designs-carousel ul li .subitem img").live("mouseover", yuunik.designsCarousel.on_show_big_preview);
        $(".jcarousel-clip").mouseleave(
            function (event) {
                yuunik.designsCarousel.reset_big_preview(true);

                return false;
            }
        );
    },

    reset: function () {
        yuunik.designsCarousel.instance.options.size = null;
        yuunik.designsCarousel.instance.reset();
    }
};

// class for handling designs category events
yuunik.designsCategoryMenu = {
    lastSelectedCategory: null,

    onCategoryClick: function(event) {
        var target = (event.target) ? event.target : event.srcElement;
        var $target = $(target);

        // if this is not a link, go to the first parent link
        var href = $target.attr("href");
        if (href == undefined)
            $target = $target.parents("a");

        yuunik.designsCategoryMenu.display_designs_for_category($target);

        // track the click on the design category
        yuunik.analytics.track('/designs/' + $target.text());

        // cancel the default action for clicking on links
        return false;
    },

    display_designs_for_category: function($category) {
        // generate the url used by the carousel
        yuunik.designsCarousel.serverUrl = $category.attr("href").replace(/BrowseDesigns/i, "ListDesignsForCategory");

        // if this is the first call, show and initialize
        if (!yuunik.designsCarousel.isInit()) {
            $("#designs-static").fadeOut("fast", function() {
                yuunik.designsCarousel.init();
            });
        }
        else {
            // let the carousel reload the designs of the newly selected category
            yuunik.designsCarousel.reset();
        }

        // mark the selected item
        if (yuunik.designsCategoryMenu.lastSelectedCategory != null) {
            yuunik.designsCategoryMenu.lastSelectedCategory.removeClass("active");
        }

        yuunik.designsCategoryMenu.lastSelectedCategory = $category;
        $category.addClass("active");
    }
};

yuunik.own_design_dlg = {
    inited: false,

    init: function() {
        if (!yuunik.own_design_dlg.inited) {
            var $own_design_dlg = $("#own_design_dlg")
            $own_design_dlg.dialog({ resizable: false, draggable: false, bgiframe: true, modal: true,
                width: 500, heigth: 450, autoOpen: false
            });

            // initializes the link to use the currently uploaded own design
            $("#select_own_design").bind("click", yuunik.own_design_dlg.select_own_design_clicked);

            // make sure the design is uploaded using ajax
            $("#upload_user_design").ajaxForm({
                dataType: "json",
                success: function(response) {
                    // reset the upload file input
                    $("#user_design_file_wrapper").html($("#user_design_file_wrapper").html());

                    if (response.path != null && response.path.length != 0) {
                        // selects the uploaded design in the configurator
                        yuunik.personalized_product.selectDesign(
                            yuunik.settings.own_design_id, response.path, "", "", 
                            response.id, false, response.ratio);

                        // saves the information about the uploaded own design in a cookie
                        // it will be available for a week and for all configurators
                        $.cookie("own_design_info", JSON.stringify(response), { path: "/Konfigurator" });
                    }

                    // closes the dialog
                    $own_design_dlg.dialog("close");
                },

                error: function() {
                    // closes the dialog
                    $own_design_dlg.dialog("close");

                    alert("Leider ist ein Fehler aufgetreten.");
                },

                beforeSubmit: function(arr, $form, options) {
                    submit_file = false;

                    // make sure to only call the serer if a file was specified
                    $.each(arr,
                        function(index, form_value) {
                            if (form_value.name == "user_design_file" && form_value.value.length != 0) {
                                submit_file = true;

                                // display the loading animation
                                $("#own_design_dlg_content").hide();
                                $("#wait_img").show();

                                // break the each cycle
                                return false;
                            }
                        }
                    );

                    return submit_file;
                }
            });

            yuunik.own_design_dlg.inited = true;
        }
    },

    show: function() {
        // display the dialog content and hide the loading animation
        $("#wait_img").hide();
        $("#own_design_dlg_content").show();

        // if a design is already loaded, display it
        var str_own_design_info = $.cookie("own_design_info");
        if (str_own_design_info != null && str_own_design_info.length != 0) {
            var own_design_info = JSON.parse(str_own_design_info);
            var $own_design_img = $("#own_design_img");

            $own_design_img.show();
            $("img", $own_design_img).attr("src", own_design_info.path);
        }

        yuunik.own_design_dlg.init();

        // show the dialog
        $("#own_design_dlg").dialog("open");

        yuunik.analytics.track('/designs/own_design');

        return false;
    },

    select_own_design_clicked: function() {
        // check if there is a currenlty uploaded own design
        var str_own_design_info = $.cookie("own_design_info");
        if (str_own_design_info != null && str_own_design_info.length != 0) {
            var own_design_info = JSON.parse(str_own_design_info);

            // selects the uploaded design in the configurator
            yuunik.personalized_product.selectDesign(
                yuunik.settings.own_design_id, own_design_info.path, "", "",
                own_design_info.id, false, own_design_info.ratio);

            // closes the dialog
            $("#own_design_dlg").dialog("close");
        }

        return false;
    }
};

// class for handling events on the mainpage
yuunik.main_page = {
    initDesignCategoryLinks: function() {
        // all links under the designCategoriesContainer
        $("#designCategoriesContainer a").bind("click", yuunik.designsCategoryMenu.onCategoryClick);
    },

    initAddToShippingCartButton: function() {
        $("#add_to_shoppingcart").bind("click", yuunik.buy.add_to_shopping_cart);
    },

    init_configure_product_link: function() {
        $("#configure_product_link").bind("click", yuunik.personalized_product.show_configurator_elements);
    },

    init_designs_box: function() {
        // create the design categories scroll pane
        $("#designCategoriesContainer").jScrollPane();

        // show the buttons available only when JavaScript is enabled
        $("#own_design").show().bind("click", yuunik.own_design_dlg.show);

        // setup the desing category links
        this.initDesignCategoryLinks();

        // show all designs
        var $all_designs = $("#all_designs");
        yuunik.designsCategoryMenu.display_designs_for_category($all_designs);
    },

    // function called by the page
    init: function() {
        // setup the add to shopping cart button
        this.initAddToShippingCartButton();

        // initializes the configurator help
        yuunik.configurator_help.init();
    }
};

