$.noConflict();
jQuery(document).ready(function(){
    initSimpleTextSpotToggler();
    topMenuScrolling();
    topMenuLinks();

    jQuery("#campaign, #historyCampaign").slider();

    tabContent();
    productsGallery();
    recipeList();

    jQuery("#footer").find(".scrollTop").click(function(){
        scrollWindow("#header");
    });
});

var pageLang = jQuery("html").attr("lang");

function productsGallery() {
    /*
        IF PAGE EDIT MODE
    */
    if( mou_isPageEdit ) {


        jQuery(".productsGallery").each(function () {
            var detailsBlockVisible; // current visible details info block

            var productsBlock = jQuery(this);
            var productsList = productsBlock.children(".productsList");
            var lock = false; // animation lock

            // --- Click event in product card
            productsList.children(".item").click(function () {
                var item = jQuery(this);
                var itemId = item.attr("id");

                var detailBlock = productsList.children().filter(".detailInfo." + itemId);

                if (detailsBlockVisible) {
                    detailsBlockVisible.slideUp(200);
                    detailsBlockVisible = null;
                    return false;
                }

                detailBlock.slideDown(200);
                detailsBlockVisible = detailBlock;
            });

            productsList.children(".detailInfo").each(function () {
                var detailInfoBlock = jQuery(this);
                var tabs = detailInfoBlock.find(".tabs");
                var tabsContent = detailInfoBlock.find(".tabsContent");
                 var closeBtn = detailInfoBlock.find(".close");
               // var popupWindowBg = jQuery('.popupWindowBg');
                tabs.children("li").click(function () {
                    var tab = jQuery(this);
                    if (tab.hasClass("active")) return false;

                    tabs.children(".active").removeClass("active");
                    tab.addClass("active");

                    tabsContent.children(".active").removeClass("active");
                    tabsContent.children(":eq(" + tab.index() + ")").addClass("active");
                });

                closeBtn.click(function () {
                    detailInfoBlock.slideUp(200);
                    detailsBlockVisible = null;
                });
            });

        });

        return false;
    }

    /*
        IF NOT PAGE EDIT MODE
    */
    jQuery(".productsGallery").each(function () {
        var productsBlock = jQuery(this);
        var productsList = productsBlock.children(".productsList");
        var detailsBlock = new ProductDetailBlock();
        var lock = false; // animation lock

        // --- Click event in product card
        productsList.children(".item").click(function () {
            if (lock) return false; lock = true;

            var item = jQuery(this);
            var itemsCount = productsList.children(".item").length;
            var tailPosition = item.position().left + (item.width() / 2);
            var lastInLine = Math.min(itemsCount, getLine(item.index(), 3)) - 1;
            var itemID = item.attr("id").replace("prod_","");

            if (detailsBlock.opened) {

                // fadeIn all items
                productsList.children(".item").fadeTo(200, 1.0);

                // collapse detail information block
                detailsBlock.collapse(function () {
                    lock = false;
                });

            } else {

                // fadeOut all items except the selected
                productsList.children(".item:not(:eq(" + item.index() + "))").fadeTo(200, 0.2);

                // construct detail information block tabs, set main image and title
                detailsBlock.construct(item.attr("title"), itemID, item.find("img").attr("src"), tailPosition, function () {

                    // when construct complete - push block after last item in line
                    productsList.children(".item:eq(" + lastInLine + ")").after(detailsBlock.block);

                    // show details info block
                    detailsBlock.expand(function () {
                        lock = false;
                    });

                });

            }
        });

        // --- close button click event
        detailsBlock.block.children().children().children().children(".close").click(function () {
            if (lock) return false; lock = true;

            // fadeIn all items
            productsList.children(".item").fadeTo(200, 1.0);

            // collapse detail information block
            detailsBlock.collapse(function () {
                lock = false;
            });
        });
    });


    function getLine(index, size) {
        return (Math.floor(index / size) + 1) * size;
    }

    function ProductDetailBlock() {
        var self = this;
        self.opened = false;
        self.block = jQuery('<li class="detailInfo"><div class="background"><div class="topBorder"><div class="bottomBorder holder">  \
                            <a href="javascript://" class="close"></a> \
                            <div class="topTail"></div> \
                            <div class="image"> \
                                <img src="" alt="" />\
                            </div> \
                            <div class="infoText"> \
                                <h2></h2> \
                                <ul class="tabs"></ul> \
                                <ul class="tabsContent"></ul> \
                                <div class="loading"></div> \
                            </div></div></div></div> \
                        </li>');
        self.title = self.block.children().children().children().children(".infoText").children("h2");
        self.image = self.block.children().children().children().children(".image").children("img");
        self.tabs = self.block.children().children().children().children(".infoText").children(".tabs");
        self.tabsContent = self.block.children().children().children().children(".infoText").children(".tabsContent");
        self.loading = self.block.children().children().children().children(".infoText").children(".loading");

        // --- show block
        self.expand = function(callback){
            self.block.slideDown(200, function(){
                self.opened = true;
                if( typeof callback == "function" ) {
                    callback();
                }
            });
        };

        // --- hide block
        self.collapse = function(callback){
            self.block.slideUp(200, function(){
                self.opened = false;
                self.block.detach();

                if( typeof callback == "function" ) {
                    callback();
                }
            });
        };

        // --- construct content
        self.construct = function (title, itemId, image, tailPos, callback) {
            // set title
            self.title.text(title);

            // set image
            self.image.attr("src", image);

            //set tail position
            self.block.children().children().children().children(".topTail").css("left", (tailPos) + "px");

            // clear existing tabs
            self.tabs.children().remove();
            self.tabsContent.children().remove();
            self.loading.show();

            // construct new tabs
            jQuery.ajax({
                url: "/productinfo.mou?pid=" + itemId + "&lang=" + pageLang,
                dataType: "XML",
                success: function (xml) {
                    self.loading.hide();
                    jQuery("tab", xml).each(function () {
                        var tab = jQuery(this);
                        var tabName = tab.attr("title");
                        var tabContent = tab.text();
                        self.tabs.append("<li>" + tabName + "</li>");
                        self.tabsContent.append('<li class="content">' + tabContent + '</li>');

                    }).promise().done(function () { // callback

                        self.tabs.children(":first").addClass("active");
                        self.tabs.children(":last").addClass("last");
                        self.tabsContent.children(":first").addClass("active");

                    });
                },
                error: function () {
                    self.loading.hide();
                    jQuery("<li>ERROR LOADING DATA</li>").appendTo(self.tabsContent).show();
                }
            });
            // do callback when all complete
            if (typeof callback == "function") {
                callback();
            }

        };

        self.tabs.delegate("li", "click", function(){
            var tab = jQuery(this);
            if( tab.hasClass("active") ) return false;

            self.tabs.children(".active").removeClass("active");
            tab.addClass("active");

            self.tabsContent.children(".active").removeClass("active");
            self.tabsContent.children(":eq(" + tab.index() + ")").addClass("active");
        });
    }
}

function tabContent() {
    jQuery(".tabContentBlock").each(function(){
        var block = jQuery(this);
        var contentType = block.hasClass("recipes") ? 'recipes' : 'groups';
        var tabList = block.find(".tabsList");
        var search = block.find(".search").children();
        var searchTimeout = 0;
        var lock = false;


        tabList.children().click(function(){
            var tab = jQuery(this);

            if( lock || tab.hasClass("active")) return false; lock = true;

            tabList.children(".active").removeClass("active");

            tab.addClass("active");

            /*
                TABS FUNCTIONAL BY CONTENT TYPE (groups, list ...)
            */
            if( contentType == 'groups' ) {
                var contentList = block.children(".contentsList");

                contentList.height(contentList.children(".active").outerHeight());

                contentList.children(".active").fadeOut(200, function(){

                    var nextTabContent = contentList.children().eq( tab.index() );
                    contentList.height("auto");
                    nextTabContent.fadeIn(200).addClass("active");
                    jQuery(this).removeClass("active");

                    lock = false;
                });
            } else if ( contentType == 'recipes' ) {
                var recipeList = block.find(".recipeList");
                var recipeCollection = [];

                // hide current content list
                recipeList.fadeTo(200, 0.0, function(){
                    var tabGroupName = mou_isPageEdit ? tab.children(".scWebEditInput").text().toLowerCase().replace(/ /g,'') : tab.text().toLowerCase().replace(/ /g,'');


                    // deactivate current recipes
                    recipeList.children().filter(".selected").removeClass("selected");

                    // activate recipes for current tab
                    recipeList.children().each(function(){
                        var recipe = jQuery(this);
                        var recipeGroupName = recipe.children("input:hidden").val().toLowerCase().replace(/ /g,"");

                        if( tabGroupName == recipeGroupName ) {
                            recipe.addClass("selected");
                            recipeCollection.push(this);
                        }
                    });

                    recipeList.fadeTo(200, 1.0, function(){
                        if( !jQuery(recipeCollection).hasClass('active') ) {
                            jQuery(recipeCollection).first().find(".title").click();
                        }
                        lock = false;
                    });
                });
            }
        });


        // search form for recipes
        if( contentType == 'recipes' ) {
            var recipeList = block.find(".recipeList");

            search.keyup(function(){
                if(searchTimeout) clearTimeout(searchTimeout);

                searchTimeout = setTimeout(function(){
                    doSearch();
                }, 400);
            });

            // if have title - set hint
            if(search.attr("title") != "") {
                search.val(search.attr("title"));

                search.blur(function(){
                    if(search.val() == '' || search.val() == search.attr("title")) {
                        search.val(search.attr("title"));
                    }
                });

                search.focus(function(){
                    if( search.val() == search.attr("title") ) {
                        search.val("");
                    }
                });
            }

            function doSearch(){
                if( search.val().length <= 3 ) return false;

                tabList.children(".active").removeClass("active");
                recipeList.children().filter(".active").removeClass("active").children(".recipeBody").css("display", "none");
                recipeList.children().filter(".selected").removeClass("selected");
                recipeList.children().each(function(){
                    var recipe = jQuery(this);
                    var title = recipe.find("div.title").text().toLowerCase();

                    if( title.indexOf( search.val().toLowerCase() ) != -1) {
                        recipe.addClass("selected");
                    }
                });
            }
        }
    });
}

function recipeList() {
    var recipeLists = jQuery(".recipeList");
    var tellaFriend = new Tell_a_friend_window();

    recipeLists.each(function () {
        var recipeList = jQuery(this);
        var items = recipeList.children("li");
        var favItems = items.filter(".fav");

        items.each(function () {
            var item = jQuery(this);
            var recipeContentHolder = item.children(".recipeBody");
            var recipeContent = recipeContentHolder.find(".ajaxPlaceHolder");
            var itemId = item.attr("id").replace("recipe_", "");
            var likeBtnLock = false;
            var itemTogglers = item.children(".recipeHeader").children(".control").children("a").add(item.children(".recipeHeader").children(".title"));

            itemTogglers.click(function () {
                if (item.hasClass("active")) {
                    item.removeClass("active");
                    recipeContentHolder.slideUp(200);
                } else {

                    if (recipeContent.is(":empty")) {
                        getContent();
                    }
                    items.filter(".active:visible").removeClass("active").children(".recipeBody").slideUp(200);
                    item.addClass("active");
                    recipeContentHolder.slideDown(200);
                }
            });

            item.delegate(".tellaFriend", "click", function () {
                tellaFriend.open();
            });
            item.delegate(".like > a", "click", function () {
                if (likeBtnLock) return false;

                likeBtnLock = true;
                var like = jQuery(this);
                jQuery.ajax({
                    url: "/recipeliker.mou?rid=" + itemId,
                    success: function (xml) {
                        if(xml.length > 0)
                        like.text(Number(like.text()) + 1);
                    }
                });

            });

            function getContent() {
                var html = jQuery('<div class="recipeLeftColumn"></div><div class="recipeContent"></div>');
                jQuery('<div class="loading"></div>').appendTo(recipeContent);
                jQuery.ajax({
                    url: "/recipeinfo.mou?rid=" + itemId + "&lang=" + pageLang,
                    dataType: "XML",
                    success: function (xml) {

                        var recipe = jQuery(xml).children();

                        if (recipe.children("image").length == 0) {
                            html.filter(".recipeLeftColumn").remove();
                            html.filter(".recipeContent").addClass("wide");
                        } else {
                            // add images
                            recipe.children("image").each(function () {
                                var img = jQuery(this);
                                jQuery('<div class="image"><img src="' + img.attr("src") + '" alt="" /></div>').appendTo(html.filter(".recipeLeftColumn"));
                            });
                        }
                        // add text
                        html.filter(".recipeContent").html(recipe.children("text").text());

                        recipeContent.fadeTo(200, 0.0, function(){
                            jQuery(this).empty();
                            html.appendTo(recipeContent);
                            recipeContent.fadeTo(300, 1.0);
                        });

                        // put all content in markup
                        recipeContentHolder.find(".sharePanel").appendTo(html.filter(".recipeContent")).show();
                        jQuery('<fb:comments href="mou.dk/?rid=' + itemId + '" num_posts="3" width="428" colorscheme="dark"></fb:comments>').appendTo(html.filter(".recipeContent"));
                        FB.XFBML.parse(html.filter(".recipeContent").get(0));

                    },
                    error: function () {
                        recipeContent.empty();
                        recipeContent.html("<strong>ERROR LOADING DATA</strong>");
                    }
                });
            }
        });

        // show random favorite recipe
        favItems.eq(Math.floor(Math.random() * (favItems.length - 1))).addClass("selected").find(".title").click();

    });
}


jQuery.fn.slider = function() {
    jQuery(this).each(function(){
        var mainHolder = jQuery(this);
        var scroller = mainHolder.children(".slideListHolder");
        var slideList = scroller.children(".slideList");
        var visibleArea = mainHolder.width();
        var slidesCount = slideList.children().length;

        if( slidesCount <= 1 ) return;

        var slideSpeed = 300;
        var slideWidth = slideList.children().eq(0).width();
        var prev = jQuery('<a href="javascript://" class="prev"></a>');
        var next = jQuery('<a href="javascript://" class="next"></a>');

        slideList.width( visibleArea * slidesCount );
        scroller.scrollLeft(0);

        prev.add(next).appendTo(mainHolder);

        validateButtons();

        prev.click(function(){
            scroller.animate({scrollLeft: "-=" + visibleArea }, slideSpeed, function() {
                validateButtons();
            });
        });

        next.click(function(){
            scroller.animate({scrollLeft: "+=" + visibleArea }, slideSpeed, function(){
                validateButtons();
            });
        });

        function validateButtons() {
            if( scroller.scrollLeft() == 0 ) {
                prev.fadeOut(200);
            } else if( !prev.is(":visible") ) {
                prev.fadeIn(200);
            }

            if( scroller.scrollLeft() + visibleArea == slideList.width() ) {
                next.fadeOut(200);
            } else if( !next.is(":visible") )  {
                next.fadeIn(200);
            }
        }

        // slide anchors
        var anchors = slideList.find('.slideAnchor > span');

        anchors.click(function(){
            var anchor = jQuery(this);
            var targetID = anchor.attr("class");
            var targetIndex = slideList.children("." + targetID).index();



            scroller.animate({scrollLeft: slideWidth * targetIndex }, slideSpeed, function() {
                validateButtons();
            });

        });
    });
};

function topMenuScrolling() {
    var menu = jQuery("#topMenu").children(".menuHolder");
    var basePosition = menu.offset().top;
    var attached = false;
    var screen = jQuery(window);

    screen.scroll(function(){
        if( screen.scrollTop() > basePosition ) {
            if( attached ) return;
            menu.addClass("attach");
            attached = true;
        } else {
            if( !attached ) return;
            menu.removeClass("attach");
            attached = false;
        }
    });
}
function topMenuLinks() {
    var menuList = jQuery("#topMenu .menuList");

    menuList.children("li").children("a").click(function(){
        var link = jQuery(this);
        var item = link.parent();

        scrollWindow("#" + link.attr("class"));

        if(item.hasClass("active")) return false;

        menuList.children(".active").removeClass("active");
        item.addClass("active");

    });
}
function scrollWindow( elementId ) {
    var scrollToElement = jQuery(elementId).offset().top - 86;
    jQuery("html, body").stop().animate({scrollTop: ( scrollToElement < 0 ? 0 : scrollToElement )}, 500);
}

function Tell_a_friend_window() {
    var self = this;
    var popupWindow = jQuery("#tellaFriendWindow");
    //var closeBtrn = jQuery("#tellaFriendWindow .closeBtn")
    var middlePanel = jQuery("#tellaFriendWindow .middle");
    var sendBtn = jQuery("#tellaFriendWindow .btn");
    var popupWindowBg = jQuery('.popupWindowBg');
    self.open = function( id ){
        if(popupWindow.is(":visible")) {
            self.close(function(){
                showWindow();
            });
		} else {
            showWindow();
        }
    };

    self.close = function( callback ) {
        popupWindow.children(".popupWindow").animate({
            marginTop: 100
        }, 200);

        popupWindow.fadeOut(200, function() {
            if( typeof callback == "function") {
                callback();
            }
        });
	};

	popupWindowBg.live("click", function (event) {
	    var elClickId = event.target.id;
	    if (elClickId == 'tellaFriendWindow') {
	        self.close();
	    }
	});
	popupWindowBg.live("mouseover", function (event) {
	    var elHoverId = event.target.id;
	    if (elHoverId == 'tellaFriendWindow') {
	        popupWindowBg.css({ 'cursor': 'pointer' });
	    }
	    else {
	        popupWindowBg.css({ 'cursor': 'default' });
	    }
	});

    sendBtn.live("click", function () {
        if (typeof (Page_ClientValidate) == 'function') {
            Page_ClientValidate("tellafriend");
        }

        if (Page_IsValid) self.close();
    });

    function showWindow(){
        popupWindow.children(".popupWindow").animate({
            marginTop: 200
        }, 200);

        popupWindow.fadeIn(200);

    }

}

function initSimpleTextSpotToggler() {
    var spots = jQuery(".simpleTextSpot");

    spots.each(function(){
        var spot = jQuery(this);
        var toggler = spot.children(".readMore");
        var moreText = spot.children(".moreText");

        toggler.fadeIn(400);

        toggler.children("a").click(function(){
            toggler.hide();
            moreText.fadeIn(400);
        });
    });
}
