var j = jQuery;
var g_timer_ajax = null;
var g_news_id = 0;
var g_callbacks = {};

function add_bookmark()
{
  // test
  var url_href = window.location.href;
  url_href = url_href.replace('http://', '');
  url_href = url_href.replace('www.', '');
  url_href = url_href.replace(/\//gi, '_');

  if(typeof(pageTracker) != 'undefined' && pageTracker._trackPageview) {
    pageTracker._trackPageview('/outbound/service_click/add_bookmark' + '/' + url_href);
  }

  var title = 'www.podrobnosti.ua - оперативно о главном';
  var url   = 'http://www.podrobnosti.ua/';

  if (window.sidebar) { // Mozilla Firefox Bookmark //Gecko
    window.sidebar.addPanel(title, url,"");
  } else if( window	.external ) { // IE Favorite IE4+
    window.external.AddFavorite( url, title);
  }
  else if(window.opera && window.print) { // Opera 7+
    var mbm = document.createElement('a');
    if (!mbm) return false; //IF Opera 6
    mbm.setAttribute('rel','sidebar');
    mbm.setAttribute('href',url);
    mbm.setAttribute('title',title);
    mbm.click();
    return true;
  }
  return false;
}

function set_homepage(ref)
{
  if(typeof(pageTracker) != 'undefined' && pageTracker._trackPageview) {
    pageTracker._trackPageview('/outbound/service_click/set_homepage');
  }

  if (typeof(document.all) != 'undefined')
  {
    ref.style.behavior = 'url(#default#homepage)';
    ref.setHomePage('http://www.podrobnosti.ua/');
  }
  return false;
}

function send2friend(url)
{
  if(typeof(pageTracker) != 'undefined' && pageTracker._trackPageview) {
    pageTracker._trackPageview('/outbound/service_click/send2friend');
  }

  window.open( url, 'send2friend', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=500,height=370');
}

/**
 * Show Tab content
 *
 * @param string prefix
 * @param object tab
 */
function showTab(prefix, tab)
{
  var n = 0;
  jQuery('ul#'+prefix+'-tabs li').each(function(i){
    if(jQuery(this).hasClass('static'))
      return;
    var tabcontent = jQuery('#'+prefix+'-tab-'+(++n));
    if(this == tab) {
      jQuery(this).addClass('active');
      tabcontent.show();
    }
    else if(tabcontent.css('display') != 'none') {
      jQuery(this).removeClass('active');
      tabcontent.hide();
    }
  });
}



var g_set_page_prev = {};
/**
 * Set active page for Block
 *
 * @param string block_id
 * @param integer page
 * @param interger cnt_page
 * return void
 */
function setPage(obj, block_id, page)
{

  if(!g_set_page_prev[block_id])
  {
    g_set_page_prev[block_id] = 1;
  }

  hideObjects(j('#' + block_id + ' li.g_' + g_set_page_prev[block_id]));
  g_set_page_prev[block_id] = page;
  showObjects(j('#' + block_id + ' li.g_' + page));

  jQuery('#' + block_id + '_page_nav li a').removeClass('active');
  jQuery(obj).addClass('active');
}

/* jQuery functions for smooth bug-less fade in and out */
(function($) {
    $.fn.ClearTypeFadeTo = function(options) {
        if (options)
            $(this)
            .show()
            .each(function() {
                if (jQuery.browser.msie) {
                    $(this).attr('oBgColor', $(this).css('background-color'));
                    $(this).css({ 'background-color': (options.bgColor ? options.bgColor : '#fff') })
                }
            })
            .fadeTo(options.speed, options.opacity, function() {
                if (jQuery.browser.msie) {
                    if (options.opacity == 0 || options.opacity == 1) {
                        $(this).css({ 'background-color': $(this).attr('oBgColor') }).removeAttr('oBgColor');
                        if(options.opacity == 0) $(this).css('display', 'none');
                        $(this).get(0).style.removeAttribute('filter');
                    }
                }
                if (options.callback != undefined) options.callback();
            });
    };

    $.fn.ClearTypeFadeIn = function(options) {
        if (options)
            $(this)
            .css({ opacity: 0 })
            .ClearTypeFadeTo({ speed: options.speed, opacity: 1, callback: options.callback });
    };

    $.fn.ClearTypeFadeOut = function(options) {
        if (options)
            $(this)
            .css({ opacity: 1 })
            .ClearTypeFadeTo({ speed: options.speed, opacity: 0, callback: options.callback });
    };
})(jQuery);

function weatherLoadCity(city, is_main)
{
   jQuery('#weather_block').ClearTypeFadeOut({speed: 200});
   jQuery.post('/cgi-bin/weather/ajax.cgi', { city: city, is_main: (is_main ? 1 : 0) }, function(data) {
      jQuery('#weather_block').html(data);
      jQuery('#weather_block').ClearTypeFadeIn({speed: 1000});
  });
}


/**
 * News by theme
 */
var g_news_related_arguments = {};
var g_news_related_direction = '';
var g_is_news_related_use_ajax = 0;
var g_news_related_page = 0;
var g_is_last_page_for_news_related = false;

function newsByTheme(news_id, direction)
{
  if(g_is_news_related_use_ajax == 1)
  {
    return;
  }

  if(direction == 'next' && g_is_last_page_for_news_related == true) {
    return;
  }

  if(direction == 'next')
  {
    g_news_related_page += 1;
  }
  else
  {
    g_news_related_page -= 1;
  }

  if(g_news_related_page <0)
  {
    g_news_related_page = 0;
    return;
  }


  j(document).scrollTop(215)

  g_news_id = news_id;
  g_news_related_direction = direction;
  j("#div_block_realated_loading").append('<img src="http://podrobnosti.ua/img/loading_sm.gif" width="25" height="25" alt="Загрузка"/>');

  g_news_related_arguments = arguments;
  g_is_news_related_use_ajax = 1;
  g_is_last_page_for_news_related = false;
  g_timer_ajax = setTimeout(_newsByThemeGet, 400);

//  g_timer_ajax = setTimeout("_newsByThemeGet(" + g_news_page_by_theme + ")", 400);
}

function _newsByThemeGet(page)
{
  jQuery.ajax({
    url: "/cgi-bin/news/related_news.cgi?news_id=" + g_news_id + '&pg=' + g_news_related_page  +  "&t=" + new Date().getTime(),
    async: false,
    success: _newsByThemeSuccess
  });
}

function _newsByThemeSuccess(data, textStatus)
{
  clearTimeout(g_timer_ajax);
  g_timer_ajax = null;

  g_is_news_related_use_ajax = 0;

  // block_news_id
  if(data == '')
  {
    j("#div_block_realated_loading img").remove();

    if(g_news_related_direction == 'prev')
    {
      j('#news_related_img_forward').attr('src', '/img/dis_forward_btn.gif');
      j('#news_related_img_forward').parent()[0].onclick = null;
    }

    if(g_news_related_direction == 'next')
    {
      j('#news_related_img_back').attr('src', '/img/dis_back_btn.gif');
      j('#news_related_img_back').parent()[0].onclick = null;
    }

    return;
  }
  else
  {
    j('#block_news_related')[0].innerHTML = data;
  }
}




var g_news_section_arguments = {};
var g_news_section_direction = '';
var g_is_news_section_use_ajax = 0;
var g_news_section_page = 0;

/**
 * Get news by section
 */
function newsBySection(sid, id1, id2, id3, sin, direction)
{
  if(g_is_news_section_use_ajax == 1)
  {
    return;
  }

  if(direction == 'next')
  {
    g_news_section_page += 1;
  }
  else
  {
    g_news_section_page -= 1;
  }

  if(g_news_section_page <0)
  {
    g_news_section_page = 0;
    j('#news_section_img_forward').attr('src', '/img/dis_forward_btn.gif');
    j('#news_section_img_forward').parent()[0].onclick = null;
    return;
  }


  j(document).scrollTop(215)

  g_news_section_direction = direction;

  j("#div_block_news_last_loading").append('<img src="http://podrobnosti.ua/img/loading_sm.gif" width="25" height="25" alt="Загрузка"/>');

  g_news_section_arguments = arguments;
  g_is_news_section_use_ajax = 1;
  g_timer_ajax = setTimeout(_newsBySectionGet, 400);
}

function _newsBySectionGet()
{
  var args = g_news_section_arguments;

  var sid = args[0];
  var id1 = args[1];
  var id2 = args[2];
  var id3 = args[3];
  var sin = args[4];
  var direction = args[5];

  jQuery.ajax({
    url: "/cgi-bin/news/section_news.cgi?sid=" + sid +  "&id1=" + id1 + '&id2=' + id2 + '&id3=' + id3 + '&sin=' + sin + '&direction=' + unescape(direction)  +  "&t=" + new Date().getTime(),
    async: false,
    success: _newsBySectionSuccess
  });
}

function _newsBySectionSuccess(data, textStatus)
{
  g_is_news_section_use_ajax = 0;

  // block_news_id
  if(data == '-1')
  {
    j("#div_block_news_last_loading img").remove();

    if(g_news_section_direction == 'prev')
    {
      j('#news_section_img_forward').attr('src', '/img/dis_forward_btn.gif');
      j('#news_section_img_forward').parent()[0].onclick = null;
    }

    if(g_news_section_direction == 'next')
    {
      j('#news_section_img_back').attr('src', '/img/dis_back_btn.gif');
      j('#news_section_img_back').parent()[0].onclick = null;
    }

    return;
  }
  else
  {
    j('#block_news_last')[0].innerHTML = data;
  }
}

function hideObjects(el)
{
  for(var i=0; i<el.length;i++)
  {
    el[i].style.display = 'none';
  }
}

function showObjects(el)
{
  for(var i=0; i<el.length;i++)
  {
    el[i].style.display = 'block';
  }
}

/*** Calendar ***/
var months = ['января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'];
var calendar_timer = null;
var calendar_object = null;
var calendar_day = null;
var calendar_subject_uri = null;

function initCalendar(init_calendar_day, init_subject_uri, onSelectHandler, min_date, max_date) {
  calendar_day = init_calendar_day;
  calendar_subject_uri = init_subject_uri;

  jQuery(document).ready(function(){
    jQuery.datepicker.setDefaults($.datepicker.regional['ru']);
    var date = $.datepicker.parseDate("yy/mm/dd", calendar_day);

    jQuery(".calendar-link").bind('click', function() {
      jQuery('#' + this.id.replace(/-link/, '')).slideToggle();
    });

    jQuery(".calendar-link").bind('mouseout', function() {
      jQuery('#' + this.id.replace(/-link/, '')).trigger('mouseout')
    });

    jQuery(".calendar").datepicker({
      showOtherMonths: true,
      hideIfNoPrevNext: true,
      changeFirstDay: false,
      minDate: min_date ? min_date : new Date(2001,09-1,08),
      maxDate: max_date ? max_date : new Date(),
      defaultDate: date,
      onSelect: onSelectHandler ? onSelectHandler : function(date) {
        var dat = date.split('.');

        var url_href = window.location.href;
        url_href = url_href.replace('http://', '');
        url_href = url_href.replace('www.', '');
        url_href = url_href.replace(/\//gi, '_');

        if(typeof(pageTracker) != 'undefined' && pageTracker._trackPageview) {
          pageTracker._trackPageview('/outbound/service_click/calendar' + '/' + url_href);
        }

        location.href = calendar_subject_uri + dat[2] + '/' + dat[1] + '/' + dat[0] + '/';
      }
    });

    jQuery(".calendar").bind('mouseout', function() {
      if(this.style.display == 'none')
        return;
      calendar_object = this;
      calendar_timer = setTimeout(function() {
        clearTimeout(calendar_timer);
        calendar_timer = null;
        jQuery(calendar_object).slideUp();
      }, 1000);
    });

    jQuery(".calendar").bind('mouseover', function() {
      if(calendar_timer && calendar_object == this)
        clearTimeout(calendar_timer);
    });
  });
}

/*** Popup Pager ***/
var popup_pager_object = {};
var popup_pager_timer = {};

function initPopupPager(block_id)
{
  j('#' + block_id + '_page_popup').bind('mouseout', function() {
    if(this.style.display == 'none')
      return;
    var id = this.id.replace(/_page_popup/, '');
    popup_pager_object[id] = this;
    popup_pager_timer[id] = setTimeout(function() {
      clearTimeout(popup_pager_timer[id]);
      popup_pager_timer[id] = null;
      jQuery(popup_pager_object[id]).slideUp();
    }, 1000);
  });

  jQuery('#' + block_id + '_page_popup').bind('mouseover', function() {
    var id = this.id.replace(/_page_popup/, '');
    if(popup_pager_timer[id] && popup_pager_object[id] == this)
      clearTimeout(popup_pager_timer[id]);
  });

  jQuery('#' + block_id + '_pulldown').bind('mouseout', function() {
    jQuery('#' + this.id.replace(/pulldown/, 'page_popup')).trigger('mouseout');
  });
}

function setPopupPage(block_id, total_pages, page, callback)
{
  jQuery('#' + block_id + '_page_popup').slideUp();

  if(!g_set_page_prev[block_id])
    g_set_page_prev[block_id] = 1;

  hideObjects(j('#' + block_id + ' li.g_' + g_set_page_prev[block_id]));
  g_set_page_prev[block_id] = page;
  showObjects(j('#' + block_id + ' li.g_' + page));

  if(callback != undefined) {
    g_callbacks[block_id] = callback;
  }

  if(total_pages > 3) {
    var prev_page = 1;
    var paging = '';
    for(var i = 1; i <= total_pages; i++) {
      //if((Math.abs(1 - i) <= 1) || (Math.abs(total_pages - i) <= 1) || (Math.abs(page - i) <= 1)) {
      if(Math.abs(page - i) <= 2) {
        //if(i - prev_page > 1) { paging += '<li>...</li>'; }
        paging += '<li id="'+block_id+'_page_'+i+'"><a href="javascript:;" onclick="setPopupPage(\''+block_id+'\', '+total_pages+', '+i+')">'+i+'</a></li>';
        prev_page = i;
      }
    }
    paging += '<li><a href="javascript:;" id="'+block_id+'_pulldown" onclick="showPopupPager(\''+block_id+'\')"><img alt="" src="/img/down_btn.gif"/></a></li>';
    jQuery('#' + block_id + '_page_nav').html(paging);
  }

  if(g_callbacks[block_id] != undefined) {
    g_callbacks[block_id](block_id, total_pages, page);
  }
  else {
    jQuery('#' + block_id + '_page_nav li a').removeClass('active');
    jQuery('#' + block_id + '_page_' + page +' a').addClass('active');
  }
}

function showPopupPager(block_id)
{
  j('#' + block_id + '_page_popup').slideToggle();
}

function commentsSetPage(block_id, total_pages, page, order)
{
   jQuery(".comments_ajax_loading").show();
   order = (order != undefined) ? parseInt(order, 10) + '/' : '';
   jQuery.get(comments_ajax_url + page + '/' + order, {}, function(data) {
      jQuery('#comments_list').html(data);
      location.href = '#commentslist';
  });
}

function commentsToggle(sender)
{
  location.href = '#comments';
  jQuery("#comments_list").toggle();
  var visible = jQuery("#comments_list:visible").length ? 1 : 0;
  $(sender).html(visible ? 'скрыть' : 'показать');
  var expire = new Date();
  expire.setFullYear(expire.getFullYear() + 3);
  document.cookie = 'comshow=' + visible + ';expires=' + expire.toGMTString() + ';path=/';
}


var g_video_related_arguments = {};
var g_video_related_ajax = 0;

function videoRelated(self, direction)
{
  if(g_video_related_ajax == 1 || /dis_/.test(self.src))
    return;
  j("#related_video .div_block_news_last_loading").append('<img src="http://podrobnosti.ua/img/loading_sm.gif" width="25" height="25" alt="Загрузка"/>');
  g_video_related_arguments.direction = direction;
  g_video_related_ajax = 1;
  g_timer_ajax = setTimeout(videoRelatedGet, 200);
}

function videoRelatedGet()
{
  var args = g_video_related_arguments;
  jQuery.ajax({
    url: "/cgi-bin/news/video_related.cgi?sid=" + args.sid + "&id=" + args.id + "&ord1=" + args.ord1 + "&ord2=" + args.ord2 + '&dir=' + args.direction + "&t=" + new Date().getTime(),
    async: false,
    success: videoRelatedSuccess
  });
}

function videoRelatedSuccess(data, textStatus)
{
  g_video_related_ajax = 0;
  j("#related_video .div_block_news_last_loading img").remove();
  var ndx = data.indexOf("\n");
  var service = '';
  if(ndx) {
    service = data.substr(0, ndx);
    data = data.substr(ndx + 1);
    var vals = service.split(',');
    g_video_related_arguments.ord1 = vals[0];
    g_video_related_arguments.ord2 = vals[1];
    var dir = g_video_related_arguments.direction;
    j('#related_video .related_video_' + dir).attr('src', '/img/' + (vals[2] == 1 ? '' : 'dis_') + (dir == 'next' ? 'back' : 'forward') + '_btn.gif');
    dir = (dir == 'next') ? 'prev' : 'next';
    j('#related_video .related_video_' + dir).attr('src', '/img/' + (dir == 'next' ? 'back' : 'forward') + '_btn.gif');
  }
  j('#video_related_block')[0].innerHTML = data;
  location.href = '#related';
}
