﻿


$(document).ready(function() {
    /*
    $("div#wrapper-MaAW").removeAttr("style");
    $("a#url_detail-MaAW").removeAttr("style");
    $("div#widget_detail_div").removeAttr("style");
    $(".wrapper_widget div").removeAttr("style");
    */

    /*
    Adds a fb-like box in the facebook box if it exist.
    This was used because of validation...
    */
    if ($('#fb_script').length > 0) {

        var fbUrl = $('#fb_url').val();
        $('#fb_script').after('<fb:like-box href="' + fbUrl + '" width="150" height="150" show_faces="false" border_color="" stream="false" header="false"></fb:like-box>');
    }

    /*  
    Sökruta, default sökord...
    */

    if ($('input.searchField').val() == "") {

        $('input.searchField').val("Sökord...");
        $('input.searchField').addClass('pale');
    } else if ($('input.searchField').val() == "Sökord...") {
        $('input.searchField').addClass('pale');
    } else {
        $('input.pale').removeClass('pale');
    }

    $('input.searchField').bind('click', function() {

        if ($('input.searchField').val() == "" || $('input.searchField').val() == "Sökord...") {
            $('input.searchField').val("");
        }
        $('input.pale').removeClass('pale');
    });


    $('input.searchField').bind('blur', function() {

        if ($('input.searchField').val() == "" || $('input.searchField').val() == "Sökord...") {
            $('input.searchField').addClass('pale');
            $('input.searchField').val("Sökord...");
        }
    });


    $('img').each(function() {
        var alt = $(this).attr("alt");
        $(this).attr("title", alt);
    });


    $('tbody tr:odd').each(function() {
        if (!$(this).hasClass('even')) {
            $(this).addClass('even');
        }
    });
    $('tbody tr:even').each(function() {
        if (!$(this).hasClass('odd')) {
            $(this).addClass('odd');
        }
    });


    

    //$('.continue').prevAll('ol:first')


    $('ol[class^="start-"]').each(function() {

        var classes = $(this).attr('class').split('/\s+/');

        var ol = $(this);

        $.each(classes, function(index, item) {
            if (item.match('start-')) {

                var number = parseInt(item.split('-')[1]);
                ol.attr('start', number);
            }
        });
    });






});








$(function() {


    if ($('div.toolicon').length != 0) {
        $('div.toolicon a.addBookmark').after('<div class="info-bubble add"><span></span></div>');
        $('div.toolicon a.delBookmark').after('<div class="info-bubble del"><span></span></div>');
        $('div.toolicon a.disBookmark').after('<div class="info-bubble dis"><span></span></div>');
        $('div.toolicon div.info-bubble span').text($('div.toolicon a').text());

        $('div.toolicon div.info-bubble').append('<div class="info-bubble-arrow-border"> </div><div class="info-bubble-arrow"> </div>');
    }
    var prefix;

    setTimeout(function() {
        $("span.thankyoumessage").slideUp();
    }, 4000);

    if ($("body").hasClass("intranet")) {
        prefix = "#Internal_ContactForm_";
    } else {
        prefix = "#External_ContactForm_";
    }

    /*
    // Activate if you want movin banners...
    $('ul.spy').simpleSpy().bind('mouseenter', function() {
    $(this).trigger('stop');
    }).bind('mouseleave', function() {
    $(this).trigger('start');
    });*/

    var firstname = $("#contactform " + prefix + "ContactFirstName"),
    lastname = $("#contactform " + prefix + "ContactLastName"),
    phone = $("#contactform " + prefix + "ContactPhone"),
    email = $("#contactform " + prefix + "ContactEmail"),
    street = $("#contactform " + prefix + "ContactStreet"),
    zip = $("#contactform " + prefix + "ContactZip"),
    message = $("#contactform " + prefix + "ContactMessage"),
    firstnamelabel = $("#contactform " + prefix + "ContactFirstNameLabel"),
    lastnamelabel = $("#contactform " + prefix + "ContactLastNameLabel"),
    phonelabel = $("#contactform " + prefix + "ContactPhoneLabel"),
    emaillabel = $("#contactform " + prefix + "ContactEmailLabel"),
    streetlabel = $("#contactform " + prefix + "ContactStreetLabel"),
    ziplabel = $("#contactform " + prefix + "ContactZipLabel"),
    messagelabel = $("#contactform " + prefix + "ContactMessageLabel"),
    EmailReplyCheckbox = $("#contactform " + prefix + "ContactEmailReply"),
    PhoneReplyCheckbox = $("#contactform " + prefix + "ContactPhoneReply"),
    LetterReplyCheckbox = $("#contactform " + prefix + "ContactLetterReply"),
    NoReplyCheckbox = $("#contactform " + prefix + "ContactNoReply"),
    ReplyRadioButtonContainer = $("#ReplyRadioButtonContainer"),
    IssueRadioButtonContainer = $("#IssueRadioButtonContainer"),
    MailboxDropDown = $("#contactform " + prefix + "ContactAreaDDL"),
    allFields = $([]).add(firstname).add(lastname).add(phone).add(email).add(street).add(zip).add(ReplyRadioButtonContainer).add(IssueRadioButtonContainer).add(MailboxDropDown),
    tips = $(".validateTips"),
    valErrors = [];

    var useTimeout = false;
    ReplyRadioButtonContainer.addClass("ui-corner-all");
    IssueRadioButtonContainer.addClass("ui-corner-all");

    messagelabel.addClass("required");

    firstnamelabel.addClass("required");
    lastnamelabel.addClass("required");

    EmailReplyCheckbox.bind("click", function() {
        toggleRequired($(this));
    });

    PhoneReplyCheckbox.bind("click", function() {
        toggleRequired($(this));
    });

    LetterReplyCheckbox.bind("click", function() {
        toggleRequired($(this));
    });

    NoReplyCheckbox.bind("click", function() {
        toggleRequired($(this));
    });






    function toggleRequired(element) {

        switch (element.attr("id")) {

            case EmailReplyCheckbox.attr("id"):
                // Add requred fileds
                emaillabel.addClass("required");
                phonelabel.removeClass("required");

                // remove requred fileds
                streetlabel.removeClass("required");
                ziplabel.removeClass("required");

                break;

            case PhoneReplyCheckbox.attr("id"):

                // Add requred fileds
                phonelabel.addClass("required");

                // Remove requred fileds
                emaillabel.removeClass("required");
                streetlabel.removeClass("required");
                ziplabel.removeClass("required");

                break;

            case LetterReplyCheckbox.attr("id"):

                // Add requred fileds
                streetlabel.addClass("required");
                ziplabel.addClass("required");

                // Remove requred fileds
                phonelabel.removeClass("required");
                emaillabel.removeClass("required");

                break;

            case NoReplyCheckbox.attr("id"):

                // Add requred fileds
                streetlabel.removeClass("required");
                ziplabel.removeClass("required");

                // Remove requred fileds
                phonelabel.removeClass("required");
                emaillabel.removeClass("required");

                break;

            default:

        }

    }
    if ($("div#contactform").length != 0) {
        $("div#contactform").form();
    }

    if ($("div.workroomForm").length != 0) {
        $("div.workroomForm").form();
    }

    if ($('.xform').length != 0) {
        var $reqs = $(".xform span.req, .xform span.sel_req1, .xform span.sel_req");
        $reqs.each(function() {

            var $elm;

            if ($(this).closest("li").find("fieldset").find("legend:first").length != 0) {
                $elm = $(this).parent().find("fieldset").find("legend:first");
            }
            else if ($(this).closest("li").find("fieldset").closest("li").prev().find("span:first").length != 0) {
                $elm = $(this).closest("li").find("fieldset").closest("li").prev().find("span:first");
            }
            else if ($(this).closest("li").find("label:first").length != 0) {
                $elm = $(this).closest("li").find("label:first")
            }
            else if ($(this).closest("li").prev().find("span:first").length != 0) {
                $elm = $(this).closest("li").prev().find("span:first");
            }

            if ($elm != undefined) {
                if ($elm.length > 0) {
                    $elm.addClass("required");
                }
            }

        });
        $('.xform').form();

        //console.log($reqs);
    }



    $('input:submit').bind("click", function(event) {

        $(".xformvalidator").each(function(index) {

            if ($(this).css('display') != 'none') {
                $(this).prev().children("input").addClass("ui-state-error");
                $(this).prev().children("textarea").addClass("ui-state-error");
                $(this).parent().children().filter("fieldset").addClass("ui-state-error");
                $(this).parent().children().filter(".selectarea").addClass("ui-state-error");

            } else {
                $(this).prev().children("input").removeClass("ui-state-error");
                $(this).prev().children("textarea").removeClass("ui-state-error");
                $(this).parent().children().filter("fieldset").removeClass("ui-state-error");
                $(this).parent().children().filter(".selectarea").removeClass("ui-state-error");
            }


            var $errorlabels = $(this).parent().find(".errorlabel");

            var $textcontainer = $(this).parent().find("input, textarea");

            if ($textcontainer.length > 0) {
                $errorlabels.each(function() {
                    if ($(this).css("display") != "none") {
                        $textcontainer.addClass("ui-state-error");
                    }
                });
            }

            if ($(this).css("display") == "inline") {
                $(this).css("display", "block");
            }


        });
    });

    $(".xformvalidator").each(function(index) {

        var errorlabel = $(this);

        $(this).parent().find("input.text, textarea.text").blur(function(event) {

            var $errorlabels = $(this).parent().parent().find(".errorlabel");

            if ($(this).css("display") == "inline") {
                $(this).css("display", "block");
            }

            if ($(errorlabel).css('display') != 'none') {

                $(this).addClass("ui-state-error");
                $(errorlabel).css('display', "block");

            } else {
                $(this).removeClass("ui-state-error");

                if (jQuery.trim($(this).val()) == "" && $(errorlabel).filter("[id*='requiredvalidator']").length > 0) {

                    $(this).addClass("ui-state-error");
                    $(errorlabel).css('display', "block");
                }

                var $textcontainer = $(this);

                $errorlabels.each(function() {
                    if ($(this).css("display") != "none") {
                        $textcontainer.addClass("ui-state-error");
                    }
                });





            }
        });

        $(this).parent().find("label select").bind("option_empty_value", function() {
            $(errorlabel).parent().find(".selectarea").addClass("ui-state-error");
            $(errorlabel).css("display", "block");
        });

        $(this).parent().find("label select").bind("option_has_value", function() {
            $(errorlabel).parent().find(".selectarea").removeClass("ui-state-error");
            $(errorlabel).css("display", "none");
        });


        var $choises = $(this).parent().children().filter("fieldset").children().filter("label").children().filter("input");

        var $myelm = $(this);


        $choises.each(function(index) {


            $(this).bind("checkboxes_some_checked", function() {
                $(this).parent().parent().removeClass("ui-state-error");
                $(errorlabel).css("display", "none");
            });
            $(this).bind("checkboxes_none_checked", function() {
                $(this).parent().parent().addClass("ui-state-error");
                $(errorlabel).css("display", "block");
            });
            $(this).bind("checkboxes_all_checked", function() {
                $(this).parent().parent().removeClass("ui-state-error");
                $(errorlabel).css("display", "none");
            });

            $(this).bind("radios_checked", function() {
                $(this).parent().parent().removeClass("ui-state-error");
                $(errorlabel).css("display", "none");
            });

        });

        if ($(this).css('display') != 'none') {
            $(this).prev().children("input").addClass("ui-state-error");
            $(this).prev().children("textarea").addClass("ui-state-error");
            $(this).parent().children().filter("fieldset").addClass("ui-state-error");
            $(this).parent().children().filter(".selectarea").addClass("ui-state-error");
        } else {
            $(this).prev().children("input").removeClass("ui-state-error");
            $(this).prev().children("textarea").removeClass("ui-state-error");
            $(this).parent().children().filter("fieldset").removeClass("ui-state-error");
            $(this).parent().children().filter(".selectarea").removeClass("ui-state-error");
        }





    });

    var $choisesWrapper = $('.xformvalidator').parent().children().filter("fieldset").has("label input");


    $(".xform").find("input:submit").click(function(event) {
        var execute = true;
        $choisesWrapper.each(function() {

            var checked = false;
            $(this).find("label input").each(function() {

                if (this.checked) {
                    checked = true;
                }

            });

            if (!checked) {
                $(this).addClass("ui-state-error");
                $(this).next().css("display", "block");
                execute = false;
            } else {
                $(this).removeClass("ui-state-error");
                $(this).next().css("display", "none");
            }



        });



        return execute;

    });



    function blankDialogBox() {
        tips.html("");
        //allFields.val("");
        $(".ui-state-error").removeClass("ui-state-error");
    }



    function updateTips(errors) {

        tips.text("Fel:");
        tips.addClass("ui-state-highlight");

        tips.append("<ul class=\"errorList\">");

        $(errors).each(function() {
            tips.children("ul").append("<li>" + this + "</li>");
        });


        valErrors = [];

        setTimeout(function() {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }



    function trimInput(s) {
        if (s != undefined) {
            s = s.replace(/<\/?[^>]+>/gi, '');
            s = s.replace(/[<>\"=]/, '');
            s = s.replace(/ +(?= )/g, '');
            return jQuery.trim(s);
        }
    }

    function checkIfRadioIsChecked(node, nameval) {


        var radioButtons = $('#' + node.attr("id") + ' input:radio');



        if ($('#' + node.attr("id") + ' input:checked').length == 0) {

            node.addClass("ui-state-error");

            var message = "Välj ett allternativ för \"" + nameval + "\".";

            valErrors.push(message);

            return false;

        } else {
            return true;
        }
    }

    function checkLength(o, n, min, max) {






        o.val(trimInput(o.val()));

        if (o.val().length > max || o.val().length < min) {



            o.addClass("ui-state-error");
            var message;
            if (min != max) {
                message = n + " måste innehålla mellan " + min + " och " + max + " tecken.";
                valErrors.push(message);
            } else {
                message = n + " måste var exakt " + min + " tecken.";
                valErrors.push(message);
            }

            return false;

        } else {
            return true;
        }
    }

    function checkRegexp(o, regexp, n) {

        o.val(trimInput(o.val()));
        if (!(regexp.test(o.val()))) {


            if (o.is('select')) {
                o.parent().addClass("ui-state-error");
            } else {
                o.addClass("ui-state-error");
            }



            valErrors.push(n);
            return false;
        } else {
            return true;
        }
    }

    function checkIfFilledIn(o, n) {
        o.val(trimInput(o.val()));

        if (o.val().length <= 0) {

            o.addClass("ui-state-error");
            var message = n + " måste fyllas i.";
            valErrors.push(message);


            return false;

        } else {
            return true;
        }
    }

    $('.ContactFormSend').hide();
    $('#ContactFormHeading').hide();




    function initDialog() {

        // Dialog
        $('#dialog-form').dialog({
            autoOpen: false,
            width: 600,
            modal: true,
            hide: "drop",
            buttons: {
                "Skicka in": function() {
                    valErrors = [];

                    formId = $(this).attr("id");

                    var bValid = true;

                    allFields.removeClass("ui-state-error");
                    MailboxDropDown.parent().removeClass("ui-state-error");

                    var feedbackWay;

                    var radioValid1 = checkIfRadioIsChecked(IssueRadioButtonContainer, "Jag vill");

                    var radioValid2 = checkIfRadioIsChecked(ReplyRadioButtonContainer, "Jag vill ha svar via");

                    var covalid = checkLength(message, "Meddelande", 10, 200);

                    var fValid = bValid = checkLength(firstname, "Förnamn", 2, 16);
                    if (firstname.val().length > 1) {

                        bValid = fValid && checkRegexp(firstname, /^([, \u00c0-\u01ffa-zA-Z'\-])+$/, "Förnamnet innehåller ogilltliga tecken");
                    }

                    var lValid = bValid = checkLength(lastname, "Efternamn", 2, 16);
                    if (lastname.val().length >= 1) {
                        bValid = lValid && checkRegexp(lastname, /^([, \u00c0-\u01ffa-zA-Z'\-])+$/, "Efternamnet innehåller ogilltliga tecken");
                    }

                    if (phone.val().length >= 1 || PhoneReplyCheckbox.attr('checked')) {
                        var pValid = bValid = checkLength(phone, "Telefon", 5, 16);
                        bValid = pValid && checkRegexp(phone, /^(([+]\d{2}[ ][1-9]\d{0,2}[ ])|([0]\d{1,3}[-]))((\d{2}([ ]{0,1}\d{2}){2})|(\d{3}([ ]{0,1}\d{3})*([ ]{0,1}\d{2})+))$/, "Telefonnummret innehåller ogilltliga tecken, exempel 070-123 45 67 eller 012-34567");

                    }

                    if (EmailReplyCheckbox.attr('checked') || email.val().length >= 1) {
                        var eValid = bValid = checkLength(email, "E-post", 6, 80);
                        bValid = eValid && checkRegexp(email, /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/, "E-postadressen innehåller ogilltliga tecken, exempel bo.ek@abcd.se");
                    }

                    if (LetterReplyCheckbox.attr('checked') || street.val().length >= 1) {
                        var sValid = bValid = checkLength(street, "Gata", 5, 16);
                        bValid = sValid && checkRegexp(street, /^([, \u00c0-\u01ffa-zA-Z'\-0-9])+/, "Gatuadressen innehåller ogilltliga tecken, exempel Storgatan 32a");
                    }

                    if (LetterReplyCheckbox.attr('checked') || zip.val().length >= 1) {
                        var zValid = bValid = checkLength(zip, "Postnummer", 5, 6);

                        bValid = zValid && checkRegexp(zip, /\d{3}\s{0,1}\d{2}/, "Postnummeret innehåller ogilltliga tecken, exempel 82400 eller 824 00");

                    }

                    bValid = checkRegexp(MailboxDropDown, /^\d+$/, "Välj en verksamhet ur listan, till exempel Bibliotek");


                    if (valErrors.length == 0) {

                        valErrors = [];
                        blankDialogBox();

                        // Stäng rutan

                        //Skicka formuläret

                        $('#dialog-form').fadeOut("slow", function() {

                        });
                        setTimeout(function() {
                            $("input[id$='External_ContactForm_ContactFormSendBtn']").trigger("click");
                        }, 1000);

                        useTimeout = true;

                        $('#thankyou').trigger("click");
                        $(this).dialog("close");


                    } else {
                        updateTips(valErrors);
                    }
                },

                "Avbryt": function() {

                    $(this).dialog("close");

                }
            },
            close: function(event, ui) {

                valErrors = [];
                blankDialogBox();

                console.log(useTimeout);

                if (useTimeout) {
                    setTimeout(function() {
                        var dlg = $('#dialog-form').dialog("destroy");
                        initDialog();
                    }, 1100);
                } else {
                    var dlg = $('#dialog-form').dialog("destroy");
                    initDialog();
                }
                useTimeout = false;
            }
        });

    }

    initDialog();

    // Dialog Link
    $('#dialog_link').click(function() {

        valErrors = [];

        var dlg = $('#dialog-form').dialog('open');
        dlg.parent().appendTo($("form:first"));
        $('input,textarea,select').removeClass("ui-state-focus");

        if (EmailReplyCheckbox.attr("checked")) {
            toggleRequired(EmailReplyCheckbox);
        } else if (PhoneReplyCheckbox.attr("checked")) {
            toggleRequired(PhoneReplyCheckbox);
        } else if (LetterReplyCheckbox.attr("checked")) {
            toggleRequired(LetterReplyCheckbox);
        } else if (NoReplyCheckbox.attr("checked")) {
            toggleRequired(NoReplyCheckbox);
        }

        return false;
    });


    if ($('#thankyou')) {
        $('#thankyou').dialog({
            width: 600,
            modal: true,
            hide: "drop",
            title: "Tack!"
        });


        setTimeout(function() {
            $('#thankyou').dialog("close");
        }, 5000);
    }

    if ($('div.toolicon').length != 0) {

        $('div.toolicon').each(function() {

            var distance = 10,
        time = 250,
        hideDelay = 500,
        hideDelayTimer = null,
        trigger = $('a', this),
        popup = $('div.info-bubble', this),
        popupcontent = $('div.info-bubble span', this),
        popupArrow = $('div.info-bubble .info-bubble-arrow, div.info-bubble .info-bubble-arrow-border'),
        popuptext = $('div.info-bubble', this).prev('a').text(),
        beingShown = false,
        visible = false;


            popupcontent.text(popuptext);


            $([trigger.get(0), popup.get(0)]).mouseover(function() {

                clearTimeout(hideDelayTimer);

                if (beingShown || visible) {
                    return;
                } else {
                    beingShown = true;
                    popup.css({
                        display: 'block',
                        top: '-33px',
                        right: '-4px'

                    }).animate({
                        opacity: 1,
                        top: '-=' + distance + 'px'

                    }, '', function() {
                        beingShown = false;
                        visible = true;
                    });

                    popupArrow.animate({
                        opacity: 1
                    }, '', function() {

                    });
                }
            }).mouseout(function() {

                if (hideDelayTimer) clearTimeout(hideDelayTimer);


                hideDelayTimer = setTimeout(function() {

                    popup.animate({
                        top: '-=' + distance + 'px',
                        opacity: 0
                    }, '', function() {
                        visible = false;
                        popup.css({
                            top: '-33px'
                        });
                    });

                    popupArrow.animate({
                        opacity: 0
                    }, '', function() {

                    });

                }, hideDelay);


            });

        });
    }

});
