function setupMCFArt() {

    Shadowbox.setup("a.mcfart-gallery", {
        gallery:        "mcfart",
        continuous:     true,
        counterType:    "skip"
    });


}

/**
 * Simple DOM Builder
 * (c) 2008, 2009 Jason Frame (jason@onehackoranother.com)
 *
 * Usage:
 *
 * $$('table#foo',
 *   $$('tr', $$('th.col-1', 'ID'), $$('th.col-2', 'Username'), $$('th.col-3', 'Email')),
 *   $$('tr', $$('td', 1), $$('td', 'jaz303'), $$('td', 'jason@magiclamp.co.uk')),
 *   {style: "margin:10px"}
 * );
 *
 * Returns a jQuery object.
 */
function $$() {
	
	var args 	= jQuery.makeArray(arguments),
		tag		= args.shift();
		last 	= args[args.length - 1],
		options	= {},
		$ele	= null,
		match	= null;
		
	if (typeof last == 'object' && !(last.html) && !(last.nodeType)) {
        options = args.pop();
    }
    
    if (match = /^([\w-]+)(#([\w-]+))?((\.[\w-]+)*)$/.exec(tag)) {
        
        var $ele = jQuery(document.createElement(match[1]));
        
        if (match[3]) $ele[0].id = match[3];
        if (match[4]) $ele[0].className = match[4].replace(/\./g, ' ');
        
        for (var k in options) {
            if (k == 'hover' && options[k] instanceof Array) {
                $ele.hover(options[k][0], options[k][1]);
            } else if (jQuery.isFunction(options[k])) {
                $ele.bind(k, options[k]);
            } else {
                $ele.attr(k, options[k])
            }
        }

		$$.appendAll($ele, args);
		
    }
    
    return $ele;

};

$$.appendAll = function($target, items) {
	for (var i = 0; i < items.length; i++) {
		var thing = items[i];
		if (thing === null) continue;
		else if (thing instanceof Array) $$.appendAll($target, thing);
		else $target.append(thing);
	}
}

$$.make = function(tagName) {
	return function() {
		var args = jQuery.makeArray(arguments);
		args.unshift(tagName);
		return $$.apply(this, args);
	};
};

(function(scope) {
	// thank you, http://www.htmldog.com/reference/htmltags/
	var tags = ["a", "abbr", "acronym", "address", "area", "b", "base", "bdo",
	            "big", "blockquote", "body", "br", "button", "caption", "cite",
	            "code", "col", "colgroup", "dd", "del", "dfn", "div", "dl",
	            "dt", "em", "fieldset", "form", "h1", "h2", "h3", "h4", "h5",
	            "h6", "head", "html", "hr", "i", "img", "input", "ins", "kbd",
	            "label", "legend", "li", "link", "map", "meta", "noscript",
	            "object", "ol", "optgroup", "option", "p", "param", "pre", "q",
	            "samp", "script", "select", "small", "span", "strong", "style",
	            "sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th",
	            "thead", "title", "tr", "tt", "ul", "var"];
	for (var i = 0; i < tags.length; i++)
		scope[tags[i].toUpperCase()] = $$.make(tags[i]);
})(this);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


if(!this.JSON){this.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());


ProductFilter = function () {
  this.data = {}
  this.filters = {}
  this.hidden = []
  
  this.loadUrl = function() {
    var path = document.location.pathname.split('-')[0];
    path = path + "/load";
    path = path.replace('//','/')
    return path;
  }
  
  this.showFirstFiltered = function() {
    var obj = this;
    var count_loaded = 0
    if ($('.filters').size() != 0) {
      $("ul.products li").hide().removeClass('will-disappear')
      var products = this.filterProducts()
      var forLoad = [];

      $.each(products, function() {
        var p = $("#product_" + this)
        if (p.length) {
          p.show();
          count_loaded = count_loaded + 1
        } else {
          forLoad.push(this);
        }
      });


      $('h1 .count').html(products.length)
      Filters.updateResetFilterButton();
    }
  },
  
  this.apply = function() {
    var obj = this;
    if ($('.filters').size() != 0) {
      $("ul.products li").hide().removeClass('will-disappear')
      var products = this.filterProducts()
      var forLoad = [];

      $.each(products, function() {
        var p = $("#product_" + this)
        if (p.length) p.show();
        else forLoad.push(this);
      });

      if (forLoad.length) {
        ScrollLoadingPage(forLoad);
      }
      $('h1 .count').html(products.length)
      State.save();
      Filters.updateResetFilterButton();
    }
  }

  this.preview = function() {
    if ($('.filters').size() != 0) {
      var products = this.filterProducts()
      $('ul.products li').each(function () {
        var productId = this.id.split("_")[1];
        if ($.inArray(productId,products) == -1) {
//           this.className = 'product-box will-disappear';
            $(this).addClass('will-disappear')
        } else {
//           this.className = 'product-box';
            $(this).removeClass('will-disappear')
        }
      });
      $('h1 .count').html(products.length)
    }
  }

  this.filterProducts = function() {
    var filter = this.currentFilter()
    var products = []
    for (productId in this.data) {
      if (filter(this.data[productId])) {
        products.push(productId)
      }
    }
    return products
  }

  this.suffixes = {
    less: function(a, b) { return a <= b; },
    greater: function(a, b) { return a >= b; },
    equals: function(a, b) { return a == b; }
  }

  this.currentFilter = function() {
    var splitSuffix = function(name) {
      for (suffix in ProductFilter.instance.suffixes) {
        var regexp = new RegExp('_' + suffix + '$')
        if (name.match(regexp)) {
          return {slug: name.replace(regexp, ''), suffix: suffix}
        }
      }
      return null
    }

    var conditions = $('.scope').map(function() {
      var value = $(this).val()
      if (!value) { return function(product) { return true; } }
      if (this.type == 'checkbox' && !this.checked) { return function(p) { return true } }

      var s = splitSuffix(this.id)
      return function(product) {
        return ProductFilter.instance.suffixes[s.suffix](product[s.slug], value)
      }
    })

    return function(product) {
      for (var i = 0; i < conditions.length; i++) {
        if (!conditions[i](product)) { return false }
      }
      return true
    }
  }

  this.reset = function() {
    $('.slider-filter').each(function () {
      var slider = $(this);
      var min = slider.find('.min:input').val(),
        max = slider.find('.max:input').val();

      slider.find('.lower').val(min);
      slider.find('.upper').val(max);

      slider.find('.dynamic .min span').html(min);
      slider.find('.dynamic .max span').html(max);

      slider.find('.ui-slider-range').css({left: 0, width: '100%'});
      slider.find('.ui-slider-handle:first').css({left: 0});
      slider.find('.ui-slider-handle:last').css({left: '100%'});
    });

    $('.check-box-filter .scope').attr('checked', false);

    $('.drop-down-filter .scope').each(function() {
      $(this).find('option:first').attr('selected', 'selected');
    });

    this.apply();
  }
}

ProductFilter.instance = new ProductFilter()

$(function() {
  State.apply();

  $('.reset-filters').click(function(e) {
    ProductFilter.instance.reset();
    $('.reset-filters').addClass('inactive-reset')
    $('.reset-filters').attr('disabled', 'disabled')
    State.reset();
    e.preventDefault();
  });

  $('.filters .submit-search').hide()

  $('.drop-down-filter').each(function () {
    var dropDown = $(this)
    dropDown.find('.scope').change(function() {
      ProductFilter.instance.apply();
    })
  })

  $('.check-box-filter').each(function () {
    var checkBox = $(this)
    checkBox.find('.scope').click(function() {
      ProductFilter.instance.apply();
    })
  })

  $('.slider-filter').each(function () {
    var slider = $(this)
    var numIn = function(sel) { return parseFloat(slider.find('input' + sel).val()) }

    slider.find('.lower[value=""]').val(slider.find('.min:input').val())
    slider.find('.upper[value=""]').val(slider.find('.max:input').val())

    slider.find('.plain').hide()
    slider.find('.dynamic').show()

    slider.find('.dynamic .min span').html(slider.find('.lower').val())
    slider.find('.dynamic .max span').html(slider.find('.upper').val())

    slider.find('.slider').slider({
      range: true,
      min: numIn('.min'),
      max: numIn('.max'),
      step: numIn('.step'),
      values: [numIn('.lower'), numIn('.upper')],
      slide: function(event, ui) {
        slider.find('.min span').html(ui.values[0])
        slider.find('.max span').html(ui.values[1])
        slider.find('.lower').val(ui.values[0])
        slider.find('.upper').val(ui.values[1])
        ProductFilter.instance.preview()
      },
      change: function(event, ui) {
        ProductFilter.instance.apply()
      }
    })
  })
  
  for (var key in ProductFilter.instance.data) {
    var series_option = $('#series_id_equals option[value='+ProductFilter.instance.data[key].series_id+']')
    series_option.show()
    series_option.parents('optgroup').show()
  }

  var brand_ids = {}, series_ids = {};
  $.each(ProductFilter.instance.data, function(key, value) {
    brand_ids[value.brand_id] = 1;
    series_ids[value.series_id] = 1;
  });
  $('#brand_id_equals option[value!=""]').each(function() {
    var $this = $(this), val = parseInt($this.val());
    if (brand_ids[val] != 1) $this.remove();
  });
  $('#series_id_equals option[value!=""]').each(function() {
    var $this = $(this), val = parseInt($this.val());
    if (series_ids[val] != 1) $this.remove();
  });
  $('#series_id_equals optgroup').each(function() {
    if ($(this).find('option').length == 0) $(this).remove();
  });

  ProductFilter.instance.showFirstFiltered();

});




function intersectArrays(a,b) {
  var res=[]
  for(var i=0; i<a.length; i++) {
    var el = a[i]
    if($.inArray(el+'', b) >= 0) res.push(el)
  }
  return res
}

var Filters = {
  updateResetFilterButton: function() {
    if(Filters.allAreClear() == true) {
      $('.reset-filters').addClass('inactive-reset')
      $('.reset-filters').attr('disabled', 'disabled')
    } else {
      $('.reset-filters').removeClass('inactive-reset')
      $('.reset-filters').removeAttr('disabled')
    }
  },
  slidersAreClear: function() {
    var res = true;
    $('.slider-filter').each(function () {
      var slider_el = $(this).find('.slider')
      var min= slider_el.slider('option', 'min')
      var max= slider_el.slider('option', 'max')
      var range = slider_el.slider('option', 'values')
      res = res && (typeof range != 'undefined' && range[0] == min && range[1] == max)
    })
    return res;
  },
  checkboxesAreClear: function() {
    return $('.check-box-filter input:checked').length == 0
  },
  selectsAreClear: function() {
    return $('.drop-down-filter :selected[value!=""]').length == 0
  },
  allAreClear: function() {
    return Filters.checkboxesAreClear() && Filters.selectsAreClear() && Filters.slidersAreClear()
  }
}

var State = {
  filters: {},
  save: function() {
    var state = this;
    state.filters = {};

    $('.scope:not(input:checkbox)').each(function(idx, item) {
      var $item = $(item);
      state.filters[$item.attr('id')] = $item.val();
    });
    $('.scope:checkbox').each(function(idx, item) {
      var $item = $(item);
      state.filters[$item.attr('id')] = $item.attr('checked');
    });

    var l = document.location.pathname;
    jQuery.cookie(l, JSON.stringify(state.filters), { path: l });
  },
  load: function() {
    var l = document.location.pathname;
    var v = jQuery.cookie(l);
    if (v) {
      this.filters = JSON.parse(v);
      return true;
    }
    return false;
  },
  apply: function() {
    if (this.load()) {
      jQuery.each(this.filters, function(k, v) {
        if (v === true || v === false) {
          $('#'+k).attr('checked', v);
        }
        else {
          $('#'+k).val(v);
        }
      });
    }
  },
  reset: function() {
    var l = document.location.pathname;
    jQuery.cookie(l, '[]', {expires: -1, path: l});
  }
};
