/*global jQuery, dotLBDetect, checkForm, window, novGlossary */
/*jslint browser: true, devel: true, regexp: false, maxlen: 100, nomen: false, plusplus: false,
    onevar: false */

if (typeof dotLBDetect === "undefined") {

    if (typeof String.trim === "undefined") {
        String.prototype.trim = function () { // missing method trim for all strings
            return this.replace(/^\s+|\s+$/g, "");
        };
    }

    jQuery.noConflict(); // jQuery with no conflict to other js libraries
    var nova = {}; // container of all our javascript functionality
    nova.cookie = { // cookie handling
        "get": function (name) {
            for (var cookie = document.cookie.split(";"), i = cookie.length - 1, element; i > -1;
                    i -= 1) {
                element = cookie[i];
                if (name === jQuery.trim(element.substring(0, element.indexOf("=")))) {
                    return jQuery.trim(element.substring(element.indexOf("=") + 1, element.length));
                }
            }
            return null;
        },
        "remove": function (name) {
            document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT;";
            return document.cookie;
        },
        "set": function (name, value, duration, domain, path, secure) {
            document.cookie = [
                name, "=", value,
                (duration ? "; expires=" + new Date(new Date().getTime() + duration)
                        .toGMTString() : ""),
                (domain ? "; domain=" + domain : ""),
                (path ? "; path=" + path : ""),
                (secure ? "; secure" : "")
            ].join("");
            return document.cookie;
        }
    };

    nova.shake = function() {
            jQuery("#login-box").animate({"margin-left":"-=10px"},"fast");
            jQuery("#login-box").animate({"margin-left":"+=20px"},"fast");
            jQuery("#login-box").animate({"margin-left":"-=20px"},"fast");
            jQuery("#login-box").animate({"margin-left":"+=20px"},"fast");
            jQuery("#login-box").animate({"margin-left":"-=20px"},"fast");
            jQuery("#login-box").animate({"margin-left":"+=10px"},"fast");
    };

    nova.footer = function () { // resizes fat-footer entries to the maximum fat-footer entry
        var max = 0;
        jQuery("#fat-footer > ul > li").each(function () {
            jQuery(this).removeAttr("style");
            var height = jQuery(this).height();
            max = max < height ? height : max;
        });
        jQuery("#fat-footer > ul > li").css("height", max + "px");
    };

    nova.font = { // resizes fonts
        "size": {
            "normal": "13px",
            "big": "15px",
            "huge": "17px"
        },

        "resize": function (classname) {
            jQuery("#subnav > ul > li > a").addClass("changing");
            jQuery("body").animate({
                "fontSize": nova.font.size[classname]
            }, 500, function () {
                document.body.className = classname;
                if (classname === "normal") {
                    jQuery("#subnav > ul > li > a").removeClass("changing");
                }
                nova.footer();
            });
            nova.cookie.set("size", classname, false, false, "/");
        }
    };

    nova.form = {
        "isMail": function (mail) {
            return (/^[^\s()<>@,;:\/]+@\w[\w\.\-]+\.[a-z]{2,}$/i).test(mail);
        }
    };

    nova.lexicon = function() {

        // window.console.log("starting nova.lexicon()...");

        // check novGlossary variable:
        if(!novGlossary || typeof novGlossary !== "object")
            return;

        // highlighting only on article detail view:
        if(!jQuery(".article").length)
            return;

        // window.console.log("nova.lexicon() still executing, checks are ok");

        var jContent = nova.contentNode, glossary = novGlossary;

        // function to pop a glossary entry from glossary:
        var popGlossaryEntry = function(glossary) {
            var key, glossaryEntry;
            for(key in glossary)
                if(glossary.hasOwnProperty(key)) {
                    glossaryEntry = glossary[key];
                    delete glossary[key];
                    return glossaryEntry;
                }
            return null;
        }

        // function to highlight a glossaryEntry:
        var highlightGlossaryEntries = function(glossaryEntry) {

            // if all entries are processed, apply tiptip and return:
            if(!glossaryEntry) {
                // window.console.log("all glossary entries processed, now applying tiptip...");
                jQuery(".lexicon-entry", jContent).tipTip();
                return;
            }

            var i, term, jTerm;
            for(i in glossaryEntry.terms) {

                term = glossaryEntry.terms[i];

                // window.console.log("searching for term '" + term + "'...");

                // highlight words to find via highlighter plugin:
                jContent.wordUp({
                    "case": true,
                    findFirstOnly: true,
                    forbiddenParents: "a, h1, h2, h3, .h1, .h2, .h3, .additionalInformation, .lexicon-entry, .highlight, .article-list-item, .article-summary, .headline",
                    needle: term,
                    standAlone: true
                });

                jTerm = jQuery(".highlight", jContent);
                if(jTerm.length > 0) { // if term found

                    // window.console.log("term '" + term + "' found, now manipulating dom for tiptip and schedule next function call...");

                    // manipulate dom node for tiptip:
                    jTerm.attr("title", glossaryEntry.description); // add title
                    jTerm.removeClass("highlight"); // used only for the current iteration
                    jTerm.addClass("lexicon-entry"); // add class for tiptip

                    // schedule highlightGlossaryEntries(...) for next glossary entry:
                    setTimeout(function() {
                        highlightGlossaryEntries(popGlossaryEntry(glossary));
                    }, 0);

                    return; // return from current function

                } // else window.console.log("term '" + term + "' not found.");

            }

            setTimeout(function() {
                highlightGlossaryEntries(popGlossaryEntry(glossary));
            }, 0);

        }

        highlightGlossaryEntries(popGlossaryEntry(glossary));

        // window.console.log("nova.lexicon() executed.");

    };

    nova.tracking = {

        trackDownload: function() {

            var jThis = jQuery(this);
            if(!jThis.is("a[href]")) // no 'a' tag with 'href' attribute, do nothing
                return;

            var value = nova.tracking.getTrackingValue(jThis);

            var target = jThis.attr("target");
            window.console.log("tracking PDF Download: " + value);
            _gaq.push(["_trackEvent", "PDF", "Download", value]);

            // <hack>
            // problem: if download starts immediately, the ga tracking image is not loaded for some reason
            // solution: delay download, so that the ga tracking image has the chance to be loaded
            // see: http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55527
            window.setTimeout(function() {
                window.open(jThis.attr("href"), !target ? "_self" : target);
            }, 200);
            return false;
            // </hack>

        },

        trackClick: function(element, label, jLink) {

            var value = nova.tracking.getTrackingValue(jLink);
            var target = jLink.attr("target");

            window.console.log("tracking '" + label + "' on '" + element + "': " + value);
            _gaq.push(["_trackEvent", element, label, value]);

            // <hack>
            // problem: if download starts immediately, the ga tracking image is not loaded for some reason
            // solution: delay download, so that the ga tracking image has the chance to be loaded
            // see: http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55527
            window.setTimeout(function() {
                window.open(jLink.attr("href"), !target ? "_self" : target);
            }, 200);
            return false;
            // </hack>

        },

        trackView: function(jLink) {
            var value = nova.tracking.getTrackingValue(jLink);
            window.console.log("tracking Image View: " + value);
            _gaq.push(["_trackEvent", "Image", "View", value]);
        },

        trackSearch: function(term) {
            window.console.log("tracking Search: " + term);
            _gaq.push(["_trackEvent", "Search", "Search", term]);
        },

        getTrackingValue: function(jLink) {

            var value = jLink.attr("data-track-value");
            if(value)
                value = value.trim();
            if(value)
                return value;

            value = jLink.attr("title");
            if(value)
                value = value.trim();
            if(value)
                return value;

            value = jLink.attr("href");
            value = value.replace(/\?.*/, "").replace(/.*\//, "");
            return value;

        }

    };

    nova.disclaimer = {

        externalLink: function(jLink) {
            var url = jLink.attr("href");
            var from = "";
            if(jQuery("body").attr("id") == "fachkreise")
                from = "fachkreise";
            window.open("/_application/disclaimer-seite-verlassen.html?url=" + encodeURIComponent(url) + "&from=" + from, "_blank", "dependent=yes,height=250,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,width=350");
            return false;
        },

        internalSiteRegexp: /^https?\:\/\/(www\.)((leben-mit-akromegalie.de)|(leben-mit-cml.de)|(leben-mit-gist.de)|(leben-mit-hypophysentumoren.de)|(leben-mit-myelofibrose.de)|(leben-mit-net.de)|(leben-mit-nierenzellkarzinom.de)|(leben-mit-prostatakrebs.de)|(leben-mit-transfusionen.de)|(leben-mit-tsc.de)|(ueberleben-mit-brustkrebs.de)).*/i

    };

    jQuery(document).ready(function () {

        if(typeof window.console === "undefined") {
            window.console = {
                log: function(text) {}
            };
        }

        nova.contentNode = jQuery("#nova-content");

        jQuery("a.send-slTopicForm").click(function () {
            var expertQuestionForPrivateData = "Bitte stellen Sie sicher, dass Sie keine persönlichen Daten wie Name, Adresse usw. in Ihrer Frage angegeben haben.";
            var jThis = jQuery(this);
            var jForm = jThis.parents("form");
            var isExpert = (jForm.find("input[type='hidden'][name='is_expert']").val() === "true");
            var checkForPrivateData = isExpert ? true : window.confirm(expertQuestionForPrivateData);
            if(checkForm() && checkForPrivateData) {
                jThis.addClass("hidden");
                jQuery("a.send-slTopicForm-inactive").removeClass("hidden");
                jForm.submit();
            }
        });

        jQuery("a.send-slPostForm").click(function () {
            var expertQuestionForPrivateData = "Bitte stellen Sie sicher, dass Sie keine persönlichen Daten wie Name, Adresse usw. in Ihrer Antwort angegeben haben.";
            var jThis = jQuery(this);
            var jForm = jThis.parents("form");
            var isExpert = (jForm.find("input[type='hidden'][name='is_expert']").val() === "true");
            var isForum = (jForm.find("input[type='hidden'][name='is_forum']").val() === "true");
            var checkForPrivateData = (isExpert || isForum) ? true : window.confirm(expertQuestionForPrivateData);
            if(checkForm() && checkForPrivateData) {
                jThis.addClass("hidden");
                jQuery("a.send-slPostForm-inactive").removeClass("hidden");
                jForm.submit();
            }
        });

        jQuery("#font-size-button-normal").click(function () {
            var oldclassname = nova.cookie.get("size");
            if (oldclassname !== "normal") {
                nova.font.resize("normal", oldclassname);
            }
            return false;
        });

        jQuery("#font-size-button-big").click(function () {
            var oldclassname = nova.cookie.get("size");
            if (oldclassname !== "big") {
                nova.font.resize("big", oldclassname || "normal");
            }
            return false;
        });

        jQuery("#font-size-button-huge").click(function () {
            var oldclassname = nova.cookie.get("size");
            if (oldclassname !== "huge") {
                nova.font.resize("huge", oldclassname || "normal");
            }
            return false;
        });

        jQuery("#newsletter-subscribe").click(function () {
            if (nova.form.isMail(this.form.email.value)) {
                this.form.action.value = "subscribe";
                this.form.submit();
                return true;
            }

            // wtf? what is that for?
            jQuery("#newsletter-error .first, #newsletter-error .last, #newsletter-error .mail")
                .removeClass("hidden")
                .addClass("hidden");

            if (!nova.form.isMail(this.form.email.value)) {
                jQuery("#newsletter-error .mail").removeClass("hidden");
            }

            jQuery("#newsletter-error").css("display", "none")
                .removeClass("hidden")
                .show("fast");
            return false;
        });

        jQuery("#newsletter-unsubscribe").click(function () {
            if (nova.form.isMail(this.form.email.value)) {
                this.form.action.value = "unsubscribe";
                this.form.submit();
                return true;
            }

            // wtf? what is that for?
            jQuery("#newsletter-error .first, #newsletter-error .last, #newsletter-error .mail")
                .removeClass("hidden")
                .addClass("hidden");

            jQuery("#newsletter-error .mail").removeClass("hidden");
            jQuery("#newsletter-error").css("display", "none")
                .removeClass("hidden")
                .show("fast");
            return false;
        });
        jQuery(".picstreet .thumb").click(function () {
            jQuery(".picstreet .full").attr("src", jQuery(this).attr("src"));
        });

        jQuery(".print-button").click(function () {
            print();
            return false;
        });

        jQuery(".video").click(function () {
            var x = open(jQuery(this).attr("href"), "_blank", ["dependent = yes", "height = 300",
                    "width = 400", "hotkeys = no", "location = no", "menubar = no",
                    "resizable = yes", "scrollbars = no", "status = no", "toolbar = no"].join(","));
            x.focus();
            return false;
        });

        jQuery("map > [id^=coord]")
            .mouseover(function () {
                var activeImage = jQuery("#click-image-description-images ." + jQuery(this)
                        .attr("id")),
                    defaultImage = jQuery("#click-image-description-images .default");
                if (activeImage.length) {
                    defaultImage.addClass("hidden");
                    activeImage.removeClass("hidden");
                }
            })
            .mouseout(function () {
                var activeImage = jQuery("#click-image-description-images ." +
                        jQuery(this).attr("id")),
                    defaultImage = jQuery("#click-image-description-images .default");
                if (activeImage.length) {
                    defaultImage.removeClass("hidden");
                    activeImage.addClass("hidden");
                }
            })
            .click(function () {
                var activeNode = jQuery("#text-" + jQuery(this).attr("id")),
                    inactiveNode = jQuery("#click-image-description-texts > div.active");
                jQuery("#click-image-description-texts").slideUp("slow", function () {
                    inactiveNode
                        .removeClass("active")
                        .addClass("hidden");
                    activeNode
                        .addClass("active")
                        .removeClass("hidden");
                    jQuery(this)
                        .slideDown("slow")
                        .removeClass("hidden");
                });
                return false;
            });

        jQuery("#orderForm").submit(function () {

            var jOrderForm = jQuery(this);

            var isComplete = true;
            jQuery(".missing").removeClass("missing");
            jQuery(".no-order-error").addClass("hidden");

            var jMoreInfo = jOrderForm.find("input#more_info");
            if(jMoreInfo && jMoreInfo.length > 0) {
                if(jOrderForm.find("input#more_info").get(0).checked) {
                    jOrderForm.find("input[type='hidden'][name='action']").val("subscribe");
                } else {
                    jOrderForm.find("input[type='hidden'][name='action']").val("");
                }
            }

            jOrderForm.find("[data-required]").each(function() {
                var jThis = jQuery(this);
                if(!jThis.val()) {
                    jThis.addClass("missing");
                    isComplete = false;
                } else if(jThis.attr("data-required") === "email" && !nova.form.isMail(jQuery(this).val())) {
                    jThis.addClass("missing");
                    isComplete = false;
                }
            });

            // if "more_info" is checked, #email gets required, otherwise, #email is not required:
            if(jOrderForm.find("input#more_info:checked").length == 1 && jOrderForm.find("input#email").length > 0) {
                jOrderForm.find("input#email").each(function() {
                    var jInputEmail = jQuery(this);
                    if(!jInputEmail.val() && !nova.form.isMail(jInputEmail.val())) {
                        jInputEmail.addClass("missing");
                        isComplete = false;
                    }
                });
            }

            // check if there is at least one order item checked:
            if(jOrderForm.find("#order-list").length > 0 && jOrderForm.find("#order-list input[type=checkbox]:checked").length == 0) {
                jQuery(".no-order-error").removeClass("hidden").addClass("missing");
                isComplete = false;
            }

            jOrderForm.find(".short").each(function() {
                var jThis = jQuery(this);
                if(!/^(\d+)$/.test(jThis.val())) {
                    jThis.addClass("missing");
                    isComplete = false;
                }
            });

            if(!isComplete) {
                jQuery(".error").css("display", "none").removeClass("hidden").show("fast");
            }

            // jQuery("#autoReplyTo").val(jQuery("#email").val());
            return isComplete;

        });

        jQuery("a[href$=.jpg], a[href$=.gif], a[href$=.jpeg], a[href$=.png], a[href$=.swf]").click(function() {
            nova.tracking.trackView(jQuery(this));
        }).fancybox({
            titlePosition: "inside",
            autoScale: false
        });

        jQuery("a.info-graphic-download").click(function() {
            return window.confirm("Wenden Sie sich bei Fragen zu dem Schaubild bitte direkt an Ihren Arzt. Vielen Dank!");
        });

        jQuery("a[href*=.pdf]").live('click', nova.tracking.trackDownload);

        jQuery("a[data-track-element]").live('click', function() {
            var jThis = jQuery(this);
            var element = jThis.attr("data-track-element");
            var label = jThis.attr("data-track-label");
            if(!element || !label || !jThis.attr("href"))
                return true;
            return nova.tracking.trackClick(element, label, jThis);
        });

        jQuery("a.external").click(function() {
            return nova.disclaimer.externalLink(jQuery(this));
        });

        jQuery("#nova-content a").click(function() {

            var jLink = jQuery(this); // get jQuery element of this

            if(jLink.hasClass("no-disclaimer")) { // if disclaimer should be avoided
                return true;
            }

            var url = jLink.attr("href"); // get url of current link

            if(!url.match(/^https?\:\/\//i)) { // if no absolute link, don't show disclaimer
                return true;
            }

            if(url.match(nova.disclaimer.internalSiteRegexp)) { // if absolute, but internal link, don't show disclaimer
                return true;
            }

            return nova.disclaimer.externalLink(jLink);

        });

        jQuery("a.submit-create-posting-form").click(function () {
            var adviceForPrivateDataUsage = "Bitte stellen Sie sicher, dass Sie keine persönlichen Daten wie Name, Adresse usw. in Ihrer Frage angegeben haben.";
            var jThis = jQuery(this);
            var jForm = jThis.parents("form");
            if(!jThis.hasClass("no-advice")) {
                var checkForPrivateData = window.confirm(adviceForPrivateDataUsage);
            } else {
            	var checkForPrivateData = true;
            }
            if(checkForPrivateData) {
                jForm.submit();
            }
        });

        jQuery("#acceptTermsOfUseForm").submit(function () {
            var form = jQuery(this);

            var isComplete = true;

            var nick = form.find('input[name="nick"]');
            if(!nick.val()) {
                nick.addClass("missing");
                jQuery(".login-messages .no-nickname").show();
                isComplete = false;
            } else {
                nick.removeClass("missing");
                jQuery(".login-messages .no-nickname").hide();
            }

            var terms_of_use = form.find('input[name="terms_of_use"]');
            if(!terms_of_use.attr('checked')) {
                terms_of_use.addClass("missing");
                jQuery(".login-messages .not-accepted").show();
                isComplete = false;
            } else {
                terms_of_use.removeClass("missing");
                jQuery(".login-messages .not-accepted").hide();
            }

            if(!isComplete) {
                jQuery(".login-messages").show();
            } else {
                jQuery(".login-messages").hide();
            }

            return isComplete;
        });

        jQuery("#crumbtrail li a:contains('Service')").removeAttr("href");

        jQuery("a.start-presentation").addClass("no-disclaimer");
        jQuery("a.start-presentation").click(function(){
        	window.open('/vortrag-prof-franz/start.html', '_blank', 'dependent=yes,height=700,location=no,titlebar=no,directories=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,width=1050');
        });

        // window.console.log('executing: require(["/service/lexicon-entries-js.html"], function() { nova.lexicon(); })...');
        require(["/service/lexicon-entries-js.html"], function() { nova.lexicon(); });
        // window.console.log('require(["/service/lexicon-entries-js.html"], function() { nova.lexicon(); }) executed.');

        //=== ajax based search ====================================================================
        nova.search = {

            pageSize: 10,
            jContentNode: nova.contentNode,
            page: 0,
            term: "",
            site: "",

            fileTypes: {
                pdf: "PDF"
            },

            /** Called from outside. */
            bingSearch: function (term, site) {
                this.page = 0;
                this.term = term;
                this.site = site;
                //this._search();
                this._bingSearch();
            },

            back: function () {
                nova.search.page--;
                //nova.search._search();
                nova.search._bingSearch();
            },

            forward: function () {
                nova.search.page++;
                //nova.search._search();
                nova.search._bingSearch();
            },

            callback: function(answer) {
                var that = nova.search;
                var html = "";
                html += '<div id="searchresults" class="shadebox"><h1>Suchergebnisse</h1>';
                var results = [];
                if(typeof answer.query !== "undefined" && answer.query != null)
                    if(typeof answer.query.results !== "undefined" && answer.query.results != null)
                        results = answer.query.results.result;
                if(!jQuery.isArray(results))
                    results = [ results ];
                if(results.length > 0) {
                    html += "<dl>";
                    jQuery.each(results, function(i, result) {
                        if(i < that.pageSize) {

                            var title = result.title;
                            // title = title.replace(/\<b\>/ig, '').replace(/\<\/b\>/ig, '');

                            var content = result["abstract"];
                            content = content.replace(/\<b\>\.\.\.\<\/b\>/ig, "...");
                            content = content.replace(/\<b\>/ig, '<span class="searchresult">').replace(/\<\/b\>/ig, '</span>');

                            var fileExtensionIndex = result.url.lastIndexOf(".");
                            if(fileExtensionIndex >= 0) {
                                var fileExtension = result.url.substring(result.url.lastIndexOf(".") + 1);
                                var fileType = that.fileTypes[fileExtension];
                                if(typeof fileType === "string") {
                                    title = '<span class="file-type">[' + fileType + ']</span> ' + title;
                                }
                            }

                            html += '<dt><a href="' + result.url + '">' + title + '</a></dt><dd>' + content + '</dd>';

                        }
                    });
                    html += "</dl>";
                    if (that.page > 0) {
                        html += '<a href="#" id="back-button" class="readMore float-left ' +
                                'arrow">Zur&uuml;ck</a>';
                    }
                    if (results.length > 10) {
                        html += '<a href="#" id="forward-button" ' +
                                'class="readMore float-right arrow">Vorw&auml;rts</a>';
                    }
                } else {
                    html += '<div class="search-results">Ihre Suche nach &quot;' + that.term +
                            '&quot; ergab keine Ergebnisse.</div>';
                }
                html += '<br clear="all"></div>';
                that.jContentNode.html(html);
            },

            bingCallback: function(answer) {
                var that = nova.search;
                var html = "";
                html += '<div id="searchresults" class="shadebox"><h1>Suchergebnisse</h1>';
                var results = [];
                if(typeof answer.SearchResponse.Web.Results !== "undefined" && answer.SearchResponse.Web.Results != null)
                    results = answer.SearchResponse.Web.Results;
                if(!jQuery.isArray(results))
                    results = [ results ];
                if(results.length > 0) {
                    html += "<dl>";
                    jQuery.each(results, function(i, result) {
                        if(i < that.pageSize) {

                            var title = result.Title;
                            title = title.replace(new RegExp("\uE000", "g"), '<span class="searchresult">').replace(new RegExp("\uE001", "g"), '</span>');

                            var content = result.Description;
                            content = content.replace(new RegExp("\uE000", "g"), '<span class="searchresult">').replace(new RegExp("\uE001", "g"), '</span>');

                            var fileExtensionIndex = result.Url.lastIndexOf(".");
                            if(fileExtensionIndex >= 0) {
                                var fileExtension = result.Url.substring(result.Url.lastIndexOf(".") + 1);
                                var fileType = that.fileTypes[fileExtension];
                                if(typeof fileType === "string") {
                                    title = '<span class="file-type">[' + fileType + ']</span> ' + title;
                                }
                            }

                            html += '<dt><a href="' + result.Url + '">' + title + '</a></dt><dd>' + content + '</dd>';

                        }
                    });
                    html += "</dl>";
                    if (that.page > 0) {
                        html += '<a href="#" id="back-button" class="readMore float-left ' +
                                'arrow">Zur&uuml;ck</a>';
                    }
                    if (results.length > 10) {
                        html += '<a href="#" id="forward-button" ' +
                                'class="readMore float-right arrow">Vorw&auml;rts</a>';
                    }
                } else {
                    html += '<div class="search-results">Ihre Suche nach &quot;' + that.term +
                            '&quot; ergab keine Ergebnisse.</div>';
                }
                html += '<br clear="all"></div>';
                that.jContentNode.html(html);
            },

            _search: function () {

                window.console.log("searching for term: " + this.term + " | site: " + this.site + " | page: " + this.page);

                var query = 'select title, abstract, url from search.web(' +
                        (this.page * this.pageSize) + ', ' + (this.pageSize + 1) +
                        ') where query = "' + this.term + ' site:' + this.site + '" and appid = "www.ueberleben-mit-brustkrebs.de"';
                window.console.log("YQL Query: " + query);

                var yql = (("https:" == document.location.protocol) ? "https://" : "http://")+
                        "query.yahooapis.com/v1/public/yql?q=" +
                        encodeURIComponent(query) + "&format=json&diagnostics=false&env=" +
                        encodeURIComponent("store://datatables.org/alltableswithkeys") +
                        "&callback=window.nova.search.callback";
                // window.console.log("YQL URL: " + yql);

                this.jContentNode.html('<div id="searchresults" class="shadebox">' +
                        '<h1>Suchergebnisse</h1><div class="search-results">Bitte warten' +
                        ', Suche wird gestartet...</div></div>');

                // jQuery.getJSON(yql, nova.search.callback);

                var script = "<script src='" + yql + "' type='text/javascript'></script>";
                // window.console.log("Script to embed: " + script);
                jQuery(script).insertAfter("script:last");

            },

            _bingSearch: function () {

                window.console.log("searching for term: " + this.term + " | site: " + this.site + " | page: " + this.page);

                var requestStr = "http://api.bing.net/json.aspx?"

                // Common request fields (required)
                + "AppId=" + "74FB666D74F9285F86DD902198B7944F578D80C0"
                + "&Query=" + this.term + " site:" + this.site
                + "&Sources=Web"

                // Common request fields (optional)
                + "&Version=2.0"
                + "&Market=en-us"
                + "&Adult=Moderate"
                + "&Options=EnableHighlighting"

                // Web-specific request fields (optional)
                + "&Web.Count=" + (this.pageSize + 1)
                + "&Web.Offset=" + (this.page * this.pageSize)
                + "&Web.Options=DisableHostCollapsing+DisableQueryAlterations"

                // JSON-specific request fields (optional)
                + "&JsonType=callback"
                + "&JsonCallback=window.nova.search.bingCallback";

                var script = document.createElement('script');
                script.src = requestStr;
                script.type = 'text/javascript';

                jQuery(script).insertAfter("script:last");
            }

        };

        jQuery("#searchForm").submit(function () {
            var jSearchForm = jQuery(this);
            var term = jQuery(":input[name='search_query']", jSearchForm).val();
            var site = jQuery(":input[name='site']", jSearchForm).val();
            nova.tracking.trackSearch(term);
            //nova.search.search(term, site);
            nova.search.bingSearch(term, site);
            return false;
        });

        jQuery("#back-button", nova.search.jContentNode).live("click", nova.search.back);
        jQuery("#forward-button", nova.search.jContentNode).live("click", nova.search.forward);

        jQuery("#search").click(function () {
            var that = jQuery(this);
            if(that.val() === "Finden Sie Ihr Thema")
                that.val("");
        });

        jQuery("#search").blur(function () {
            var that = jQuery(this);
            if(that.val() === "")
                that.val("Finden Sie Ihr Thema");
        });

        jQuery(window).load(function () {
            nova.footer();
        });

    });
}

