$(function() {

    //set submit buttons hover effect
    setButtonsMouseOver();

    //ajax setup
    $.ajaxSetup({ cache: false, dataType: "html" });

    //when ESC key is pressed close popup
    $(document).keypress(function(e) {
        if (e.keyCode == 27 && popupStatus == 1) {
            closePopup();
        }
    });

    /*//return nothing if click inside help popup
    $('.helpicon').click(function(evt) {
    alert('helpiconclick');
    return false;
    });
    $('.helppopup').click(function(evt) {
    alert('helpipopupclick');
    return false;
    });*/

    //document click
    $(document).click(function(e) {

        //hide calendar
        if ($('.ajaxcalendardiv').length > 0)
            $('.ajaxcalendardiv').hide();

        if ($('#interactiveover').length > 0)
            $('#interactiveover').hide();

    });

    //calendar click disable
    $(".ajaxcalendardiv").click(function() {
        return false;
    });



    //interactive click disable
    $("#interactiveover").click(function(event) {
        //return false;
        event.stopPropagation();
    });
    $(".interactivemain").click(function() {
        if ($('#interactiveover').is(':visible'))
            $('#interactiveover').hide();
        else
            $('#interactiveover').show();

        return false;
    });


    //when arrow key is pressed for gallery popup
    $(document).keydown(function(e) {
        if (popupStatus == 1) {
            var keyCode = e.keyCode || e.which;
            var arrow = { left: 37, right: 39 };

            //keycode - left arrow and right arrow
            switch (keyCode) {
                case arrow.left:
                    $('.goleft').click();
                    break;
                case arrow.right:
                    $('.goright').click();
                    break;
            }
        }
    });

    //close event on popup background
    $('#modalwindowbackground').click(function() { closePopup(); });

    //menu selected item - add arrow that item has sub content
    if ($('#menu .selecteditem ').length > 0 && $('#menu .selecteditem ').hasClass('menuitemmore')) {
        $('#menu .selecteditem ').css('background-color', '#f2f2f2').css('background-image', 'url(http://www.nkbm.si/images/menu_main_selected_arrow.png)').find('a').css('color', '#af0333');
    }

    //tab content
    $('#tabs .tab').click(function() {
        //change active tab
        $('#tabs .tab').removeClass('active');
        $(this).addClass('active');

        //get tabid
        var tabid = $(this).attr('id');

        //change tab content
        $('#tabcontents .tabcontent').hide();
        $('#' + tabid + 'content').show();
        setAjaxCarousel();
    });

    //open first tab content
    $('#tabs .active').click();

    //menu slide down on mouse over
    $('#menu .menuitem').hover(function() {
        //set background color and font color
        if (!$(this).hasClass('selecteditem')) {
            $(this).css('background-color', '#f2f2f2').find('a').css('color', '#af0333');
        }

        //if menu item has sub content
        if ($(this).hasClass('menuitemmore')) {
            //change icon
            $(this).css('background-image', 'url(http://www.nkbm.si/images/menu_main_selected_arrow.png)');
            //this element
            var element = $(this);
            //set timer for this element
            var t = setTimeout(function() {
                //slide down content
                $(element).find('.menusubitem').slideDown(200);
            }, 700);
            //set timer to this element
            $(this).data('timeout', t);
        }
    }, function() {
        //clear background color and font color
        if (!$(this).hasClass('selecteditem')) {
            $(this).css('background-color', '').find('a').css('color', 'white');
        }

        //if menu item has sub content
        if ($(this).hasClass('menuitemmore')) {
            //change icon
            if (!$(this).hasClass('selecteditem')) {
                $(this).css('background-image', 'url(http://www.nkbm.si/images/menu_main_arrow.png)');
            }
            //slide up content
            $(this).find('.menusubitem').slideUp(200);
            //clear timer
            clearTimeout($(this).data('timeout'));
        }
    });

    //click on radio button enable disable extra fields
    $('input[name=contacttypeid]:radio').bind('click', function() {
        if (this.value == 1) {
            $('.disabletext').removeClass('disabletext').addClass('enabletext');
            $('.creditcity').attr('disabled', 'disabled');
            $('.creditdate').attr('disabled', 'disabled');
            $('.datetime').attr('disabled', 'disabled');

            //additional (7.3.2011) hide adviser form
            $('#contactwithadviser').hide();

        } else {
            $('.enabletext').removeClass('enabletext').addClass('disabletext');
            $('.creditcity').attr('disabled', '');
            $('.creditdate').attr('disabled', '');
            $('.datetime').attr('disabled', '');

            //additional (7.3.2011) show adviser form
            $('#contactwithadviser').show();
        }
    })

    //contactform textarea - limit
    $('#contacttextarea').keyup(function() {
        limitChars('contacttextarea', 255);
    });

    //pagination
    $('.paginationbutton').click(function() {
        if ($(this).html() > 0) {
            $('#page').val($(this).html());
            $('#searchform').submit();
        }
    });

    //next/previous link
    $('.paginationactive').click(function() {
        var page = parseInt($('#page').val());

        if ($(this).hasClass('paginationnext')) {
            $('#page').val(page + 1);
        }

        if ($(this).hasClass('paginationprev')) {
            $('#page').val(page - 1);
        }

        $('#searchform').submit();
    });

    //check for default value in search input on click
    $('#header .searchinput input').click(function() {
        if ($(this).val() == $(this).attr('id').replace(/#/g, " ")) {
            $(this).val('');
            $(this).focus();
        }
    });

    //check for default value in search input on blur
    $('#header .searchinput input').blur(function() {
        if ($(this).val() == '') {
            $(this).val($(this).attr('id').replace(/#/g, " "));
        }
    });

    //content carousel
    $('#photogalleryholder').jcarousel({
        vertical: false,
        scroll: 5, //number of items to scroll
        initCallback: photogalleryholder_initCallback, //for control buttons
        //this tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    //check photo gallery controls
    if ($('#photogallery').length > 0) {
        checkPhotoGalleryControls();
    }

    //show push data holder and loop content
    if ($('.pushinfoboxholder_content').children('.one').length > 1) {
        $(this + '.one[id|=infopush1]').slideDown(400).everyTime(4000, function(i) {

            if ($(this).parent('.pushinfoboxholder_content').children('.one:visible').next('.one').length > 0) {

                $(this).parent('.pushinfoboxholder_content').children('.infopushbutton[id|=' + $(this).parent('.pushinfoboxholder_content').children('.one:visible').attr("id") + ']').attr('src', 'http://www.nkbm.si/images/pushibuttonselected.png');

                $(this).parent('.pushinfoboxholder_content').children('.one:visible').hide().next('.one:first').show();

                $(this).parent('.pushinfoboxholder_content').children('.infopushbutton[id|=' + $(this).parent('.pushinfoboxholder_content').children('.one:visible').attr("id") + ']').attr('src', 'http://www.nkbm.si/images/pushibutton.png');
            }
            else {
                $(this).parent('.pushinfoboxholder_content').children('.infopushbutton[id|=' + $(this).parent('.pushinfoboxholder_content').children('.one:visible').attr("id") + ']').attr('src', 'http://www.nkbm.si/images/pushibuttonselected.png');

                $('.one:visible').hide();

                $(this + '.one[id|=infopush1]').show();

                $(this).parent('.pushinfoboxholder_content').children('.infopushbutton[id|=infopush1]').attr('src', 'http://www.nkbm.si/images/pushibutton.png');
            }
        });
    }

    //click on push next button
    $(".pushinfoboxholder_content .infopushbutton").click(function() {
        $(this).parent('.pushinfoboxholder_content').children('.infopushholder:visible').hide();
        $(".pushinfoboxholder_content .infopushbutton").attr('src', 'http://www.nkbm.si/images/pushibuttonselected.png');
        $(this).parent('.pushinfoboxholder_content').children('.infopushholder[id=' + $(this).attr("id") + ']').show();
        $('.infopushbutton[id|=' + $(this).attr("id") + ']').attr('src', 'http://www.nkbm.si/images/pushibutton.png');
    })

    $(".pushinfoboxholder_content .numblock").click(function() {
        $(this).parent('.numberblockholder').parent('.pushinfoboxholder_content').children('.infopushholder:visible').hide();
        $(".pushinfoboxholder_content .infopushbutton").attr('src', 'http://www.nkbm.si/images/pushibuttonselected.png');
        $(this).parent('.numberblockholder').parent('.pushinfoboxholder_content').children('.one[id=' + $(this).attr("id") + ']').show();
        $('.infopushbutton[id|=' + $(this).attr("id") + ']').attr('src', 'http://www.nkbm.si/images/pushibutton.png');
    })


    //on load set carousel
    if ($('#promotionscarousel').length > 0 && $('.navigationitemlinkselected').length > 0) {
        var documentid = $('.navigationitemlinkselected:first').attr('href').split("#")[0];
        var nodeposition = $('.navigationitemlinkselected:first').attr('href').split("#")[1];

        //call ajax
        setPromotionItem(documentid, nodeposition);
    }

    //click navigation item
    $("#rightbar .navigationitemlink").click(function() {
        //call ajax
        setPromotionItem($(this).attr('href').split("#")[0], $(this).attr('href').split("#")[1]);

        //deselect last selected
        $('#rightbar .navigationitemlinkselected').removeClass('navigationitemlinkselected');
        //select
        $(this).addClass('navigationitemlinkselected');
        //stop
        $('#rightbar .navigationgroupselected').stopTime();

        //return false
        return false;
    })

    //select firts category link and loop
    if ($('#rightbar .navigationgroupselected').length > 0) {
        $('#rightbar .navigationgroupselected').next('.navigationitem').slideDown(200);

        //loop
        $('#rightbar .navigationgroupselected').everyTime(parseInt($('#promotionscarouseltime').val()), function(i) {
            //set next (??? added :first -28.3.2011)
            if ($('.navigationitemlinkselected:first').next('.navigationitemlink').length > 0) {
                $('.navigationitemlinkselected:first').removeClass('navigationitemlinkselected').next('.navigationitemlink').addClass('navigationitemlinkselected');

                //call ajax
                setPromotionItem($('.navigationitemlinkselected').attr('href').split("#")[0], $('.navigationitemlinkselected').attr('href').split("#")[1]);
            }
            //go back to first
            else {
                $('.navigationitemlinkselected').removeClass('navigationitemlinkselected');
                $('.navigationitem').children('.navigationitemlink:first').addClass('navigationitemlinkselected');

                //call ajax
                setPromotionItem($('.navigationitemlinkselected').attr('href').split("#")[0], $('.navigationitemlinkselected').attr('href').split("#")[1]);
            }
        });
    }

    //default page navigation click
    $('#rightbar .navigationgroup').click(function() {
        if (!$(this).next('.navigationitem').is(':visible')) {
            $('#rightbar .navigationgroupselected').stopTime();
            $('.navigationgroup').removeClass('navigationgroupselected');
            $(this).addClass('navigationgroupselected');
            $('.navigationitem').slideUp(200);
            $(this).next('.navigationitem').slideDown(200).children().removeClass('navigationitemlinkselected');
            $(this).next('.navigationitem').children('.navigationitemlink:first').addClass('navigationitemlinkselected');

            //call ajax
            setPromotionItem($(this).next('.navigationitem').children('.navigationitemlink:first').attr('href').split("#")[0], $(this).next('.navigationitem').children('.navigationitemlink:first').attr('href').split("#")[1]);
        }
    });

    //contact organization
    if ($('#contactboxorganization').length > 0) {
        getAjaxOrganizationOffices(0, 0);
    }

    //???
    //    //oragnization offices
    //    if ($('#contactboxorganizationoffices').length > 0) {
    //        getAjaxCreditOrganizationOffices(0);
    //    }
});

//set submit buttons hover effect
function setButtonsMouseOver() {

    //button normal right hover effect
    $('.button-normal-right-middle').hover(function() {
        $(this).next('.button-normal-right-right').css('background-image', 'url(http://www.nkbm.si/images/button_normal_right_right_hover.png)');
    }, function() {
        $(this).next('.button-normal-right-right').css('background-image', 'url(http://www.nkbm.si/images/button_normal_right_right.png)');
    });

    $('.button-normal-right-right').hover(function() {
        $(this).css('background-image', 'url(http://www.nkbm.si/images/button_normal_right_right_hover.png)');
    }, function() {
        $(this).css('background-image', 'url(http://www.nkbm.si/images/button_normal_right_right.png)');
    });

    //button normal left hover effect
    $('.button-normal-left-middle').hover(function() {
        $(this).prev('.button-normal-left-left').css('background-image', 'url(http://www.nkbm.si/images/button_normal_left_left_hover.png)');
    }, function() {
        $(this).prev('.button-normal-left-left').css('background-image', 'url(http://www.nkbm.si/images/button_normal_left_left.png)');
    });

    $('.button-normal-left-left').hover(function() {
        $(this).css('background-image', 'url(http://www.nkbm.si/images/button_normal_left_left_hover.png)');
    }, function() {
        $(this).css('background-image', 'url(http://www.nkbm.si/images/button_normal_left_left.png)');
    });
}

//pricelist open/close
function openPriceListItem(classname) {
    //animation time 
    var nSlideTime = 0;

    //check to scroll
    if (checkToScroll()) { nSlideTime = 500; }
    
    if ($('.pricelistslide' + classname).is(':hidden')) {

        //close all open price list items
        setTimeout(function() {
            $('.pricelistslideitem').slideUp(300);
            $('.arrowup').removeClass('arrowup').addClass('arrowdown');

            //open selected content list data
            $('#pricelisttypetwo' + classname + ' .arrowdown').removeClass('arrowdown').addClass('arrowup');
            $('.pricelistslide' + classname).slideDown(300);
        }, nSlideTime);
    }
    else {
        //close all open price list items
        setTimeout(function() {
            $('.pricelistslideitem').slideUp(300);
            $('.arrowup').removeClass('arrowup').addClass('arrowdown');
        }, nSlideTime);
    }
}

//???
function closePriceListItem(classname) {
    //animation time 
    var nSlideTime = 0;

    //check to scroll
    if (checkToScroll()) { nSlideTime = 500; }

    //close all open price list items
    setTimeout(function() {
        $('.pricelistslideitem').slideUp(300);
        $('.arrowup').removeClass('arrowup').addClass('arrowdown');
    }, nSlideTime);
}

//open content list data of selected year
function openContentListYear(year) {
    //if selected year is hidden
    if ($('#contentlistdata' + year).is(':hidden')) {

        //close all open content list data
        $('.contentlistdata').slideUp(300);
        $('.arrowup').removeClass('arrowup').addClass('arrowdown');

        //open selected content list data
        $('#contentlist' + year + ' .arrowdown').removeClass('arrowdown').addClass('arrowup');
        $('#contentlistdata' + year).slideDown(300);
    } 
    //if selected year is already open, then close all
    else {        
        //close all open content list data
        setTimeout(function() {
            $('.contentlistdata').slideUp(300);
            $('.arrowup').removeClass('arrowup').addClass('arrowdown');
        }, 700);
    }
}

//open event list data of selected year
function openEventListYear(year) {
    //if selected year is hidden
    if ($('#eventlistdata' + year).is(':hidden')) {

        //close all open content list data
        $('.eventlistdata').slideUp(300);
        $('.arrowup').removeClass('arrowup').addClass('arrowdown');

        //open selected content list data
        $('#eventlist' + year + ' .arrowdown').removeClass('arrowdown').addClass('arrowup');
        $('#eventlistdata' + year).slideDown(300);
    }
    //if selected year is already open, then close all
    else {
        //close all open content list data
        setTimeout(function() {
            $('.eventlistdata').slideUp(300);
            $('.arrowup').removeClass('arrowup').addClass('arrowdown');
        }, 500);
    }
}

//open / close attachement block
function openIndexAttachement(position) {
    //show
    if ($('#eventlistdata' + position).is(':hidden')) {
        $('#arrow' + position).removeClass('arrowdown').addClass('arrowup');

        //disable slide if video
        if ($('#ajaxvideodocid_' + position).length > 0)
            $('#eventlistdata' + position).show();
        else
            $('#eventlistdata' + position).slideDown(300);

    }
    //close
    else {
        //disable slide if video
        if ($('#ajaxvideodocid_' + position).length > 0)
            $('#eventlistdata' + position).hide();
        else
            $('#eventlistdata' + position).slideUp(300);
        
        $('#arrow' + position).removeClass('arrowup').addClass('arrowdown');
    }
}

//set promotion item with ajax
function setPromotionItem(documentid, nodeposition) {
    $.ajax({
        cache: true,
        url: 'http://www.nkbm.si/ajaxdefault.aspx',
        data: ({ docid: documentid, nodepos: nodeposition }),
        success: function(data) 
        {
            $('#promotionscarousel').html(data);
        }
    });
   
}

//photo gallery variable for sliding
var photogalleryslide = true;

//photo gallery carousel handler
function photogalleryholder_initCallback(carousel) {

    //read scroll position
    $('#photogallery .jcarousel-control-button').click(function() {
        if (photogalleryslide) {
            photogalleryslide = false;
            carousel.scroll($.jcarousel.intval($(this).attr('alt')));
            $('#photogallery .jcarousel-control-button').removeClass('jcarousel-control-button-selected');
            $(this).addClass('jcarousel-control-button-selected');

            checkPhotoGalleryControls();

            //enable scroll after 500 miliseconds
            setTimeout(function() { photogalleryslide = true; }, 500);
        }
        return false;
    });

    //previous event
    $('#photogallery .jcarousel-prev-horizontal').click(function() {
        if (photogalleryslide) {
            $('#photogallery .jcarousel-control-button-selected').prev('.jcarousel-control-button').click();

            //check photo gallery controls
            checkPhotoGalleryControls();
        }
    });

    //next event
    $('#photogallery .jcarousel-next-horizontal').click(function() {
        if (photogalleryslide) {
            $('#photogallery .jcarousel-control-button-selected').next('.jcarousel-control-button').click();

            //check photo gallery controls
            checkPhotoGalleryControls();
        }
    });
}

//check pohoto gallery controls
function checkPhotoGalleryControls() {
    //check if previous slide posible for prev button
    if ($('#photogallery .jcarousel-control-button-selected').prev('.jcarousel-control-button').length == 0) {
        $('#photogallery .jcarousel-prev-horizontal').addClass('jcarousel-prev-disabled-horizontal');
    }
    else {
        $('#photogallery .jcarousel-prev-horizontal').removeClass('jcarousel-prev-disabled-horizontal');
    }

    //check if next slide posible for next button
    if ($('#photogallery .jcarousel-control-button-selected').next('.jcarousel-control-button').length == 0) {
        $('#photogallery .jcarousel-next-horizontal').addClass('jcarousel-next-disabled-horizontal');
    }
    else {
        $('#photogallery .jcarousel-next-horizontal').removeClass('jcarousel-next-disabled-horizontal');
    }
}

//hides photo gallery controls
function hidePhotoGalleryControls() {
    $('.jcarousel-control-holder').hide();
}

//content image popup
function imagePopup(pos) {
    $('#modalwindow').css('width', '600px');
    //get array of images with class contentimage on page
    var imgs = $('#photogalleryholder .carouselimage').get();

    //set position of next image
    var posprev = parseInt(pos) - 1;
    //set position of previous image
    var posnext = parseInt(pos) + 1;
    //get fileid
    var fileid = $('#photogalleryholder .carouselimage[data-pos=' + pos + ']').attr('data-fileid');
    //get title
    var title = $('#photogalleryholder .carouselimage[data-pos=' + pos + ']').attr('title');

    //creating pager next previous and image position
    var htmlcontent = '<div class="modaldialog-gallery">';

    //count image na position
    htmlcontent = htmlcontent + '<div class="imagecounter">' + pos + ' od ' + imgs.length + ' </div><img onclick="closePopup()" src="http://www.nkbm.si/images/modaldialog_close.png" class="closebox" /><div class="spacer10"></div><div class="headerline"></div>';

    //end of htmlcontent creating
    htmlcontent = htmlcontent + '<div class="image-container"><img src="http://www.nkbm.si/contentimage_' + fileid + '_560_425.jpg" alt=""></div><div id="imagepopuptitle">' + title + '</div></div>'
    htmlcontent = htmlcontent + '<table cellspacing="0" cellpadding="0" width="100%"><tr><td class="modal-bottom-left"></td><td class="modal-bottom"></td><td class="modal-bottom-right"></td></tr></table>'

    //add javascript for left and right button
    htmlcontent = htmlcontent + '<script type="text/javascript"> $(".goleft").hover(function() { $(".goleft img").show(); }, function() { $(".goleft img").hide(); });'
    htmlcontent = htmlcontent + '$(".goright").hover(function() { $(".goright img").show(); }, function() { $(".goright img").hide(); });'
    htmlcontent = htmlcontent + '</script>'

    //previous image
    if (posprev > 0) {
        htmlcontent = htmlcontent + '<div class="goleft" onclick="imagePopup(' + posprev + ');" ><img src="http://www.nkbm.si/images/modaldialog_goleft.png" /></div>';
    }

    //next image
    if (posnext <= imgs.length) {
        htmlcontent = htmlcontent + '<div class="goright" onclick="imagePopup(' + posnext + ');" ><img src="http://www.nkbm.si/images/modaldialog_goright.png" /></div>';
    }

    //set popup image
    $('#modalwindow').html(htmlcontent);

    //hide image and animate fadein after delay
    $('.image-container').css({ display: 'none' });
    $('.image-container').fadeIn(200);

    //popup - load
    openPopup();
    
    //popup - center
    centerPopup();
  
}

//POPUP ###############
//0 = disabled; 1 = enabled;  
var popupStatus = 0;

//show popup
function openPopup() {
    if (popupStatus == 0) {
        //check for IE
        if ($.browser.msie) {
            $('#modalwindowbackground').css({ opacity: '0.4' }).css('display', 'block');
            $('#modalwindow').css('display', 'block');
        }
        else {
            $('#modalwindowbackground').css({ opacity: '0.4' }).fadeIn('fast');
            $('#modalwindow').fadeIn('fast');
        }

        //popup - center
        centerPopup();

        //set that popup is open
        popupStatus = 1;
    }
}

//position popup in center of window
function centerPopup() {
    //request data for centering
    var windowWidth = 675; //$(window).width();
    var windowHeight = $(window).height();

    var popupWidth = $("#modalwindow").width();
    var popupHeight = $("#modalwindow").height();

    var newTop = 165; //windowHeight / 2 - popupHeight / 2;
    var newLeft = windowWidth / 2 - popupWidth / 2;
    //centering
    $('#modalwindow').animate({ top: newTop, left: newLeft }, 250);

    //set modal window background height
    $('#modalwindowbackground').css({ height: $(document).height() - 148}) //remove height of head and menu
}

//position popup in center of window
function centerInfoPopup() {

    //request data for centering
    var windowWidth = 675; //$(window).width();
    var windowHeight = $(window).height();

    var popupWidth = $("#modalwindow").width();
    var popupHeight = $("#modalwindow").height();

    var newTop = 160; //windowHeight / 2 - popupHeight / 2;
    var newLeft = windowWidth / 2 - popupWidth / 2;
    //centering
    $('#modalwindow').animate({ top: newTop, left: newLeft }, 250);

    //set modal window background height
    $('#modalwindowbackground').css({ height: $(document).height() - 148 }) //remove height of head and menu
}

//dispose popup
function disposePopup() {
    //disables popup only if it is enabled
    if (popupStatus == 1) {
        //mozilla
        if ($.browser == "mozilla" && $.browser.version.substr(0, 3) == "1.9") {
            $('#modalwindowbackground').fadeOut('fast');
            $('#modalwindow').fadeOut('fast').css('top', '20%').html('');
        } else {
            $('#modalwindowbackground').css('display', 'none');
            $('#modalwindow').css('display', 'none').css('top', '20%').html('');
        }

        //set that popup is closed
        popupStatus = 0;
    }
}

//close popup window
function closePopup() {
    //popup - dispose
    disposePopup();
}

//start jquery timer plugin 
jQuery.fn.extend({
    everyTime: function(interval, label, fn, times) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.extend({
    timer: {
        global: [],
        guid: 1,
        dataKey: "jQuery.timer",
        regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseFloat(result[1]);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times) {
            var counter = 0;

            if (jQuery.isFunction(label)) {
                if (!times)
                    times = fn;
                fn = label;
                label = interval;
            }

            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval < 0)
                return;

            if (typeof times != 'number' || isNaN(times) || times < 0)
                times = 0;

            times = times || 0;

            var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

            if (!timers[label])
                timers[label] = {};

            fn.timerID = fn.timerID || this.guid++;

            var handler = function() {
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
            };

            handler.timerID = fn.timerID;

            if (!timers[label][fn.timerID])
                timers[label][fn.timerID] = window.setInterval(handler, interval);

            this.global.push(element);

        },
        remove: function(element, label, fn) {
            var timers = jQuery.data(element, this.dataKey), ret;

            if (timers) {

                if (!label) {
                    for (label in timers)
                        this.remove(element, label, fn);
                } else if (timers[label]) {
                    if (fn) {
                        if (fn.timerID) {
                            window.clearInterval(timers[label][fn.timerID]);
                            delete timers[label][fn.timerID];
                        }
                    } else {
                        for (var fn in timers[label]) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }

                    for (ret in timers[label]) break;
                    if (!ret) {
                        ret = null;
                        delete timers[label];
                    }
                }

                for (ret in timers) break;
                if (!ret)
                    jQuery.removeData(element, this.dataKey);
            }
        }
    }
});

jQuery(window).bind("unload", function() {
    jQuery.each(jQuery.timer.global, function(index, item) {
        jQuery.timer.remove(item);
    });
});
//end jquery timer code



//get ajax organization offices
function getAjaxOrganizationOffices(organizationid, secondorganizationid) {
    $.ajax({
        cache: true,
        url: 'http://www.nkbm.si/ajaxorganization.aspx',
        data: ({ docid: $('#contactboxorganizationdocid').val(), catalognodeid: $('#contactcatalognodeid').val(), organizationid: organizationid, secondorganizationid: secondorganizationid }),
        success: function(data) {
            //set data
            if (jQuery.trim(data.split('###')[0]) == "0") {
                $('#contactboxorganization').html(data.split('###')[1]);
            }
            else
                getAjaxOrganizationOffices(organizationid, data.split('###')[0]);
        }
    });
}

//get ajax Credit organization offices
function getAjaxCreditOrganizationOffices(organizationid, nodeid) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxorganizationoffice.aspx',
        data: ({ organizationid: organizationid,nodeid: nodeid }),
        success: function(data) {
            $('#contactboxorganizationoffices').html(data);
        }
    });
}

function getAjaxCreditOrganizationOfficesSelected(organizationid, secondorganizationid, nodeid) {
    $.ajax({
    url: 'http://www.nkbm.si/ajaxorganizationoffice.aspx',
        data: ({ organizationid: organizationid, secondorganizationid: secondorganizationid,nodeid: nodeid }),
        success: function(data) {
            $('#contactboxorganizationoffices').html(data);
        }
    });
}

//get currency exchange amount
function getCurrencyExchange(location, e) {

    //validate input
    if (navigator.appName == "Netscape")
        var keyIndex = e.which; //for netscape
    else
        var keyIndex = window.event.keyCode; //other

    //alert(keyIndex);

    if (keyIndex != 9) {

        //alert('not 9');
    
        //first exchange value change - set second
        if (location == 1) {

            //call ajax
            $.ajax({
                url: 'http://www.nkbm.si/ajaxcurrencyexchange.aspx',
                data: ({ amountfrom: $('#exchangevaluefrom').val(), currencyidfrom: $('#currencyidfrom').val(), currencyidto: $('#currencyidto').val() }),
                success: function(data) {
                    //set data
                    $('#exchangevalueto').val(data);
                    formatCurrency(document.getElementById('exchangevalueto'), 2);
                }
            });
        }

        //second exchange value change - set first
        if (location == 2) {

            //call ajax
            $.ajax({
                url: 'http://www.nkbm.si/ajaxcurrencyexchange.aspx',
                data: ({ amountfrom: $('#exchangevalueto').val(), currencyidfrom: $('#currencyidto').val(), currencyidto: $('#currencyidfrom').val() }),
                success: function(data) {
                    //set data
                    $('#exchangevaluefrom').val(data);
                    formatCurrency(document.getElementById('exchangevaluefrom'), 2);
                }
            });
        }
    }
}

//currency format
function formatCurrency(name, dec) {
    //init variables
    inp = name.value;
    comma = 0;
    sign = ""

    //get sign
    if (inp.substring(0, 1) == '-') {
        sign = "-";
        inp = inp.substring(1, inp.length);
    };

    //validate input value
    if (inp == "")
        return;
    outt = "";

    //loop characters
    for (var i = 0; i < inp.length; i++) {
        //get character
        sChar = inp.charAt(i);
        if (sChar == ".")
            continue;
        else if (sChar == ",") {
            if (dec == 0)
                break;
            if (comma > 0)
                break;
            comma = 1;
            outt = outt + sChar;
        }
        else if (sChar < "0" || sChar > "9")
            break;
        else
            outt = outt + sChar;
    }

    //get value with zeros
    out = "";
    if (dec) {
        zeros = "000000000";
        out = ",";
        pos1 = outt.indexOf(",");
        if (pos1 != -1) {
            pos2 = outt.length;
            if (pos2 - pos1 - 1 > dec)
                pos2 = pos1 + dec + 1;
            out = out + outt.substring(pos1 + 1, pos2);
            outt = outt.substring(0, pos1);
        }
        out = out + zeros.substring(0, 3 - out.length);
    }
    //format value with separators
    for (i = outt.length; i > 3; i -= 3)
        out = "." + outt.substring(i - 3, i) + out;

    //return formated value
    out = outt.substring(0, i) + out;
    name.value = sign + out;

}

//key: only numeric 
function keyOnlyNumericWEnter(e) {
    //validate input
    if (navigator.appName == "Netscape")
        var keyIndex = e.which; //for netscape
    else
        var keyIndex = window.event.keyCode; //other

    //only allow numbers and backspace
    if ((keyIndex > 47 && keyIndex < 58) || keyIndex == 0 || keyIndex == 8 || keyIndex == 46 || keyIndex == 44 || keyIndex == 13)
        return true;
    else
        return false;
}

//set currency exchange newsletter
function setAjaxCurrencyExchangeNewsletter(add, remove) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxcurrencyexchangenewsletter.aspx',
        data: ({ mailingid: $('#exchangenewslettermailingid').val(), name: $('#exchangenewslettername').val(), email: $('#exchangenewsletteremail').val(), add: add, remove: remove }),
        success: function(data) {
            //error
            if (data.split("###")[0] == "1") {
                //no mailingid
                if ($('#exchangenewslettermailingid').val() == "0") {
                    $('#exchangenewslettermailingid').addClass('error');
                    $('#exchangenewsletteremail').removeClass('error');
                    $('#exchangenewsletterresult').addClass('errortext');
                }

                //no mailingid
                if ($('#exchangenewslettermailingid').val() > 0) {
                    $('#exchangenewslettermailingid').removeClass('error');
                    $('#exchangenewsletteremail').addClass('error');
                    $('#exchangenewsletterresult').addClass('errortext');
                }

                //error
                $('#exchangenewsletterresult').html(data.split("###")[1]);
            }

            //info
            if (data.split("###")[0] == "2") {
                $('#exchangenewsletterresult').html(data.split("###")[1]);
                $('#exchangenewsletteremail').removeClass('error');
                $('#exchangenewslettermailingid').removeClass('error');
                $('#exchangenewsletterresult').removeClass('errortext');
                $('#exchangenewslettermailingid').val("0");
                $('#exchangenewslettername').val("");
                $('#exchangenewsletteremail').val("");
            }
        }
    });
}

//set newsletter
function setAjaxNewsletter(mailingid) {

    $.ajax({
        url: 'http://www.nkbm.si/ajaxnewsletter.aspx',
        data: ({ mailingid: mailingid, name: $('#newslettername').val(), email: $('#newsletteremail').val() }),
        success: function(data) {
        
            //error
        if (data.split("###")[0] == "1") {
            
                //mailingid
                if (mailingid > 0) {
                    $('#newslettermailingid').removeClass('error');
                    $('#newsletteremail').addClass('error');
                    $('#newsletterresult').addClass('errortext');
                }

                //error
                $('#newsletterresult').html(data.split("###")[1]);
            }

            //info
            if (data.split("###")[0] == "2") {
                $('#newsletterresult').html(data.split("###")[1]);
                $('#newsletteremail').removeClass('error');
                $('#newslettermailingid').removeClass('error');
                $('#newsletterresult').removeClass('errortext');
                $('#newslettermailingid').val("0");
                $('#newslettername').val("");
                $('#newsletteremail').val("");
            }
        }
    });
}

//ajax survey
function getAjaxSurvey(docid, validate) {

    var nodepos = 0;

    //vote
    if (validate == 1) {
        nodepos = $('.answers input:radio:checked').val();
    }


    if (validate != 1 || nodepos > 0) {

        $.ajax({
            url: 'http://www.nkbm.si/ajaxsurvey.aspx',
            data: ({ docid: docid, validate: validate, nodepos: nodepos }),
            success: function(data) {

                $('#ajaxsurvey').html(data);

                setButtonsMouseOver();
            }
        });
    }
}

//open popup info modal dialog
function InfoPopUp(nodeid, catalognodeid) {


    $.ajax({
        url: 'http://www.nkbm.si/ajaxinfo.aspx',
        data: ({ nodeid: nodeid, catalognodeid: catalognodeid }),
        success: function(data) {

            //display once every 24hours (by sid)
            if (data != '') {
                $('#modalwindow').css('width', '600px');
                $('#modalwindow').html(data);

                setButtonsMouseOver();

                //popup - load
                openPopup();
                //popup - center
                centerInfoPopup();
            }
        }
    });

    //send request
    //sendAjaxRequest(rooturl + "ajaxinfo.aspx?nodeid=" + nodeid + "&localeid= " + localeid + "&catalognodeid=" + catalognodeid, "modalWindow", "CheckInfoPopUpContent");
}


//get timeline content with ajax
function getTimelineContent(docid) {
    
    //call ajax
    $.ajax({
        url: 'http://www.nkbm.si/ajaxtimeline.aspx',
        data: ({ docid: docid }),
        success: function(data) {
            //load new content
        $('#timelinecontent').fadeOut('fast', function() { $('#timelinecontent').html(data); });

            $('#timelinecontent').fadeIn('slow');
        }
    });
}

//auto load timer
function autoLoad() {
    var offset = $("#slidehandler").offset();

    //set new offset
    if (parseInt(offset.left) < 51)
        $("#slidehandler").css({ left: '550px' }); 
    else
        $("#slidehandler").css({ left: (parseInt($("#slidehandler").css('left')) - tickspace) });

    //get offset and calculate
    offset = $("#slidehandler").offset();
    var index = parseInt((offset.left - 50) / tickspace);
    $("#slidehandler").html(yearArray[index]);
    
    //set document
    currentdocid = yearArrayDocid[index];
    getTimelineContent(currentdocid);    
    
    //set to 0
    if(index == 0)
        $("#slidehandler").css({ left: '10px' });

    //auto load
    timelineautoloadtimer = setTimeout("autoLoad()", 3000);
}

//hide / show calendar
function openCalendar(targetid, divtargetid) {
    
    if ($('#' + divtargetid).is(':visible')) {
        $('#' + divtargetid).hide();
    }
    else {
        $('#' + divtargetid).show();
        setCalendar('', '', '', $('#' + targetid).val(), targetid, divtargetid);
    }
}

//set calendar
function setCalendar(day, month, year, date, targetid, divtargetid) {
    //call ajax
    $.ajax({
        cache: true,
        url: 'http://www.nkbm.si/ajaxcalendar.aspx',
        data: ({ date: date, day: day, month: month, year: year, targetid: targetid, divtargetid: divtargetid }),
        success: function(data) {
            //set data
        $('#' + divtargetid).html(data);
        }
    });
}

//calendar set date
function setDate(date, id, divtargetid) {
    //set date
    $('#' + id).val(date);
    $('#' + divtargetid).hide();
}

//limit input
function limitChars(textid, limit) {
    var text = $('#' + textid).val();
    var textlength = text.length;
    if (textlength > limit) {
        //limit input
        $('#' + textid).val(text.substr(0, limit));
        return false;
    } else {
        //allow input
        return true;
    }
}

//scroll window to menu
function scrollWin(seconds) {
    var menuposition = $("#menu").offset().top

    if (checkToScroll()) {
        $('html, body').animate({ scrollTop: menuposition }, seconds);
    }
}

//check if to scroll
function checkToScroll() {
    var menuposition = $("#menu").offset().top
    var currentscrollposition = $(window).scrollTop();

    if (menuposition < currentscrollposition) {
        return true;
    }
    else {
        return false;
    }
}

//set comparator data
function setProductComparatorAjax(nodeid, docid) {
    var remove = false;

    //set remove variable
    if (docid > 0 && !$('#compare' + nodeid + 'doc' + docid).is(':checked'))
        remove = true;

    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcomparator.aspx',
        data: ({ nodeid: nodeid, docid: docid, remove: remove }),
        success: function(data) {

            //disable all / enable
            if (data.split('###')[0].replace('doc', '') != '' && data.split('###')[1].replace('doc', '') != '' && data.split('###')[2].replace('doc', '') != '')
                $('.productcheckbox').attr('disabled', true);
            else
                $('.productcheckbox').removeAttr('disabled');

            //uncheck
            $('.productcheckbox').attr('checked', false);

            //enable
            $('#compare' + data.split('###')[0]).removeAttr('disabled');
            $('#compare' + data.split('###')[1]).removeAttr('disabled');
            $('#compare' + data.split('###')[2]).removeAttr('disabled');

            //check
            $('#compare' + data.split('###')[0]).attr('checked', true);
            $('#compare' + data.split('###')[1]).attr('checked', true);
            $('#compare' + data.split('###')[2]).attr('checked', true);

            //set data
            $('#ajaxproductcomparatordiv').html(data.split('###')[3]);
        }
    });

    if (docid > 0 && !remove)
        $('html, body').animate({ scrollTop: $(".comparatortop").offset().top }, 1000);
}

function openCreditCalculation() {
    //call ajax
    $.ajax({
        url: 'http://www.nkbm.si/ajaxcreditcalculation.aspx',
        data: ({ validate: 0 }),
        success: function(data) {
            //fill modal window
            $('#modalwindow').css('width', '600px');
            $('#modalwindow').html(data);

            //popup - load
            openPopup();

            //popup - center
            centerPopup();
        }
    });
}

//get ajax product calculator
function getAjaxProductCalculatorSaving(productid, validate, producttypeid, amount, term, termtypeid, currencyid, simulation, simulationinterestratepercent, productinterestrateversionid) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcalculator.aspx',
        data: ({ productid: productid, validate: validate, producttypeid: producttypeid, amount: amount, term: term, termtypeid: termtypeid, currencyid: currencyid, simulation: (simulation ? 1 : 0), simulationinterestratepercent: (simulation ? simulationinterestratepercent : 0), productinterestrateversionid: productinterestrateversionid }),
        success: function(data) {
            //set data
            $('#calculation' + productid).html(data);
        }
    });
}

//print popup window calculation saving
function popupPrintCalculationWindowSaving(productid, producttypeid, amount, term, termtypeid, currencyid, simulation, simulationinterestratepercent, productinterestrateversionid) {
    var url = "http://www.nkbm.si/ajaxproductcalculator.aspx?print=true&validate=1&productid=" + productid + "&producttypeid=" + producttypeid + "&amount=" + amount + "&term=" + term + "&termtypeid=" + termtypeid + "&currencyid=" + currencyid + "&simulation=" + simulation + "&simulationinterestratepercent=" + simulationinterestratepercent + "&productinterestrateversionid=" + productinterestrateversionid;
    var h = 600;
    var w = 600;

    windowprops = "height=" + h + ",width=" + w + ",location=no,menubar=no,toolbar=no,titlebar=no,status=no";
    var windowReference = window.open(url, "Picture" + w + h, windowprops);
}

//set product calculator saving simulation
function setProductCalculatorSavingSimulation(simulation, productid) {
    //enable/disable simulation
    if (simulation) {
        $('#simulationinterestratepercent' + productid).attr('disabled', '');
        $('#simulationpercent' + productid).removeClass('inputdisabled');
        $('#simulationmargin' + productid).removeClass('inputdisabled');
        
    }
    else {
        $('#simulationinterestratepercent' + productid).attr('disabled', 'disabled');
        $('#simulationpercent' + productid).addClass('inputdisabled');
        $('#simulationmargin' + productid).addClass('inputdisabled');
    }
}

//set product calculator saving simulation type
function setProductCalculatorSavingSimulationType(simulationtype, productid) {
    //show/hide simulation percent by simulationtype
    if (simulationtype == 0) {
        $('#simulationpercent' + productid).show();
        $('#simulationmargin' + productid).hide();
    }
    else {
        $('#simulationpercent' + productid).hide();
        $('#simulationmargin' + productid).show();
    }
}

//get ajax product calculator loan
function getAjaxProductCalculatorLoan(productid, validate, producttypeid, productinterestratetypeid, insurancetypeid, amount, annuity, term, termtypeid, currencyid, annuitycurrencyid, simulation, simulationinterestratepercent, productadditionalcostversionid, productinterestrateversionid, paymentvalidate) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcalculator.aspx',
        data: ({ productid: productid, validate: validate, producttypeid: producttypeid, productinterestratetypeid: productinterestratetypeid, insurancetypeid: insurancetypeid,
            amount: amount, annuity: annuity, term: term, termtypeid: termtypeid, currencyid: currencyid, annuitycurrencyid: annuitycurrencyid,
            simulation: (simulation ? 1 : 0), simulationinterestratepercent: (simulation ? simulationinterestratepercent : 0), simulationpaymentcostpercent: 0, productadditionalcostversionid: productadditionalcostversionid, productinterestrateversionid: productinterestrateversionid
        }),
        success: function(data) {
            //set data
            $('#calculation' + productid).html(data);

            //set next tab inputs values
            var amount = document.getElementById('ajaxproductcalculatorloan' + productid).amount.value;
            var annuity = document.getElementById('ajaxproductcalculatorloan' + productid).annuity.value;
            var term = document.getElementById('ajaxproductcalculatorloan' + productid).term.value;
            $('input[name=amountofcreditineuros]').val(amount);
            $('input[name=commitmentpermonthineuros]').val(annuity);

            //??? conver years to months if selected
            if (termtypeid == 3) {
                //years
                $('input[name=repaymentperiodinmonths]').val(Number(term) * 12);
            }
            else {
                //months
                $('input[name=repaymentperiodinmonths]').val(term);
            }
        }
    });
}

//print popup window calculation saving
function popupPrintCalculationWindowLoan(productid, producttypeid, productinterestratetypeid, insurancetypeid, amount, annuity, term, termtypeid, currencyid, annuitycurrencyid, simulation, simulationinterestratepercent, productadditionalcostversionid, productinterestrateversionid, validatepayment) {
    var url = "http://www.nkbm.si/ajaxproductcalculator.aspx?print=true&productid=" + productid + "&validate=1&producttypeid=" + producttypeid + "&productinterestratetypeid=" + productinterestratetypeid +
    "&insurancetypeid=" + insurancetypeid + "&amount=" + amount + "&annuity=" + annuity + "&term=" + term + "&termtypeid=" + termtypeid +
    "&currencyid=" + currencyid + "&annuitycurrencyid=" + annuitycurrencyid + "&simulation=" + (simulation ? 1 : 0) +
    "&simulationinterestratepercent=" + (simulation ? simulationinterestratepercent : 0) + "&simulationpaymentcostpercent=0&productadditionalcostversionid=" + productadditionalcostversionid +
    "&productinterestrateversionid=" + productinterestrateversionid + "&validatepayment=" + validatepayment;
    var h = 800;
    var w = 800;

    windowprops = "height=" + h + ",width=" + w + ",location=no,menubar=no,toolbar=no,titlebar=no,status=no";
    window.open(url, "Picture" + w + h, windowprops);
}

//payment plan
function popupPaymentCalculationWindowLoan(productid, producttypeid, productinterestratetypeid, insurancetypeid, amount, annuity, term, termtypeid, currencyid, annuitycurrencyid, simulation, simulationinterestratepercent, productadditionalcostversionid, productinterestrateversionid) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcalculator.aspx',
        data: ({ productid: productid, validate: 1, producttypeid: producttypeid, productinterestratetypeid: productinterestratetypeid, insurancetypeid: insurancetypeid,
            amount: amount, annuity: annuity, term: term, termtypeid: termtypeid, currencyid: currencyid, annuitycurrencyid: annuitycurrencyid,
            simulation: (simulation ? 1 : 0), simulationinterestratepercent: (simulation ? simulationinterestratepercent : 0), simulationpaymentcostpercent: 0, productadditionalcostversionid: productadditionalcostversionid, productinterestrateversionid: productinterestrateversionid, validatepayment: 1
        }),
        success: function(data) {
            //set data
            var newdata = "<div id='ajaxcreditcalculation'><img onclick='closePopup()' src='http://www.nkbm.si/images/modaldialog_close.png' class='closebox'/><div class='spacer10'>&nbsp;</div><div class='data'>" + data + "</div></div><table cellspacing='0' cellpadding='0' width='100%'><tr><td class='modal-bottom-left'></td><td class='modal-bottom'></td><td class='modal-bottom-right'></td></tr></table>";

            //fill modal window
            $('#modalwindow').css('width', '600px');
            $('#modalwindow').html(newdata);

            //popup - load
            openPopup();

            //popup - center
            centerPopup();
        }
    });
}

//set product calculator loan simulation
function setProductCalculatorLoanSimulation(simulation, productid) {
    //enable/disable simulation
    if (simulation) {
        $('#simulationinterestratepercent' + productid).attr('disabled', '');
        $('#simulationpercent' + productid).removeClass('inputdisabled');
        $('#simulationpercentsign' + productid).removeClass('inputdisabled');
        $('#simulationmargin' + productid).removeClass('inputdisabled');

    }
    else {
        $('#simulationinterestratepercent' + productid).attr('disabled', 'disabled');
        $('#simulationpercent' + productid).addClass('inputdisabled');
        $('#simulationpercentsign' + productid).addClass('inputdisabled');
        $('#simulationmargin' + productid).addClass('inputdisabled');
    }
}

//set approve cost type
function setAjaxProductCalculatorLoanSimulationApproveCostType(number) {
    $('.approvecosttypeid1').hide();
    $('.approvecosttypeid2').hide();
    $('.approvecosttypeid3').hide();
    $('.approvecosttypeid' + number).show();
}

//set product calculator loan simulation type
function setProductCalculatorLoanSimulationType(simulationtype, productid) {
    //show/hide simulation percent by simulationtype
    if (simulationtype == 0) {
        $('#simulationpercent' + productid).show();
        $('#simulationmargin' + productid).hide();
    }
    else {
        $('#simulationpercent' + productid).hide();
        $('#simulationmargin' + productid).show();
    }
}

//get ajax product calculator loan
function getAjaxProductCalculatorLoanSimulation(productid, validate, productinterestratetypeid, amount, annuity, term, termtypeid, currencyid, annuitycurrencyid, interestratepercent, approvecosttypeid, approvecostamount, approvecostpercent, approvecostpercentwlimit, approvecostpercentwlimitminamount, approvecostpercentwlimitmaxamount, paymentcostpercent) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcalculator.aspx',
        data: ({ productid: productid, validate: validate, productinterestratetypeid: productinterestratetypeid, amount: amount, 
                annuity: annuity, term: term, termtypeid: termtypeid, currencyid: currencyid, annuitycurrencyid: annuitycurrencyid, 
                interestratepercent: interestratepercent, approvecosttypeid: approvecosttypeid, approvecostamount: approvecostamount,
                approvecostpercent: approvecostpercent, approvecostpercentwlimit: approvecostpercentwlimit, 
                approvecostpercentwlimitminamount: approvecostpercentwlimitminamount, approvecostpercentwlimitmaxamount: approvecostpercentwlimitmaxamount,
                paymentcostpercent: paymentcostpercent
        }),
        success: function(data) {
            //set data
            $('#calculation' + productid).html(data);
        }
    });
}

//payment plan
function popupPaymentCalculationWindowLoanSimulation(productid, validate, productinterestratetypeid, amount, annuity, term, termtypeid, currencyid, annuitycurrencyid, interestratepercent, approvecosttypeid, approvecostamount, approvecostpercent, approvecostpercentwlimit, approvecostpercentwlimitminamount, approvecostpercentwlimitmaxamount, paymentcostpercent) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcalculator.aspx',
        data: ({ productid: productid, validate: validate, productinterestratetypeid: productinterestratetypeid, amount: amount,
            annuity: annuity, term: term, termtypeid: termtypeid, currencyid: currencyid, annuitycurrencyid: annuitycurrencyid,
            interestratepercent: interestratepercent, approvecosttypeid: approvecosttypeid, approvecostamount: approvecostamount,
            approvecostpercent: approvecostpercent, approvecostpercentwlimit: approvecostpercentwlimit,
            approvecostpercentwlimitminamount: approvecostpercentwlimitminamount, approvecostpercentwlimitmaxamount: approvecostpercentwlimitmaxamount,
            paymentcostpercent: paymentcostpercent, validatepayment: 1
        }),
        success: function(data) {
            //set data
            var newdata = "<div id='ajaxcreditcalculation'><img onclick='closePopup()' src='http://www.nkbm.si/images/modaldialog_close.png' class='closebox'/><div class='spacer10'>&nbsp;</div><div class='data'>" + data + "</div></div><table cellspacing='0' cellpadding='0' width='100%'><tr><td class='modal-bottom-left'></td><td class='modal-bottom'></td><td class='modal-bottom-right'></td></tr></table>";

            //fill modal window
            $('#modalwindow').css('width', '600px');
            $('#modalwindow').html(newdata);

            //popup - load
            openPopup();

            //popup - center
            centerPopup();
        }
    });
}


//print popup window calculation loan simulation
function popupPrintCalculationLoanSimulationWindow(productid, productinterestratetypeid, amount, annuity, term, termtypeid, currencyid, annuitycurrencyid,
            interestratepercent, approvecosttypeid, approvecostamount, approvecostpercent, approvecostpercentwlimit, approvecostpercentwlimitminamount,
            approvecostpercentwlimitmaxamount, paymentcostpercent, validatepayment) {

    var url = "http://www.nkbm.si/ajaxproductcalculator.aspx?print=true&productid=" + productid + "&validate=1" + 
    "&productinterestratetypeid=" + productinterestratetypeid +
    "&amount=" + amount +
    "&annuity=" + annuity +
    "&term=" + term + 
    "&termtypeid=" + termtypeid +
    "&currencyid=" + currencyid +
    "&annuitycurrencyid=" + annuitycurrencyid +
    "&interestratepercent=" + interestratepercent +
    "&approvecosttypeid=" + approvecosttypeid +
    "&approvecostamount=" + approvecostamount +
    "&approvecostpercent=" + approvecostpercent +
    "&approvecostpercentwlimit=" + approvecostpercentwlimit +
    "&approvecostpercentwlimitminamount=" + approvecostpercentwlimitminamount +
    "&approvecostpercentwlimitmaxamount=" + approvecostpercentwlimitmaxamount +
    "&paymentcostpercent=" + paymentcostpercent +
    "&validatepayment=" + validatepayment;
    var h = 800;
    var w = 800;

    windowprops = "height=" + h + ",width=" + w + "";
    window.open(url, "Picture" + w + h, windowprops);
}

//get ajax product calculator life annuity
function getAjaxProductCalculatorLifeAnnuity(productid, validate, productpaymentperiodid, productadvantageclassperiodid, paymentperiods, amount, term, termtypeid, currencyid, simulation, simulationinterestratepercent, productadvantageclassversionid, productinterestrateversionid) {
    //
    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcalculator.aspx',
        data: ({ productid: productid, validate: validate, productpaymentperiodid: productpaymentperiodid, productadvantageclassperiodid: productadvantageclassperiodid, paymentperiods: paymentperiods, amount: amount, term: term, termtypeid: termtypeid, currencyid: currencyid, simulation: (simulation ? 1 : 0), simulationinterestratepercent: (simulation ? simulationinterestratepercent : 0), productadvantageclassversionid: productadvantageclassversionid, productinterestrateversionid: productinterestrateversionid }),
        success: function(data) {
            //set data
            $('#calculation' + productid).html(data);
        }
    });
}

//print popup window calculation saving
function popupPrintCalculationWindowLifeAnnuity(productid, productpaymentperiodid, productadvantageclassperiodid, paymentperiods, amount, term, termtypeid, currencyid, simulation, simulationinterestratepercent, productadvantageclassversionid, productinterestrateversionid) {
    var url = "http://www.nkbm.si/ajaxproductcalculator.aspx?print=true&productid=" + productid + "&validate=1&productpaymentperiodid=" + productpaymentperiodid +
    "&productadvantageclassperiodid=" + productadvantageclassperiodid + "&paymentperiods=" + paymentperiods + "&amount=" + amount + "&term=" + term +
        "&termtypeid=" + termtypeid + "&currencyid=" + currencyid + "&simulation=" + (simulation ? 1 : 0) +
    "&simulationinterestratepercent=" + (simulation ? simulationinterestratepercent : 0) +
    "&productadvantageclassversionid=" + productadvantageclassversionid +
    "&productinterestrateversionid=" + productinterestrateversionid;
    var h = 800;
    var w = 800;

    windowprops = "height=" + h + ",width=" + w + ",location=no,menubar=no,toolbar=no,titlebar=no,status=no";
    var windowReference = window.open(url, "Picture" + w + h, windowprops);
}

//set product calculator saving simulation type
function setProductCalculatorLifeAnnuityPaymentPeriods(paymentperiodsenabled, productid) {

    //enable/disable payment periods
    if (paymentperiodsenabled == 0) {
        $('#paymentperiods').attr('disabled', 'disabled');
        $('#paymentperiods').val('/');
    }
    else {
        $('#paymentperiods').attr('disabled', '');
        $('#paymentperiods').val('');
    };
}

//set product calculator life annuity simulation
function setProductCalculatorLifeAnnuitySimulation(simulation, productid) {
    
    //enable/disable simulation
    if (simulation) {
        $('#simulationinterestratepercent' + productid).attr('disabled', '');
        $('#simulationpercent' + productid).removeClass('inputdisabled');
        $('#simulationmargin' + productid).removeClass('inputdisabled');

    }
    else {
        $('#simulationinterestratepercent' + productid).attr('disabled', 'disabled');
        $('#simulationpercent' + productid).addClass('inputdisabled');
        $('#simulationmargin' + productid).addClass('inputdisabled');
    }
}

//get ajax product calculator saving with dimension
function getAjaxProductCalculatorSavingWithDimension(productid, validate, producttypeid, amount, term, termtypeid, currencyid, simulation, simulationinterestratepercent, productinterestrateversionid) {
    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductcalculator.aspx',
        data: ({ productid: productid, validate: validate, producttypeid: producttypeid, amount: amount, term: term, termtypeid: termtypeid, currencyid: currencyid, simulation: (simulation ? 1 : 0), simulationinterestratepercent: (simulation ? simulationinterestratepercent : 0), productinterestrateversionid: productinterestrateversionid }),
        success: function(data) {
            //set data
            $('#calculation' + productid).html(data);
        }
    });
}

//print popup window calculation saving
function popupPrintCalculationWindowSavingWithDimension(productid, producttypeid, amount, term, termtypeid, currencyid, simulation, simulationinterestratepercent, productinterestrateversionid) {
    var url = "http://www.nkbm.si/ajaxproductcalculator.aspx?print=true&validate=1&productid=" + productid + "&producttypeid=" + producttypeid + "&amount=" + amount + "&term=" + term + "&termtypeid=" + termtypeid + "&currencyid=" + currencyid + "&simulation=" + simulation + "&simulationinterestratepercent=" + simulationinterestratepercent + "&productinterestrateversionid=" + productinterestrateversionid;
    var h = 600;
    var w = 600;

    windowprops = "height=" + h + ",width=" + w + ",location=no,menubar=no,toolbar=no,titlebar=no,status=no";
    var windowReference = window.open(url, "Picture" + w + h, windowprops);
}


//set product calculator saving with dimension simulation type
function setProductCalculatorSavingWithDimensionSimulationType(simulationtype, productid) {
    //show/hide simulation percent by simulationtype
    if (simulationtype == 0) {
        $('#simulationpercent' + productid).show();
        $('#simulationmargin' + productid).hide();
    }
    else {
        $('#simulationpercent' + productid).hide();
        $('#simulationmargin' + productid).show();
    }
}

//set product calculator saving with dimension simulation
function setProductCalculatorSavingWithDimensionSimulation(simulation, productid) {
    //enable/disable simulation
    if (simulation) {
        $('#simulationinterestratepercent' + productid).attr('disabled', '');
        $('#simulationpercent' + productid).removeClass('inputdisabled');
        $('#simulationmargin' + productid).removeClass('inputdisabled');

    }
    else {
        $('#simulationinterestratepercent' + productid).attr('disabled', 'disabled');
        $('#simulationpercent' + productid).addClass('inputdisabled');
        $('#simulationmargin' + productid).addClass('inputdisabled');
    }
}

//get ajax product interest rate
function getAjaxProductInterestRate(productid, currencyid, produtinterestrateversionid) {

    $.ajax({
        url: 'http://www.nkbm.si/ajaxproductinterestrate.aspx',
        data: ({ productid: productid, currencyid: currencyid, produtinterestrateversionid: produtinterestrateversionid }),
        success: function(data) {
            //set data
            $('#ajaxproductinterestrate' + productid).html(data);
        }
    });
}

//submit currency exchange
function setCurrencyExchangeExchange() {
    $('#validate').val(2);
    $('#currencyexchangeform').submit();
}

//cancel submit on enter
function cancelOnEnter(e) {
    if (navigator.appName == "Netscape")
        var key_index = e.which;
    else
        var key_index = window.event.keyCode;

    if (key_index == 13)
        return false;
    else
        return true;
}

//get ajax questionary
function getAjaxQuestionary(questionaryquestionid, questionaryanswerid, questionaryid, errors) {
    //call ajax
    $.ajax({
        url: 'http://www.nkbm.si/ajaxquestionary.aspx',
        data: ({ questionaryquestionid: questionaryquestionid, questionaryanswerid: questionaryanswerid, questionaryid: questionaryid, errors: errors }),
        success: function(data) {
            //set data
            $('#questionaryanswerid').val(data.split('###')[0]);
            //$("#" + questionaryquestionid + "file").html(data.split('###')[1]);
            //$("#" + filename).html(data.split('###')[1]);
            $("#file_" + questionaryquestionid + "_" + $('#pagenumber').val()).html(data.split('###')[1]);
            //alert("#file_" + questionaryquestionid + "_" + $('#pagenumber').val());
        }
    });
}

//set ajax quesitonary
function setAjaxQuestionary(questionaryquestionid) {
    //hide error
    $('#' + questionaryquestionid + 'error').hide();
    
    //hide error
    var action = $('#questionaryform').attr('action');
    
    $('#questionaryform').attr('action', 'http://www.nkbm.si/ajaxquestionary.aspx');
    $('#questionaryform').attr('target', 'uploadiframe');
    $('#questionaryquestionid').val(questionaryquestionid);
    $('#questionaryform').submit();
    $('#questionaryform').attr('action', action);
    $('#questionaryform').attr('target', '');
    $('#questionaryquestionid').val('');
}

//remove questionary file
function removeQuestionaryFile(questionaryquestionid, questionaryanswerid, questionaryid, removefileid) {
    //hide error
    $('#' + questionaryquestionid + 'error').hide();
    
    $.ajax({
        url: 'http://www.nkbm.si/ajaxquestionary.aspx',
        data: ({ questionaryquestionid: questionaryquestionid, questionaryanswerid: questionaryanswerid, questionaryid: questionaryid, removefileid: removefileid }),
        success: function(data) {
            //set data
        //$("#" + questionaryquestionid + "file").html(data.split('###')[1]);
        $("#file_" + questionaryquestionid + "_" + $('#pagenumber').val()).html(data.split('###')[1]);
        }
    });
}

//show/hide help popup
function showHideHelpPopup(id, hide) {
    //alert('showhide');
 
    if ($('#helppopup' + id).is(':visible') || hide == 'true') {
        $('#helppopup' + id).hide();
        
        //alert('#helppopup' + id + ' - visible');
      
    }
    else {
        $('#helppopup' + id).show();

        //alert('#helppopup' + id + ' - not visible');
    }
}

//document click
$(document).click(function(evt) {
    //hide help popups
    /*if ($('.helppopup').length > 0) {
        $('.helppopup').hide();
        alert('hide');
    }*/

if (evt.target.className != 'helpicon' && evt.target.className != 'helppopuptext') {
        $('.helppopup').hide();
    }
});

/* ATMS */
//show atm property description popup
function showAtmIconPopup(id) {
    //show popup
    $('#atmpopup_' + id).show();
    
    //set bottom offset for popup
    //$('#atmpopup_' + id).css('bottom', Number($('#atmpopup_' + id).height()) - 21);
    $('#atmpopup_' + id).css('bottom', -5);

}

//hide atm property description popup
function hideAtmIconPopup(id) { 
    $('#atmpopup_' + id).hide();
}

//sorting
function changeSorting(sortfield, sortorder) {

    if (sortorder != 'ascending' && sortorder != 'descending') {
        if ($('#sortfield').val() != sortfield) {

            //change sortfield
            $('#sortfield').val(sortfield);

            //reset sortorder
            $('#sortorder').val('ascending');
        }
        else {
            //toggle sortorder
            if ($('#sortorder').val() == 'ascending') {
                $('#sortorder').val('descending');

                //alert('toggle a->d');
            }
            else {
                $('#sortorder').val('ascending');

                //alert('toggle d->a');
            }
        }
    }
    else {
        //change sortfield
        $('#sortfield').val(sortfield);

        //reset sortorder
        $('#sortorder').val(sortorder);
    }

    //redirect   
    window.location = 'http://www.nkbm.si/atms.aspx?nodeid=' + $('#nodeid').val() + '&zip=' + $('#city').val() + '&sortfield=' + $('#sortfield').val() + '&sortorder=' + $('#sortorder').val();
}

/* OFFICES */
function showHideOffices() {

    //alert($('#officeslink').text());
    //alert($('#officeslinktext_temp').val());
    

    if ($('#offices-wrapper').is(':visible')) {
        //hide & change arrow image
        $('#offices-wrapper').hide();
        $('#officesarrowimage').attr('src', $('#officesarrowimage').attr('src').replace('up', 'down'));
    }
    else {
        //show & change arrow image
        $('#offices-wrapper').show();
        $('#officesarrowimage').attr('src', $('#officesarrowimage').attr('src').replace('down', 'up'));
    }

    //toggle link text
    var temp = $('#officeslink').text();
    $('#officeslink').text($('#officeslinktext_temp').val());
    $('#officeslinktext_temp').val(temp);

}

/* AJAXVIDEO */
function getAjaxVideo(docid, videofileid) {

    if (videofileid > 0) {
        $("#ajaxvideo" + docid).html("<div style='height:452px;'>&nbsp;</div>");
    }

    //call ajax
    $.ajax({
        url: 'http://www.nkbm.si/ajaxvideo.aspx',
        data: ({ docid: docid, videofileid: videofileid }),
        success: function(data) {
            //set data
            if (videofileid == 0) {
                $("#ajaxvideolist" + docid).html(data);
                setAjaxCarousel();
                setTimeout("setAjaxCarousel()", 2000);
                setTimeout("setAjaxCarousel()", 3000);
                setTimeout("setAjaxCarousel()", 4000);
            }
            else
                $("#ajaxvideo" + docid).html(data);
        }
    });
}


function setAjaxCarousel() {
    $(".scroller").jcarousel({ scroll: 1 });
}


/* SEND TO FRIEND */
//open popup send to friend
function sendToFriendPopUp() {

    var pagetitle = $("#windowtitle").val();
    var contentlink = $("#contentlink").val(); 
    var recipientname = $("#recipientname").val();
    var recipientemail = $("#recipientemail").val();
    var sendername = $("#sendername").val();
    var senderemail = $("#senderemail").val();
    var message = $("#message").val();    

    //ajax post
    $.post('http://www.nkbm.si/ajaxsendtofriend.aspx', { pagetitle: pagetitle, contentlink: contentlink, recipientname: recipientname, recipientemail: recipientemail, sendername: sendername, senderemail: senderemail, message: message },

        function(data) {
            //if function returns data
            if (data != '') {
                $('#modalwindow').css('width', '600px');
                $('#modalwindow').html(data);

                setButtonsMouseOver();

                //popup - load
                openPopup();                
               
            }      
    });
}

//sumbit send to friend data
function submitSendToFriendPopUp() {  

    var pagetitle = $("#pagetitle").val();
    var contentlink = $("#contentlink").val();
    var recipientname = $("#recipientname").val();
    var recipientemail = $("#recipientemail").val();
    var sendername = $("#sendername").val();
    var senderemail = $("#senderemail").val();
    var message = $("#message").val();
    var equationresult = $("#equationresult").val();
    var equationvalue = $("#equationvalue").val();

    //ajax post
    $.post('http://www.nkbm.si/ajaxsendtofriend.aspx', { pagetitle: pagetitle, contentlink: contentlink, recipientname: recipientname, recipientemail: recipientemail, sendername: sendername, senderemail: senderemail, message: message, equationresult: equationresult, equationvalue: equationvalue, validate: 1 },

        function(data) {
            //if function returns data
            if (data != '') {
                $('#modalwindow').css('width', '600px');
                $('#modalwindow').html(data);

                setButtonsMouseOver();

                //popup - load
                openPopup();

            }
        });
    }


    function closevideoTab(number) {
        $('#eventlistdata' + number).removeClass('eventlistdataopened').addClass('eventlistdata');
    }

