function trace(obj) { if (console.log) console.log(obj); }

var is_ie6 = (function() { var b = jQuery.browser; return b.msie && (b.version == '6.0'); }());
var is_ie8 = (function() { var b = jQuery.browser; return b.msie && (b.version == '8.0'); }());
var selects_hidden = false;

var toggle_selects = is_ie6 ? function() {
  if (selects_hidden) $('select').removeClass('hidden_select'); else $('select').addClass('hidden_select');
  selects_hidden = !selects_hidden;
} : function() {};

var g_boxnews = {
  COOKIE_NAME: 'hp_news_box',
  order: [],
  o_all: null,

  init: function() {
    var me = g_boxnews; 
    me.order = gazeta_pl.hp_box_news;
    me.all = $('#box_news_all');
    me.all.find('.box_news:first').addClass('box_news_first');
    me.all.find('.box_news:last').addClass('box_news_last');
    me.all.find('.box_news .head').append('<span class="move_btn"><span class="move_up"></span><span class="move_down"></span></span>');
    me.all.find('.move_up').click(function() { g_boxnews.move_up($(this).parents().filter('.box_news').eq(0)); });
    me.all.find('.move_down').click(function() { g_boxnews.move_down($(this).parents().filter('.box_news').eq(0)); });
    me.all.find('script').remove();
    
    alt_group = [];
    alt_group_m = [];
    for (var i = 0; i < 3; i++) {
      alt_group.push($.cookie('hp_link_alt_'+i) ? parseInt($.cookie('hp_link_alt_'+i)) : 0);
      alt_group_m.push(0);
    }
    
    me.all.find('li').each(function() {
      if ($(this).attr('className')) {
       var malt = $(this).attr('className').match(/^alt([0-2])([0-2])/);
       if (malt) {
        var ngroup = parseInt(malt[1]);
        var nelem = parseInt(malt[2]);
        if(alt_group_m[ngroup] < nelem) alt_group_m[ngroup] = nelem;
        if (alt_group[ngroup] == nelem) {
         $(this).css({display: 'block'});
        } else {
         $(this).css({display: 'none'});
        }
       }
      }
    });

    me.all.find('li a').click(function(e){
     if ($(this).parent().attr('className')) {
      var malt = $(this).parent().attr('className').match(/^alt([0-2])([0-2])/);
      if (malt) {
       var ngroup = parseInt(malt[1]);
       var nelem = parseInt(malt[2]);
       if(alt_group_m[ngroup] == nelem) nelem = -1;
       $.cookie('hp_link_alt_'+ngroup, nelem+1, { expires: (1/48) });
      }
     } 
    });
    
  },

  move_up: function(elem) {
    var me = g_boxnews;
    if (elem.hasClass('box_news_first')) return;
    var pos = me.all.find('.box_news').index(elem);
    elem.insertBefore(elem.prev('.box_news'));
    me.replace(pos, pos - 1);
  },

  move_down: function(elem) {
    var me = g_boxnews;
    if (elem.hasClass('box_news_last')) return;
    var pos = me.all.find('.box_news').index(elem);
    elem.before(elem.next('.box_news'));
    me.replace(pos, pos + 1);
  },

  replace: function(i, j) {
    var me = g_boxnews;
    var tmp = me.order[i]; me.order[i] = me.order[j]; me.order[j] = tmp;
    me.all.find('.box_news_first').removeClass('box_news_first');
    me.all.find('.box_news_last').removeClass('box_news_last');
    me.all.find('.box_news:first').addClass('box_news_first');
    me.all.find('.box_news:last').addClass('box_news_last');
    $.cookie(me.COOKIE_NAME, me.order.join(','), { expires: 365 });
  }
};

var g_city = {
  o_form: null,
  o_box: null,
  o_ajax_box: null,
  o_selected: null,
  o_list: null,
  o_list_elem: null,
  enabled: true,

  init: function() {
    var me = g_city;
    me.o_form = $('#form_select_city');
    if (me.o_form.length == 0) return;
    me.o_box = $('#box_news_all .bn_lokale');
    var htm = '<div id="ajax_select_city"><div class="selected">Wybierz miasto<span></span></div><ul>';
    me.o_form.find('option').each(function() {
      if ($(this).val() == 'lokale') {
        htm += '<li class="spec select_'+$(this).val()+'">Wiadomości lokalne</li>';
      } else {
        htm += '<li class="select_'+$(this).val()+'">'+$(this).text()+'</li>';
      }
    });
    htm += '</ul></div>';
    me.o_form.before(htm);

    me.o_ajax_box = $('#ajax_select_city');
    me.o_selected = me.o_ajax_box.find('.selected');
    me.o_list = me.o_ajax_box.find('ul');
    me.o_list_elem = me.o_ajax_box.find('li');

    me.o_ajax_box.hover(
      function() { if (!me.enabled) return; me.o_list.show(); },
      function() { if (!me.enabled) return; me.o_list.hide(); }
    );
    me.o_list_elem.hover(
      function() { $(this).addClass('hover'); },
      function() { $(this).removeClass('hover'); }
    );

    me.o_list_elem.click(function() {
      if (!me.enabled) return;
      me.enabled = false;
      me.o_list.hide();
      $(this).removeClass('hover');
      var selected = $(this).attr('className').match(/select_([^ ]+).*$/).pop();
      $.cookie('hp_news_city', selected, { expires: 365 });

      $.ajax({
        url: '/aliasy/hp2009/box_news/'+selected+'.htm',
        success: function(msg) {
          msg = $.trim(msg.replace(/<script[^<]+<\/script>/g, ''));
          var newBoxId = msg.match(/^<li id=\"(\w+)/)[1];
          msg = msg.replace(/^<li[^>]+>/, '');
          msg = msg.replace(/<\/li>$/, '');
          me.o_box.html(msg);
          me.o_box.attr('id',newBoxId);
          try{ window.external.ContentDiscoveryReset(); }catch(e){}

          me.enabled = true;
          me.o_box.find('.head').append('<span class="move_btn"><span class="move_up"></span><span class="move_down"></span></span>');
          me.o_box.find('.move_up').click(function() { g_boxnews.move_up($(this).parents().filter('.box_news').eq(0)); });
          me.o_box.find('.move_down').click(function() { g_boxnews.move_down($(this).parents().filter('.box_news').eq(0)); });
          me.init();
        }
      });

      var tmpSelected = selected;
      if(tmpSelected == 'lokale') tmpSelected = 'warszawa';

      $.ajax({
        url: '/aliasy/hp2009/pogoda/'+tmpSelected+'.htm',
        success: function(msg) {
          $('#k3 .weather').replaceWith(msg);
        }
      });

      $.ajax({
        url: '/aliasy/hp2009/moto/'+selected+'.htm',
        success: function(msg) {
          $('#mod_ads_moto').replaceWith(msg);
        }
      });

      $.ajax({
        url: '/aliasy/hp2009/dom/'+selected+'.htm',
        success: function(msg) {
          $('#mod_ads_dom').replaceWith(msg);
        }
      });

      $.ajax({
        url: '/aliasy/hp2009/praca/'+selected+'.htm',
        success: function(msg) {
          $('#mod_ads_praca').replaceWith(msg);
        }
      });

    });
  }
};

var g_overlay = {
  BACKGROUND_PADDING: 48,
  MIN_MARGIN_TOP: 12,
  o_shown: null,
  o_bg: null,
  dbg: null,
  init: function() {
    var me = g_overlay;
    me.o_bg = $('#overlay_holder');
    me.o_bg.find('.close_btn').click(function() { g_overlay.hide(); });
    $('#overlay_holder_bg, #overlay_holder .overlay_bg').css({ opacity: 0.5 });
  },
  show: function(name) {
    toggle_selects();
    var me = g_overlay;
    if (me.o_shown) me.hide();
    me.o_shown = $('#ov_'+name);
    me.o_bg.show();
    me.o_shown.show();
    var oh = me.o_shown.find('.inner').height();
    var obh = oh + me.BACKGROUND_PADDING;
    var ot = Math.max(Math.round(($(window).height() - obh) / 2), me.MIN_MARGIN_TOP)
    me.dbg = [oh, obh, ot];
    me.o_shown.find('.overlay_bg').height(obh);
    me.o_shown.css({ marginTop: ot+'px' });
  },
  hide: function() {
    toggle_selects();
    var me = g_overlay;
    if (!me.o_shown) return;
    me.o_shown.hide();
    me.o_bg.hide();
    me.o_shown = null;
  },
  register: function(arg) {
    $(arg.button).click(function(e) { 
      e.preventDefault();
      g_overlay.show(arg.overlay); 
    });
  }
};

var g_offers = {
  MAX_ELEMS: 6,
  ELEM_SIZE: 155,
  o_box: null,
  o_list: null,
  o_list_elem: null,
  o_left: null,
  o_right: null,
  o_left_s: null,
  o_right_s: null,
  position: 0,
  count: 0,
  init: function() {
    var me = g_offers;
    me.o_box = $('#mod_offer');
    if (me.o_box.length == 0) return;
    me.o_list = me.o_box.find('.list_holder ul');
    me.o_list_elem = me.o_list.find('li');
    me.count = me.o_list_elem.length;
    if (me.count > me.MAX_ELEMS) {
      me.o_list.parent().before('<span id="mod_offer_scroll_left"><span></span></span>');
      me.o_list.parent().after('<span id="mod_offer_scroll_right" class="active"><span class="active"></span></span>');
      me.o_left = $('#mod_offer_scroll_left');
      me.o_right = $('#mod_offer_scroll_right');
      me.o_left_s = me.o_left.find('span');
      me.o_right_s = me.o_right.find('span');
      me.o_left.click(function() {
        if (me.position == 0) return;
        me.position--;
        if (me.position == 0) {
          me.o_left.removeClass('active');
          me.o_left_s.removeClass('active');
        }
        if (!me.o_right.hasClass('active')) {
          me.o_right.addClass('active');
          me.o_right_s.addClass('active');
        }
        me.o_list.animate({left: '+='+me.ELEM_SIZE+'px'});
      });
      me.o_right.click(function() {
        if (me.position == me.count - me.MAX_ELEMS) return;
        me.position++;
        if (me.position == me.count - me.MAX_ELEMS) {
          me.o_right.removeClass('active');
          me.o_right_s.removeClass('active');
        }
        if (!me.o_left.hasClass('active')) {
          me.o_left.addClass('active');
          me.o_left_s.addClass('active');
        }
        me.o_list.animate({left: '-='+me.ELEM_SIZE+'px'});
      });
    }
  }
};

var g_small_offers = {
  MAX_ELEMS: 3,
  ELEM_SIZE: 310,
  o_box: null,
  o_list: null,
  o_list_elem: null,
  o_left: null,
  o_right: null,
  o_left_s: null,
  o_right_s: null,
  position: 0,
  count: 0,
  init: function() {
    var me = g_small_offers;
    me.o_box = $('#mod_offer_small');
    if (me.o_box.length == 0) return;
    me.o_list = me.o_box.find('.list_holder > ul');
    me.o_list_elem = me.o_list.find('> li');
    me.count = me.o_list_elem.length;
    if (me.count > me.MAX_ELEMS) {
      me.o_list.parent().before('<span id="mod_offer_small_scroll_left"><span></span></span>');
      me.o_list.parent().after('<span id="mod_offer_small_scroll_right" class="active"><span class="active"></span></span>');
      me.o_left = $('#mod_offer_small_scroll_left');
      me.o_right = $('#mod_offer_small_scroll_right');
      me.o_left_s = me.o_left.find('span');
      me.o_right_s = me.o_right.find('span');
      me.o_left.click(function() {
        if (me.position == 0) return;
        me.position--;
        if (me.position == 0) {
          me.o_left.removeClass('active');
          me.o_left_s.removeClass('active');
        }
        if (!me.o_right.hasClass('active')) {
          me.o_right.addClass('active');
          me.o_right_s.addClass('active');
        }
        me.o_list.animate({left: '+='+me.ELEM_SIZE+'px'});
      });
      me.o_right.click(function() {
        if (me.position == me.count - me.MAX_ELEMS) return;
        me.position++;
        if (me.position == me.count - me.MAX_ELEMS) {
          me.o_right.removeClass('active');
          me.o_right_s.removeClass('active');
        }
        if (!me.o_left.hasClass('active')) {
          me.o_left.addClass('active');
          me.o_left_s.addClass('active');
        }
        me.o_list.animate({left: '-='+me.ELEM_SIZE+'px'});
      });
    }
  }
};

var g_alert = {
  init: function() {
    if ($('#main_alert').length > 0) {
      $('#main_alert .close').click(function() {
        $('#main_alert').remove();
      });
    }
  }
};

var g_radio = {
  popup: null,

  init: function() {
    var me = g_radio;
    $('#form_select_radio').submit(function(e) {
      e.preventDefault();
      var v = $('#i_select_radio').val();
      if (v == -1) return;
      me.popup = window.open(v, 'radio_popup','menubar=0,resizable=0,status=0,scrollbars=0,width=712,height=650');
    });
  }
};

var g_autopromo = {
  init: function() {
    var obj = $('#autopromo');	
    if (obj.length == 0) return;
    var num = $('#autopromo div').length;
    var count = 0;
    var roll = 0;
    
    if ($.cookie('autopromo_roll')) {
      var t = $.cookie('autopromo_roll');
      if (t.match(/^[0-9]+,[0-9]+$/)) {
        t = t.split(/,/); 
        roll = t[0];
        count = t[1];
        if (roll < 0 || roll >= num) roll = 0;
        if (count < 0 || count >= 2) count = 0;

        count++;
        if (count >= 2) {
          count = 0;
          roll++;
          if (roll >= num) roll = 0;
        }
      }
    };

    $.cookie('autopromo_roll', roll+','+count, { expires: 1 });

    var curr_obj = $('#autopromo div').eq(roll);
    curr_obj.removeClass('not_displayed');
    curr_obj.addClass('displayed');
  }
};

var g_search = {
  form_name: 'gazetapl',
  main_input: $('#hd_k2_search_gazeta_q'),
  init: function() {
    g_search.main_input.addClass(g_search.form_name);
    g_search.main_input.attr('oldclass', g_search.form_name);
    if($.trim(g_search.main_input.val()) != ''){
     g_search.main_input.addClass('hasQuery');
    }else{
     g_search.main_input.removeClass('hasQuery');
    }
    $('#hd_k2_dropdown div').click(function() {
      if ($(this).hasClass('hover')) {
        g_search.toggle(false);   
      } else {
        g_search.toggle(true);
      }
    });
    var elems = $('#hd_k2_dropdown li');
    elems.each(function() {
      $(this).append('<span class="bg"></span>');
    });
    $('#hd_search_s').hover(
      function() {
        $(this).addClass('hover');
      },
      function() {
        $(this).removeClass('hover');
      }
    );
    elems.hover(
      function() {
        var cln = $(this).attr('className');
        cln = 'hover '+cln+' '+cln+'_hover';
        $(this).attr('className', cln);
      },
      function() {
        var cln = $(this).attr('className');
        cln = cln.replace(/([a-z]+)?_?hover/g, '').replace(/ /g, '');
        $(this).attr('className', cln);
      }
    );
    elems.click(function() {
      var cln = $(this).attr('className');
      cln = cln.replace(/([a-z]+)?_?hover/g, '').replace(/ /g, '');
      $(this).attr('className', cln);
      g_search.form_name = cln;
      g_search.toggle(false);
      g_search.main_input.removeClass(g_search.main_input.attr('oldclass'));
      g_search.main_input.addClass(g_search.form_name);
      g_search.main_input.attr('oldclass', g_search.form_name);
    });
    g_search.main_input.focus(function(){
     $(this).addClass('inEdit');
    });
    g_search.main_input.blur(function(){
     $(this).removeClass('inEdit');
     if($.trim($(this).val()) != ''){
      $(this).addClass('hasQuery');
     }else{
      $(this).removeClass('hasQuery');
     }
    });
    $('#hd_k2_search_gazeta').submit(function(e) {
      if (g_search.form_name == 'gazetapl') {
        return true;
      }
      e.preventDefault();
      $('#hd_k2_search_'+g_search.form_name+'_q').val($('#hd_k2_search_gazeta_q').val());
      $('#hd_k2_search_'+g_search.form_name).submit();
      return false;
    });
  },

  toggle: function(show) {
    var o_ul = $('#hd_k2_dropdown ul');
    var o_div = $('#hd_k2_dropdown div');
    if (show) {
      o_ul.show();
      o_div.addClass('hover');
    } else {
      o_ul.hide();
      o_div.removeClass('hover');
    }
  }
};

$(document).ready(function() {
  if (!$(document.body).hasClass('js_enabled')) $(document.body).addClass('js_enabled');

  if (window.location.href.match(/\?wyl/)) {
    $('#hd_k3').append('<div id="mail_logout"><div class="inner"><span class="c0">Zostałeś wylogowany</span><a href="http://poczta.gazeta.pl/" class="c1">Zaloguj się</a><span class="c2">X</span></div></div>');
    var obj = $('#mail_logout');
    var p = $('#box_links .link_poczta').offset();
    var h = $('#head').offset();
    obj.css({ left: (p.left - h.left - 48) + 'px', top: (p.top - h.top + 30) + 'px' });
    obj.find('.c2').click(function() { $('#mail_logout').remove(); });
  }

  // embed flash
  (function() {
    if (gazeta_pl.flash_holders) {
      var l = gazeta_pl.flash_holders.length;
      if (l > 0) {
        var params = { wmode: 'opaque', allowScriptAccess: 'always', allowFullScreen: 'true' };
        for (var i = 0; i < l; i++) {
          var fl = gazeta_pl.flash_holders[i];
          params.flashvars = fl.vars;
          swfobject.embedSWF(fl.url, fl.id, fl.width, fl.height, '9.0.0', '/info/expressInstall.swf', {}, params);
        }
      }
    }
  }());

  $('#mod_most li:not(li li)').gazeta(gfunc.switchbox, {
    tabs: '.head li',
    elems: 'ol'
  });

  try {
    $('#hd_h1_sup a').click(function() {
    $(this)[0].style.behavior='url(#default#homepage)';
    $(this)[0].setHomePage('http://www.gazeta.pl');
   });
  } catch (e) {} 

  g_overlay.init(); 
  g_overlay.register({ button: '#k1 .exp_more_services', overlay: 'all_services' });
  g_overlay.register({ button: '#k1 .exp_popular_topic', overlay: 'popular_topics' });


  g_boxnews.init();
  g_city.init();
  g_offers.init();
  g_small_offers.init();
  g_alert.init();
  g_radio.init();
  g_autopromo.init();
  g_search.init();

});

function pop(plik,w,h) {
  var aw=800;
  var ah=600;
  var okno = null;
  if(window.screen) {
    var aw = screen.availWidth;
    var ah = screen.availHeight;
  }
  var dane="width="+w+",height="+h+",left="+(aw-w)/2+",top="+(ah-h)/2+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no";
  okno = window.open(plik,'pop',dane);
} 

