// jQuery initializing script
$(function () {

    $('div.search :text, div.searchArea :text, div.newsletterSubscribe :text, div.search :password, div.newsletterSubscription :text, div.innerInputWrapper :text').toggleInputText();
    setSameHeightAsContainer('div.underlayColor');

    $('div.magazinepageNews li:gt(0), div.frontpageNews li').click(function () {
        location.href = $('a:last', this).attr('href');
    }).hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    })

    $('div.frontpageNews li.imgRight, div.frontpageNews li.imgLeft, div.frontpageNews li.colortan, div.frontpageNews li.focus, ').click(function () {
        location.href = $('a:last', this).attr('href');
    }).hover(function () {
        $(this).addClass('hoverAlt');
    }, function () {
        $(this).removeClass('hoverAlt');
    })

    $('table#id_matrix tr td:even').addClass('firstCell');
    $('table#id_matrix tr td:odd').addClass('lastCell');
    $('table#id_matrix span.sectionHeader').parent().parent().addClass('oddRow');
    $('table#id_matrix .oddRow td').attr({
        colspan: "2"
    });
    $('table#id_matrix input:not(input[type="submit"])').addClass('normalInput');

    $('table#id_matrix span.sectionHeader').parent().next().remove();
    $('table#id_matrix input[type="submit"]').hide().parent().append('<div class="smallButton"><span>' + $(this).find(":submit").attr('value') + '</span></div>');

    $('table#id_matrix div.smallButton').click(function () {
        $('table#id_matrix input[type="submit"]').click();
        return false;
    });

    $(".boxedForm div label, .login div label").click(function () {
        $(this).hide().next().focus();
    }).next().focus(function () {
        $(this).prev().hide();
    });

    $(".boxedForm.password input, .login.changePassword input").blur(function () {
        var inp = $(this);
        if (inp.val() == '') {
            $(this).prev('label').show();
        }
    });
    $("div.articleHeadNoPic").parent().next().addClass('column33noPic');

    $(".mainFooter ul.footerLinks > li:last").addClass('about');
    $(".mainFooter ul.footerLinks > li:eq(6)").addClass('breakLine');

    $("div.paging a").click(function () {
        $(this).addClass('active');
    });

    /* checks whether icon is shown or not */
    $(".topNameBg").parent().addClass('topNameBgIcon');

    $(".magazinepageNews h3").addClass('topHeaderActive');
    $("h3.topHeaderActive").next().addClass('topHeaderActive');

    $(".threadReply .topicReply").hide();

    function resetValidators() {

        // hide all validators
        if (typeof (Page_Validators) != "undefined") {
            for (var i = 0; i < Page_Validators.length; i++) {
                var validator = Page_Validators[i];
                validator.isvalid = true;
                ValidatorUpdateDisplay(validator);
            }
        }

        // hide all validationsummaries
        if (typeof (Page_ValidationSummaries) != "undefined") {
            for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
                summary = Page_ValidationSummaries[sums];
                summary.style.display = "none";
            }
        }
    }

    function moveForm(link, dest, insertAfter) {
        var topicReply = $("div.topicReply");
        var challengeField = $("input#recaptcha_challenge_field").val();
        $('div.topicReply input[type="hidden"]').val($(link).attr('href'));
        topicReply.find('script').remove();
        var p = topicReply.detach();
        p.find('script').remove();
        if (!insertAfter) {
            dest.append(p);
        } else {
            p.insertAfter(dest);
        }

        p.show();

        $("input#recaptcha_challenge_field").val(challengeField);
    }

    $('a.replyAction').click(function () {

        resetValidators();

        moveForm(this, $(this), true);


        $('a.replyAction').removeClass('inActive');
        $(this).addClass('inActive');
        $('.topicReply').not('.topicReply:first').hide();
        $(this).next().next().show('.topicReply');
        $(this).parent().parent().prev().prev().addClass('topicTitleReset');
        $('.threadReplyactive').removeClass('threadReplyactive');
        $(this).prev().addClass('threadReplyactive');

        $(this); { return true; }
    });



    //Commentform slidedown
    $('.commentsCon .bubble').click(function () {
        resetValidators();
        moveForm(this, $(this), true);
        $(this).next().find('.topicReply:first').slideToggle('fast');
        $('.threadReplyactive').removeClass('threadReplyactive');
        $('a.replyAction').removeClass('inActive');
    });


    if ($(".validation:visible").length != 0) {
        $('.validation:visible').parents('.topicReply:first').css('display', 'block');
        $(window).scrollTop($('.validation:visible').parents('.topicReply').position().top);
    }

    // set keypresses
    $(".createThread input, .topicReply input").keypress(function (e) {
        if (e.which == 13) {
            $(e.target).parent().parent().parent().parent().find(".submitButton").click();
            return false;
        }
    });

    $(".search input, .newsletterSubscribe input").keypress(function (e) {
        if (e.which == 13) {
            $(e.target).parent().find(".smallButton").click();
            return false;
        }
    });

    // fix for headerTitle
    $('li.klView div h3').next().addClass('topHeaderActiveMoveUp');
    $('.politicalCv table tr td:first').addClass('first');


    // Button hover
    $('button.smallButton, button.searchButton').hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    })

    $('div.searchResults div.results ul li a').bind('click', function () {
        if ($(this).parent().parent().parent().parent().parent().hasClass('bmdbResults')) return true;
        if ($(this).parent().parent().parent().parent().hasClass('bmdbResults')) return true;
        var maxSizeWidth = 1060;
        if (maxSizeWidth > screen.availWidth) {
            maxSizeWidth = screen.availWidth;
        }
        var sizeHeight = 1000;
        if (sizeHeight > screen.availHeight) {
            sizeHeight = screen.availHeight;
        }
        window.open($(this).attr('href'), 'SearchResultWindow', 'menuvar=yes,toolbar=yes,location=yes,status=yes,resizeable=yes,scrollbars=yes,height=' + sizeHeight + ',width=' + maxSizeWidth);
        return false;
    });

    //Blog 'read more' slidedown
    var blogFunctions = {
        init: function () { },
        showMorePosts: function () {
            var open = false;
            var domObjLink = $('.blogProfile .block01 .moreLink');
            var domObjText = $('.blogProfile .block01 .moreText');
            var closedText = domObjLink.text();
            var openText = "Luk";

            domObjLink.addClass('moreContent');
            domObjLink.click(function () {
                if (open) {
                    domObjText.css('display', 'none');
                    domObjLink.text(closedText).removeClass('open');
                    open = false;
                } else {
                    domObjText.css('display', 'block');
                    domObjLink.text(openText).addClass('open');
                    open = true;
                }
            });
        }

    }
    if ($('.blogProfile .block01 .moreText').length)
        blogFunctions.showMorePosts();
    else
        $('.blogProfile .block01 .moreLink').remove();

    /*
    //Blog 'read more' slidedown
    //Modified by MLE
    if ($('.blogProfile .block01 .moreText').length != 0) {
    var RM = new Object();
    RM.openRM = false;
    $('.blogProfile .block01 .moreLink').html('L&aelig;s mere').addClass('moreContent');
    RM.rmText = $('.blogProfile .block01 .moreLink').html();

    $('.blogProfile .block01 .moreLink').click(function () {
    _this = this;
    $(this).prev('.moreText').toggle('fast', function () {
    if (RM.openRM == false) {
    $('.blogProfile .block01 .moreLink').addClass('open')
    $('.blogProfile .block01 .moreLink').text('Luk');
    RM.openRM = true;
    }
    else {
    $('.blogProfile .block01 .moreLink').removeClass('open')
    $('.blogProfile .block01 .moreLink').text(RM.rmText);
    RM.openRM = false;
    }
    });
    });
    } else {
    $('.blogProfile .block01 .moreLink').html('').addClass('noMore');
    }
    */
    
    //Blog 'more blogposts' slidedown
    if ($('.blogProfile .block03 .hiddenBlogPosts').length) {
        var MP = new Object();
        MP.openRM = false;
        $('.blogProfile .block03 .moreLink').html('Flere blog indl&aelig;g').addClass('moreContent');
        MP.rmText = $('.blogProfile .block03 .moreLink').html();

        $('.blogProfile .block03 .moreLink').click(function () {
            _this = this;
            $(this).prev('.hiddenBlogPosts').toggle('fast', function () {
                if (MP.openRM == false) {
                    $('.blogProfile .block03 .moreLink').addClass('open');
                    $('.blogProfile .block03 .moreLink').text('Luk');
                    MP.openRM = true;
                }
                else {
                    $('.blogProfile .block03 .moreLink').removeClass('open');
                    $('.blogProfile .block03 .moreLink').text(MP.rmText);
                    MP.openRM = false;
                }
            });
        });
    } else {
        $('.blogProfile .block03 .moreLink').html('').addClass('noMore');
    }

    // Link function
    $('.linkTarget').each(function () {
        var url = $(this).find('a:first').attr('href');
        $(this).css('cursor', 'pointer').mousedown(function () {
            window.open(url, '_self');
            return false;
        });

        $(this).hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); });
    });

    //BMDB.init();

});

var BMDB = {
    init: function() {
        BMDB.hooks.fadeEffect();
        BMDB.hooks.searchEvents();
        //$('.bmdbSearchContainer').unblock();
    },
    hooks: {
        fadeEffect: function() {
            // Borgmester Database hooks
            $('a.fadeToggle').bind('click', function() {
                $(this).parent().find('.displayBlock').eq(0).toggle("fast");
                if ($(this).hasClass('open')) {
                    $(this).attr('title', $(this).attr('title_show'));
                    $(this).html($(this).attr('title_show'));
                    $(this).addClass('closed');
                    $(this).removeClass('open');
                } else {
                    $(this).attr('title', $(this).attr('title_hide'));
                    $(this).html($(this).attr('title_hide'));
                    $(this).addClass('open');
                    $(this).removeClass('closed');
                }
                return false;
            });
        },
        searchEvents: function() {
            // Borgmester search events
            $('a.bmdbAddMoreButton').click(function() {
                var dropDown = $(this).parent().find('.bmdbSelect');
                var select1 = $(this).parent().find('.bmdbMultiSelect1');
                var select2 = $(this).parent().find('.bmdbMultiSelect2');

                select1.empty();
                select2.empty();

                $(this).hide().next().show().end().parent().find('.addMore').show().end();
                if (dropDown.val() > 0) {
                    dropDown.find('option:selected').appendTo(select2);
                }
                dropDown.find('option:not(:selected)').appendTo(select1);
                dropDown.attr('disabled', 'true');

                select2.find('option').removeAttr('selected');

                //.parent().find('.bmdbSelect option:selected').appendTo('.select2').end().parent().find('.bmdbSelect option:not(:selected):gt(0)').appendTo('.select1');
                $(this); { return false; }
            });

            $('.bmdbAddButton').click(BMDB.functions.add);
            $('.bmdbMultiSelect1').dblclick(BMDB.functions.add);
            $('.bmdbRemoveButton').click(BMDB.functions.remove);
            $('.bmdbMultiSelect2').dblclick(BMDB.functions.remove);
            $('.bmdbResetButton').click(BMDB.functions.reset);
            //$('.bmdbSubmitButton').click(BMDB.functions.submit);

            $(".bmdbSearchContainer input, .bmdbSearchContainer input, .borgmesterFaktaSearch input").keypress(function(e) {
                if (e.which == 13) {
                    $(e.target).parent().find(".smallButton").click();
                    return false;
                }
            });
        }
    },
    misc: {
        sortList: function(listToSort) {
            var arrayOfOptions = listToSort.find('option');
            var arrayOfMunicipals = new Array();
            var arrayOfRegions = new Array();

            listToSort.find('option').each(function(idx) {
                var element = $(this);
                var text = element.text();
                if (text != '') {
                    if (text.length > 6 && text.substring(0, 6).toLowerCase() == 'region') {
                        arrayOfRegions.push(element);
                    } else {
                        arrayOfMunicipals.push(element);
                    }
                }
            });

            arrayOfMunicipals.sort(BMDB.misc.sortOption);
            arrayOfRegions.sort(BMDB.misc.sortOption);

            listToSort.empty();
            BMDB.misc.appendToList(listToSort, arrayOfMunicipals);
            if (arrayOfRegions.length > 0) {
                BMDB.misc.appendEmptySpacer(listToSort);
                BMDB.misc.appendToList(listToSort, arrayOfRegions);
            }

        },
        appendToList: function(destList, sourceArray) {
            for (var i = 0; i < sourceArray.length; i++) {
                destList.append(sourceArray[i]);
            }
        },
        appendEmptySpacer: function(destList) {
            if (destList.find('option').length > 0) {
                var clonedOption = $(destList.find('option')[0]).clone();
                clonedOption.val(0);
                clonedOption.text('');
                destList.append(clonedOption);
            }
        },
        sortOption: function(optionA, optionB) {
            var textA = optionA.text().toLowerCase();
            var textB = optionB.text().toLowerCase();

            textA = BMDB.misc.prepTextForSort(textA);
            textB = BMDB.misc.prepTextForSort(textB);

            if (textA == textB) {
                return 0;
            }
            if (textA > textB) {
                return 1;
            }
            return -1;
        },
        prepTextForSort: function(text) {
            text = text.replace('aa', 'å');
            text = text.replace('ae', 'æ');
            text = text.replace('oe', 'ø');

            return text;
        }
    },
    functions: {
        add: function() {
            var select1 = $(this).parent().parent().find('.bmdbMultiSelect1');
            var select2 = $(this).parent().parent().find('.bmdbMultiSelect2');

            var success = !select1.find('option:selected').remove().appendTo(select2);

            if (!success) {
                select2.find('option').removeAttr('selected');
            }

            BMDB.misc.sortList(select2);

            return success;
        },
        remove: function() {
            var select1 = $(this).parent().parent().find('.bmdbMultiSelect1');
            var select2 = $(this).parent().parent().find('.bmdbMultiSelect2');

            var success = !select2.find('option:selected').remove().appendTo(select1);

            if (!success) {
                select1.find('option').removeAttr('selected');
            }

            BMDB.misc.sortList(select1);

            return success;

            //return !$('.select2 option').remove().appendTo('.select1');
        },
        reset: function() {
            var dropDown = $(this).parent().find('.bmdbSelect');
            var select1 = $(this).parent().find('.bmdbMultiSelect1');
            var select2 = $(this).parent().find('.bmdbMultiSelect2');

            select1.find('option').remove().appendTo(dropDown);
            select2.find('option').remove().appendTo(dropDown);
            dropDown.removeAttr('disabled');

            $(this).hide().prev().show().end().parent().find('.addMore').hide().end();

            BMDB.misc.sortList(dropDown);

            dropDown.find('option:first').attr('selected', 'true');

            return false;
        },
        submit: function() {
            $('.bmdbMultiSelect2 option').attr('selected', 'true');

            window.setTimeout('BMDB.functions.showBlock()', 500);
        },
        showBlock: function() {
            $('.bmdbSearchContainer').block({ message: '<img style="float:left;margin-left:40px;" src="/images/graphics/ajax-loader_small.gif" /><h3 style="float:left;margin-left: 10px;">S&oslash;ger...</h3>' });
        }
    }
};

/*
$(function() {
    $('.searchArea a').click(function() {
        if ($(this).attr("class") != "simpelSearchLink") {
            $(this).parent().parent().toggleClass('swapActive');
            $(this).parent().parent().next().slideToggle("1000");
            $(this); { return false; }
        }
    });
});
*/
function add() {
return !$('.select1 option:selected').remove().appendTo('.select2');
}
function remove() {
return !$('.select2 option').remove().appendTo('.select1');
}

// home made jQuery plugin to toggle the value of the text input fields on focus / blur
// All it needs is a title attribute on the text input field with the relevant text to be shown / hidden, if there's nothing in the input value field 
(function($) {
    $.fn.toggleInputText = function() {
        var elements = this;
        return (elements.each(function() {
            var el = $(this), title = el.attr('title');
            if (el.val() == "") el.val(title);
            el.focus(function() {
                if (el.val() == title) el.val("");
            }).blur(function() {
                if (el.val() == "") el.val(title);
            });
        }));
    };
})($);



// fix IE6 problem with absolutely positioned elements not being able to be 100% of the container height
function setSameHeightAsContainer(cssSel){
	if ($.browser.msie){
  	var el = $(cssSel);
  	el.height(el.parent().height());
  }
}

function CustomValidatorEmailIfChecked(source, args) {
    var $source = $(source),
        chkBoxId = $source.attr('checkboxcontrol'),
        chkBoxChecked = $('#' + chkBoxId).attr('checked'),
        emailId = $source.attr('emailcontrol'),
        emailIsValid = $('#' + emailId).val() != '';
    if (chkBoxChecked && !emailIsValid) {
        args.IsValid = false;
    }
}

function validateCaptcha(source, args) {

    var allValid = true;

    for (var i = 0; i < Page_Validators.length; i++) {
        if($(Page_Validators[i]).is(':visible')) { 
            if($(Page_Validators[i]).hasClass('validatorBlock')) {
            } else {
                allValid = false;
                break;
            }
        }
    }

    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();

    var html = $.ajax({
        type: "POST",
        url: "/services/RecaptchaService.ashx",
        data: "challengeField=" + challengeField + "&responseField=" + responseField,
        async: false
    }).responseText;
    
    if (html.replace(/^\s+|\s+$/, '') == "True" && allValid == true) {
        args.IsValid = true;
        return true;
    }
    else {
        args.IsValid = false;
        $('.topicReply #recaptcha_response_field').val('');
        Recaptcha.reload();
        return false;
    }
}

