/**
* 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() {
            if (j$("#topmenu li.selected")) {
                if (j$("#topmenu li.selected").next("li")) {
                    j$("#topmenu li.selected").next("li").addClass("firstAfterSelected");
                }
            }
            if (j$("#topmenu li")) {
                j$("#topmenu li").hover(
				            function() {
				                j$(this).addClass("hover");
				                if (j$(this).next("li").hasClass("selected")) {
				                    j$(this).next("li").addClass("firstAfterHoveredSelected");
				                } else {
				                    j$(this).next("li").addClass("firstAfterHovered");
				                }
				                if (j$(this).prev("li").hasClass("selected")) {
				                    j$(this).prev("li").addClass("prevAfterHoveredSelected");
				                } else {
				                    j$(this).prev("li").addClass("prevAfterHovered");
				                }
				            },
				            function() {
				                j$(this).next("li").removeClass("firstAfterHovered").removeClass("firstAfterHoveredSelected");
				                j$(this).prev("li").removeClass("prevAfterHovered").removeClass("prevAfterHoveredSelected");
				                j$(this).removeClass("hover");
				            }
			            );
            }
        },
        MegaDropDown: {
            init: function() {
                if (j$("#megadropdown-map")) {
                    // set inital flag to closed
                    j$("#megadropdown-map").data("state", "closed");
                    // add events to all menuitems
                    j$("#submenu a").click(
				                    function(e) {
				                        e.preventDefault();
				                        var $this = j$(this); // reference to the link
				                        if ($this.data("active") == "open") {
				                            App.UI.MegaDropDown.close();
				                            j$("#submenu a").data("active", "closed");
				                        }
				                        else {
				                            // delete all selected classes from li items
				                            j$("#submenu li").removeClass("selected");
				                            // add selected class to clicked item
				                            $this.parent().addClass("selected");
				                            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$("#submenu a").data("active", "closed");
				                                $this.data("active", "open")
				                            } else {
				                                App.UI.MegaDropDown.changeSlide($this.attr("rel"))
				                                j$("#submenu a").data("active", "closed");
				                                $this.data("active", "open")
				                            }
				                        }
				                    });
                }
            },
            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$("#submenu li").removeClass("selected");
                var sitemapHeight = j$("#megadropdown-map").height();
                j$("#megadropdown-map").stop().animate({ top: (sitemapHeight * -1) + "px" }, 250, "linear", function() { j$("#megadropdown-mask").css("height", "0px"); j$(this).data("state", "closed"); });
            }
        },


        /* ==== BEGIN : TRANSIT === */
        Transit: {
            eC: {},
            init: function(url) {
                this.eC.RedirectUrl = url;
                j$(document).ready(function() {
                
                
                    // *** Quick Fix for persona transit ***
                    // Remove if statement when implementing permanent solution
                    var transitDomain = App.UI.Transit.eC.RedirectUrl.match(/:\/\/(.[^/]+)/)[1];
                    //alert(location.host + " | " + transitDomain);
                    
                    if (location.host != transitDomain) {
                        j$('#fancyboxButtonTransit').trigger('click');
                        j$('#fancybox-outer').width(355); 
                        setTimeout('App.UI.Transit.doRedirect();', 5000);
                    }
                    else {
                        j$('#bdBody').html("");
                        window.location = App.UI.Transit.eC.RedirectUrl;
                    }
                    
                });
            },
            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('#submenu')
            ) {
            // 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: "{'email':'" + j$("#txtEmailToSendPasswordTo").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$("#txtEmailToSendPasswordTo").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$("#txtEmailToSendPasswordTo").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');
});