// 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:text, table#id_matrix input:radio').addClass('normalInput');


    $('table#id_matrix span.sectionHeader').parent().next().remove();
    // Use button tag instead!! but only in IE7+/firefox!!!
    var substituteButton = true;
    if (jQuery.browser.msie) {
        var ieVersion = parseInt(jQuery.browser.version.substr(0, jQuery.browser.version.indexOf('.')));
        if (ieVersion <= 6) {
            substituteButton = false;
        }
    }

    if (substituteButton) {
        $("table#id_matrix :submit").hide().parent().append('<button class="smallButton"><span>' + $(this).find(":submit").attr('value') + '</span></button>').click(function() {
            $("table#id_matrix :submit").click();
            return false;
        });
    } else {
        $("table#id_matrix :submit").addClass("submitButtonIe6");
    }

    // $('table#id_matrix tr td span.xformvalidator').before('<br />');




    $(".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');

    $("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();
    $('a.replyAction').click(function() {
        $('a.replyAction').removeClass('inActive');
        $(this).addClass('inActive');
        $('.topicReply').hide();
        $(this).next().next().show('.topicReply');
        $(this).parent().parent().prev().prev().addClass('topicTitleReset');
        $('.threadReplyactive').removeClass('threadReplyactive');
        $(this).prev().addClass('threadReplyactive');
        $(this); { return false; }
    });
    if ($(".validation:visible").length > 0) {
        if ($(".validation:visible").parent().parent().parent().parent().attr("class") != "primaryContent") {
            $(".primaryContent .topicReply").hide();
            $(".validation:visible").parent().parent().show('.topicReply');
            $(".validation:visible").parent().focus();
        }
    }


    // 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;
    });

    //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());
  }
}

