//-- ajax loader
Limb.Class('ajaxLoader',
{
  __construct: function(container)
  {
    if (container && jQuery(container)[0])
      this.container = jQuery(container);
    else
      this.container = jQuery('body');
    this.title = "Подождите ...";
    this.build();
  },
  build: function()
  {
    var html = '<div class="ajax_loader" style="display:none;">';
    html += '<strong>' + this.title + '</strong>';
    html += '</div>';
    this.container.append(html);
    this.ajaxLoader = jQuery('.ajax_loader');
  },
  show: function (title)
  {
    var title = title || this.title;
    this.ajaxLoader.find('strong').html(title);
    this.ajaxLoader.show();
  },
  hide: function ()
  {
    this.ajaxLoader.hide();
  }
});

//-- scroller
function scroller_init(id, displayed_items_count, step) {

  var obj = document.getElementById(id);
  if (obj) {
    var object = jQuery('#expertReviewContainer_'+id)[0];
    var i = 0;
    for (var childItem in object.childNodes) {
      if (object.childNodes[childItem].nodeType == 1){
        i++;
      }
    }
    obj.maxHor = (i - displayed_items_count) * step;
  }
}

function scroll_right(id, displayed_items_count, step)
{
  if(displayed_items_count == undefined)
    displayed_items_count = 3;

  if(step == undefined)
    step = 181;

  var obj = document.getElementById(id);

  if(!obj.maxHor)
    scroller_init(id, displayed_items_count, step);

  if(obj.maxHor > obj.scrollLeft)
  {
    jQuery(obj).animate({scrollLeft:(parseInt(obj.scrollLeft)+step)+"px"}, "fast");
    jQuery('img#lArrow_'+id).show();
  }

  if(obj.maxHor <= (obj.scrollLeft + step))
    jQuery('img#rArrow_'+id).hide();
}

function scroll_left(id, displayed_items_count, step)
{
  if(displayed_items_count == undefined)
    displayed_items_count = 3;

  if(step == undefined)
    step = 181;

  var obj = document.getElementById(id);

  if(!obj.maxHor)
    scroller_init(id, displayed_items_count, step);

  if(obj.scrollLeft > 0)
  {
    if(obj.scrollLeft > step)
      jQuery(obj).animate({scrollLeft:(parseInt(obj.scrollLeft)-step)+"px"}, "fast");
    else
      jQuery(obj).animate({scrollLeft:"0px"}, "fast");

    jQuery('img#rArrow_'+id).show();
  }

  if(obj.scrollLeft <= step)
    jQuery('img#lArrow_'+id).hide();
}


//-- pageInit
function pageInit(){
  initFancyBox();

  jQuery('.leftArrow img').hide();
}


function initFancyBox(parent_element)
{
  if(!parent_element)
    collection = jQuery('a.fancy-box');
  else
    collection = parent_element.find('a.fancy-box');

  collection.fancybox(
  {
    hideOnContentClick: false,
    centerOnScroll: false
  });
}


function swapAnnounce(id)
{
  jQuery('#tabs li').removeClass('active');
  jQuery('#t'+id).addClass('active');

  jQuery('#announces div.announce').hide();
  jQuery('#announce'+id).show();
}

function swapNiceBlock(itemId, itemPrefix, containerId, childItemContainer){
  jQuery('#'+itemPrefix+'List li').removeClass('active');
  jQuery('#'+itemPrefix+'List'+itemId).addClass('active');

  jQuery('#'+containerId+' '+childItemContainer).hide();
  jQuery(childItemContainer+'#'+itemPrefix+itemId).show();
}

function initTrophiesSortLinks()
{
  jQuery('.trophies_sort').click(function(){

    element = jQuery(this);

    category_id = element.parent().find('input[type="hidden"]').val();
    load_to = '#table_' + category_id;
    ajaxLoader.show();

    jQuery(load_to).find('tbody').load(
      element.attr('href'),
      {'ajax' : 1,
       'category_id' : category_id},
      function(){finishSortingLoading(jQuery(load_to));}
    );

    element.parent().find('.trophies_sort:hidden').show();
    element.hide();
    element.siblings('b').hide();
    element.next('b').show();

    return false;
  });
}

function initTrophiesSortLinksForCompetitor()
{
  jQuery('.trophies_sort_competitor').click(function(){

    element = jQuery(this);
    category_id = element.parent().find('input[type="hidden"]').val();
    load_to = '#scrollme_' + category_id;

    ajaxLoader.show();

    jQuery(load_to).find('div').load(
      element.attr('href'),
      {'ajax' : 1,
       'category_id' : category_id},
      function(){finishSortingLoading(jQuery(load_to));}
    );

    element.parent().find('.trophies_sort_competitor:hidden').show();
    element.hide();
    element.siblings('b').hide();
    element.next('b').show();

    return false;
  });
}

function finishSortingLoading(parent_element)
{
  ajaxLoader.hide();
  initFancyBox(parent_element);
}

function initAnnouncmentsRoller()
{
  var COOKIE_NAME = 'announcments_roller';

  if(!jQuery.cookie(COOKIE_NAME))
  {
    jQuery.cookie(COOKIE_NAME, 1);
    swapAnnounce(1);
    return;
  }
  
  var count = jQuery('#announces div.announce').length;
  var current_num = parseInt(jQuery.cookie(COOKIE_NAME));
  var next_num = ( (current_num + 1) > count) ? 1 : (current_num + 1);

  jQuery.cookie(COOKIE_NAME, next_num);
  swapAnnounce(next_num);
}

function showMenu(call)
{
  call.className = 'hover_link';
}
function hideMenu(call)
{
  call.className = 'out_link';
}

function initDocumentStructure ()
{
  var body = jQuery('body');
  var docWidth = jQuery(window).width();

  body.removeClass('thinSite');
  body.removeClass('bigSite');
  body.removeClass('Site');
  if (docWidth < 1200)
    body.addClass('thinSite');
  else
  {
    if (docWidth >= 1400)
      body.addClass('bigSite');
    if (1260<= docWidth <= 1280)
      body.addClass('Site');
  }

  jQuery('.gallery_photos').each(function(){
    var list_item = jQuery(this).find('li');
    if (list_item.length <= 3 || (1024 < docWidth <= 1280) && (list_item.length <= 4) || ((docWidth >= 1400) && (list_item.length <= 5)))
      jQuery(this).parents('.photo_block').find('.next').hide();
  });
}

/*============================== IFR.js ==============================*/
function com_stewartspeak_replacement() {
/*
  Dynamic Heading Generator
    By Stewart Rosenberger
    http://www.stewartspeak.com/headings/

  This script searches through a web page for specific or general elements
  and replaces them with dynamically generated images, in conjunction with
  a server-side script.
*/

//replaceSelector(".copyist_title","ifr.php",false);
//replaceSelector(".copyist_title_current","ifr.php",false);
//replaceSelector(".copyist_title_digit","ifr.php",false);
var testURL = "/images/test.png" ;

var doNotPrintImages = false;
var printerCSS = "/styles/replacement-print.css";

var hideFlicker = true;
var hideFlickerCSS = "/styles/replacement-screen.css";
var hideFlickerTimeout = 1000;

/* ---------------------------------------------------------------------------
    For basic usage, you should not need to edit anything below this comment.
    If you need to further customize this script's abilities, make sure
  you're familiar with Javascript. And grab a soda or something.
*/

var items;
var imageLoaded = true;
var documentLoaded = false;

function replaceSelector(selector,url,wordwrap)
{
  if(typeof items == "undefined")
    items = new Array();

  items[items.length] = {selector: selector, url: url, wordwrap: wordwrap};
}

if(hideFlicker)
{
  document.write('<link id="hide-flicker" rel="stylesheet" media="screen" href="' + hideFlickerCSS + '" />');
  window.flickerCheck = function()
  {
    if(!imageLoaded)
      setStyleSheetState('hide-flicker',false);
  };
  setTimeout('window.flickerCheck();',hideFlickerTimeout)
}

if(doNotPrintImages)
  document.write('<link id="print-text" rel="stylesheet" media="print" href="' + printerCSS + '" />');
/*
var test = new Image();
test.onload = function() { imageLoaded = true; if(documentLoaded) replacement(); };
test.src = testURL + "?date=" + (new Date()).getTime();
*/
addLoadHandler(function(){ documentLoaded = true; if(imageLoaded) replacement(); });

function documentLoad()
{
  documentLoaded = true;
  if(imageLoaded)
    replacement();
}

function replacement()
{
  if(typeof items == "undefined")
    items = new Array();

  for(var i=0;i<items.length;i++)
  {
    var elements = getElementsBySelector(items[i].selector);
    var elements = jQuery(items[i].selector);
    if(elements.length > 0) for(var j=0;j<elements.length;j++)
    {
      if(!elements[j])
        continue ;

      var text = extractText(elements[j]);
        while(elements[j].hasChildNodes())
        elements[j].removeChild(elements[j].firstChild);

      var tokens = items[i].wordwrap ? text.split(' ') : [text] ;
      for(var k=0;k<tokens.length;k++)
      {
        var url = items[i].url + "?text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector);
        if(elements[j].className == 'copyist_title_current')
          url = items[i].url + "?text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector)+"&bg_color=5D523B&font_color=DFC695";
        if(elements[j].className == 'copyist_title_digit')
            url = items[i].url + "?text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector)+"&bg_color=D9C394&font_color=DFC695&font_size=50";
        if(elements[j].className == 'copyist_title')
          url = items[i].url + "?text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector)+"&bg_color=D9C394&font_color=5C513A";
        var image = document.createElement("img");
        image.className = "replacement";
        image.alt = tokens[k] ;
        image.src = url;
        elements[j].appendChild(image);
      }

      if(doNotPrintImages)
      {
        var span = document.createElement("span");
        span.style.display = 'none';
        span.className = "print-text";
        span.appendChild(document.createTextNode(text));
        elements[j].appendChild(span);
      }
    }
  }

  if(hideFlicker)
    setStyleSheetState('hide-flicker',false);
}

function addLoadHandler(handler)
{
  if(window.addEventListener)
  {
    window.addEventListener("load",handler,false);
  }
  else if(window.attachEvent)
  {
    window.attachEvent("onload",handler);
  }
  else if(window.onload)
  {
    var oldHandler = window.onload;
    window.onload = function piggyback()
    {
      oldHandler();
      handler();
    };
  }
  else
  {
    window.onload = handler;
  }
}

function setStyleSheetState(id,enabled)
{
  var sheet = document.getElementById(id);
  if(sheet)
    sheet.disabled = (!enabled);
}

function extractText(element)
{
  if(typeof element == "string")
    return element;
  else if(typeof element == "undefined")
    return element;
  else if(element.innerText)
    return element.innerText;

  var text = "";
  var kids = element.childNodes;
  for(var i=0;i<kids.length;i++)
  {
    if(kids[i].nodeType == 1)
    text += extractText(kids[i]);
    else if(kids[i].nodeType == 3)
    text += kids[i].nodeValue;
  }

  return text;
}

/*
  Finds elements on page that match a given CSS selector rule. Some
  complicated rules are not compatible.
  Based on Simon Willison's excellent "getElementsBySelector" function.
  Original code (with comments and description):
    http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
*/
function getElementsBySelector(selector)
{
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for(var i=0;i<tokens.length;i++)
  {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
    if(token.indexOf('#') > -1)
    {
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if(tagName && element.nodeName.toLowerCase() != tagName)
        return new Array();
      currentContext = new Array(element);
      continue;
    }

    if(token.indexOf('.') > -1)
    {
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if(!tagName)
        tagName = '*';

      var found = new Array;
      var foundCount = 0;
      for(var h=0;h<currentContext.length;h++)
      {
        var elements;
        if(tagName == '*')
          elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
        else
          elements = currentContext[h].getElementsByTagName(tagName);

        for(var j=0;j<elements.length;j++)
          found[foundCount++] = elements[j];
      }

      currentContext = new Array;
      var currentContextIndex = 0;
      for(var k=0;k<found.length;k++)
      {
        if(found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b')))
          currentContext[currentContextIndex++] = found[k];
      }

      continue;
      }

    if(token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
    {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if(!tagName)
        tagName = '*';

      var found = new Array;
      var foundCount = 0;
      for(var h=0;h<currentContext.length;h++)
      {
        var elements;
            if(tagName == '*')
          elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
        else
          elements = currentContext[h].getElementsByTagName(tagName);

        for(var j=0;j<elements.length;j++)
          found[foundCount++] = elements[j];
      }

      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction;
      switch(attrOperator)
      {
        case '=':
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~':
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|':
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^':
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$':
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*':
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }

      currentContext = new Array;
      var currentContextIndex = 0;
      for(var k=0;k<found.length;k++)
      {
        if(checkFunction(found[k]))
          currentContext[currentContextIndex++] = found[k];
      }

      continue;
    }

    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for(var h=0;h<currentContext.length;h++)
    {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for(var j=0;j<elements.length; j++)
        found[foundCount++] = elements[j];
    }

    currentContext = found;
  }

  return currentContext;
}

}// end of scope, execute code
if(document.createElement && document.getElementsByTagName && !navigator.userAgent.match(/opera\/?6/i))
  com_stewartspeak_replacement();

/*============================== RESTAURANT ==============================*/
function set_current_weekday(day){
  if(!day){
    if(elem = jQuery('#week li')[0])
    {
      elem.className = 'current_day';
      jQuery('#week li h4.copyist_title_current').css('display', 'none');
      jQuery('#week li h4.copyist_title').css('display', 'block');

      jQuery('#week li.current_day h4.copyist_title_current').css('display', 'block');
      jQuery('#week li.current_day h4.copyist_title').css('display', 'none');

      set_menu_day('monday');
    }
  }
  else{
    jQuery('#week li.current_day h4.copyist_title_current').css('display', 'none');
    jQuery('#week li.current_day h4.copyist_title').css('display', 'block');
    jQuery('#week li.current_day').removeClass('current_day');

    jQuery('#' + day).parent().addClass('current_day');
    jQuery('#week li.current_day h4.copyist_title_current').css('display', 'block');
    jQuery('#week li.current_day h4.copyist_title').css('display', 'none');

    set_menu_day(day);
  }
}

function set_current_menu_dish(dish){
  if(!dish){
    if(elem = jQuery('#dish li')[0])
    {
      elem.className = 'current_day';
      jQuery('#dish li h4.copyist_title_current').css('display', 'none');
      jQuery('#dish li h4.copyist_title').css('display', 'block');

      jQuery('#dish li.current_day h4.copyist_title_current').css('display', 'block');
      jQuery('#dish li.current_day h4.copyist_title').css('display', 'none');

      set_menu_dish();
    }
  }
  else{
    jQuery('#dish li.current_day h4.copyist_title_current').css('display', 'none');
    jQuery('#dish li.current_day h4.copyist_title').css('display', 'block');
    jQuery('#dish li.current_day').removeClass('current_day');

    jQuery('#' + dish).parent().addClass('current_day');
    jQuery('#dish li.current_day h4.copyist_title_current').css('display', 'block');
    jQuery('#dish li.current_day h4.copyist_title').css('display', 'none');

    set_menu_dish(dish);
  }
}

function set_menu_day(day){
  jQuery('.menu_content').css('display', 'none');
  jQuery('#menu_content_'+day).css('display', 'block');
}

function set_menu_dish(dish){
  if(!dish){
    elem = jQuery('.menu_dish_content')[0];
    jQuery('.menu_dish_content').css('display', 'none');
    elem.style.display = "block";
  }
  else{
    jQuery('.menu_dish_content').css('display', 'none');
    jQuery('#menu_dish_content_'+dish).css('display', 'block');
  }
}


/*============================== WINDOW READY ==============================*/

jQuery(document).ready(function()
{
  jQuery('#announces .announce').hide();
  initAnnouncmentsRoller();

  jQuery('.media a, .niceBlock.small .link, .player .previw_video_image, .expertReviewContainer a').hover(function()
  {
    jQuery(this).addClass('over_video');
  }, function()
  {
    jQuery(this).removeClass('over_video');
  });

  jQuery('.table tr:last-child, .add_table tr:last-child').addClass('last-child');
  jQuery('.niceBlock .cWrapper .link:first-child, .niceBlock .cWrapper .chemp_description:first-child, .niceBlock .cWrapper .link:first-child, .niceBlock .cWrapper #absChempContainer img:first-child').addClass('first-child');

  initTrophiesSortLinks();
  initTrophiesSortLinksForCompetitor();

  //-- adminAjaxLoader
  ajaxLoader = new ajaxLoader('#wrapper');

  initDocumentStructure();
  if(!jQuery.browser.msie)
    jQuery(window).resize(initDocumentStructure);
  else
    window.onresize = function(){initDocumentStructure();}
});
