$(document).ready(function(){
    // GALERIA
    $(".galerie a").fancybox({
                    'overlayOpacity': 0.8,
                    'overlayColor'  : '#000000',
    });

    // NEWSLETTER
    $("#id_email").focus(function(){
        $(this).val("");
        $(this).unbind('focus');
    });

    // WYSZUKIWARKA
    $("#search_query").autocomplete("/restricted/autocomplete/", {
              dataType: 'json',
              scroll: false,
              selectFirst: false,
              max: 99, //limit musi byc ustalony po stronie serwera (to jest suma rezultatow poszczegolnych dzialow)
              parse: function(data) {
                  var rows = new Array();
                  for(var i=0; i<data.length; i++){
                      rows[i] = { data:data[i], value:data[i].name, result:data[i].name };
                  }
                  return rows;
              },
              formatItem: function(row, i, n) {
                  var header = "";
                  if (row.type_counter == 0) {
                      header = "<div class='header' style='display:none; font-family:arial !important;'>" + row.type + "</div>";
                  }
                  img = ""; //jezeli nie bedzie tej linijki to jezeli nie bedzie obrazka to wezmie poprzedni
                  if (row.obrazek != "") {
                      img = '<img src="'+row.obrazek+'">';
                  }
                  return header + '<div style="display:block; height:40px; width:80px; float:left;">' + img + '</div>' +row.name;
              },
              formatResult: function(row, i, n) {
                  return row.url;   
              },
              showCallback: function() {
                  query = $('#search_query').val();
                    
                  $('.ac_results li:last').after('<li style="background:#dfdfdf;"><a href="#" class="all_results">Pokaż wszystkie wyniki dla frazy: <strong>' + query + '</strong></a></li>');
                  $('.ac_results li').css('padding', '5px');
                  $('.all_results').click(function(){
                     document.location = '/search/?cx=partner-pub-0712024496864754%3Ailv7hhgbvn4&cof=FORID%3A9&ie=UTF-8&q='+ query +'#885'; 
                  });
                  $('.ac_results .header').each(function(){
                      header_txt = $(this).html();
                      $(this).parent().before('<li style="font-size:1em; padding:7px; background:#444; color:#ffffff;">'+ $(this).html() +'</li>');
                  });
              }
    }).result(function(event, data, formatted) {
        location.href = data.url
    });
	
    // NEWSLETTER
    $("#newsletter-form").submit(function(event) {
        /* stop form from submitting normally */
        event.preventDefault(); 
            
        /* get some values from elements on the page: */
        var $form = $(this),
            email = $form.find('input[name="email"]').val(),
            url = $form.attr('action');

        /* send the data using post and put the results in a div */
        $.post( url, { email: email, subscribed: true},
            function(data) {
                $(".newsletter-info").empty().append(data);
            }
        );
    });

    // LINKI DO PARTNEROW W PD I RANKINGACH
    $('.shop_link').live('click', function() {
        if ($(this).attr('href').indexOf('zadowolenie') != -1) {
            link = location.pathname + "outgoing/cena/" + "zadowolenie"
        } else if ($(this).attr('href').indexOf('ceneo') != -1) {
            link = location.pathname + "outgoing/cena/" + "ceneo"
        } else if ($(this).attr('href').indexOf('skapiec') != -1) {
            link = location.pathname + "outgoing/cena/" + "skapiec"
        } else if ($(this).attr('href').indexOf('neo24') != -1) {
            link = location.pathname + "outgoing/cena/" + "neo"
        }
        _gaq.push(['_trackPageview', link]);
    });

    // MENU - BLACKBAR
    $('.blacktlo').css('opacity', 0.75);

    var blackbar = $('#blackbar a').not(':eq(0)')
        
    blackbar.each(function(){
        $(this).mouseover(function(){
            $('.tab').hide();
            var tab_name = $(this).attr('id')
            $('.' + tab_name).show();
            if ($('.tab').length){
                blackbar.removeClass('blackbar-hover');
                $(this).addClass('blackbar-hover');
            }
        });
    });

    // GLOSOWANIE
    $('.user-star').rating({
          callback: function(value, link){
               // 'this' is the hidden form element holding the current value
               // 'value' is the value selected
               // 'element' points to the link element that received the click.
               //alert("The value selected was '" + value + "'\n\nWith this callback function I can automatically submit the form with this code:\nthis.form.submit();");
               
               // To submit the form automatically:
                //this.form.submit();
               
               // To submit the form via ajax:
               $(this.form).ajaxSubmit();
               $('.user-star').rating('readOnly', true);
               $('.thankyou').toggle();
          }
    });

    // VISITED
    $('#visited-toggle').click(function() {
        var vi = $('#visited-container');
        var vit = $('#visited-toggle');

        vi.toggleClass('hide');
        if (vi.is(":visible")) {
            vit.find('span').html('&darr;');
            move_recommended_box('hide');
        } else {
            vit.find('span').html('&uarr;');
        }
    });

    vi_carousel = $('#visited-items-carousel').bxSlider({
        displaySlideQty: 6,
        moveSlideQty: 1,
        infiniteLoop: false,
        hideControlOnEnd: true
    })

    $('object').prepend('<param name="wmode" value="transparent">');
    $('embed').attr('wmode', 'transparent');

    // RECOMMENDED-BOX
    function isScrolledIntoView(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return (elemTop <= docViewBottom);
    }

    var lock = false;

    function move_recommended_box(action) {
        if (action == "show") {
            var direction = "+";
        } else {
            var direction = "-";
        }
        var recommended_box = $('.recommended-wrapper');
        recommended_box.animate({"right": direction+"="+recommended_box.width()}, "slow", complete=function(){ lock = false; });
    }

    var recommended_box = $('.recommended-wrapper');
    if ($('#end-of-article').length) {
        $(window).scroll(function(){
            if (isScrolledIntoView('#end-of-article')) {
                if (recommended_box.css('right') == "-"+recommended_box.width()+"px") {
                    if (!lock && !$('#visited-container').is(":visible")) {
                        lock = true;
                        move_recommended_box('show');
                    }
                }
            } else {
                if (recommended_box.css('right') == "0px") {
                    if (!lock) {
                        lock = true;
                        move_recommended_box('hide');
                    }
                }
            }
        });
    }


    // SOCIAL BUTTONS
    $('.list-object').live('mouseenter', function() {
        var gplus_cont = $(this).find('.gplus');
        var fblike_cont = $(this).find('.fblike');
        if (gplus_cont.is(':empty') || fblike_cont.is(':empty')) {
            var link = 'http://videotesty.pl' + $(this).find('.list-object-link').attr('href');
            var object_id = $(this).attr('id');

            var gplus = '<g:plusone size="medium" href="' + link + '"></g:plusone>';
            var fblike = '<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="' + link + '" send="false" layout="button_count" width="100" show_faces="true" action="like" font=""></fb:like>';

            gplus_cont.css('width', '70px').css('background', 'none').find('div').html(gplus);
            fblike_cont.css('width', '100px').css('background', 'none').html(fblike);

            gapi.plusone.go('gplus_' + object_id);
            FB.XFBML.parse(document.getElementById('fblike_' + object_id));
        }
    });
});

