$(document).ready(function () {
  initEmail();
  initCartridgeTypeToggler();
  initPrinterTX();
  initAjax();
  initPrint();
  initTable();
});

/**
 * Операции с классом .table
 */
function initTable() {
  $('.table tr:odd td').addClass('bg-gray');
}

function initPrint() {
  $$ = $('.print');
  if ($$.length) {
    $$.click(function (ev) {
      ev.preventDefault();
      print();
    });
  }
}

function initEmail() {
  $.each($('.email'), function (i, v) {
    $(v).html($(v).html().replace('[at]', '@'));
    $(v).attr('href', 'mailto:'+ $(v).html());
  });
}

function initBuy() {
  $('.buy').click(function (ev) {
    ev.preventDefault();
    var l = location.href,
        pos = Math.min(l.indexOf('#') == -1 ? 1e10 : l.indexOf('#'),
                       l.indexOf('?') == -1 ? 1e10 : l.indexOf('?'));
    if (pos != -1 && pos != 1e10) {
      l = l.substring(0, pos);
    }
    l = l +'?'+ $(this).attr('href').substring(1);
    location.href = l;
  });
}

function initCartridgeTypeToggler() {
  var tog = $('#type-toggler span');
  if (tog.length) {
    var tt = $('#ajax .title');
    if (!tt.length || tt.length == 1) {
      $('#type-toggler').hide().prev().hide();
    } else {
      var brand = $('#type-toggler').attr('rel'),
          url = '/b/cartridges/'+ (brand ? brand +'/' : ''),
          $$ = $('#ajax');

      $('#t-all').click(function () {
        tog.removeClass('active');
        $(this).addClass('active');
        initAjaxLoader($$, function () {
          updateCartridges(url);
        });
      });
      $('#t-laser').click(function () {
        tog.removeClass('active');
        $(this).addClass('active');
        initAjaxLoader($$, function () {
          updateCartridges(url +'?type=laser');
        });
      });
      $('#t-ink').click(function () {
        tog.removeClass('active');
        $(this).addClass('active');
        initAjaxLoader($$, function () {
          updateCartridges(url +'?type=ink');
        });
      });

    }
  }
}

function updateCartridges(url) {
  $('#ajax').load(url, null, function () {
    $('.pagination a').click(paginationAjax);
  });
}


function initPrinterTX() {
  $('.tx-all').hide();
  var txc = $('.tx-c span');
  if (txc.length) {
    txc.click(function () {
      var $$ = $(this);
      if (!$$.hasClass('active')) {
        txc.removeClass('active');
        $$.addClass('active');
        if ($$.hasClass('tx-c-common')) {
          $('.tx').slideDown();
          $('.tx-all').slideUp();
        } else {
          $('.tx').slideUp();
          $('.tx-all').slideDown();
        }
      }
    });
  }
}

function initAjax() {
  var $$ = $('#ajax');
  if ($$) {
    var ss = $('#series-toggler span');
    if (ss.length) {
      $.each(ss, function (i, span) {
        span = $(span);
        span.click(function () {
          if (span.attr('block')) {
            ss.removeClass('active');
            span.addClass('active');
            initAjaxLoader($$, function () {
              $$.load('/b/'+ span.attr('block'), null, function () {
                $('.pagination a').click(paginationAjax);
              });
            });
          }
        });
      });
    }
    
    // For users
    $('.pagination a').click(paginationAjax);
  }
}

function paginationAjax(ev) {
  ev.preventDefault();
  var $$ = $('#ajax'),
      $a = $(this),
      url = $a.attr('href');

  // fix url
  if (url.indexOf('/b/') == -1) {
    url = '/b/'+ (url.indexOf('printer') == -1 ? 'cartridges': 'printers') + url.substring(url.indexOf('/', 5));
  }
  
  $.scrollTo($('#menu'), 500);
  initAjaxLoader($$, function () {
      $$.load(url, null, function () {
      $('.pagination a').click(paginationAjax);
    });
  });
}

function initAjaxLoader($$, callback) {
  $$.prepend('<div class="ajax">Идёт загрузка...</div>')
    .find('.ajax').hide().fadeIn(200, callback);
}




/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
*		- A percentage of the container's dimension/s, for example: 50% to go to the middle.
 *		- The string 'max' for go-to-end.
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends.
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
(function($){var $scrollTo=$.scrollTo=function(target,duration,settings){$(window).scrollTo(target,duration,settings);};$scrollTo.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};$scrollTo.window=function(scope){return $(window)._scrollable();};$.fn._scrollable=function(){return this.map(function(){var elem=this,isWin=!elem.nodeName||$.inArray(elem.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!isWin)
return elem;var doc=(elem.contentWindow||elem).document||elem.ownerDocument||elem;return $.browser.safari||doc.compatMode=='BackCompat'?doc.body:doc.documentElement;});};$.fn.scrollTo=function(target,duration,settings){if(typeof duration=='object'){settings=duration;duration=0;}
if(typeof settings=='function')
settings={onAfter:settings};if(target=='max')
target=9e9;settings=$.extend({},$scrollTo.defaults,settings);duration=duration||settings.speed||settings.duration;settings.queue=settings.queue&&settings.axis.length>1;if(settings.queue)
duration/=2;settings.offset=both(settings.offset);settings.over=both(settings.over);return this._scrollable().each(function(){var elem=this,$elem=$(elem),targ=target,toff,attr={},win=$elem.is('html,body');switch(typeof targ){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ)){targ=both(targ);break;}
targ=$(targ,this);case'object':if(targ.is||targ.style)
toff=(targ=$(targ)).offset();}
$.each(settings.axis.split(''),function(i,axis){var Pos=axis=='x'?'Left':'Top',pos=Pos.toLowerCase(),key='scroll'+Pos,old=elem[key],max=$scrollTo.max(elem,axis);if(toff){attr[key]=toff[pos]+(win?0:old-$elem.offset()[pos]);if(settings.margin){attr[key]-=parseInt(targ.css('margin'+Pos))||0;attr[key]-=parseInt(targ.css('border'+Pos+'Width'))||0;}
attr[key]+=settings.offset[pos]||0;if(settings.over[pos])
attr[key]+=targ[axis=='x'?'width':'height']()*settings.over[pos];}else{var val=targ[pos];attr[key]=val.slice&&val.slice(-1)=='%'?parseFloat(val)/100*max:val;}
if(/^\d+$/.test(attr[key]))
attr[key]=attr[key]<=0?0:Math.min(attr[key],max);if(!i&&settings.queue){if(old!=attr[key])
animate(settings.onAfterFirst);delete attr[key];}});animate(settings.onAfter);function animate(callback){$elem.animate(attr,duration,settings.easing,callback&&function(){callback.call(this,target,settings);});};}).end();};$scrollTo.max=function(elem,axis){var Dim=axis=='x'?'Width':'Height',scroll='scroll'+Dim;if(!$(elem).is('html,body'))
return elem[scroll]-$(elem)[Dim.toLowerCase()]();var size='client'+Dim,html=elem.ownerDocument.documentElement,body=elem.ownerDocument.body;return Math.max(html[scroll],body[scroll])
-Math.min(html[size],body[size]);};function both(val){return typeof val=='object'?val:{top:val,left:val};};})(jQuery);
