/**
* DBU UI js
* Be aware that all custom scripts will break in SiteCore editmode when using 
* jQuery because the editmode includes Prototype.js and therefore the $ functions will clash.
* To avoid this a new alias for the $ has been created "j$".
*/

var j$ = jQuery.noConflict();
var App = {
    UI: {
        Print: function() {
            j$("#print").click(function() {
                window.print();
            });
        },
        BlockLinks: function() {
            if (j$(".blockLink")) {
                j$(".blockLink").each(function() {
                    var href = j$(this).find("a").attr("href");
                    j$(this).data("href", href).addClass("link").click(
                                function() {
                                    window.location.href = j$(this).data("href");
                                }).mouseover(
                                function() {
                                    window.status = j$(this).data("href");
                                }).mouseout(
                                function() {
                                    window.status = window.defaultStatus;
                                });
                });
            }
        },
        TopMenu: function() { },
        MegaDropDown: {
            init: function() {
                if (j$("#megadropdown-map")) {

                    if (j$.browser.msie) {
                        App.UI.MegaDropDown.ieFix();
                    }

                    // set inital flag to closed
                    j$("#megadropdown-map").data("state", "closed");
                    j$("#topmenu a:not(.specialdisabled)").click(function(e) {
                        e.preventDefault();
                        e.stopImmediatePropagation();

                        var $this = j$(this); // reference to the link
                        if ($this.data("active") == "open") {
                            App.UI.MegaDropDown.close();
                            $this.data("active", "closed");
                        }
                        else {
                            $this.addClass("selected")
                                .parent()
                                .siblings()
                                .find('a')
                                    .removeClass("selected");

                            // Cufon active hack
                            if ($this.hasClass('last') && !$this.hasClass('special')) {
                                Cufon.replace(this, { color: '#000' });
                            } else {
                                var changeMyColor = $this.parent()
                                    .siblings()
                                        .find('a.last')[0];

                                if (changeMyColor && !j$(changeMyColor).hasClass('special')) {
                                    Cufon.replace(changeMyColor, { color: '#fff' });
                                }
                            }

                            j$("#megadropdown-map .slide").hide(); // hide all content in the megadropdown
                            if (j$("#megadropdown-map").data("state") == "closed") {
                                var sitemapHeight = j$("#megadropdown-map").height();
                                j$("#megadropdown-mask").css("height", sitemapHeight + "px");
                                j$("#megadropdown-map").css("top", "-" + sitemapHeight + "px");
                                App.UI.MegaDropDown.changeSlide($this.attr("rel"));
                                j$("#megadropdown-map").stop().animate({ top: "0" }, 500, "linear", function() {
                                    j$(this).data("state", "open");
                                    j$("#megadropdown-mask").css({ overflow: 'visible' });
                                });
                                j$("#topmenu a").data("active", "closed");
                                $this.data("active", "open");
                            } else {
                                App.UI.MegaDropDown.changeSlide($this.attr("rel"))
                                j$("#topmenu a").data("active", "closed");
                                $this.data("active", "open")
                            }
                        }
                    });

                    /* Attach click handler på first level in the submenu */
                    /*
                    Disabled according to spec
                    var slidemenu_click = function(event) {
                    //event.stopPropagation();
                    j$(this).addClass('hover').siblings().removeClass('hover');
                    };
                    var slidemenu_mouseover = function(event) {
                    //$(event.currentTarget)
                    event.stopPropagation();
                    j$(this).removeClass('hover').siblings().removeClass('hover');
                    };
                    j$("#megadropdown-map div.slide ul.slidemenu > li")
                    .click(slidemenu_click)
                    .mouseover(slidemenu_mouseover);
                    */

                    /* Define this handler and attach it to the spot selector li elements */
                    j$("#megadropdown-map div.slide_spot_viewer").each(function(index, div) {
                        j$(div).children().hide().eq(0).show();
                    });
                    var slide_spot_viewer = function(event) {
                        event.stopPropagation();
                        var $li = j$(this);

                        // Add 'active' class for future use
                        $li
                            .addClass('active')
                            .siblings()
                                .removeClass('active');

                        // Find and show div from ul index
                        var indexMouseOver = j$.inArray(this, j$(this.parentNode).children());
                        $li.parent().prev().children()
                            .hide()
                            .eq(indexMouseOver)
                                .show();
                    };
                    j$("#megadropdown-map div.slidecontent li")
                        .mouseenter(slide_spot_viewer);
                }
            },

            ieFix: function() {
                j$("#topmenu a").attr("hideFocus", "true").css("outline", "none");
            
                j$('#topmenu a .ear')
                // Imitate the :active state for nested block nodes
    				.mousedown(function() {
    				    j$(this.parentNode).addClass('selected');
    				})
                // Remove the :active state for clicks that do not course a page loads
					.mouseup(function() {
					    j$(this.parentNode).removeClass('selected');
					});
            },

            changeSlide: function(index) {
                j$("#megadropdown-map .slide").hide();
                // when dropdown is open and we're toggling through the different menuitems
                if (j$("#megadropdown-map").data("state", "open")) {
                    // We cant do a nice fade because of ie's very odd handling of animating 
                    // transparent PNG's (it looks like sh*t).
                    // So just show without an animation if IE
                    if (j$.browser.msie) {
                        j$("#megadropdown-map .slide").eq(index).fadeIn(0);
                        j$("#megadropdown-map .slide").eq(index).show();
                    } else {
                        j$("#megadropdown-map .slide").eq(index).fadeIn("slow");
                    }
                } else {
                    // When dropdown opens the first time
                    j$("#megadropdown-map .slide").eq(index).show();
                }
            },

            close: function() {
                j$("#topmenu a").removeClass("selected").data("active", "closed");
                var sitemapHeight = j$("#megadropdown-map").height();
                j$("#megadropdown-mask").css({ overflow: 'hidden' });
                j$("#megadropdown-map").stop().animate({ top: (sitemapHeight * -1) + "px" }, 250, "linear", function() {
                    j$("#megadropdown-mask").css("height", "0px");
                    j$(this).data("state", "closed");
                });

                var changeMyColor = j$("#topmenu a.last")[0];

                if (changeMyColor && !j$(changeMyColor).hasClass('special')) {
                    Cufon.replace(changeMyColor, { color: '#fff' });
                }
            }
        },


        // Funktionalitet til videresende bruger ud fra landsdelsvalgscookie, er udkommenteret [2011-03-24 by DNA]
        /* ==== BEGIN : TRANSIT === */
        /*
        Transit: {
        eC: {},
        init: function(url) {
        this.eC.RedirectUrl = url;
        j$(document).ready(function() {                    
        j$('#fancyboxButtonTransit').trigger('click');
        j$('#fancybox-outer').width(355); 
        setTimeout('App.UI.Transit.doRedirect();', 5000);
        });
        },
        doRedirect: function() {
        if (App.UI.Transit.eC !== null && App.UI.Transit.eC.RedirectUrl !== null) {
        window.location = App.UI.Transit.eC.RedirectUrl;
        }
        }
        },
        */
        /* ==== END : TRANSIT === */

        Recommend: {
            config: {},
            init: function() {
                var exerciseId = getUrlParameters()['Id'];
                if (exerciseId) {
                    App.UI.Recommend.config.CurrentExerciseId = exerciseId;
                }
                else {
                    App.UI.Recommend.config.CurrentItemId = App.TargetItemId;
                }

                App.UI.Recommend.config.IsExercise = App.IsExercise == 'True';

                var serviceUrl = "";
                var data = "";
                if (App.UI.Recommend.config.IsExercise) {
                    serviceUrl = "/services/UserServices.asmx/GetCurrentOevelseAnbefal";
                    data = "{'centralDbOevelseId':'" + App.UI.Recommend.config.CurrentExerciseId + "'}";
                }
                else {
                    serviceUrl = "/services/UserServices.asmx/GetCurrentItemAnbefal";
                    data = "{'itemId':'" + App.UI.Recommend.config.CurrentItemId + "'}";
                }
                j$(".recommendations").show();
                /*                
                j$.ajax({
                type: "POST",
                url: serviceUrl,
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                App.UI.Recommend.notifyVisuals(msg.d);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert(textStatus);
                }
                });
                */
                if (App.UI.Recommend.isItemIdInCookie()) {
                    j$("#recommend").addClass("disabled").attr("title", "Du har allerede anbefalet denne side");

                }

                j$("#recommend").click(function(e) {
                    e.preventDefault();
                    if (!App.UI.Recommend.isItemIdInCookie()) {
                        var $this = j$(this)
                        var serviceUrl = "";
                        var data = "";
                        if (App.UI.Recommend.config.IsExercise) {
                            serviceUrl = "/services/UserServices.asmx/UpdateOevelseAnbefaling";
                            data = "{'centralDbOevelseId':'" + App.UI.Recommend.config.CurrentExerciseId + "'}";
                        }
                        else {
                            serviceUrl = "/services/UserServices.asmx/UpdateAnbefaling";
                            data = "{'itemId':'" + App.UI.Recommend.config.CurrentItemId + "'}";
                        }
                        j$.ajax({
                            type: "POST",
                            url: serviceUrl,
                            data: data,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function(msg) {
                                App.UI.Recommend.setCookie();
                                App.UI.Recommend.notifyVisuals(msg.d);
                                $this.addClass("disabled");
                            },
                            error: function(XMLHttpRequest, textStatus, errorThrown) {
                                //alert(textStatus);
                            }
                        });
                    }
                });
            },
            isItemIdInCookie: function() {
                var cookieVal = j$.cookie('DBURecommendations');
                if (cookieVal) {
                    if (App.UI.Recommend.config.IsExercise) {
                        return cookieVal.indexOf(App.UI.Recommend.config.CurrentExerciseId) != -1;
                    }
                    else {
                        return cookieVal.indexOf(App.UI.Recommend.config.CurrentItemId) != -1;
                    }
                }
                else {
                    return false;
                }
            },
            setCookie: function() {
                var newCookieVal = '';
                if (App.UI.Recommend.config.IsExercise) {
                    newCookieVal = App.UI.Recommend.config.CurrentExerciseId;
                }
                else {
                    newCookieVal = App.UI.Recommend.config.CurrentItemId;
                }
                if (!App.UI.Recommend.isItemIdInCookie()) {
                    newCookieVal = j$.cookie("DBURecommendations") + ";" + newCookieVal;
                }
                j$.cookie('DBURecommendations', newCookieVal, { expires: 30 });
            },
            notifyVisuals: function(count) {
                // update div that show how many recommendations an item have
                j$(".recommendations").show().find("span.count").text(count);
            }
        },
        Rating: {
            config: {},
            init: function() {
                var exerciseId = getUrlParameters()['Id'];
                if (exerciseId) {
                    App.UI.Rating.config.CurrentExerciseId = exerciseId;
                    App.UI.Rating.IsRatingAllowed();
                }
                else {
                    App.UI.Rating.config.CurrentItemId = App.TargetItemId;
                    if (App.UI.Rating.config.CurrentItemId) {
                        App.UI.Rating.IsRatingAllowed(); // start chain reaction
                    }
                }
                App.UI.Rating.config.IsExercise = App.IsExercise == 'True';

            },
            isItemIdInCookie: function() {
                var cookieVal = j$.cookie('DBURatings');
                //console.log("ifItemin coolie: " + cookieVal)
                if (cookieVal) {
                    if (App.UI.Rating.config.IsExercise) {
                        return cookieVal.indexOf(App.UI.Rating.config.CurrentExerciseId) != -1;
                    }
                    else {
                        return cookieVal.indexOf(App.UI.Rating.config.CurrentItemId) != -1;
                    }
                } else {
                    return false;
                }
            },
            setCookie: function() {
                //console.log("setting cookie")
                var newCookieVal = '';
                if (App.UI.Rating.config.IsExercise) {
                    newCookieVal = App.UI.Rating.config.CurrentExerciseId;
                }
                else {
                    newCookieVal = App.UI.Rating.config.CurrentItemId;
                }
                if (!App.UI.Rating.isItemIdInCookie()) {
                    newCookieVal = j$.cookie("DBURatings") + ";" + newCookieVal;
                }
                //console.log(newCookieVal)
                j$.cookie('DBURatings', newCookieVal, { expires: 30 });
            },
            setInitalState: function() {
                if (App.UI.Rating.isItemIdInCookie() || App.IsLoggedIn != 'True') {
                    j$('.auto-submit-star').rating({ 'readOnly': false });
                    j$('.auto-submit-star').rating('select', "" + App.UI.Rating.config.CurrentItemRating, false);
                    j$('.auto-submit-star').rating('readOnly', true);
                } else {
                    j$('.auto-submit-star').rating({ callback: function(value, link) { App.UI.Rating.onClick(value, link); } });
                    j$('.auto-submit-star').rating('select', "" + App.UI.Rating.config.CurrentItemRating, false);
                }
            },
            onClick: function(value, link) {
                var serviceUrl = "";
                var data = "";
                if (App.UI.Rating.config.IsExercise) {
                    serviceUrl = "/services/UserServices.asmx/UpdateOevelseRating";
                    data = "{'oevelseId':'" + App.UI.Rating.config.CurrentExerciseId + "','rating':" + value + "}";
                }
                else {
                    serviceUrl = "/services/UserServices.asmx/UpdateRating";
                    data = "{'itemId':'" + App.UI.Rating.config.CurrentItemId + "','rating':" + value + "}";
                }
                j$.ajax({
                    type: "POST",
                    url: serviceUrl,
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        App.UI.Rating.setCookie();
                        //console.log("allscore: " + msg.d);
                        j$(".ajaxRating").animate({}, function() {
                            j$('.auto-submit-star').rating('select', "" + parseInt(msg.d), false);
                            j$('.auto-submit-star').rating('readOnly', true);
                            setTimeout(function() {
                                j$(".ajaxRating").animate({});
                            }, 500);
                        });
                        setTimeout(function() {
                            j$('.auto-submit-star').rating('select', "" + msg.d, false);
                        }, 250);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        //alert(textStatus);
                    }
                });
            },
            IsRatingAllowed: function() {
                //console.log("3: IsRatingAllowed");
                // console.log(App.UI.Rating.config.CurrentItemId);
                j$.ajax({
                    type: "POST",
                    url: "/services/UserServices.asmx/IsRatingAllowed", //public bool IsRatingAllowed(string itemIdOfSideItemToBeCommented)
                    data: "{'itemId':'" + App.UI.Rating.config.CurrentItemId + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        //console.log("3: IsRatingAllowed - succes 1");
                        App.UI.Rating.config.IsRatingAllowed = msg.d;
                        App.UI.Rating.GetCurrentItemRating();
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        return false; //alert(textStatus);
                    }
                });
            },
            GetCurrentItemRating: function() {
                //console.log("4: GetCurrentItemRating");
                //console.log("App.UI.Rating.config.CurrentItemId: " + App.UI.Rating.config.CurrentItemId + ",");
                var serviceUrl = "";
                var data = "";
                if (App.UI.Rating.config.IsExercise) {
                    serviceUrl = "/services/UserServices.asmx/GetCurrentOevelseRating";
                    data = "{'oevelseId':'" + App.UI.Rating.config.CurrentExerciseId + "'}";
                }
                else {
                    serviceUrl = "/services/UserServices.asmx/GetCurrentItemRating";
                    data = "{'itemId':'" + App.UI.Rating.config.CurrentItemId + "'}";
                }
                j$.ajax({
                    type: "POST",
                    url: serviceUrl, //public double GetCurrentItemRating(string itemIdOfSideItemToBeCommented)
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        //console.log("4: GetCurrentItemRating - succes: " + msg.d);
                        App.UI.Rating.config.CurrentItemRating = Math.round(parseInt(msg.d));
                        App.UI.Rating.setInitalState();
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        return textStatus;
                    }
                });
            }
        },
        begin: function() {
            App.UI.TopMenu();
            App.UI.MegaDropDown.init();
            App.UI.BlockLinks();
            App.UI.Print();
            // App.UI.Rating.init();
            //App.UI.Recommend.init();
            //  App.UI.Geo.init();

            j$(".form select, .form input:checkbox, .form input:radio, .form input:file").uniform();
            j$("#loginLink").fancybox({
                'titlePosition': 'inside',
                'transitionIn': 'none',
                'transitionOut': 'none',
                "padding": 0,
                "overlayOpacity": 0.8,
                "overlayColor": "#000",
                "autoDimensions": false,
                "width": 355,
                "height": 290,
                "showCloseButton": false,
                "onStart": function() {
                    j$("form").append(j$("#fancybox-wrap"));
                    j$("#loginbox").removeClass("offscreen");
                },
                "onClosed": function() {
                    //try {
                    Login.hidePasswordFields();
                    //} catch(e){}
                    j$("#loginbox").addClass("offscreen");
                }
            });




            // move Sportssys toolbar up in DBU toolbar and use Sportssys print
            if (j$("#SportssysTopRight").length != 0) {
                j$("table.layout div.right").html(j$("#SportssysTopRight"));
                if (j$("a[id$='TopPrintNormalLinkLeft']").length != 0) {
                    j$("a[id$='TopPrintNormalLinkLeft']").hide();
                    j$("a[id$='TopPrintNormalLinkRight']").hide();
                    j$("#print").attr("href", j$("a[id$='TopPrintNormalLinkLeft']").attr("href"));
                    j$("#print").unbind('click');
                }
            }
        }
    }
};                                                                                                                               // App.UI

// fire the app
j$(App.UI.begin);

j$(document).bind('click', function(e) {
    if (j$('#megadropdown')) {
        var $clicked = j$(e.target); // get the element clicked
        if (
        	    $clicked.is('#megadropdown') ||
        	    $clicked.parents().is('#megadropdown') ||
        	    $clicked.parents().is('#topmenu')
            ) {
            // do nothing
        } else {
            if (j$("#megadropdown-map").data("state") == "open") {
                App.UI.MegaDropDown.close();
            }
        }
    }
});

/* TODO: MBR implement Stefans validation methods */
var Dbu = {};
Dbu.validate = {
    extendError: function() { },
    showError: function() { },
    hideError: function() { },
    contractError: function() { }
};

function getUrlParameters() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    } return vars;
}

// From loginSublayout
var Login = {
    requestPassword: function() {
        j$.ajax({
            type: "POST",
            url: "/services/UserServices.asmx/SendPasswordToUser",
            data: "{'username':'" + j$("#txtUsernameToSendPasswordTo").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                document.getElementById("msgLbl").innerHTML = msg.d;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert(textStatus);
            }
        });
    },
    showPasswordFields: function(e) {
        e.preventDefault();
        j$("#txtUsernameToSendPasswordTo").val(j$("#loginbox input[type=text]").val());
        j$("#loginFields").fadeOut("fast", function() {
            j$("#forgotPasswordHelp").fadeIn();
        });
    },
    hidePasswordFields: function() {
        j$("#forgotPasswordHelp").fadeOut("fast", function() {
            j$("#loginFields").fadeIn();
            document.getElementById("msgLbl").innerHTML = "";
        });
    }
};

j$(document).ready(function() {
    j$("#loginbox input[type=password]").parent().append(j$("#loginbox a[id$='PasswordRecoveryLink']").addClass("smaller forgotPassword").click(Login.showPasswordFields));
    j$("#loginbox input[type=submit]").parent().prepend(j$("#loginbox a[id$=CreateUserLink]").addClass("smaller createProfile"));
    j$("#loginbox input[type=submit]").wrap("<span class='standard'></span>");
    j$("#loginbox").keydown(function(event) { if (event.keyCode == 13) { return false } });
    j$("#loginBox_lgForm_UserName").keydown(function(event) { if (event.keyCode == 13) { j$("#loginBox_lgForm_Password").focus() } });
    j$("#loginBox_lgForm_Password").keydown(function(event) { if (event.keyCode == 13) { j$("#loginBox_lgForm_LoginButton").click(); return false } });
    j$("#txtUsernameToSendPasswordTo").keydown(function(event) { if (event.keyCode == 13) { j$("#requestPassword").click() } });

    //j$('#topmenu li').removeClass('selected');
    //j$('#topmenu li').removeClass('firstAfterSelected');
    //j$('#topmenu a[href^="/' + location.pathname.split("/")[1].split(".")[0] + '.aspx"]').parent().parent().next().addClass('firstAfterSelected');
    //j$('#topmenu a[href^="/' + location.pathname.split("/")[1].split(".")[0] + '.aspx"]').parent().parent().addClass('selected');

    j$('.wpsubmenu .line.submenu li:last-child').addClass('last');
    //j$('#IndholdToKolonnerOpdeltVenstre').prepend(j$('.wpsubmenu').html());

});
