if (typeof (Tody) === "undefined") var Tody = {};

(function($) {

    Tody.MasterPage = new function() {

        var self = this;

        var orderSwitchConfirmTemplate = '<p>Sigur doriti sa anulati comanda curenta, si sa incepeti o noua comanda de __orderType__?</p>'
	        + '<div>__closeButton__ __confirmationButton__</div>';

        self.initAuthentificated = function(mbBlocked, odBlocked, mbBlockedText, odBlockedText) {
            setHeartbeat();

            if (odBlocked) {
                $('#paidOrderLink').click(function() {

                    Boxy.alert(odBlockedText, null,
	                         {
	                             title: "Atentie",
	                             closeOnButtonClick: true
	                         });
                });
            } else {
                $('#paidOrderLink').click(self.getPaidOrderForm);
            }

            innerInit();
        };

        var setHeartbeat = function() {
            setTimeout("Tody.MasterPage.heartbeat()", 1000 * 60 * 5); // every 5 min
        }

        self.heartbeat = function() {
            try {
                $.get(
                    actionUrl("heartbeat"),
                    null,
                    function(data) {
                        //$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)
                        setHeartbeat();
                    },
                    "json"
                );
            } catch (e) { }
        }


        self.initNotAuthentificated = function() {
            if (paidOrderLinkUrlEnding != undefined) {
                $('#paidOrderLink').attr("href", actionUrl("/catalog/" + paidOrderLinkUrlEnding));
            }
            $('#freeOrderLink').attr("href", actionUrl("/login"));
            $('#btnOrder').attr("href", actionUrl("/login"));
            innerInit();
        };

        self.initWithNoClientFile = function() {

            $('#paidOrderLink').attr("href", actionUrl("/clientfile"));
            $('#freeOrderLink').attr("href", actionUrl("/clientfile"));
            $('#btnOrder').attr("href", actionUrl("/clientfile"));
            innerInit();
        };


        innerInit = function() {

            $(".sidebar-item h3").hover(
                function() { $(this).css('color', '#395473'); },
                function() { $(this).css('color', '#ffffff'); }
             );


            if ($(".utilbuttons ul:has(*)").length != 0 && $("#dontDisplayUtils").length == 0) {
                $(".utilbuttons").show();
                Tody.Common.recalculateContentPadding();
            }

            $(".jcarousel").jcarousel({ vertical: true, scroll: 2 });

            $("div.default-collapsed div.collapse-me").hide();

            $("div.i-can-be-collapsed h3").click(function() {
                $(this).next('div.collapse-me').slideToggle('slow');
            });

            /*var sidebarHeight = $("#sidebar").height();
            var contentHeight = $("#content").height();
            //alert('sidebar: ' + sidebarHeight + ', content: ' + contentHeight);
            if (contentHeight < sidebarHeight)
            $("#content").css("height", sidebarHeight + "px");
            else $("#fillSidebar").css("height", (contentHeight - sidebarHeight) + "px");*/

            $.updnWatermark.attachAll();
        };

        self.getPaidOrderForm = function(ordertype, onUnload) {
            Tody.ContentMenu.deleteCookie();
            self.showBoxy(actionUrl('/choosepaidorder?ordertype=' + ordertype), ' ', onUnload);
        };

        self.getFreeOrderForm = function(ordertype) {
            Tody.ContentMenu.deleteCookie();
            self.showBoxy(actionUrl('/choosefreeorder?ordertype=' + ordertype), ' ');
        };

        self.collapseLinks = function(menuId) {
            $("div.collapsible" + menuId).slideToggle();
        };

        self.getFreeAdvanceOrderForm = function(isLabSet, orderType) {
            Tody.ContentMenu.deleteCookie();
            $.get(actionUrl('/choosefreeadvanceorder?isLabSet=' + isLabSet + '&orderType=' + orderType), function(result) {

                if (result === '' || result === ' ') {
                    window.location = actionUrl('/patient?isLabSet=' + isLabSet + '&orderType=' + orderType + '&requiresOrderSetInWork=false');
                }
                else {
                    self.showBoxyHtml(result);
                }

            });


        };

        self.getChooseOrderTypeForm = function(isPrivateClient, orderBlocked, blockedText, button, ordertype, onUnload) {
            if ($("#ClientQuestionary_QuestionaryId").length == 0) {
                Tody.ContentMenu.deleteCookie();

                if (isPrivateClient == 'True') {
                    self.showBoxy(actionUrl('/chooseordertype'), ' ', onUnload);
                } else if (orderBlocked !== undefined && orderBlocked == 'True') {
                    Boxy.alert(blockedText, null,
                        {
                            title: "Atentie",
                            closeOnButtonClick: true
                        });
                } else {
                    self.getPaidOrderForm(ordertype, onUnload);
                }
            }
        };

        self.getPaidOrderOptions = function(button, orderBlocked, orderBlockedText, ordertype) {
            var box = Boxy.get(button);
            box.hideAndUnload();

            if (orderBlocked == 'True') {
                Boxy.alert(orderBlockedText, null,
                        {
                            title: "Atentie",
                            closeOnButtonClick: true
                        });
            }
            else {
                self.getPaidOrderForm(ordertype);
            }
        };

        self.getFreeOrderOptions = function(button, mbBlocked, mbBlockedText, ordertype) {
            var box = Boxy.get(button);
            box.hideAndUnload();

            if (mbBlocked == 'True') {
                Boxy.alert(mbBlockedText, null,
            {
                title: "Atentie",
                closeOnButtonClick: true
            });
            }
            else {
                self.getFreeOrderForm(ordertype);
            }
        };

        self.getFreeAdvanceOrderOptions = function(button, isLabSet, orderType) {
            var box = Boxy.get(button);
            box.hideAndUnload();
            self.getFreeAdvanceOrderForm(isLabSet, orderType);
        };

        self.switchToReactivesOrderConfirm = function(title, orderType) {
            self.switchToOrderConfirm(title, '/switchorder/reactives?orderType=' + orderType);

        }

        self.switchToLaboratoryOrderConfirm = function(title, orderType) {

            self.switchToOrderConfirm(title, '/switchorder/laboratory?orderType=' + orderType);

        }

        self.switchToAdvanceReactivesOrderConfirm = function(title, orderType) {

            self.switchToOrderConfirm(title, '/switchorder/advancereactives?orderType=' + orderType);

        }

        self.switchToAdvanceLaboratoryOrderConfirm = function(title, orderType) {

            self.switchToOrderConfirm(title, '/switchorder/advancelaboratory?orderType=' + orderType);

        }

        self.switchToOrderConfirm = function(title, action) {

            var html = orderSwitchConfirmTemplate.replace("__orderType__", title)
	            .replace("__confirmationButton__", Tody.Common.getLinkButton(action, 'DA', 'accept.png'))
	            .replace("__closeButton__", Tody.Common.getBoxyCloseButton('NU', 'cancel.png'));

            self.showBoxyHtml(html);

        }

        self.showBoxyHtml = function(resultHtml, canClose) {
            var result = $('<div></div>').append(resultHtml);
            contactBoxy = new Boxy(result[0], {
                title: " ",
                draggable: false,
                modal: true,
                show: true,
                closeable: canClose !== undefined ? canClose : true
            });

            return contactBoxy;
        };

        self.showBoxy = function(address, title, onUnload) {

            onUnload = onUnload || function() { };

            var boxyToClose = Tody.MasterPage.showBoxyHtml("<div><img src='content/ajax-loader-large.gif' style='padding-left:170px' alt='loader'/></div>", false);

            Boxy.load(address, {
                title: title,
                draggable: false,
                modal: true,
                show: true,
                unloadOnHide: true,
                afterShow: function() {
                    boxyToClose.hideAndUnload();
                },
                afterHide: onUnload
            });
        };
    };

})(jQuery);



(function($) {

    $.fn.button = function() {
        return this.each(function() {
            var button = (this);

            $.fn.extend({
                setWorking: function(value) {
                    var self = (this);
                    var img = $(self).find("img:eq(0)");

                    self.attr("disabled", value);

                    if (value) {
                        img.data("originalsrc", img.attr("src"));
                        img.attr("src", imageUrl("/working-button.gif"));
                    } else {
                        img.attr("src", img.data("originalsrc"));
                        img.removeData("originalsrc");
                    }
                }
            }); //fn.extend

        }); //each
    };

    jQuery(function() {
        $("button, a.button, .btnBlue").button();
    });

})(jQuery);



// tooltip

tooltip = function() {
    /* CONFIG */
    xOffset = 30;
    yOffset = 5;
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result		
    /* END CONFIG */
    $("a.tooltip").hover(function(e) {
        this.t = this.title;
        this.title = "";
        $("body").append("<p id='tooltip'>" + this.t + "</p>");
        $("#tooltip")
			      .css("top", (e.pageY - xOffset) + "px")
			      .css("left", (e.pageX + yOffset) + "px")
			      .css("background-color", "#6CA60E")
			      .css("color", "White")
			      .css("padding", "3px")
			      .css("font-size", "16px")
			      .css('position', 'absolute')
			      .fadeIn("fast");
    },
	function() {
	    this.title = this.t;
	    $("#tooltip").remove();
	});
    $("a.tooltip").mousemove(function(e) {
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
    });
};

// starting the script on page load
$(document).ready(function() {

    //tooltip(); 
    $("a.tooltip").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        fade: 250
    });

    $(".utilbuttons a").click(function() {

        var form = lastSubmittedForm;

        if (form && $(form).valid) {
            if ($(form).valid()) {
                $(this).setWorking(true);
            }
        }
        else $(this).setWorking(true);

    });

    $(".btnBlue").click(function() {
        var form = $(this).parents('form:eq(0)')

        if (form && $(form).valid) {
            if ($(form).valid()) {
                $(this).setWorking(true);
            }
        }
        else $(this).setWorking(true);
    });

    $("#txtSearch").val(decodeURIComponent(Tody.Common.getUrlParameter("searchstring")));



});


function setMaxHeight(elementClass, height) {
    var container = $("." + elementClass);
    container.height((container.height() > (height - 1)) ? height + "px" : "auto");
}

$(function() {
    jQuery('.leftmenu').accordion();
});
