 /**
 * The following variables should be set by the user who is configuring the faq.
 */
// Number of searches befor the user can see the contact customer services form
//var showEmailFormAt = 3;
// Url to the search button image that will be used in the JS search form
var searchButtonImage = "/static/faq/img/btn_sok.gif";
// Text that is displayed when the search has 0 matches.
var noSearchResultText = 'Din sökning gav inga träffar.';
// The label for search by category
var selectCategoryText = 'Välj kategori';
// Show alla categories option text for the selectbox
var allCategoriesText = 'Alla kategorier';
// The label text for the search box. "search all categories"
var freeSearchTextLabel = 'Sök i alla kategorier';
// Value of the search button.
var searchButtonValue = 'Sök';
// Set a prefix for the questions if you want one. eg "q: "
var questionPrefix = "";
// Set a prefix for the answers if you want one. eg "a: "
var answerPrefix = "";
// set the hidden category
var hiddenCategory = "Övrigt";
//set the top category
var topCategory = "Vanliga frågor";


$(document).ready(function() {
    jQuery.fn.scrollTo = function(speed) {
        if (speed === null)
            speed = 500;
        $('html,body').animate({scrollTop: $(this).offset().top}, speed);
        return false;
    };
    // Set a counter to keep track of the users searches.
    var searchCount = 0;
    // Extend Jquery with a :contains that is case insensitive. use :containsNC for case insensitive traversing.
    $.extend($.expr[":"], {
        "containsNC": function(elem, i, match, array) {
            return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
        }
    });
    // Add prefix to questions and answers
    $(".question").prepend(questionPrefix);
    $(".answer").prepend(answerPrefix);
    // Hide the email information initially. We want to let the user do x searches before we show it
    $("#emailUs").hide();

    // Prepend the search forms to the page.
    prependSearchForms();

    // Hide all the answers.
    $(".answer").hide();

    // Click handler for the questions. on click toggeles the visibility of the answer.
    $("p.question").click(function() {
        answerTo = this.id;
        if (!$("#a_" + answerTo).is(':visible')) {
            sitestatFAQ($("#category :selected").text(), $(this).text(), 1);
        }
        $("#a_" + answerTo).toggle("fast");
    });

    // Search by category
    $("#category").change(function() {
        $("div.qaa").show();
        $(".category").show();
        $("#no_result").hide();
        if ($("#category").attr("value") != "all") { // If a category is selected
            $(".category").hide();
            $("#" + $("#category").attr("value")).fadeIn();
            /* do not open answers anymore
            var qaa = $("#"+$("#category").attr("value")).children(".qaa");
            qaa.each(function(){
                $(this).children(".answer").show();
            });
            */
            // Set status and show emailForm if num of searches is reached.
            if (searchCount >= showEmailFormAt) {
                $("#emailUs").show();
            } else {
                searchCount++;
            }
            sitestatFAQ($("#category :selected").text(), "", 1);
            return false;
        } else { // if all categories are selected
            $(".category").each(function() {
                if ($(this).children("h2").text().indexOf(hiddenCategory) != -1) {
                    $(this).hide();
                } else {
                    $(this).fadeIn();
                }
            });
            // Set status and show emailForm if num of searches is reached.
            if (searchCount >= showEmailFormAt) {
                $("#emailUs").show();
            } else {
                searchCount++;
            }
            return false;
        }
    });

    // Start with Top Category
    $("select#category option").each(function() {
        if ($(this).text() == topCategory) {
            $(this).attr("selected", "selected");
            $(this).change()
        }
    });

    // Search by keyword
    $("#by_key_word").click(function() {
        $("select#category option[value='all']").attr("selected", "selected");
        $("div.qaa").show();
        $(".category").show();
        $("#no_result").hide();
        if ($("#search_all").attr("value") != "") { // If the user has specified a search word or phrase.
            $("div.qaa").hide();
            $(".category").hide();
            var numResults = 0;

            /* do not search for category anymore
            var category = $(".category h2:containsNC('"+$("#search_all").attr("value")+"')");
            if(category.length > 0){
                category.each(function(){
                    numResults++;
                    $(this).parent().show();
                    $(this).parent().children(".qaa").show();
                    $(this).parent().children(".qaa").children(".answer").show();
                });
            } */
            
            var qaas = $("div.qaa:containsNC('" + $("#search_all").attr("value") + "')");
            qaas.each(function() {
                if ($(this).parent().children("h2").text().indexOf(hiddenCategory) == -1 || $(this).children("span.hide:containsNC('" + $("#search_all").attr("value") + "')").length > 0) {
                    numResults++;
                    $(this).show();
                    $(this).parent().show();
                }
            });

            /* do not open answers anymore
            $("div.qaa:containsNC('"+$("#search_all").attr("value")+"')").children(".answer").show();
            */

            // If the search yields 0 results
            if (numResults == 0) {
                $('.results').prepend('<div id="no_result"><p>' + noSearchResultText + '</p></div>');
                searchCount = showEmailFormAt;
            }
            // Set status and show emailForm if num of searches is reached.
            if (searchCount >= showEmailFormAt) {
                $("#emailUs").show();
                $("#toForm").show();
            
            } else {
                searchCount++;
            }
            sitestatFAQ("", $("#search_all").attr("value"), numResults);
            return false;
        } else {
            // Set status and show emailForm if num of searches is reached.
            if (searchCount >= showEmailFormAt) {
                $("#emailUs").show();
                $("#toForm").show();
            } else {
                searchCount++;
            }
            return false;
        }
        return false;
    });
    // Bind scrollfunction for klickin anchor files.
    $("#faq").delegate("a[href*='#']", "click", function() {
        var target = $(this).attr("href");
        // Fix for ie7 that can't handle hiden links.
        target = "#" + target.split("#")[1];
        if ($(target).length) {
            $(target).scrollTo();
            return false;
        } else
            return true;
    });
});



function sitestatFAQ(ns_cat, faq_q, faq_a) {
    try {
        var ns_l = (("https:" == document.location.protocol) ? "https" : "http");
        ns_l += tag + '.FAQ&amp;ns_type=hidden&amp;ns__t=' + (new Date()).getTime();
        if (ns_cat != '') {
            ns_l += '&amp;cat=' + encodeURIComponent(ns_cat);
        }    
        if (faq_q != ''){
            ns_l += '&amp;faq_q=' + encodeURIComponent(faq_q);
        }
        ns_l += '&amp;faq_a=' + faq_a;
        if (document.images) {
            ns_1 = new Image();
            ns_1.src = ns_l;
        } else {
            document.write('<img src="' + ns_l + '" width="1" height="1" alt=""/>');
        }
    } catch (err) {
        //
    }
}

function returnForm() {
    $("#by_key_word").click();
    return false;
}

// Add Forms for js search of FAQ
function prependSearchForms() {
    var outputHTML = '<form class="jsGenerated"><fieldset class="first"><div class="categories">';
    outputHTML += '<label for="category">' + selectCategoryText + '</label><select id="category" name="search_caregory">';
    outputHTML += '<option value="all">' + allCategoriesText + '</option>';
    $(".category").each(function() {
        if ($(this).children("h2").text().indexOf(hiddenCategory) == -1) {
            outputHTML += '<option value="' + $(this).attr("id") + '">' + $(this).children("h2").text().replace("[Till toppen]", "") + '</option>';
        }
    });
    outputHTML += '</select></div></fieldset></form><form class="jsGenerated" onsubmit="return returnForm();"><fieldset><div>';
    outputHTML += '<label for="search_all">' + freeSearchTextLabel + '</label><input type="text" name="search_cat" id="search_all" />';
    outputHTML += '<input type="image" id="by_key_word" class="search_button" src="' + searchButtonImage + '" value="' + searchButtonValue + '" /></div></fieldset></form>';
    outputHTML += '<div id="toForm">Om du inte hittar svaret på din fråga, <a href="#emailUs" id="toFormLink">klicka här</a> för att skicka den till kundservice.</div>';
    $(".faq").prepend(outputHTML);
}

