
$(function () {
    $("#globalNavigation ul").find("li:first").addClass("firstchild");
    $(".nav-breadcrumb ul").find("li:first").addClass("firstchild");

    // navigation
    $("#globalNavigation > ul > li").mouseenter(function () {
        $(this).children("ul").show();
    }).mouseleave(function () {
        $(this).children("ul").hide();
    });

    //	ie6fix
   // $('ul.nav-sub').bgiframe({ src: "/system/blank.html" });
});

$(document).ready(function () {

    $(".nav-main-menu > ul > li").mouseenter(function () {
        $(this).children("ul").show();
        $(this).children("a").addClass("active");
    }).mouseleave(function () {
        $(this).children("ul").hide();
        $(this).children("a").removeClass("active");
    });


    if ($_GET('var') != null) {
        var site = $_GET('var');
        if (site == 's') {
            $("#tempCss").attr("href", "/system/css/sam.css");
            Cufon.refresh();
        };
    };

    $("#toggleClass").toggle(function () {
        $("#tempCss").attr("href", "/system/css/sam.css");
    }, function () {
        $("#tempCss").attr("href", "");
    });

    $('#actionMenu > li.handle > h3').click(function () {
        ToggleList($(this));
    });

    $("#actionMenu > li.handle").hover(
        function () {
            if ($(this).hasClass('prio')) {
                $(this).addClass('hoverPrio');
            } else {
                $(this).addClass('hover');
            }
        },
        function () {
            $(this).removeClass('hover');
            $(this).removeClass('hoverPrio');
        }
    );

    $('#actionMenu li h4').click(function () {
        ToggleList($(this));
    });

    $('table.tablesorter').each(function (intIndex) {
        var rowCount = $(this).attr('rows').length;
        if (rowCount > 1) {
            $.tablesorter.defaults.widgets = ['zebra'];
            $.tablesorter.defaults.widgetZebra = { css: ["odd", "even"] };

            $(this).find('td').each(function () {
                var col = $(this).parent().children().index($(this));
                switch (col) {
                    case 6: // percentage pos or neg
                        $(this).addClass('percentage');
                        var str = $.trim($(this).html().replace('.', ','));
                        if (str.charAt(0) == "-") {
                            $(this).html("<span class='neg'>" + str + "</span>");
                        }
                        else if (str.charAt(0) == "0") {
                            $(this).html("<span class='zero'>" + str + "</span>");
                        }
                        else {
                            $(this).html("<span class='pos'>" + str + "</span>");
                        };
                        break;
                };
            });

            var sortColumn = new Array();
            if ($.cookie('fondsActive') != null) {
                sortColumn.push([0, 0], [1, 0]);
            } else {
                sortColumn.push([1, 0]);
            };


            $(this).tablesorter({
                dateFormat: 'uk',
                sortList: sortColumn,
                headers: {
                    0: { sorter: true },
                    1: { sorter: true },
                    2: { sorter: false },
                    3: { sorter: false },
                    4: { sorter: false },
                    5: { sorter: false },
                    6: { sorter: true },
                    7: { sorter: true }
                }
            });
        } else {
            $("#div_Koersen").hide();
        };
    });

    $('#slider').tinycarousel({ pager: true, interval: true, intervaltime: 10000, duration: 100, animation: true, axis: 'y' });

//    $("ul.overview li a.sliderurl").each(function (e) {
//        var url = $(this).attr('href');
//        $(this).parent().parent().parent().parent().click(function (e) {
//            e.preventDefault();
//            $(window.open(url, '_blank'));
//        });
//    });

    if ($.browser.msie && parseFloat($.browser.version) < 7) {
        $('div.columnsTop').equalBoxes();
        $('div.columnsSeparator').equalBoxes();
    };

    $("#searchOptions div").each(function () {
        $(this).hide();
    });

    $("#searchOptions div:first").show();

    $("#SelectSearchoption").change(function () {
        $("#searchOptions div").each(function () {
            $(this).hide();
        });
        var searchOption = "option_" + $(this).val();
        $("#" + searchOption).show();
    });

    $("#tbSearchKoersen").focus(function () {
        $(this).filter(function () {
            return $(this).val() == "" || $(this).val() == $(this).attr('title')
        }).removeClass("watermarkOn").val("");
    });

    $("#tbSearchKoersen").blur(function () {
        $(this).filter(function () {
            return $(this).val() == ""
        }).addClass("watermarkOn").val($(this).attr('title'));
    });

    $("a.modal").fancybox({
        'titlePosition': 'inside',
        overlayColor: '#3A2808',
        overlayOpacity: 0.8,
        hideOnOverlayClick: false,
        type: 'iframe',
        width: 1000,
        height: 500,
        centerOnScroll: true,
        padding: 23
    });

    var cookieValue = $.cookie('fondsActive');
    var fundsString = "";
    var options = { path: '/', expires: 10 };

    if (cookieValue != null) {
        fundsString = cookieValue;
        if (cookieValue != null && cookieValue != "") {
            if (cookieValue.substr(0, 1) == ",") {
                fundsString = cookieValue.substring(1, cookieValue.length);
            }
        }

        if (cookieValue == "") {
            $.cookie('fondsActive', null, { path: '/', expires: -10 });
        } else {
            // set active funds        
            //if (fundsString.indexOf(",") != -1 && fundsString.length != 0) {
            arrfunds = fundsString.split(",");
            $("#div_Koersen").show();
            for (var i = 0; i < arrfunds.length; i++) {
                var value = arrfunds[i];
                if (value.length > 0) {
                    if ($("#" + value).length) {
                        $("#" + value).attr("src", "/images/fav_on.gif");

                        var newId = "f" + value;
                        var clonedRow = $("#" + value).parents('tr').clone().attr("id", newId);
                        var image = clonedRow.find('.img-swap').attr('id', "fr" + value);
                        clonedRow.find(".img-swap").attr('id', "fr" + value);
                        clonedRow.appendTo("#table_favorites");
                    }
                }
            }

            //            }
            //            else { // there should be only one
            //                $("#div_Koersen").show();
            //                $("#" + fundsString).attr("src", "/images/fav_on.gif");
            //                var newId = "f" + fundsString;
            //                var clonedRow = $("#" + fundsString).parents('tr').clone().attr("id", newId);
            //                var image = clonedRow.find('.img-swap').attr('id', "fr" + fundsString);
            //                clonedRow.find(".img-swap").attr('id', "fr" + fundsString);
            //                clonedRow.appendTo("#table_favorites");
            //            }
        }
    }



    $(".img-swap").live('click', function () {

        if ($('#div_Koersen').is(':hidden')) {
            $('#div_Koersen').show('slow');
        }

        var fondsID = $(this).attr("id").replace('fr', '');
        var fundsArray = new Array();

        if (fundsString != null) {
            fundsArray = fundsString.split(",").clean();
        }

        // check if clicked fund is in array
        if (fundsArray.exists(fondsID)) {
            var tempArray = new Array();
            tempArray = fundsArray;
            // swap image van on -> off
            this.src = this.src.replace("_on", "_off");
            // remove from array                    
            fundsArray = removeItems(tempArray, fondsID);
            // remove item from favorites table
            $("#f" + fondsID).remove();
            // swap image in koersen table if clicked image is in favorites table
            var image = $("#" + fondsID);
            var imageUrl = image.attr('src').replace("_on", "_off");
            image.attr('src', imageUrl);
        }
        else {
            // swap image from off -> on
            this.src = this.src.replace("_off", "_on");
            // add item to array
            fundsArray.push(fondsID);
            // add row to favorites table
            var newId = "f" + fondsID;
            var clonedRow = $(this).parents('tr').clone().attr("id", newId);
            var image = clonedRow.find('.img-swap').attr('id', "fr" + fondsID);
            clonedRow.find(".img-swap").attr('id', "fr" + fondsID);
            clonedRow.appendTo("#table_favorites");
        }

        var numberOfFunds = fundsArray.length;
        if (numberOfFunds == 0) {
            $.cookie('fondsActive', null, { path: '/', expires: -10 });
            $.cookie("fondsActive", null);
            $("#div_Koersen").hide('slow');
        } else {
            fundsString = fundsArray.join(",");
            $.cookie('fondsActive', fundsArray.join(","), options);
        };

        $(this).toggleClass("on");
    });

    $('#list-dossiers').each(function () {
        $(this).children('li:gt(2)').hide();
    });

    $('.showhideul').toggle(
        function () {
            $(".box-header-right").css({ height: 'auto' });
            $('#list-dossiers').children('li:gt(2)').toggle();
        },
        function () {
            $('#list-dossiers').children('li:gt(2)').hide();
            $('.box-header-right').removeAttr("style");
        }
    );

});

    function $_GET(q, s) {
        s = (s) ? s : window.location.search;
        var re = new RegExp('&amp;' + q + '=([^&amp;]*)', 'i');
        return (s = s.replace(/^\?/, '&amp;').match(re)) ? s = s[1] : s = '';
    }


    function ToggleList(element) {
        // remove dotted line from next item

        var nextItem = element.parent().next();
        nextItem.find('h3').removeClass();        

        element.parent().children('ul').slideToggle("slow");

        if (element.parent().hasClass('selected')) {
            element.parent().removeClass('selected');
            element.parent().removeClass('selectedPrio');
            nextItem.find('h3').addClass("lined");
        } else {
            nextItem.find('h3').addClass("unlined");
            if (element.parent().hasClass('prio')) {
                element.parent().addClass('selected selectedPrio');
            } else {
                element.parent().addClass('selected');
            };
        }
    }

function removeItems(array, item) {
    var i = 0;
    while (i < array.length) {
        if (array[i] == item) {
            array.splice(i, 1);
        } else {
            i++;
        }
    }
    return array;
}

Array.prototype.exists = function (search) {
    for (var i = 0; i < this.length; i++)
        if (this[i].replace(",", "") == search) {
            return true;
        }

    return false;
}

Array.prototype.clean = function (deleteValue) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == deleteValue) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
};


String.prototype.trim = function(value) { 
    return this.replace(/^\s+|\s+$/g, ''); 
}

jQuery.fn.equalBoxes = function () {
    var arrHeights = [];

    $(this[0]).find("div.box").each(function (i) {
        var height = $(this).height();
        arrHeights.push(height);
    });

    var largest = (Math.max.apply(Math, arrHeights)) - 12;

    $(this[0]).find("div.box").each(function (i) {
        $(this).height(largest);
    });
};
