/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, strict: true, newcap: true, immed: true */
/*global console, $, dotLBDetect */

"use strict";
var sl = (function () {
    //private
    var ajaxNewsURI = "/news/ajax-news-loader.html",
        ajaxJobURI = "/karriere/jobs/bewerbung.html",

        speed = "fast", // jQuery-Animations
        contentWidth = 924,
        referenceImageWidth = 290,
        referenceDetail, // to hold the reference detail node

        // arrangeColumns
        hr = /<hr[^>]*?>/ig,
        wordsPerColumn = 96,
        columns,        // to hold a node
        precolumn = "<div class='column hidden'>",
        postcolumn = "</div>",
        column = postcolumn + precolumn,

        tooltip = "<div class='tooltip hidden'></div>",

        // where am i?
        isNews = /^\/news\//ig.test(location.pathname),
        isJob = /^\/karriere\/jobs\//ig.test(location.pathname),
        isReferences = /^\/referenzen\//ig.test(location.pathname) || /^\/medical\/referenzen\//ig.test(location.pathname),

        hash = location.hash && location.hash.substring(1),

        newslistheight, // to hold the recent news list heights

        navigationColumns = 3,
        navigationStep,
        navigate = function (columns, further) {
            var previous = [],
                active = columns.filter(function (i) {
                    return i < navigationColumns;
                }).removeClass("hidden");
            navigationStep = 1;
            if (columns.length > navigationColumns) {
                further.removeClass("hidden").click(function () {
                    navigationStep += 1;
                    previous.push(active.addClass("hidden").addClass("obsolete"));
                    active = columns.filter(function (i) {
                        return !$(this).hasClass("obsolete") && i < navigationColumns * navigationStep;
                    }).removeClass("hidden");
                    if (navigationColumns * navigationStep >= columns.length) {
                        $(this).addClass("hidden");
                    }
                    further.next().removeClass("hidden");
                }).next().click(function () {
                    active.addClass("hidden");
                    active = previous.pop().removeClass("hidden").removeClass("obsolete");
                    navigationStep -= 1;
                    if (!previous.length) {
                        $(this).addClass("hidden");
                    }
                    further.removeClass("hidden");
                });
            }
        };

    // public
    return {
        "arrangeColumns": function (parameter) {
            var i,
                k,
                text = parameter.text || parameter.node.html();

            hr.lastIndex = 0;
            if (hr.test(text)) {
                //hr.lastIndex = 0; //Do we need that line?
                text = /column/i.test(text) ? text.replace(hr, column) : precolumn + text.replace(hr, column) + postcolumn;
            } else if (parameter.force) {
                text = (function (s, tmp) {
                    while (/<[^>]*?\s[^>]*?>/.test(s)) {
                        s = s.replace(/<([^>]*?)\s/ig, ("<$1_qwertz_"));
                    }
                    return s;
                }(text)).split(/\s+/);
                for (i = 1, k = text.length / wordsPerColumn; i < k; i += 1) {
                    text[i * wordsPerColumn] += column;
                }
                text = text.join(" ").replace(/_qwertz_/ig, " ");
            } else {
                text = null;
            }

            return text;
        },

        "arrangeColumnsInitially": function () {
            var node,
                text;
            node = $("div#content div.entry");
            node = node.length ? node : $("div#content > div.columns");
            node.each(function () {
                text = sl.arrangeColumns({
                    "node": $(this)
                });
                if (text) {
                    $(this).html(text);
                }
            });
        },

        "arrangeNewsOverview": function () {
            var that = $(this),
                year = that.removeClass("active").attr("class"),
                left = that.position().left,
                news = $("div#news-" + year),
                current = $("div#content div.news-navigation div.active");
            that.addClass("active").siblings().removeClass("active");
            current.addClass("hidden").removeClass("active");
            news.css("marginLeft", (function () {
                var result = left - 128;
                return (result < 7 ? 7 : result > 658 ? 658 : result) + "px";
            }())).removeClass("hidden").addClass("active").children(":eq(3)").children(":eq(0)").removeAttr("style");

            newslistheight = [];
            newslistheight.push((function () {
                var x = 0;
                news.children(":eq(3)").children().each(function () {
                    x += $(this).height() + 20;
                });
                return x;
            }()));
            newslistheight.push(news.children(":eq(3)").height());
        },

        "getAndPrintNews": function (inode) {
            columns = columns || $("div#content div.columns").after('<div class="news-columns"></div>').next();
            inode = typeof inode === "number" || typeof inode === "string" ? inode : $(this).attr("class");

            var parent = $(this).parent().parent();
            if (parent.hasClass("news")) {
                parent.addClass("hidden");
            }

            columns.fadeOut(speed, function () {
                columns.addClass("loading");
                columns.html("");
                columns.fadeIn(speed, function () {
                    $.ajax({
                        "cache" : true,
                        "data" : {
                            "newsid" : inode
                        },
                        "dataType" : "html",
                        "success" : function (text, status) {
                            columns.fadeOut(speed, function () {
                                columns.html(sl.arrangeColumns({
                                    "node": columns,
                                    "text": text,
                                    "force": true
                                }));
                                columns.removeClass("loading");
                                var further = $("a#further");
                                navigate(further.siblings("div.column"), further);
                                columns.fadeIn(speed);
                            });
                        },
                        "url" : ajaxNewsURI
                    });
                });
            });
        },

        "printFirstNews": function () {
            if (isNews) {
                sl.getAndPrintNews(hash || $("div#content div.news li:ep(0)").attr("class"));

                var up = $("div#content div.news-navigation div.up");

                up.mousedown(function () {
                    var that = $(this),
                        list = that.next().next().children(":eq(0)");
                    that.next().removeClass("hidden");
                    list.stop().animate({
                        "marginTop": "0px"
                    }, 3500, function () {
                        that.addClass("hidden");
                    });
                }).mouseup(function () {
                    $(this).next().next().children(":eq(0)").stop();
                }).next().mousedown(function () {
                    var that = $(this),
                        list = that.next().children(":eq(0)");
                    that.prev().removeClass("hidden");
                    list.stop().animate({
                        "marginTop": "-" + (newslistheight[0] - newslistheight[1]) + "px"
                    }, 2500, function () {
                        that.addClass("hidden");
                    });
                }).mouseup(function () {
                    $(this).next().children(":eq(0)").stop();
                });
            }
        },

        "printReferences": function () {
            if (isReferences) {
                var referenceList = $("div#content > div.reference-overview > ul"),
                    length = referenceList.children().length,
                    width = length * (referenceImageWidth + 4);
                referenceList.css("width", width + "px").removeClass("hidden");
                if (width > contentWidth) {
				
					// display arrow to scroll left when we have an inital margin setting - set by referencelisting.vtl from a cookie value
					var left = -parseInt(referenceList.css("marginLeft"), 10);
					if (left > 0) {
						referenceList.prev().removeClass("hidden");
					}
				
                    referenceList.prev().mouseover(function () {
                        var that = $(this);
                        that.prev().removeClass("hidden");
                        referenceList.stop().animate({
                            "marginLeft": "0px"
                        }, (-parseInt(referenceList.css("marginLeft"), 10) + 882) * 1.5, function () {
                            that.addClass("hidden");
                        });
                    }).mouseout(function () {
                        var left = -parseInt(referenceList.css("marginLeft"), 10);
                        if (left < 50) {
                            $(this).addClass("hidden");
                        }
                        if ($(this).is(":visible")) {
                            referenceList.stop().animate({
                                "marginLeft": left < 50 ? "0px" : "+=50px"
                            }, speed);
                        }
                    }).prev().removeClass("hidden").mouseover(function () {
                        var that = $(this);
                        that.next().removeClass("hidden");
                        referenceList.stop().animate({
                            "marginLeft": ["-", width - 3 * (referenceImageWidth + 4), "px"].join("")
                        }, (width + parseInt(referenceList.css("marginLeft"), 10)) * 1.5, function () {
                            that.addClass("hidden");
                        });
                    }).mouseout(function () {
                        var left = -(parseInt(referenceList.css("marginLeft"), 10)) + 50 > width - 882 ? -(width - 882) : "-=50px";
                        if (typeof left === "number") {
                            left += "px";
                            $(this).addClass("hidden");
                        }
                        if ($(this).is(":visible")) {
                            referenceList.stop().animate({
                                "marginLeft": left
                            }, speed);
                        }
                    });
					
					$(".reference-link").click(function() {
						var lastMargin = parseInt(referenceList.css("marginLeft"), 10);
						document.cookie = "reference_margin=" + lastMargin + "; path=/";
					});
                }
            }
        },

        "printJob": function () {
            if (isJob && hash) {
                sl.displayJobOffer(hash);
            }
        },

        "displayJobOffer": function (inode) {
            inode = typeof inode === "number" || typeof inode === "string" ? inode : $(this).attr("href").substring(1);
            $("div#job-detail-" + inode).removeClass("hidden").addClass("active").siblings().not("div.job-column").addClass("hidden").removeClass("active");
        },

        "displayJobApplicationForm": function () {
            var jobDetailIdentifier = "job-detail-",
                jobId = $(this).parent().attr("id");

            if (jobId && new RegExp("^" + jobDetailIdentifier).test(jobId)) {
                jobId = jobId.substr(jobDetailIdentifier.length);
            } else {
                jobId = 0;
            }

            $("div#content div.wide div.active").addClass("hidden").removeClass("active");
            columns = columns || $("div#content > div.columns").after('<div class="job-application"><div class="button close" onclick="$(this).parent().addClass(\'hidden\');"></div><div></div></div>').next().children(":eq(1)");

            columns.fadeOut(speed, function () {
                columns.parent().addClass("loading");
                columns.html("");
                columns.fadeIn(speed, function () {
                    $.ajax({
                        "cache" : true,
                        "data" : {
                            "jobid" : jobId
                        },
                        "dataType" : "html",
                        "success" : function (text, status) {
                            columns.fadeOut(speed, function () {
                                columns.html(text);

                                $("div#step_2 > div > input.almost-hidden").change(function () {
                                    $(this).prev().val($(this).val());
                                });

                                columns.parent().removeClass("loading");

                                var bwd = $("li#bwd"),
                                    fwd = $("li#fwd"),
                                    subm = $("li#submit"),
                                    steps = $("form#application_form > div.step"),
                                    state = $("ul.application-wiz-state li.active"),
                                    activestep = steps.filter(function () {
                                        return $(this).hasClass("active");
                                    });

                                $("form#application_form").ajaxForm(function () {
                                    $("div.job-application ul.application-wiz-nav").addClass("hidden");
                                    activestep = activestep.addClass("hidden").removeClass("active").next().addClass("active").removeClass("hidden");
                                });

                                fwd.click(function () {
                                    var isComplete = true;
                                    if (activestep.nextAll().length > 1) {
                                        $("form#application_form > div.active .missing").removeClass("missing");

                                        $("form#application_form > div.active [required]").each(function () {
                                            if (!$(this).val()) {
                                                $(this).addClass("missing");
                                                if ($(this).prev().hasClass("dummy")) {
                                                    $(this).prev().addClass("missing");
                                                }
                                                isComplete = false;
                                            } else if ($(this).attr("required") === "email" && !(/^[^\s()<>@,;:\/]+@\w[\w\.\-]+\.[a-z]{2,}$/i).test($(this).val())) {
                                                $(this).addClass("missing");
                                                isComplete = false;
                                            }
                                        });

                                        if (isComplete || /igor/.test(location.search)) {
                                            activestep = activestep.addClass("hidden").removeClass("active").next().addClass("active").removeClass("hidden");
                                            state = state.removeClass("active").addClass("done").next().addClass("active");
                                            if (activestep.prev().length) {
                                                bwd.removeClass("hidden");
                                            }
                                            if (activestep.nextAll().length < 2) {
                                                fwd.addClass("hidden");
                                                subm.removeClass("hidden");
                                            }
                                        }
                                    }
                                });

                                bwd.click(function () {
                                    subm.addClass("hidden");
                                    activestep = activestep.addClass("hidden").removeClass("active").prev().addClass("active").removeClass("hidden");
                                    state = state.removeClass("active").prev().addClass("active");
                                    fwd.removeClass("hidden");
                                    if (!activestep.prev().length) {
                                        bwd.addClass("hidden");
                                    }
                                });

                                subm.click(function () {
                                    if ($("input#confirm:checked").length > 0) {
                                        $("form#application_form").submit();
                                        state.addClass("done").removeClass("active");
                                    } else {
                                        $("input#confirm").parent().addClass("missing");
                                    }
                                });
                                columns.fadeIn(speed);
                            });
                        },
                        "url" : ajaxJobURI
                    });
                });
            }).parent().removeClass("hidden");
        },

        "close": function () {
            //location.href = "#";
            $(this).parent().addClass("hidden").removeClass("active");
        },

        "switchDrivingDirections": function () {
            $("div#bigPicture > img." + $(this).attr("id")).removeClass("hidden").siblings().addClass("hidden");
            $(this).addClass("active").siblings().removeClass("active");
        },

        "showLayer": function () {
            $("div#content div.wrap").addClass("hidden");
            $(this).parent().addClass("active").siblings().removeClass("active");
            $(this).next().removeClass("hidden");
        },

        "showLayerInitially": function () {
            if (hash) {
                $("div#content div." + hash).removeClass("hidden").parent().addClass("active");
            }
        },

        "tooltip": function () {
            var text = $(this).attr("sldescription"),
                height;
            if (text) {
                text = text.split("/-/");
                text[0] = ["<div class=\"orange strong\">", text[0], "</div>"].join("");
                tooltip = typeof tooltip === "string" ? $("div#page").after(tooltip).next() : tooltip;
                tooltip.html(text.join(""));
                height = parseInt(tooltip.height(), 10);
                $(this).mousemove(function (e) {
                    tooltip.css("left", e.pageX + -17 + "px");
                    tooltip.css("top", e.pageY + -40 - height + "px");
                });
                tooltip.removeClass("hidden");
            }
        },

        "extooltip": function () {
            tooltip.addClass("hidden");
        },

        "showColumns" : function () {
            if (!isReferences) {
                $("div.columns, div.column").removeClass("hidden");
            }
        },

        "showDetail": function () {
            referenceDetail = referenceDetail || $("#reference-detail");
            $(this).addClass("hidden").next().removeClass("hidden");
            referenceDetail.removeClass("hidden");
        },

        "hideDetail": function () {
            referenceDetail = referenceDetail || $("#reference-detail");
            $(this).addClass("hidden").prev().removeClass("hidden");
            referenceDetail.addClass("hidden");
        },
        "startNewsNav": function () {
            var years = $("ul.years > li"),
                next,       //node left
                prev,       //node right
                wrap,       //node wrap

                running,    //flag running animation
                k = years.length,
                p = 0;

            if (k < 10) {
                return;
            }

            wrap = $("ul.years");
            next = $("div.old-years").addClass("old-years-active");
            prev = $("div.new-years");

            next.click(function (pre) {
                if (running || !next.hasClass("old-years-active")) {
                    return;
                }
                running = true;
                p += 1;
                wrap.animate({
                    "marginLeft": "-=98px"
                }, speed, function () {
                    if (p + 9 === k) {
                        next.removeClass("old-years-active");
                    }
                    prev.addClass("new-years-active");
                    running = false;
                });
            });

            prev.click(function (pre) {
                if (running || !prev.hasClass("new-years-active")) {
                    return;
                }
                running = true;
                p -= 1;
                wrap.animate({
                    "marginLeft": "+=98px"
                }, speed, function () {
                    if (!p) {
                        prev.removeClass("new-years-active");
                        wrap.removeAttr("style");
                    }
                    next.addClass("old-years-active");
                    running = false;
                });
            });
        }
    };
}());

$(document).ready(function () {
    // event handlers
    $("div#content ul.years > li").click(sl.arrangeNewsOverview);
    $("div#content div.news li").click(sl.getAndPrintNews);

    $("div#content div.career a.arrow").click(sl.showLayer);
    $("div#content div.job-offer a").click(sl.displayJobOffer);
    $("div#content a.job-application").click(sl.displayJobApplicationForm);

    $("div#content div.close").click(sl.close);
    $("div#content img.drivingDirections").click(sl.switchDrivingDirections);

    $("map#CompetenceOverview > area, div#content a.reference-link > img").
            mouseover(sl.tooltip).
            mouseout(sl.extooltip);

    $("a#reference-detail-in").click(sl.showDetail);
    $("a#reference-detail-out").click(sl.hideDetail);

    //initial method calls
    sl.arrangeColumnsInitially();
    sl.printFirstNews();
    sl.printJob();
    sl.printReferences();
    sl.showLayerInitially();
    sl.showColumns();
    sl.startNewsNav();

    if (typeof dotLBDetect !== "undefined") {
        $(".hidden").removeClass("hidden");
    }
});
