function AdPortal(element) {

  var hijaxForm = function(form){

    $(form).submit(function(){

      $.ajax({
        type: "POST",
        url: $(this).attr("action"), 
        data: $(this).serialize(),
        success: function(data){
          $(form).replaceWith(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
          var errors = XMLHttpRequest.responseText;
          var fieldset = $("#web-form").find("fieldset");

          if( $(fieldset).find("p.errors").size() > 0 ){
            $(fieldset).find("p.errors").replaceWith(XMLHttpRequest.responseText)
          }else{
            $(fieldset).prepend(XMLHttpRequest.responseText);
          }
          
          $(fieldset).find("input.submit").show().next("img").remove();
        }
      });
      return false;
    });
  };
  
  this.init = function () {
   if( $(element).find("form").size() > 0){
     hijaxForm( $(element).find("form") );
   }
  };

  this.init();

}

function ArticleAddons(element) {

    var ee,ge,zoom,type;

    var gmapHandle = function() {
        ee = $('#gmaps_ee').val();
        ge = $('#gmaps_ge').val();
        zoom = parseInt($('#gmaps_zoom').val(), 10);
        type = $('#gmaps_map_type').val();

        $('.gmaps').flash({
            swf: '/_common/flash/googlemaps.swf',
            height: 330,
            width: 430,
            //hasVersion: 10, // optional and temporary
            //expressInstaller: '/_common/flash/playerProductInstall.swf',
            flashvars: {
                lat: ee,
                lng: ge,
                zoom: zoom,
                mapType: type,
                key: "ABQIAAAA_Lznvy0qKCJxv4DGtLvZlhRtmlmO7K6YWQbeYZiYB6dl7vyJhBQr3sTZiaunK1hnLVgB-tDnGhGtWw"
                // staging ABQIAAAA_Lznvy0qKCJxv4DGtLvZlhQmXNI2Pj25K3VHovqtTasteebU8BRC_2g-oVeqCp0y70saOrebkGy64w
            }
        });
    };

    var textGalleryHandle = function() {
        $(element).find('.slider').serialScroll({
            items:'li',
            prev:$(element).find('.prev'),
            next:$(element).find('.next'),
            offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)
            start:false, //as we are centering it, start at the 2nd
            duration:1000,
            force:false,
            step: 1,
            stop:true,
            lock:false,
            cycle:false, //don't pull back once you reach the end
            easing:'easeOutQuart', //use this easing equation for a funny effect
            jump: false, //click on the images to scroll to them
            onBefore:paging
        });
    };

    var paging = function(event, el, next, collection, position) {
        position = position + 1;
        $(element).find('.text-gallery .pages').text(position + ' od ' + $(element).find('.text-gallery .slider li').length);
    };

    this.init = function() {
        gmapHandle();
        textGalleryHandle();
    };

    this.init();

}

$.fn.replace = function(o) {
    return this.after(o).remove();
};


$().ready(function() {
    $('#breaking-news').cycle();
});
$.fn.cycle = function(options) {
    var defaults = {
        speed : 15000,
        childNode : 'li'
    };
    options = $.extend(defaults, options);
    var cont = this;
    var max = cont.width();
    var li = cont.find(options.childNode);
    if (li.width() < max) {
        li.css({width : max + 'px'});
    }

    function slide(ul) {
        li = ul.find(options.childNode + ':first');
        li.clone(true).insertAfter(li);
        li.animate({marginLeft : '-' + li.width() + 'px'}, options.speed, 'linear', function() {
            li.remove();
            slide(ul);
        });
    }

    slide(li.parent());
};

// FACEBOOK - has to be outside onload..
function IE6() {
    var version = 999;
    if (navigator.appVersion.indexOf("MSIE") != -1) {
        version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    }
    return version < 7;
}

function Comments(element) {

    var form = $('.comments form');
    var url = form.attr('action');

    function formInputs() {
        return $('.comments form input.text, .comments form textarea.text');
    }

    function myVal(el) {
        var node = el.get(0).nodeName;
        if (node == 'TEXTAREA') {
            return el.get(0).value;
        }
        else {
            return el.val();
        }
    }

    function setVal(el, val) {
        var node = el.get(0).nodeName;
        if (node == 'TEXTAREA') {
            el.get(0).innerHTML = val;
        }
        else {
            el.val(val);
        }
    }

    function emptyFormInputs() {
        return formInputs().filter(function() {
            var result = (myVal($(this)) == "") || myVal($(this)) == $(this).attr('alt');
            return result;
        });
    }

    function initializeFormFields() {
        emptyFormInputs().each(function() {
            var input = $(this);
            input.addClass('initial');
            setVal(input, input.attr('alt'));
        });
    }

    formInputs().focus(function() {
        var input = $(this);
        if (input.hasClass('initial')) {
            setVal(input, '');
            input.removeClass('initial');
        }
    });

    formInputs().blur(function() {
        var input = $(this);
        if (myVal(input) == '') {
            setVal(input, input.attr('alt'));
            input.addClass('initial');
        }
    });

    form.submit(function() {
        if ($('#comment_text').attr('value') == '' || $('#comment_text').attr('value') == 'Vaš komentar') {
            return false;
        }

        $('.post-comment .submit').hide();
        $.ajax({
            type: form.attr('method'),
            url: url,
            data: serializeFilledIn(form),
            dataType: 'json',
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            success: function(data, textStatus) {
                form.find('.comment-notice').text('');
                form.find('.comment-errors').text(data.errors);

                $('#comment_text').attr('value', '');

                if (data.errors == '') {
                    form.find('.comment-notice').text('Hvala za komentar!');
                    if (formInDefaultPlace()) {
                        var list = $('.comment-list');
                        list.prepend(data.new_comment);
                        var new_comment = list.find('li:first-child p').eq(0);
                        $.scrollTo(new_comment, 200);
                        new_comment.css({backgroundColor: "#ffffcc"}).animate({backgroundColor: "#eeeeee"}, 1500);
                    } else {
                        form.before(data.new_comment);
                    }
                } else {
                    $("#comment_text").val(data.comment_text);
                }
                $('.post-comment .submit').show();
            }
        });
        return false;
    });

    function serializeFilledIn(form) {
        form.find('.initial').removeClass('initial').val('');
        form.find('input[name=authenticity_token]').val(web.authToken());
        var data = form.serialize();
        initializeFormFields();
        return data;
    }

    $('.comments .reply').live('click', function() {
        var reply_list = $(this).parents('.comment').eq(0).children('.reply-list');
        var form = $('.comments form');
        form.find('#comment_parent_id').val(getCommentId($(this)));
        reply_list.append(form);
        form.find("textarea").focus();
        form.find('.comment-notice').text('');
        $('.comments .post-comment').hide();
        return false;
    });

    $('.post-comment-link').click(function() {
        putFormBackInDefaultPlace();
        var form = $('.post-comment form');
        $.scrollTo(form, 200);
        form.find("textarea").focus();
        return false;
    });

    function putFormBackInDefaultPlace() {
        if (!formInDefaultPlace()) {
            form = $('.comments form');
            form.find('#comment_parent_id').val('');
            $('.comments .instructions').before(form);
            $('.comments .post-comment').show();
            form.find('.comment-notice').text('');
        }
    }

    function formInDefaultPlace() {
        return $('.post-comment form').length > 0;
    }

    $('.comments .pagination a').live('click', function() {
        putFormBackInDefaultPlace();
        load_comments($(this).attr('href'));
        return false;
    });

    $('.comments .order a').click(function() {
        putFormBackInDefaultPlace();
        load_comments($(this).attr('href'));
        $(this).parents('.order').find('.active').removeClass('active');
        $(this).addClass('active');
        return false;
    });

    function load_comments(url) {
        $.ajax({
            type: 'get',
            url: url,
            success: function(data) {
                $('.comment-list-with-pagination').empty().append(data);
            }
        });
    }

    $('.comments .comment-vote a').live('click', function() {
        var vote_number = $(this).parent('.comment-vote').children('.votes');
        var up_voter = vote_number.parent().find('.up');
        var down_voter = vote_number.parent().find('.down');
        var id = getCommentId(vote_number);
        var down = $(this).hasClass('down');

        if (!up_voter.hasClass('disabled')) {
            up_voter.addClass('disabled');
            down_voter.addClass('disabled');
            $.ajax({
                type: 'put',
                url: $(this).attr('href'),
                success: function(data, textStatus) {
                    var votes = parseFloat(data, 10);
                    if (votes < 0) {
                        vote_number.addClass('negative');
                    } else {
                        vote_number.removeClass('negative');
                    }
                    vote_number.text('(' + (votes > 0 ? '+' : '') + votes + ')');
                }
            });
        }
        return false;
    });

    function getCommentId(child) {
        return child.parents('.comment').attr('id').replace('comment_', '');
    }

    function badComments() {
        var bc = $('.comments .very-bad');
        bc.find('h6').append('<a class="open" href="#">Neprimeren komentar</a>');
        bc.find('.open').click(function(e) {
            $(this).parent().parent().parent().find('p').slideDown();
            $(this).parent().find('em,span').show();
            $(this).hide();
            e.preventDefault();
        });
    }

    this.init = function() {
        initializeFormFields();
        badComments();
    };

    this.init();

}




function Comparison(element) {

    var optionClick = function(option) {
        $(element).find("div.option").each(function(n) {
            if (option == "enable") {
                $(this).find("img").bind("click.vote", function(e) {
                    if (web.authToken() !== undefined) {
                        $('<div class="loader">&nbsp;</div>').insertBefore($(element).find("div.nav"));
                        markImageAsSelected(this);
                        vote($(this).attr("id"));
                    } else {
                        alert("Za glasovanje morate imte vklopljene piškotke(cookies)!");
                    }
                });
            } else {
                $(this).find("img").unbind("click.vote");
            }
        });
    };

    var markImageAsSelected = function(image) {
        $(image).parent().addClass("green");
    };

    var vote = function(id) {
        var token = web.authToken();
        var url = $(element).find("a.next").attr("href").match(/.+\/glasovanje/);
        var next_page = window.location.href.match(/\d+$/) === null ? 1 : window.location.href.match(/\d+$/);
        var items = [];
        $(".chooser .option > img").each(function(n) {
            items.push($(this).attr("id"));
        });

        $.post(
            url + '/glasuj',
            {authenticity_token:token, next_page: next_page, item_id:id, step_items: items.join(",")},
            function(data) {

                $(element).find("div.option img").unbind('mouseenter').unbind('mouseleave');
                $(element).find("div.option h3:visible").fadeOut("fast");
                $(element).find("div.loader").remove();
                next_href("enable");
                optionClick("disable");

                if (data.a_color !== undefined) {
                    //this data is shown in standard mode (not continous comparison)
                    var el_first = "<div class='progress " + data.a_color + "'><em style='height:" + data.a_height + "%'>" + data.a_height + "%</em></div>";
                    var el_second = "<div class='progress " + data.b_color + "'><em style='height:" + data.b_height + "%'>" + data.b_height + "%</em></div>";
                    $(element).find("div.progress").remove();
                    $(element).find(" > div").eq(0).append(el_first);
                    $(element).find(" > div").eq(1).append(el_second);

                } else {
                    //if we have continous comparison go forward;
                    $(element).find("a.next").bind("click.auto", function() {
                        window.location = $(this).attr("href");
                    });

                    $(element).find("a.next").trigger("click.auto");
                }
            },
            "json"
            );
    };

    var next_href = function(option) {
        if (option == "disable") {
            $(element).find("a#disabled").bind("click.next", function() {
                alert("Glasovati morate za eno izmed možnosti.");
                return false;
            });
        } else {
            $(element).find("a#disabled").unbind("click.next").removeAttr("id");
        }
    };

    var image_hover = function() {
        $(element).find("div.option img").hover(
            function(e) {
                $(this).prev("h3").slideDown();
            },
            function(e) {
                $(this).prev("h3").slideUp();
            });
    };

    this.init = function () {
        next_href("disable");
        optionClick("enable");
        image_hover();

    };

    this.init();
}

function EventsFilter(element) {
    //TODO dunno why cant get the elemet from the function argument e - :(((
    $(element).change(function() {
        
        path = $(this).nextAll('.exact_date_link').attr('value');
        
        if( $(this).hasClass("to") ){
          //filter 'to date'
          date = $(this).attr('value').replace(/\./g, '-');
          path = path.replace('date_to', date);
          var date_from = $(this).parent().prev().find("input.date-picker-input").val();
          if(date_from != 'od-dne'){
            date_from = date_from.replace(/\./g, '-');
            path = path.replace('dd.mm.yyyy', date_from);
          }else{
            path = path.replace('dd.mm.yyyy', 'do');
          }
        }else{
          //from
          date = $(this).attr('value').replace(/\./g, '-');
          path = path.replace('dd.mm.yyyy', date);
        }
        window.location = path;
    });

}

function Facebook(element) {

  var document_domain = 'http://' + document.domain;

  var utils = {
    first_name: "",
    last_name: "",
    email: "",
    facebook_uid: "",
    perms: "",
    xfbml_parse: function(){
      FB.XFBML.parse();
    },
    init_login_button: function(){
      $(element).html(
        "<p>Vpis z uporabo Facebook računa</p>" +
        "<p><a id='facebook_button' href='#' title='facebook login'></a></p>"
      );

      $("a#facebook_button").click(function(){
        utils.login();
        return false;
      });
    },
    login: function(){
      FB.login(function(response) {
        var send_login = false;
        var perms_ok = false;
        if (response.session) {
          //user connected to FB
          utils.facebook_uid = response.session.uid;
          send_login = true;
          if (response.perms) {
            // user is logged in and granted some permissions; perms is a comma separated list of granted permissions
            utils.perms = response.perms;
            if(utils.perms.indexOf("publish_stream") != -1 && utils.perms.indexOf("email") != -1){
              perms_ok = true;
            }
          } else {
            // user is logged in, but did not grant any permissions
            alert("Morate potrditi pravice za uporabo FB računa na našem portalu.");
          }

          utils.show_user_info(response);
        } else {
          //not logged in
        }
        if(send_login && perms_ok){
          //check if user exists in our db, else redirect him to register form, with his data nfo
          $(".facebook_login").append("<img class='spinner' src='/_common/images/icons/loaders/big_blue.gif' alt='spinner'");
          FB.api('/me', function(response) {
            utils.login_portal(response.email);
          });
        }else{
          alert("Ni dovolj pravic (publish_stream, email)!");
        }

      }, {perms:'publish_stream,email'});
    },
    login_portal: function(email, place){
      //var token = $("form input[name=authenticity_token]").attr("value");
      var token  = web.authToken();
      $.post(
        "/prijava-fb",
        {authenticity_token: token, 'facebook_uid': utils.facebook_uid, 'facebook_perms':utils.perms, 'email': email },
        function(data){
          if(data == "success"){
            if ($("input#return_to").size() > 0) {
              window.location.href = $("input#return_to").attr("value");
            } else {
              location.reload();
            }
          } else {
            //would redirect user to register form if user is trying to login
            if(place != "comment"){
              window.location.href = data;
            }
          }
        });
    },
    logout: function(){
      FB.logout(function(response) {
        if($(element).hasClass("facebook_login")){
          utils.init_login_button();
        }
      });
    },
    show_user_info: function(response){
      $(element).html(
           "<p>" +
           "<fb:profile-pic uid='" + response.session.uid +"' facebook-logo='true'></fb:profile-pic>" +
           "<br/>Dobrodošel/a, <fb:name uid='" + response.session.uid +"' useyou='false'></fb:name>" +
           "</p>" +
           '<p>' +
           'Odjavite se <a href="#" id="fb-logout">tukaj</a>' +
           '</p>'
         );
      utils.xfbml_parse();
      $(element).find("a#fb-logout").one('click',function(){
        utils.logout();
        return false;
      });
    },
    fill_in_user_registration_form: function(response){
      $(element).find("#user_first_name").attr("value", response.name.split(" ")[0]);
      $(element).find("#user_last_name").attr("value", response.name.split(" ")[1]);
      $(element).find("#user_email").attr("value", response.email);
      $(element).find("#user_facebook_uid").attr("value", response.id);
    },
    post_a_comment_if_publish_checked: function(){
        $("#comment_submit").bind("click.fb", function(){
          if( $("input#publish_on_facebook:checked").size() > 0 ){
          var url = '/' + $("#user_facebook_uid").html() + '/feed';
          var image_url = "";
          if($("div.cms img").size() > 0){
            image_url = document_domain + $("div.cms img").eq(0).attr("src").replace(/article.*/, "thumb80.jpg");
          }
          FB.api(url,
            'post',
            {
              message: 'je komentiral/a ' +  $("h1").html() ,
              picture: image_url,
              link: window.location.href,
              name: 'zurnal24.si',
              caption: $("h1").html(),
              description: $('#comment_text').attr('value') },
              function(response) {
                if (!response || response.error) {
                  alert('Prišlo je do napake pri pošiljanju podatkov!');
                } else {
                  //'Post ID: ' = response
                }
              });
        }
      });
    },
    like: function(){
      FB.Event.subscribe('edge.create', function(response) {
        //update semantics like
         $.get(
            $("span#like_path").html(),
             {},
             function(data){
                //alert("updated sematics to " + data );
              },
             'json'
           );
      });
    }
  };
  
  var faceBook = function(){
    
    //we use this code for register form, sign-in form, and adding comments form
    FB.init({appId: '248f186875c8cd70b02cc95096320e51', status: true, cookie: true, xfbml: true});
    utils.like(); // subscribe for FBlike callback
    FB.getLoginStatus(function(response) {
      if (response.session) {
        //user logged in FB
        if( $(element).attr("id") == "new_user"){ //when creating new user
          FB.api('/me', function(response) {  //fetch data, for form prefill
            utils.fill_in_user_registration_form(response);
            $("input#user_facebook_enabled").attr('checked', true );
          });
        }else if($(element).hasClass("article-tabs")){ //when posting comment
          if(!web.loggedIn()){
            //register user in portal with his email
            FB.api('/me', function(response) {
              utils.login_portal(response.email, "comment");
            });
          }
          utils.post_a_comment_if_publish_checked();
        }else if($(element).hasClass("facebook_login")){
          utils.show_user_info(response); //when registering user in FB
          FB.api('/me', function(response) {
            $(".facebook_login").append("<img class='spinner' src='/_common/images/icons/loaders/big_blue.gif' alt='spinner' />");
            if(response.perms != undefined){
              utils.login_portal(response.email, "login");
            }else{
              //user must grant some perms
              utils.login();
            }
            
          });

        }
      } else {
        //user not connected in FB
        if($(element).attr("id") == "new_user"){
          // do nothing for now
        }else if($(element).hasClass("facebook_login")){
          utils.init_login_button();
          $("#fb_login").click(function(){
            facebook_connect();
            return false;
          });
        }else if($(element).hasClass("post-comment")){
          //user is not connected with FB acc, so no stream publishing is in the game
          $("li.fb_stream").html("").removeClass("bg_bubble");
        }
      }
    });
    //utils.xfbml_parse(); //needed for likeIT
    
  }

  this.init = function () {
    
    if( $(element).hasClass("article-tabs") && $(element).hasClass("wide") ){
      //skipp facebook for now
    }else{
      faceBook();
    }
    
    
    $("a.logout").click(function(){
      utils.logout();
    });
    
  };

  this.init();

}

function FixedNavigation(element) {

    var moveHeader = function() {
        var left = $('#site').position().left;
        var top = $(window).scrollTop();
        if (top >= 108) {
            if ($(element).parent().attr('id') != 'header-wrap') {
                $(element).wrap('<div id="header-wrap"></div>');
            }
            $(element).css({'position' : 'fixed', 'left' : left, 'top' : 0, 'z-index' : '10000'});
            $('#site').css({'margin-top' : '55px'});
            /* banner can be fixed to top:55 */
            $('#right-banner').css({'position' : 'fixed', 'left' : left + 777, 'top' : 0, 'z-index' : '10000'});
        } else {
            $(element).css({'position' : 'relative', 'left' : 'auto', 'top' : 'auto'});
            $('#right-banner').css({'position' : 'static', 'left' : 'auto', 'top' : 'auto'});
            $('#site').css({'margin-top' : '0'});
            $(element).parents('#header-wrap').after($(element)).remove();
        }
    };

    this.init = function() {
        if (web.browserVersion() > 6 && !web.isInIFrame) {
            $(window).scroll(function() {
                moveHeader();
            });
            $(window).smartresize(function() {
                moveHeader();
            });
        }
    };

    this.init();

}

function FullscreenGallery(element) {

    var bottomArea = false;

    var currentPhoto = function() {
        var parts = location.href.split('/');
        var part = parts[parts.length - 1].split('?')[0];
        return (!/^[0-9]+$/.test(part)) ? 1 : part;
    };

    var originalUrl = function(docId) {
        var host = $(element).find('#selected-image').attr('meta:host');
        if (host != '') {
            host = 'http://' + host;
        }
        var len = docId.length;
        var path = docId.substring(len - 4, len - 2) + '/' + docId.substring(len - 2, len) + '/' + docId
       
        return host + '/images/' + path + '/fullscreen2.jpg';
    };

    var showImage = function (idx) {
        var id = $('#thumbnail-' + idx + ' a').attr('rel');
        var subtitle = $('#thumbnail-' + idx + ' .subtitle').html();
        var copyright = $('#thumbnail-' + idx + ' .copyright').html();
        var count = $(element).find('.thumb-list li').length;
        var next = $('#thumbnail-' + idx).next() ? $('#thumbnail-' + idx).next().find('a').attr('href') : null;
        var prev = $('#thumbnail-' + idx).prev() ? $('#thumbnail-' + idx).prev().find('a').attr('href') : null;
        var back = $(element).find('.header a.back');

        back.attr('href', back.attr('href') + '/' + idx);
        $(element).find('.next a').toggleClass('disabled', !next).attr('href', next);
        $(element).find('.previous a').toggleClass('disabled', !prev).attr('href', prev);

        $('p.p').text(idx + ' / ' + count).toggleClass('last', !subtitle && !copyright);
        $('.gallery-full .comment .t').html(subtitle).toggleClass('last', !copyright);
        if (copyright != '') {
            copyright = '(' + copyright + ')';
        }
        $('.gallery-full .comment .f').html(copyright);
        $('#thumbnail-' + idx).addClass('active');

        var img_alt = subtitle.match(/span/i) !== null ? $(subtitle).html() : subtitle; // subtitle could have <span> element
        var img = new Image();
        $(img).load(function() {
            $(this).hide();
            $('#selected-image').append(this).removeClass("loading");
            $(this).fadeIn(500);
        }).attr({'src': originalUrl(id), 'alt': img_alt});

    };

    var scrolling = function() {
        $(element).find('.scroller').serialScroll({
            items:'li',
            axis:'y',
            prev:'.scroll-wrap .prev',
            next:'.scroll-wrap .next',
            offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)
            start:currentPhoto() - 1, //as we are centering it, start at the 2nd
            duration:800,
            force:true,
            step: 3,
            stop:true,
            lock:false,
            cycle:false, //don't pull back once you reach the end
            easing:'easeOutQuart', //use this easing equation for a funny effect
            jump: false //click on the images to scroll to them
        });
        $(element).find('a.disabled').unbind('click');
    };

    var setShortcuts = function() {
        $(document).keydown(function(e) {
            var key = {left: 37, right: 39, esc: 27};
            var keyCode = e.keyCode || e.which;
            switch (keyCode) {
                case key.left:
                    link = $('.gallery-nav .previous a').attr('href');
                    if (link !== undefined) {
                        location.href = link;
                    }
                    break;
                case key.right:
                    link = $('.gallery-nav .next a').attr('href');
                    if (link !== undefined) {
                        location.href = link;
                    }
                    break;
            }
        });


    };

    this.init = function () {
        setShortcuts();
        showImage(currentPhoto());
        scrolling();

    };

    this.init();
}

function Gallery(element) {

    var currentPhoto = function() {
        var parts = location.href.split('/');
        var part = parts[parts.length - 1].split('?')[0];
        var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
        if (!reg.test(part))
        {
            part = 1;
        }
        return part;

    };

    var hover = function(h) {
        if (h) {
            if (web.browserVersion > 6) {
                $(element).find('.comment').slideDown();
                $(element).find('.qn-prev').animate({width:'show'}, 1400);
                $(element).find('.qn-next').animate({width:'show'}, 1400);
            } else {
                $(element).find('.comment').show();
                $(element).find('.qn-prev').show();
                $(element).find('.qn-next').show();
            }
        } else {
            if (web.browserVersion() > 6) {
                $(element).find('.comment').slideUp('fast');
                $(element).find('.qn-prev').animate({width:'hide'}, 100);
                $(element).find('.qn-next').animate({width:'hide'}, 100);
            } else {
                $(element).find('.comment').hide();
                $(element).find('.qn-prev').hide();
                $(element).find('.qn-next').hide();
            }
        }
    };

    var pageHover = function(h, el) {
        var w = $(el).parents().find('.paging');
        var a = $(el).find('a');
        var cls = a.attr('class');
        var pos = $(el).position().left;
        var thumb = $(element).find('.thumb-list .' + cls);
        if (h) {
            w.css({'z-index':'2'});
            thumb.show();
            thumb.css({'margin-left' : (parseInt(pos, 10) + 2) + 'px' });
        } else {
            thumb.find('.photo').hover(
                    function () {
                        thumb.show();
                        a.addClass('active');
                        w.css({'z-index':'2'});
                    },
                    function () {
                        thumb.hide();
                        a.removeClass('active');
                        w.css({'z-index':'0'});
                    }
                    );
            thumb.hide();
        }
    };

    var showImage = function (idx) {
        var id = $('#thumbnail-' + idx + ' a').attr('rel');

        var len = id.length;
        var path = id.substring(len - 4, len - 2) + '/' + id.substring(len - 2, len) + '/' + id;

        var src = '/images/' + path + '/gallery_big.jpg';
        var subtitle = $('#thumbnail-' + idx + ' .subtitle').html();
        var copyright = $('#thumbnail-' + idx + ' .copyright');
        var count = $(element).find('.thumb-list li').length;
        var next = $('#thumbnail-' + idx).next() ? $('#thumbnail-' + idx).next().find('a').attr('href') : null;
        var prev = $('#thumbnail-' + idx).prev() ? $('#thumbnail-' + idx).prev().find('a').attr('href') : null;
        var fullscreenHref = window.location.href.replace(/iframe-galerija/, 'velika-galerija');

        $('#thumbnail-' + idx).addClass('active');

        var img_alt = subtitle.match(/span/i) !== null ?  subtitle.replace(/(<.*?>)/ig,"") : subtitle;
        $('#selected-image').html('<img src="' + src + '" alt="' + img_alt + '" />');


        $('#selected-image img, .fullscreen').click(function() {
            parent.location.href = fullscreenHref;
        });
        if (parseInt(idx, 10) != count) {
            var prefetchId = $('#thumbnail-' + (parseInt(idx, 10) + 1) + ' a').attr('rel');

            var len = prefetchId.length;
            var path = prefetchId.substring(len - 4, len - 2) + '/' + prefetchId.substring(len - 2, len) + '/' + prefetchId;

            var prefetchSrc = '/images/' + path + '/gallery_big.jpg';
            $('#prefetch-image').html('<img src="' + prefetchSrc + '" alt="" />');
        }
        $(element).find('.comment .p').html(idx + '/' + count);
        $(element).find('.comment .t').html(subtitle);
        $(element).find('.comment .f').html(copyright);
        $(element).find('.comment .f').html(copyright);

        if (next) {
            $(element).find('.qn-next').attr('href', next);
        } else {
            $(element).find('.qn-next').remove();
        }
        if (prev) {
            $(element).find('.qn-prev').attr('href', prev);
        } else {
            $(element).find('.qn-prev').remove();
        }
    };

    this.init = function () {
        showImage((window.location.href.match(/galerija\/([0-9]{1,3})/) || [null, 1])[1]);

        $(element).hover(
                function () {
                    hover(true);
                },
                function () {
                    hover(false);
                }
                );
        $(element).find('.page').hover(
                function () {
                    pageHover(true, this);
                },
                function () {
                    pageHover(false, this);
                }
                );
        if ($(element).find('li.page').length > 17) {
            $(element).find('.scroll').serialScroll({
                items:'li',
                prev:'.paging .bk',
                next:'.paging .fw',
                offset:-50, //when scrolling to photo, stop 230 before reaching it (from the left)
                start:currentPhoto(), //as we are centering it, start at the 2nd
                duration:1000,
                force:true,
                step: 4,
                stop:true,
                lock:false,
                cycle:false, //don't pull back once you reach the end
                easing:'easeOutQuart', //use this easing equation for a funny effect
                jump: false //click on the images to scroll to them
            });
        } else {
            $(element).find('.paging .bk,.paging .fw').css({'visibility' : 'hidden'});
        }
    };

    this.init();
}

function Header(element) {

    var speed = 100;

    var switchNext = function(e) {
        var a = $(e);
        if (a.hasClass('active')) {
            a.removeClass('active');
            a.next().slideUp(speed);
        } else {
            $(element).find('a.switch-next').removeClass('active').next().hide();
            a.addClass('active');
            a.next().hide().removeClass('hidden').stop(true, true).slideDown(speed);
            //to = setTimeout(function(){a.removeClass('active');a.next().slideUp();},15000);
        }
    };

    var updateChangeView = function() {
        var currentPrimary = $(element).find('#main-nav a.root.active').eq(0).attr('href');
        if (currentPrimary != '/') {
            $(element).find('.view li[class!=poll-view] a').each(function() {
                var newLink = $(this).attr('href').replace(/vse/, SECTION_SLUG);
                $(this).attr('href', newLink);
            });
        }
    };

    var initIE6warning = function(){
      $("body").append(
        "<div id='overlay-info'>" +
          "<div class='details'>" +
            "<p>Vaš brskalnik Internet Explorer 6 ne omogoča optimalne uporabniške izkušnje na portalu Zurnal24.si.</p>" +
            "<p>Prosimo posodobite ga na novejšo različico IE8</p><a target='_blank' href='http://www.ie8.si/'><img src='/_common/images/icons/ie-64x64.jpg' alt='ie' /></a>" +
            "<p>ali si namestite katerega od drugih brezplačnih brskalnikov:</p>" +
            "<ul class='links'>" +
              "<li><a target='_blank' href='http://www.mozilla.com/en-US/firefox/firefox.html'><img src='/_common/images/icons/firefox-64x64.jpg' alt='firefox' /></a><span>Fire Fox</span></li>" +
              "<li><a target='_blank' href='http://www.google.com/chrome'><img src='/_common/images/icons/chrome-64x64.jpg' alt='chrome' /></a><span>Chrome</span></li>" +
              "<li><a target='_blank' href='http://www.opera.com/download/'><img src='/_common/images/icons/opera-64x64.jpg' alt='opera' /></a><span>Opera</span></li>" +
              "<li><a target='_blank' href='http://www.apple.com/safari/download/'><img src='/_common/images/icons/safari-64x64.jpg' alt='ie' /></a><span>Safari</span></li>" +
            "</ul>" +
            "<div class='clear'>&nbsp;</div>" +
            "<div class='no_more'>" +
              "<input id='no_more' type='checkbox' />" +
              "<label for='no_more'>Ne prikaži več</label>" +
            "</div>" +
            "<button class='close'>Zapri</button>" +
            "<div class='clear'>&nbsp;</div>" +
          "</div>" +
        "</div>"
        );

        $("#overlay-info button.close").click(function(){
          if( $("#overlay-info input[type=checkbox]:checked").size() > 0 ){
            $.cookie("ie6warning", "hide", { expires: 7 });
          }
        });

        $("#overlay-info").overlay({
            top: 100,
            onBeforeLoad: function(){
                $("#header").hide("slow"); //z-index issues fixed with hiding/showing elements
            },
            onBeforeClose: function(){
               $("#header").show("fast");
            },
            mask:{
                color: '#dadada',
                loadSpeed: 200,
                opacity: 0.7
            },
            closeOnClick: false,
            api: true
        }).load();
    };

    var initPdfIssueOverlay = function(){
      $("body").append("<div id='overlay-info-pdf'><div class='pdf_issue'></div><button class='close'>Zapri</button></div>");
      var pdf_href = "";
      $("a[rel='overlay']").click(function(){
        pdf_href = $(this).attr("href");
        if(pdf_href.match(/#/) === null){
          var pdf_height = pdf_href.match(/height.\d+/)[0].split("=")[1];
          var pdf_width = pdf_href.match(/width.\d+/)[0].split("=")[1];
          $("div#overlay-info-pdf").overlay({
           onBeforeLoad: function(){
              $("#header").hide("slow"); //z-index issues fixed with hiding/showing elements
              this.getOverlay().find("div.pdf_issue").html(
                "<object width='" + pdf_width + "' height='" + pdf_height + "' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'>" +
                  "<param value='opaque' name='wmode'>" +
                  "<param value='true' name='allowfullscreen'>" +
                  "<param value='always' name='allowscriptaccess'>" +
                  "<param value='" + pdf_href + "' name='movie'>" +
                  "<embed width='" + pdf_width + "' height='" + pdf_height + "' wmode='opaque' allowscriptaccess='always' allowfullscreen='true' type='application/x-shockwave-flash' src='" + pdf_href +"'>" +
                "</object>"
              );
            },
            onBeforeClose: function(){
               $("#header").show("fast");
            },
            mask: { 
              color: '#fff',
              loadSpeed: 200,
              opacity: 0.7
            },
            closeOnClick: true,
            api: true
          }).load();
        }
        return false;
      }); 
    };

    this.init = function() {
      
        if($("a[rel='overlay']").size() > 0){
          initPdfIssueOverlay();
        }
      
        var ie6 = $.browser.msie&&($.browser.version == "6.0")&&!window.XMLHttpRequest;
        if (ie6 && $.cookie("ie6warning") === null ){
          initIE6warning();
        }

        $("a[rel='out-link']").click(function() {
            window.open(this.href);
            return false;
        });

        $(element).find('a.switch-next').click(function(e) {
            switchNext(this);
            setTimeout(function() {
                $(element).find('#search-input').focus();
            }, 500);
            e.preventDefault();
        });
        $(element).find('.view').hoverIntent({
            sensitivity: 3,
            interval: 200,
            over: function() {
                switchNext($(element).find('.change-view'));
            },
            timeout: 500,
            out: function() {
                switchNext($(element).find('.change-view'));
            }
        });
        $('a.change-view').click(function(e) {
            e.preventDefault();
        });
        updateChangeView();
    };

    this.init();

}

$().ready(function() {
    var headlines = $('#headline li');
    if (headlines.length === 0) {
        return;
    }

    headlines.each(function(e) {
        $(this).click(function() {
            location.href = $(this).find('a').attr('href');
        });
        var images = $(this).find('.headline-images img').get();
        if (images.length > 1) {
            $(this).find('.headline-images').vitlaj({appear: 'fadeIn', disappear: 'fadeOut', speed: 500, wait: 5000});
        }

        if ($(this).find('.movie-tape').length > 0) {
            $(this).hover(
                function() {
                    $(this).find('object').css({'visibility' : 'visible'});
                },
                function() {
                    $(this).find('object').css({'visibility' : 'hidden'});
                }
            );
        }

    });
});

function HoroscopeCompatibility(element) {

    this.init = function () {
        $(element).find("input[type=submit]").click(function() {
            var horoscope_type = $(element).find("input#horoscope-type").get(0).value;
            var sign_first = $(element).find("select#first_sign_zodiac").get(0).value;
            var sign_second = $(element).find("select#second_sign_zodiac").get(0).value;

            window.location.href = "/" + horoscope_type + "/kompatibilnost/" + sign_first + "/in/" + sign_second;

            return false;
        });
    };

    this.init();
}

function HoroscopeWidget(element) {

    var show = function () {
        el = $(element).find('.drop-list');
        if (el.hasClass('hidden') || !el.is(':visible')) {
            el.hide().removeClass('hidden').slideDown();
        }
        else {
            el.slideUp();
        }

        return false;
    };

    var change = function() {
        sign = this.href.split('/');
        sign = sign[sign.length - 1];
        $(element).find('.horoscopes li').hide();
        $(element).find('.horoscopes .' + sign).hide().removeClass('hidden').fadeIn();
        $(element).find('.dropdown').text($(this).text());
        $(element).find('.drop-list').hide();
        $.cookie('horoscope-sign', sign, {expires: 10000});
        return false;
    };

    this.init = function () {
        sign = $.cookie('horoscope-sign') || '';
        if (sign != '') {
            $(element).find('.horoscopes .' + sign).hide().removeClass('hidden').fadeIn();
            $(element).find('.dropdown').text($(element).find('.horoscopes .' + sign + ' em').text());
        } else {
            $(element).find('.horoscopes li:first').hide().removeClass('hidden').fadeIn();
            $(element).find('.dropdown').text($(element).find('.horoscopes li:first em').text());
        }
        $(element).find('.dropdown').click(show);
        $(element).find('.drop-list a').click(change);
    };

    this.init();
}

function LatestMedia(element) {

    var last_visible = 0;

    var loadGalleries = function () {
        $(this).parent().siblings().removeClass('active');
        $(this).parent().addClass('active');
        $(element).find('.related-galleries-wrap').html('<div class="loader></div>');
        $.ajax({
            type: "GET",
            url: this.href,
            success: function(msg) {
                $(element).find('.related-galleries-wrap').html(msg);
                stretch();
                margins();
            }
        });
        return false;
    };

    var visibleElements = function() {
        var sh = $("#sidebar").height();
        last_visible = $(element).find('.related-galleries li').length;
        $(element).find('.related-galleries li').each(function(i) {
            var pos = $(this).position();
            var overflow = sh - pos.top - $(this).height();
            if (overflow < 0) {
                last_visible = i;
                return false;
            }
        });
    };

    var stretch = function() {
        var el = $(element).find('.related-galleries');
        var li = el.find('li:first');
        var unit_height = li.outerHeight(true);
        el.css({'overflow' : 'hidden'});
        el.height(unit_height * last_visible);
    };

    var margins = function() {
        var sh = $("#sidebar").height();
        var el = $(element).find('.related-galleries li').eq(last_visible - 1);
        var pos = el.position().top;
        var gap = sh - (pos + el.height() + parseInt(el.css('margin-top').replace('px', ''), 10));
        if (gap <= 0) {
            return;
        }
        var each_margin = gap / last_visible;
        el.parent().height(el.parent().height() + gap - 2);
        $(element).find('.related-galleries li').each(function(i) {
            if (i < last_visible) {
                $(this).css('margin-bottom', each_margin + 'px');
            }
        });
    };

    this.init = function () {
        var is = $(element).find('.related-galleries li').length;
        if (is > 0) {
            visibleElements();
            if (is > 2) {
                stretch();
                margins();
            }
            $(element).find('.tabs li a').click(loadGalleries);
        }
        /* height fixes */
        real_height = $('#sidebar-banner').height();
        if (real_height < 200) {
            $('#sidebar').addClass('big-bg');
        }
    };

    this.init();
}

function Like(element) {

    var like = function () {
        $.get(
            $(this).attr('class'),
            {},
            function(data) {
                e = $(element).find('.voteup span');
                e.text('(' + data + ')');
                e.unbind('click').click(function() {
                    return false;
                });
            },
            'json'
            );

        return false;
    };

    this.init = function () {
        $(element).find('.voteup span').click(like).css({'visibility' : 'visible'});
    };

    this.init();
}

function LiveComment(element) {
    var reload = function() {
        widget_id = $(element).find('h4').attr('class').replace('id-', '');
        comment_id = $(element).find('ol li:first').attr('class').replace('live-', '');
        $.get(
                '/live-comment/' + widget_id + '/' + comment_id,
        {},
                function(data) {
                    var scroll = $(element).find('ol').scrollTop();
                    $(element).find('ol').remove();
                    $(element).find('.loading').after(data);
                    $(element).find('ol').scrollTop(scroll);
                }
                );
    };

    this.init = function() {
        reload();
        setInterval(function() {
            reload();
        }, 10000);
    };

    this.init();

}

function LoginLogout(element) {

    var reset_password = function() {
        var name = this.name;
        var id = this.id;
        var html = '<input type="password" name="' + name + '" id="' + id + '" />';
        $(this).after(html);
        $(this).next().focus();
        $(this).remove();
    };

    var reset_email = function () {
        $(this).attr('value', '');
    };

    var login = function(e) {
        e.preventDefault();
        form = $(this).parents('form');
        $.post(form.attr('action'), form.serialize() + '&' + web.authTokenParam(), function(data) {
            if (data.success + "" != "false") {
                location.reload();
            } else {
                $('#new_user_session fieldset.form').hide();
                $('#new_user_session fieldset.error').hide().removeClass('hidden').fadeIn();
                setTimeout(function() {
                    $('#new_user_session fieldset.error').hide();
                    $('#new_user_session fieldset.form').fadeIn();
                }, 4000);
            }
        }, 'json');
    };

    var logout = function () {
        var form = $(element).next();
        form.append('<input type="hidden" value="' + web.authToken() + '" name="authenticity_token"/>');
        form.attr('method', 'post');
        form.submit();
        return false;
    };

    this.init = function () {
        $(element).filter('.logout').click(logout);
        $(element).next().find('#user_session_password').focus(reset_password);
        $(element).next().find('#user_session_email').focus(reset_email);
        $(element).next().find('#user_session_submit').click(login);
        if (web.loggedIn()) {
            $(element).parents('.logged_in').show();
        }
        else {
            $(element).parents('.not_logged_in').show();
        }
    };

    this.init();
}

$.fn.slideToggle = function() {
    return this.each(function() {
        var el = $(this);
        el.find('h4 a').click(function(e) {
            e.preventDefault();
        });
        el.children('li').click(function() {
            if ($(this).find('.content').is(':hidden')) {
                el.find('.content').slideUp().parent().removeClass('active');
                $(this).find('.content').slideDown().parent().addClass('active');
            }
        });
    });
};

function Marketing(element) {

    this.init = function () {
        $(element).find('.accordion ul').slideToggle();
    };

    this.init();
}

function MultipleWidget(element) {

  var hijaxForm = function(form){

    $(form).submit(function(){
      $(this).find("input[name=authenticity_token]").attr("value", web.authToken() );
      $(this).after('<img class="loader" style="margin:10px 0 0 15px;" src="/_common/images/icons/loaders/indicator.gif" alt="Počakajte prosim." />');
      
      $.ajax({
        type: "POST",
        url: $(this).attr("action"), 
        data: $(this).serialize(),
        dataType: 'json',
        success: function(data){
          $("img.loader").remove();
          if( data.errors.length != 0){
            var message = 
              "<p class='errors'>" +
              "<strong>Naslednja polja so obvezna:</strong> <br />" +
              data.errors +
            "</p>";
            
            var fieldset = $("#multiple-widget").find("fieldset")[0];
            if( $(fieldset).find("p.errors").size() > 0 ){
              $(fieldset).find("p.errors").replaceWith(message);
            }else{
              $(fieldset).prepend(message);
            }
            
          }else{
            $(form).replaceWith("<p><strong>Zahvaljujemo se za poslane podatke!</strong></p>");
            if(!web.loggedIn()){
              enterLot();
            }
          }

        }
      });
      return false;
    });
  };
  
  var enterLot = function() {
      $("#overlay-info").overlay({
          // custom top position
          top: 272,
          // some expose tweaks suitable for facebox-looking dialogs
          expose: {
              // you might also consider a "transparent" color for the mask
              color: '#fff',
              // load mask a little faster
              loadSpeed: 200,
              // highly transparent
              opacity: 0.5
          },
          // disable this for modal dialog-type of overlays
          closeOnClick: false,
          onStart: function() {
              $("div#overlay-info a.signup_trigger").click(function() {
                  $("div.not_logged_in a.login").trigger("click");
                  $("#overlay-info").overlay().close();
                  return false;
              });
          },
          // we want to use the programming API
          api: true
          // load it immediately after the construction
      }).load();
  };

  
  this.init = function () {
    hijaxForm(element);
  };

  this.init();

}

function Navigation(element) {

    var activateCurrentSection = function(section_path) {
        $(element).find("a[href='" + section_path + "']'").addClass("active").each(function() {
            $(this).parents("ul").addClass("active").siblings("a").addClass("active");
        });
    };

    var setSelected = function() {
        //always show selected submenu
        $(element).hover(
            function() {
            },
            function() {
                $(element).find('li ul.active').show();
            }
        );
    };

    var generateMore = function(passed_ul) {
        ul = typeof passed_ul == 'number' ? $(this) : passed_ul;
        if (ul.height() > 30) {
            var before_last = parseInt(ul.children().length, 10);
            more_section = ul.find('.more-section');
            if (more_section.length === 0) {
                before_last = before_last - 1;
                createMoreSection(ul);
            } else {
                before_last = before_last - 2;
            }
            more_section = ul.find('.more-section');
            var old = ul.children().eq(before_last);
            var copy = old.clone(true);
            first_li = more_section.find('li:first');
            if (first_li.length) {
                first_li.before(copy);
            } else {
                more_section.prepend(copy);
            }
            old.remove();
            generateMore(ul);
        }
    };

    var removeCssFix = function() {
        $(element).find('ul li ul').css({'overflow' : 'visible', 'height' : 'auto'});
    };
    var createMoreSection = function(ul) {
        var more = '<li class="has-children more"><a href="#">Več</a><ul class="more-section"></ul></li>';
        ul.find('li:last').after(more);
    };

    this.init = function() {
        $('#main-nav').addClass('dis-rule');
        var to = null;
        $('#main-nav ul li').hover(
                function() {
                    var el = $(this);
                    clearTimeout(to);
                    to = setTimeout(function() {
                        //$('#main-nav ul li ul').hide();
                        if (el.siblings().find('a.root').length) {
                            el.siblings().each(function () {
                                $(this).find('ul').hide();
                                $(this).find('a.primary').removeClass('active');
                            });
                        }
                        el.find('ul').show();
                        el.find('a.primary').addClass('active');
                    }, 300);
                },
                function() {
                    var el = $(this);
                    clearTimeout(to);
                    to = setTimeout(function() {
                        if (!el.find("ul").hasClass("active")) {
                            el.find('ul').hide();
                            el.find('a.primary').removeClass('active');
                        }
                        $(element).find('li ul.active').prev().addClass('active');
                    }, 300);
                }
                );
        activateCurrentSection(SECTION_PATH);
        setSelected();
        removeCssFix();
        $(element).find('li ul').each(generateMore);
    };

    this.init();

}

function NewUserAction(element) {

    var checkURL = function() {
        if (window.location.href.match(/action/) !== null) {
            var id = window.location.href.split("?")[1].match(/\d+/);
            $(element).find(".action_value").eq(0).attr("value", id);
        }
    };

    this.init = function () {
        checkURL();
    };

    this.init();
}

function NoScroll(element) {

    /* banner values */
    var minHeight_b = 745;
    var minHeight_no_b = 632;
    var enoughForBanner = 734;
    var breaking_news_space = 32;

    var banner = function(space) {
        if ($('#breaking-news').length) {
            space = space - breaking_news_space;
        }
        if (space >= enoughForBanner && $('#top-banner').length) {
            $('body').removeClass('no-top-banner');
            minHeight = minHeight_b;
        } else {
            $('body').addClass('no-top-banner');
            minHeight = minHeight_no_b;
        }
        return space - minHeight;
    };

    var availableHeight = function() {
        var max = $(window).height();
        var space_left = banner(max);
        return space_left;
    };

    var apply = function(selector, className) {
        if ($(selector).length) {
            className(availableHeight(), $(selector));
        }
    };

    var initNoScrolls = function() {
        availableHeight();
        apply('.section', NoScrollSection);
        apply('.popular-galleries', NoScrollPopularContent);
        apply('#sub-content', NoScrollMinisites);
    };

    var pageLayoutHorizontalFix = function() {

    };

    this.init = function () {
        pageLayoutHorizontalFix();
        initNoScrolls();
        $(window).smartresize(function() {
            initNoScrolls();
        });
    };

    this.init();

}

function NoScrollMinisites(space, element) {

    var startHeight = 460;

    this.handleMain = function(space, el) {
        startHeight = startHeight - this.nonStretchableHeights(el.parent().parent().parent());
        var topDiff = $('#sub-content').position().top - $('#content').position().top;
        startHeight = startHeight - topDiff;
        var li = $(el).find('li');
        var rowHeight = li.outerHeight(true);
        startHeight = this.roundToRowValue(startHeight, rowHeight);
        var maxRows = li.length;
        var gap = Math.floor(space / rowHeight);
        if (gap < 0) {
            gap = 0;
        }
        if (gap > maxRows) {
            gap = maxRows;
        }
        var nh = startHeight + (rowHeight * gap);

        if ($(el).height() != nh) {
            $(el).height(nh);
            //now handle sidebar
            $(element).find('#sidebar .stretchable ul').height(0);
            this.handleSidebar($(element).height(), $(element).find('#sidebar'));
        }
    };

    this.roundToRowValue = function(startHeight, rowHeight) {
        num = Math.ceil(startHeight / rowHeight);
        return rowHeight * num;
    };

    this.handleSidebar = function(space, el) {
        space = space - this.nonStretchableHeights(el);
        el.find('.stretchable ul').height(space);
        heightDiff = el.find('.stretchable').height() - el.find('.stretchable ul').height();
        el.find('.stretchable ul').height(space - heightDiff);
        var li = el.find('.stretchable li');
        var rowHeight = li.outerHeight(true);
        el.find('.stretchable ul li').css({'margin-bottom' : 0});
        var gap = Math.floor((space - heightDiff) / rowHeight);
        var margins = ((space - heightDiff) - (gap * rowHeight)) / gap;
        el.find('.stretchable ul li').css({'margin-bottom' : margins});
    };

    this.nonStretchableHeights = function(el) {
        var ht = 0;
        el.children().filter('div:not(.stretchable)').each(function(i) {
            ht += $(this).height();
        });
        return ht;
    };

    this.handleMain(space, $(element).find('#mainbar .stretchable ul'));
}

function NoScrollPopularContent(space, element) {

    var inner_max_height = 128;
    var inner_min_height = 60;

    this.handleContent = function(space, element) {
        if (space >= 84) {
            element.hide().removeClass('hidden').show();
            if (space >= 150) {
                element.find('.in ul').height(inner_max_height);
            } else {
                element.find('.in ul').height(inner_min_height);
            }
        } else {
            element.hide();
        }
    };

    this.handleContent(space, element);
}

function NoScrollSection(space, element) {

    var rowHeight = $('.collapsable li.pic-news').outerHeight(true);
    var maxRows = ($('.collapsable .newest li').length / 2) - 1;
    var startHeight = 58;

    this.handleContent = function(space) {
        var gap = Math.ceil(space / rowHeight);
        if (gap < 0) {
            gap = 0;
        }
        if (gap > maxRows) {
            gap = maxRows;
        }
        var nh = startHeight + (rowHeight * gap);
        $('.collapsable').height(nh);
    };

    this.handleContent(space);

}

function PdfSearchEnhance(element) {

    var submitQuery = function() {
        var query = $(element).find('input[name="isci"]').val();
        if (typeof(query) != 'undefined' && query != '') {
            window.location.href = '/pdf/kadarkoli/vse-regije/' + query;
        }
        return false;
    };

    this.init = function() {
        $(element).submit(submitQuery);
    };


    this.init();
}

function PollWidget(element) {

    var vote = function () {
        var url = $(element).find('form').attr('action');
        var option = $(element).find('li input:checked').val();
        if (!option) {
            return false;
        }

        $(element).find('.area').html('<div class="loader></div>');
        $.post(url, { authenticity_token: web.authToken(), option: option }, function(content) {
            $(element).replaceWith(content);
        });
        return false;
    };

    var results = function () {
        $(element).find('.area').html('<div class="loader></div>');
        var url = $(this).attr('href');
        $.get(url, {}, function(content) {
            $(element).replaceWith(content);
        });
        return false;
    };

    this.init = function () {
        $(element).find('input.submit').click(vote);
        $(element).find('a.results').click(results);
    };

    this.init();
}

function Quiz(element) {

    this.init = function () {
        $(element).find('input[name=authenticity_token]').val(web.authToken());
    };

    this.init();
}

function Registration(element) {

    var onchange = function(el) {
        $(element).find("input#user_news_updates").change(function() {
            if ($(this).attr("checked")) {
                $(el).slideDown("fast");
            } else {
                $(el).find("li input:checked").each(function() {
                    //uncheck selected, if user don't want to recieve newsletters at first place
                    $(this).attr("checked", "");
                });
                $(el).slideUp("fast");
            }
        });
    };
    
    var addDeleteAvatarLink = function(){
      $(element).find("div.avatar img").after("<a id='avatar_delete' href='#'>odstrani</a>");
      $(element).find("a#avatar_delete").one('click', function(e){
        $(e.target).prevAll("img").remove();
        $(element).find("div.avatar").append("<input type='hidden' name='remove_avatar' value='yes' />");
        $(e.target).remove();
        $(element).find("#user_avatar").show();
        return false;
      });
    };
    
    var postsAutocomplete = function(){
      $(element).find('#user_post_id').autocomplete('posts.json', {
         width: 116,
         autoFill : true,
         max : 7,
         scroll : false,
         scrollHeight : 120,
         selectFirst : true,
         minChars: 4,
         error_callback: function(){
          if( $(element).find('p.post-notice').size() == 0 ){
            $('#user_post_id').parent().prepend('<p class="post-notice"><strong>Poštna številka ni veljavna. Prosimo vnesite veljavno poštno številko.</strong></p>');
          }
         },
         success_callback: function(){
           $(element).find('p.post-notice').remove();
         },
         formatItem: function(row) {
            return row[0].split(",")[1];
          },
          comma_separated: true // row value is colon separated value 1000:Ljubljana...
      });
    }
    this.init = function () {
        postsAutocomplete();
        
        var ul_mailing_sections = $(element).find("ul.mailing_sections");
        if ($(element).find("input#user_news_updates").attr("checked")) {
            $(ul_mailing_sections).slideDown("fast");
        } else {
            $(ul_mailing_sections).slideUp("fast");
        }
        onchange(ul_mailing_sections);
        
        if( $(element).find("div.avatar img").size() > 0 ){
          $(element).find("#user_avatar").hide();
          addDeleteAvatarLink();
        }
    };

    this.init();
}

function SearchEnhance(element) {

    this.init = function () {
        //when submit is clicked we remove input#zurnal24 so that parameter is not posted => cleaner url, then we must insert dummy input for better looks =)
        $(element).find("input.submit").click(function() {
            if ($(element).find("input#zurnal24:checked").size() > 0) {
                $(element).find("input#zurnal24").remove();
                $("<input/>").attr({"style":"margin-right:6px","id":"zurnal24","type":"radio","checked":"checked"}).insertBefore($(element).find("label[for=zurnal24]"));
            }
        });

        // if( $(element).find("li.content-picker").size() > 0 ){
        //       var angle = $(element).find("li.content-picker a.sw").attr("href");
        //        $("div#right-head a.rss").attr("href", "/rss" + angle + ".xml" );
        //     }
    };

    this.init();
}

function SemanticNews(element) {

    this.init = function () {
        var loadSemanticNews = $("#semantic-news .loading").size() > 0;
        if (loadSemanticNews) {
            $.get('/priporoceno' + SECTION_PATH, {}, function(data) {
                $(element).html(data);
            });
        }
    };

    this.init();
}

function SetAsHomepage(element) {

    this.init = function () {
        if ($.browser.msie === true && $.browser.version > 6) {
            $(element).click(function(e) {
                document.body.setHomePage(window.location);
                return false;
            });
        } else {
            $(element).fancybox();
            $('#set-as-homepage ul li a').click(function(e) {
                e.preventDefault();
                $('#set-as-homepage ul li div').hide();
                $(this).next().show();
            });
        }
    };

    this.init();
}

function SidebarMedia(element) {

    var pages = function() {
        var feeds = $(element).find('.photo-news li').size();
        var n = Math.round(feeds / 2);
        return n;
    };

    var paging = function(event, el, next, collection, position) {
        if ($(element).find('.page:last').hasClass('active') && $(event.currentTarget).hasClass('fw')) {
            return false;
        }
        position = (position + 1) / 2;
        $(element).find('.page').removeClass('active');
        $(element).find('.page').eq(position).addClass('active');
    };

    var createPage = function() {
        if ($(element).find('.page').size() < pages()) {
            $(element).find('.page:first').clone(true).insertAfter($(element).find('.page:last'));
            createPage();
        }
        $(element).find('.page:first').addClass('active');

    };

    this.init = function() {
        createPage();
        $(element).find('.page').click(function() {
            return false;
        });
        $(element).find('.photo-news').serialScroll({
            items:'li',
            prev:$(element).find('.bk'),
            next:$(element).find('.fw'),
            offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)
            start:false, //as we are centering it, start at the 2nd
            duration:1000,
            force:false,
            step: 2,
            stop:true,
            lock:false,
            cycle:false, //don't pull back once you reach the end
            easing:'easeOutQuart', //use this easing equation for a funny effect
            jump: false, //click on the images to scroll to them
            onBefore:paging
        });
    };

    this.init();

}

function SimpleWeatherWidget(element) {
   var prevent = false;
   var query = function(element) {
      $(element).find('#simple-weather-search').val('Ljubljana');
      $(element).find('#simple-weather-search').focus(function() {
         this.value = '';
      });
      $(element).find('#simple-weather-search').autocomplete('simple_weather/cities', {
         width: 116,
         autoFill : true,
         max : 7,
         scroll : false,
         scrollHeight : 120,
         selectFirst : true
      });
   };
   $(element).find('#simple-weather-search').result(function(event, data, formatted) {
      if (!data) {
         return;
      }
      reloadWeather(data);
   });

   var reloadWeather = function(city) {
      var lis = $(element).find('.cast');
      lis.find('.flash').html('').addClass('loading');
      lis.find('.cast').css({'visibility':'hidden'});

      setTimeout(function() {
         $(element).find('#simple-weather-search').attr('value', city);
      }, 500);

      $.get(
           '/simple_weather/forecast',
            {q: city},
              function(data) {
                    var i = 0;
                    var el = lis.eq(i);
                    el.find('.temperature').text(data.temperature);
                    el.find('.wind_speed').text(data.wind_speed);
                    el.find('.wind_direction').text(data.wind_direction);
                    el.find('.cast').css({'visibility':'visible'});
                    el.find('.flash').flash({swf:'/_common/flash/weather/' + data.state + '.swf',height:50,width:55,wmode:'transparent'});
                    el.find('.flash').removeClass('loading');
            }, 'json');

        $.get(
                '/weather/redirect',
        {q: city},
                function(data) {
                    $(element).find('.link-over').attr('href', data).attr('title', city).css({ 'cursor' : 'pointer'});
                }
                );
   };

   this.init = function() {
      $(element).find(".vreme-net,.link-over").click(function() {
         this.target = "_blank";
      });
      $(element).find('form').submit(function(e) {
         e.preventDefault();
      });
      query(element);
   };

   this.init();
}


function Talcho(element) {

    this.init = function () {
        //chat app should not auto refresh
        $("meta[http-equiv=refresh]").remove();
    };

    this.init();
}

function TextArea(element) {

    var manageTextArea = function() {
        var max = parseInt($(element).attr("title").split("-")[1], 10);
        var show_notice = false;
        $(element).keyup(function() {
            if (this.value.length > max) {
                show_notice = true;
                this.value = this.value.substring(0, max);
                if ($(this).next().length === 0) {
                    $(this).parent().append("<p class='errors'>Vnesete lahko " + max + " znakov.</p>");
                }
            } else {
                if ($(this).next().length !== 0) {
                    $(this).next().remove();
                }
            }
        });

    };

    this.init = function () {
        manageTextArea();
    };

    this.init();
}

function VotingSignup() {

    this.init = function () {
        $("div#signup a.signup_trigger").click(function() {
            $("div.not_logged_in a.login").trigger("click");
            return false;
        });
    };

    this.init();
}

function VotingSubmission(element) {

    var captchaURL = "";
    var voteURL = "";
    var vote = function() {
        if ($(this).hasClass('loading')) {
            return false;
        } else if ($(this).parents('.rate:first').hasClass('disabled')) {
            alert("Ker ste pred kratkim že glasovali, boste lahko naslednji glas na tem prispevku oddali po preteku 1 ure od vašega zadnjega glasu.");
            return false;
        } else {
            //captcha not loaded
            if ($(element).find(".captchaImages").size() === 0) {
                $('#captcha').addClass('loading');
                captchaURL = $(this).attr('href') + "/captcha";
                voteURL = $(this).attr('href');
                loadCaptcha(captchaURL, voteURL); // hm....
            }
            return false;
        }
    };

    var rate_over = function () {
        mark_stars($(this));
        unmark_stars($(this));
    };

    var unmark_stars = function(el) {
        $(el).parent().nextAll().each(function () {
            $(this).find('a').removeClass('selected');
        });
    };

    var mark_stars = function(el) {
        reset_stars();
        $(el).parent().prevAll().andSelf().each(function () {
            $(this).find('a').addClass('selected');
        });
    };

    var reset_stars = function() {
        $("div[id^=submission_vote_] > ul li a.selected").removeClass("selected");
    };

    var rate_out = function () {
        $(this).closest('ul').find('a').each(function () {
            $(this).removeClass('selected');
        });
    };

    var rate = function() {
        if ($(this).parents('ul:first').hasClass('loading')) {
            return false;
        } else if ($(this).parents('.rate:first').hasClass('disabled')) {
            alert("Ker ste pred kratkim že glasovali, boste lahko naslednji glas na tem prispevku oddali po preteku 1 ure od vašega zadnjega glasu.");
            return false;
        } else {
            unbind_mouseover();
            if ($(element).find(".captchaImages").size() === 0) {
                $('#captcha').addClass('loading');
                captchaURL = $(".rate1 a").attr("href") + "/captcha";
                voteURL = $(this).attr('href');
                loadCaptcha(captchaURL, voteURL); // hm....
            }
            return false;
        }
    };

    var loadCaptcha = function(url, vote_url) {
        $('#captcha').bind('loaded.simpleCaptcha', function() {
            $('#captcha').removeClass('loading');
            bind_mouseover();
            $(this).find("div.captchaImages > img").bind("click.vote", function() {

                if (web.authToken() !== undefined) {
                    submitVoteOrRate(vote_url, $(this).attr("title"));
                    $('#captcha').addClass('loading');
                } else {
                    alert("Za glasovanje morate imte vklopljene piškotke(cookies)!");
                }

            });
        }).simpleCaptcha({
            scriptPath: url,
            introText: "<p>Za glasovanje kliknite na <span class='captchaText'> </span></p>"
        });
    };

    var enterLot = function() {
        $("#overlay-info").overlay({
            // custom top position
            top: 272,
            // some expose tweaks suitable for facebox-looking dialogs
            expose: {
                // you might also consider a "transparent" color for the mask
                color: '#fff',
                // load mask a little faster
                loadSpeed: 200,
                // highly transparent
                opacity: 0.5
            },
            // disable this for modal dialog-type of overlays
            closeOnClick: false,
            onStart: function() {
                $("div#overlay-info a.signup_trigger").click(function() {
                    $("div.not_logged_in a.login").trigger("click");
                    $("#overlay-info").overlay().close();
                    return false;
                });
            },
            // we want to use the programming API
            api: true
            // load it immediately after the construction
        }).load();
    };

    var submitVoteOrRate = function(href, c_hash) {
        $.ajax({
            type: 'post',
            url: href,
            data: {authenticity_token: web.authToken(), hash: c_hash},
            dataType: 'html',
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            success: function(data, textStatus) {
                $(element).find('.submission-info').replaceWith(data);
                $(element).find('.rate').addClass('disabled');
                $('<div class="success">Uspešno ste oddali glas</div>')
                        .insertBefore($(element).find("a.comment"));
                //if user is not logged in and voting is for prizes, then inform user of a chance to win a prize, if he/she will login or register
                if ($("div.logged_in:visible").size() === 0 && $(element).find(".voting_meta .vote-for-prize").html() == "true") {
                    enterLot();
                }
                unbind_mouseover();
            },
            error: function(xml, status, e) {
                $('#captcha').unbind('loaded.simpleCaptcha').addClass('loading');
                var answer = parseInt(xml.responseText, 10) - 1;
                //var vote_url = $(".rate1").parent().find("li").eq(answer).find("a").attr("href");
                loadCaptcha(captchaURL, voteURL);
            }
        });
    };

    var checkRecentlyVoted = function() {
        cookie_key = $(element).find('.rate').attr('id');
        if (cookie_key && $.cookie(cookie_key) == 't') {
            $(element).find('.rate').addClass('disabled');
        }
    };

    var bind_mouseover = function() {
        $(element).find('a.submit-rate').bind('mouseover.stars', rate_over);
        $(element).find('a.submit-rate').bind('mouseout.stars', rate_out);
    };

    var unbind_mouseover = function() {
        $(element).find('a.submit-rate').unbind('mouseover.stars', rate_over);
        $(element).find('a.submit-rate').unbind('mouseout.stars', rate_out);
    };

    this.init = function () {
        bind_mouseover();
        $(element).find('a.submit-rate').live('click', rate);
        $(element).find('a.submit-vote').live('click', vote);
        checkRecentlyVoted();
    };

    this.init();
}

function WeatherWidget(element) {
    var prevent = false;
    var query = function(element) {
        $(element).find('#weather-search').val('Slovenija');
        $(element).find('#weather-search').focus(function() {
            this.value = '';
        });
        $(element).find('#weather-search').autocomplete('weather/cities', {
            width: 116,
            autoFill : true,
            max : 7,
            scroll : false,
            scrollHeight : 120,
            selectFirst : true
        });
    };
    $(element).find('#weather-search').result(function(event, data, formatted) {
        if (!data) {
            return;
        }
        reloadWeather(data);
    });

    var reloadWeather = function(city) {
        var lis = $(element).find('.cast li');
        lis.find('.flash').html('').addClass('loading');
        lis.find('.temperature').css({'visibility':'hidden'});
        setTimeout(function() {
            $(element).find('#weather-search').attr('value', city);
        }, 500);
        $.get(
                '/weather/forecast',
        {q: city},
                function(data) {
                    for (var i = 0; i <= 2; i++) {
                        if (!data[i]) {
                            break;
                        }
                        var el = lis.eq(i);
                        el.find('.max').text(data[i].max);
                        el.find('.min').text(data[i].min);
                        el.find('.temperature').css({'visibility':'visible'});
                        el.find('.flash').flash({swf:'/_common/flash/weather/' + data[i].state + '.swf',height:50,width:55,wmode:'transparent'});
                        el.find('.flash').removeClass('loading');
                    }
                },
                'json'
                );

        $.get(
                '/weather/redirect',
        {q: city},
                function(data) {
                    $(element).find('.link-over').attr('href', data).attr('title', city).css({ 'cursor' : 'pointer'});
                }
                );
    };

    this.init = function() {
        $(element).find(".vreme-net,.link-over").click(function() {
            this.target = "_blank";
        });
        $(element).find('form').submit(function(e) {
            e.preventDefault();
            //reloadWeather($(element).find('#weather-search').val());
        });
        query(element);
    };

    this.init();
}


function WebForm(element) {

    var submitForm = function () {
        $(element).find('input[name=authenticity_token]').val(web.authToken());
    };

    this.init = function () {
        $(element).find('form').submit(submitForm);
        $(element).find('input.submit').click(
            function() {
                $(this).after('<img style="margin:10px 0 0 15px;" src="/_common/images/icons/loaders/indicator.gif" alt="Počakajte prosim." />');
                $(this).hide();
            }
        );

    };

    this.init();
}

function Welcome(element) {

    var modal = function () {
        $.cookie('zurnal24_beta_welcome', '1');
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        $('#mask').css({'width':maskWidth,'height':maskHeight});

        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow", 0.8);

        var winH = $(window).height();
        var winW = $(window).width();

        $(element).css('top', winH / 2 - $(element).height() / 2);
        $(element).css('left', winW / 2 - $(element).width() / 2);

        $(element).fadeIn(2000);
    };

    this.init = function () {
        if ($.cookie('zurnal24_beta_welcome') != '1') {
            modal();
        }
        $(element).find('.close').click(function (e) {
            e.preventDefault();
            $('#mask').hide();
            $('.window').hide();
        });
        $('#mask').click(function () {
            $(this).hide();
            $('.window').hide();
        });
    };

    this.init();
}

function Web() {

    this.authToken = function() {
        return $.cookie('auth_token');
    };

    this.authTokenParam = function() {
        return 'authenticity_token=' + encodeURIComponent(web.authToken());
    };

    this.loggedIn = function() {
        return $.cookie('logged_in') == 't';
    };

    var attach = function(root, selector, clazz, callback) {
        root.findOrFilter(selector).each(function() {
            var object = new clazz(this);
            if (callback) {
                callback(object);
            }
        });
    };

    this.browserVersion = function() {
        var version = 999;
        if (navigator.appVersion.indexOf("MSIE") != -1) {
            version = parseFloat(navigator.appVersion.split("MSIE")[1]);
        }
        return version;
    };
    // this.isInIFrame = (window.location != window.parent.location) ? true : false;
    this.isInIFrame = false;

    var ieFlashFix = function() {
        $('#headlines object').each(function() {
            this.outerHTML = this.outerHTML;
        });
    };

    this.init = function (root) {
        root = (typeof(root) == 'undefined' || !(root instanceof jQuery)) ? $(document) : root;
        if (!web.isInIFrame) {
            attach(root, '#banner-wrap:not(.article #banner-wrap)', NoScroll);
        }
        attach(root, 'a.login, a.logout', LoginLogout);
        if (!web.isInIFrame) {
            attach(root, '.article #header', FixedNavigation);
        }
        attach(root, '.poll', PollWidget);
        attach(root, '#main-nav', Navigation);
        attach(root, '#content', Like);
        attach(root, '#horoscope', HoroscopeWidget);
        attach(root, 'form.sign-comp', HoroscopeCompatibility);
        attach(root, '.sidebar-media', SidebarMedia);
        attach(root, '#weather', WeatherWidget);
        attach(root, '#simple-weather', SimpleWeatherWidget);
        attach(root, '#content .cms', ArticleAddons);
        attach(root, '#header', Header);
        attach(root, '.livecomments, #live-comment', LiveComment);
        if (!web.isInIFrame) {
            attach(root, '.post-comment', Comments);
        }
        if (!web.isInIFrame) {
            attach(root, '.article-tabs', Facebook);
        }
        attach(root, '.quiz-hold', Quiz);
        attach(root, '.date-picker-input.events-filter', EventsFilter);
        attach(root, '#web-form', WebForm);
        attach(root, '#signup', VotingSignup);
        attach(root, 'form.filters', SearchEnhance);
        attach(root, 'form.new_user', Registration);
        attach(root, 'form#new_user, .facebook_login', Facebook);
        attach(root, '.voting #content', VotingSubmission);
        attach(root, '#semantic-news', SemanticNews);
        attach(root, 'body.marketing', Marketing);
        attach(root, '.chooser', Comparison);
        attach(root, 'form.new_user_session', NewUserAction);
        attach(root, 'form.new_user', NewUserAction);
        attach(root, 'textarea[title^=limit]', TextArea);
        attach(root, '#header .homepage', SetAsHomepage);
        attach(root, '#talcho_chat_iframe', Talcho);
        attach(root, 'form.pdf.filters', PdfSearchEnhance);
        attach(root, '.accordion', AdPortal);
        attach(root, 'form#multiple-widget', MultipleWidget);
        $('.date-picker-input').date_input();
    };

    this.initGalleries = function (root) {
        root = (typeof(root) == 'undefined' || !(root instanceof jQuery)) ? $(document) : root;
        attach(root, '#fullscreen-gallery', FullscreenGallery);
        attach(root, '#iframe-gallery', Gallery);
    };

    this.initLatestMedia = function(root) {
        root = (typeof(root) == 'undefined' || !(root instanceof jQuery)) ? $(document) : root;
        attach(root, '.gallery #sidebar, .video #sidebar, .quiz #sidebar, .voting #sidebar, .comparison #sidebar', LatestMedia);
    };

    //$(document).ready(this.init);
}

var gmap_api = "ABQIAAAAnfs7bKE82qgb3Zc2YyS-oBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSySz_REpPq-4WZA27OwgbtyR3VcA";
var addthis_config = { services_compact: 'email,facebook,twitter', username: 'zurnal', ui_language: "sl"};
var web = new Web();
