/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 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
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key 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 key The key 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 key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key 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 (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

(function($) {
        $.fn.equalHeight = function() {
                var minimum = arguments[0] || 0;
                this.each(function() {
                        if($(this).height() > minimum) {
                                minimum = $(this).height();
                        }
                });
                
                $(this).css("min-height",minimum+'px');
                if($.browser.msie){
                        $(this).height(minimum).css('overflow','hidden');
                }
        }
})(jQuery);

/**
 * sfSlider
 *
 * @version: 1.4
 * @author SimpleFlame http://www.simpleflame.com/
 *
 * Required settings:
 *  display   - provide number of items displayed at once
 *
 * Other settings:
 *  time      - transition time
 *  easing    - easing for the transition
 *  width     - width of the scrolled area (by default visible area + right margin on the last visible item)
 *  previous  - previous link text
 *  next      - next link text
 *  wrap      - wrap container selector
 *  slider    - items container selector
 *  items     - items selector
 *  paging    - set it to true if you want to display paging numbers
 *  auto      - set to true to enable autosliding
 *  autoTime  - duration between auto sliding
 *  transition - transition effect to be used - slide (default) or fade
 *  wrapSlides - should first slide be displayed after the last slide
 */ 

(function($) {
	$.fn.sfSlider = function(options){
		var defaults = {
			width     : 0,
			display   : 6,
			
			time      : 500,
			easing    : 'swing',
			
			previous  : 'Previous',
			next      : 'Next',
			wrap      : 'div.wrap',
			slider    : 'ul.items',
			items     : 'ul.items li',
			paging    : false,
			auto      : false,
			autoTime  :	3000,	
			transition : 'slide',
			wrapSlides : false
		};
		
		var settings = $.extend({}, defaults, options);
		
		return this.each(function(){
			var 
				move, $pagingTriggers,
				$root = $(this),
				$wrap = $root.find(settings.wrap),
				$slider = $root.find(settings.slider),
				$items = $root.find(settings.items),
				all = $items.size(),
				pages = Math.ceil(all/settings.display);
				
			
			$items.filter(':last').addClass('last');
			$items.filter(':first').addClass('first');
			
			// check is there enough items for paging
			if($items.size() <= settings.display) {
				return false;
			}
			
			// try to estimate visible area width if not set
			var width = settings.width;
			if(settings.width === 0) {
				width = $wrap.width() + parseInt($items.css('margin-right'),10);
			}
			
			// defaults
			var current = 0;
			
			// insert paging links					
			
			var $previousTrigger = $('<a href="#previous">'+settings.previous+'</a>').click(function(e){
				e.preventDefault();
				move(current - 1);
			});
			
			if (settings.wrapSlides === false) {
				$previousTrigger.addClass('off');
			}
			
			var $nextTrigger = $('<a href="#next">'+settings.next+'</a>').click(function(e){
				e.preventDefault();
				move(current + 1);
			});
			var $controls = $('<ul class="index"><li class="prev"/><li class="next"/></ul>');
			
			$controls.find('.prev').append($previousTrigger);
			$controls.find('.next').append($nextTrigger);
			
			$root.append($controls);			
			
			if (settings.paging === true) {
				var 
					$paging = $('<ul class="paging"></ul>');

				for (var i = 0; i < pages; i++) {
					$paging.append('<li><a href="#">'+(i+1)+'</a></li>');
				}
				
				$pagingTriggers = $paging.find('a');
				$pagingTriggers.eq(0).addClass('active');
				$pagingTriggers.click(function(e){
					e.preventDefault();					
					move(parseInt($(this).text(), 10) - 1);
				});
				$root.append($paging);
			}
			
			var timeout = null;

			var restartTimer = function(){
				timeout = window.setTimeout(function(){
					move(current + 1);
				}, settings.autoTime + settings.time);
			};
			
			if (settings.auto === true) {			
				restartTimer();
			}
			
			//hide all but the first element
			if (settings.transition === 'fade') {
				$items.filter(':gt(0)').hide();
			}
			
			move = function(position){		
				if(position === current) {
					return false;
				}						
				
				if (settings.wrapSlides === false && (position < 0 || position >= pages)) {
					return false;
				}
				else if (settings.wrapSlides === true && position < 0) {
					position = pages - 1;
				}
				else if (settings.wrapSlides === true && position >= pages) {
					position = 0;
				}
				
				
				current = position;
				//disable navigation if first/last item and slider should not wrap
				if (settings.wrapSlides === false) {
					$previousTrigger.toggleClass('off', current === 0);
					$nextTrigger.toggleClass('off', current + 1 === pages);				
				}
			
				if (settings.paging === true) {
					$pagingTriggers.removeClass('active');
					$pagingTriggers.eq(current).addClass('active');
				}
				
				if (settings.transition === 'slide') {
					var offset = - position * width;
					$slider.stop().animate({'marginLeft': offset + 'px'}, settings.time, settings.easing);
				}
				else if (settings.transition === 'fade') {
					$items.filter(':visible').fadeOut(function(){
						$(this).hide();
					});
					$items.eq(position).fadeIn();
				}
				
				if (settings.auto === true) {
					window.clearTimeout(timeout);
					restartTimer();
				}
			};		
									
		});
	};
})(jQuery);


/**
 * Compact labels plugin
 */
(function($){$.fn.compactize=function(){return this.each(function(){var label=$(this),input=$('#'+label.attr('for'));input.focus(function(){label.hide();}).blur(function(){if(input.val()===''){label.show();}});window.setTimeout(function(){if(input.val()!==''){label.hide();}},50);});};})(jQuery);

/*
 * hrefID jQuery extention - returns a valid #hash string from link href attribute in Internet Explorer
 */
(function($){$.fn.extend({hrefId:function(){return $(this).attr('href').substr($(this).attr('href').indexOf('#'));}});})(jQuery);

/**
 * jQuery.query - Query String Modification and Creation for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/8/13
 *
 * @author Blair Mitchelmore
 * @version 2.1.7
 *
 **/
new function(settings) { 
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  var $numbers = settings.numbers === false ? false : true;
  
  jQuery.query = new function() {
    var is = function(o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function(target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };
    
    var queryObject = function(a) {
      var self = this;
      self.keys = {};
      
      if (a.queryObject) {
        jQuery.each(a.get(), function(key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function() {
          var q = "" + this;
          q = q.replace(/^[?#]/,''); // remove any leading ? || #
          q = q.replace(/[;&]$/,''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
          
          jQuery.each(q.split(/[&;]/), function(){
            var key = decodeURIComponent(this.split('=')[0] || "");
            var val = decodeURIComponent(this.split('=')[1] || "");
            
            if (!key) return;
            
            if ($numbers) {
              if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
                val = parseFloat(val);
              else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
                val = parseInt(val, 10);
            }
            
            val = (!val && val !== 0) ? true : val;
            
            if (val !== false && val !== true && typeof val != 'number')
              val = val;
            
            self.SET(key, val);
          });
        });
      }
      return self;
    };
    
    queryObject.prototype = {
      queryObject: true,
      has: function(key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function(key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return typeof target == 'number' ? target : target || "";
      },
      get: function(key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function(key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function(key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function(key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function(key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function() {
        var self = this;
        jQuery.each(self.keys, function(key, value) {
          delete self.keys[key];
        });
        return self;
      },
      load: function(url) {
        var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
        var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
        return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
      },
      empty: function() {
        return this.copy().EMPTY();
      },
      copy: function() {
        return new queryObject(this);
      },
      COMPACT: function() {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function(key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function() {
        return this.copy().COMPACT();
      },
      toString: function() {
        var i = 0, queryString = [], chunks = [], self = this;
        var encode = function(str) {
          str = str + "";
          if ($spaces) str = str.replace(/ /g, "+");
          return encodeURIComponent(str);
        };
        var addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [encode(key)];
          if (value !== true) {
            o.push("=");
            o.push(encode(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function(key, value) {
            if (typeof value == 'object') 
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };
        
        build(this.keys);
        
        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));
        
        return queryString.join("");
      }
    };
    
    return new queryObject(location.search, location.hash);
  };
}(jQuery.query || {}); // Pass in jQuery.query as settings object


/*
 * Scripts
 *
 */
jQuery(function($) {
 
	var Engine = {
		utils : {
			links : function(){
				$('a[rel*=external]').click(function(e){
					e.preventDefault();
					window.open($(this).attr('href'));						  
				});
			},
			mails : function(){
				$('a[href^=mailto:]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() == mail) {
						$(this).text(replaced);
					}
				});
			}
		},
		fixes : {
			productDetails : function(){
/*
				var l = window.location+'';
				if (l.indexOf('_product_') === -1 && l.indexOf('product.html') === -1) {
					return;
				}
*/
if(typeof(productDetailRewrite) !== 'undefined') {

				$('#aside').remove();
				$('#main').removeAttr('id').addClass('productLargeWrapper');
				$('.paging-a').remove();
				$('h2.categoryName').remove();
				$('.categories-a').remove();
				$('.productList').replaceWith($('.productList div.product'));
				
				var relatedProducts = $('.product .description .productTable');
				if (relatedProducts.length > 0) {
					var featuredProducts = $('#content > .related ul');
					featuredProducts.prev('h2').html('Related products');
					
					featuredProducts.find('li').remove();
					relatedProducts.find('td.productItem').each(function(index, item){
						var li = $('<li class="productItem" />');
						li.attr('id',$(item).attr('id'));
						li.html($(item).html());
						featuredProducts.append(li);
					});
					
					relatedProducts.remove();
				};
                                if ($('.autoship').find('.catProdAttributeItem select').size() == 0) { $('.autoship').css('display','none'); }

} // end if

			}			
		},
		ui : {
			testimonials : function(){
				$('.testimonials-a').each(function(){
					var items = $(this).find('div.item');
					items.filter(':gt(0)').hide();
					
					var current = 0;

					var move = function(offset){
						items.eq(current).hide();
						current = current + offset;
						if (current < 0) {
							current = items.length - 1;
						}
						else if (current >= items.length) {
							current = 0;
						}
						
						items.eq(current).fadeIn();
					};
					
					var nav = $('<ul class="index"><li class="prev"/><li class="next" /></ul>');
					
					var prev = $('<a href="#">Previous</a>').click(function(e){
						e.preventDefault();
						move(-1);
					});

					var next = $('<a href="#">Next</a>').click(function(e){
						e.preventDefault();
						move(1);
					});
					
					nav.find('.prev').append(prev);
					nav.find('.next').append(next);
					
					$(this).find('h2').after(nav);
				});
			},
			slider : function(){
				$('#featured-products div.slider-a').sfSlider({
					width     : 883,
					display   : 4,
					time      : 500,
					wrap      : 'div.slider',
					slider    : 'div.wrapper',
					items     : 'div.wrapper div.item'
				});
			},
			featured : function(options){
				
				var defaults = {
					speed : 5 //speed in seconds of how often transition should occur
				};
				
				var options = $.extend(defaults,options);
				
				$('#featured-a').each(function(){
					//do not run if there is less than 4 items
					var items = $(this).find('div.item');
					if (items.length < 4) {
						return;
					}
					//hide extra elemenets
					items.filter(':gt(3)').hide();
					
					var wrap = $(this).find('.wrap');
					
					window.setInterval($.proxy(function(){
						var first = $(this).find('div.item:eq(0)').fadeTo('fast',0);
						$(this).find('div.item:eq(3)').fadeTo('slow',1);
						
						wrap.stop().animate({'left' : -325}, function(){
							$(this).append(first);
							$(this).css('left',0);
						});
					},this), options.speed * 1000);
					
				});
			}
		},
		
		tweaks : {
			
			cartBox : function(){
				// if the cart is empty hide the utility box 
				if ($('#catCartSummary .cartSummaryItem').html() != 'Shopping cart is empty.') {
				
					var summary = $('#catCartSummary .cartSummaryItem').text().split(" ");
					
					var total = summary[0];
					
					$("span.itemAmount").html(total+" ");
				}else{
					
					$("span.itemAmount").html("0");
				}
				
			},// cartBox
			
			ecomTweak : function(){
				
				// if no cat then hide cat table.
				if($(".catalogueItemNotFound").length > 0){
					$("table.catalogueTable, div.categories-a").hide();
				}
					
					
				if($(".productItemNotFound").length > 0){
					$("div.products-a").hide();
				}
				
				if($("td.catalogueItem").length > 0){
					$("div.categories-a").show();
				}
				
				//featured items
				$("ul.productfeaturelist li").each(function(){
				    var html = $(this).html();
				    $("ul.productfeaturelist").hide();
				    $("#featured-b div.featuredProductsWrapper div.items").append(html);

				});
				
				/* if(window.location.href.indexOf("_product_") == -1){ */

if(typeof(productDetailRewrite) !== 'undefined') {
					
					$("ul.productfeaturelist li").each(function(){
						var html = $(this).html();
						$("ul.productfeaturelist").hide();
						$("#featured-b div.items").append(html);
						
						
					});
					
				}
				
				
				// related products
				/* if(window.location.href.indexOf("_product_") != -1){ */

if(typeof(productDetailRewrite) !== 'undefined') {
					
					$("div.featuredProductsWrapper").hide(); // kill the featured prods div
					$("#featured-b .head h2").text("Products you might also be interested in:"); // change heading
					$("#featured-b .head p.more").hide(); // kill view more link
					
					// grab html from hidden div for related prods
					$(".relatedProducts li.productItem").each(function(){
						var html = $(this).parent().html(); 
						$("#featured-b div.relatedProductWrapper ul").append(html);
	
					});
					
					
					if($(".relatedProducts").html() == "This product has no related products."){
							$("div.relatedProductWrapper, div#featured-b").hide();
					}
					
					
				}

				$("table.productSmall tr td.productItem").each(function(){

                                      	var html = $(this).html();
					$("div.products-a").find("ul").append(html);
                                        $("table.productTable").hide();
				
				});
				
				// hide newsletter
				if(document.location.href.indexOf("_catalog_") != -1){
					$(".aside-newsletter").hide();	
					$("#nav_943075 li:nth-child(3)").addClass("selected");
				}
				
				// slam for product detail
				/* if(document.location.href.indexOf("_product_") != -1){ */

if(typeof(productDetailRewrite) !== 'undefined') {
					

					//var html = $("div.products-a ul").html();
					//$("div.products-a").html(html);
					
                                        var html = $("div.products-a ul div.product").clone();
					$("div.products-a").append(html);
                                        $("div.products-a ul:first").hide();
                                        $('div.products-a').attr('id',$('table.productLarge tr td').attr('id'));
                                        $('table.productLarge').remove();
				}
				
				
				// catalog strip tables
				$("td.catalogueItem").each(function(){
					var html = $(this).html();
					$("table.catalogueTable").hide();
					$("div.categories-a ul").append(html);
				
				});

				// give cool checkout button the href of lame BC button
				$("li.checkout a").attr("href",$("#catshopbuy").attr("href"));
				
				
				// same as shipping - 
				$("#f-shipping-same").bind("change", function(e){
					
					var n = $("#f-shipping-same:checked").length
						if(n == 0){
							//$("#ShippingAttention").val('');
							//$("#CAT_Custom_116466").val('');
							//$("#CAT_Custom_117102").val('');
							$("#BillingAddress").val('');
							$("#BillingCity").val('');
							$("#BillingState").val('');
							$("#BillingZip").val('');
							$("#BillingPhone").val('');
						}else{
							
							//$("#ShippingAttention").val($("#FirstName").val() + " " + $("#LastName").val());
							//$("#CAT_Custom_116466").val($("#CAT_Custom_117102").val());
							$("#BillingAddress").val($("#ShippingAddress").val());
							$("#BillingCity").val($("#ShippingCity").val());
							$("#BillingState").val($("#ShippingState").val());
							$("#BillingZip").val($("#ShippingZip").val());
							$("#BillingPhone").val($("#ShippingPhone").val());
						}
				
				});
				
				$("#catCartDetails #EmailAddress").blur(function(){
					$("#UserName").val($("#EmailAddress").val());
					
				});
				
				if(document.location.href.indexOf("OrderRetrievev2") != -1){
					$("#featured-b").hide();
					
					}

				
				
			},
			
			affiliate : function(){
				
				$("div.col-a p.submit button").click(function(){
				$("#UserName").val($("#EmailAddress").val());
		
				});
				
				$("#showLoginBox").click(function(){
					
					$(".registerForm").hide();
					$(".loginForm").show();
				});
				
			},// affiliate
			
			loginPeepShow : function(){
			
				$("#btnLostPass").click(function(){
					$("#lostPass").slideToggle();
					return false;
				});
			
				
				$("#btnRegister").click(function(){
					$("#registerForm").slideToggle();
					return false;
				});
				
				if(document.location.href.indexOf("log-in") != -1){
					$("div.aside-newsletter").hide();
					}
			
			
			},
			
			ccvBox : function(){
				$("p.ccv a").click(function(){
					$(".ccvBox").colorbox({iframe:true, innerWidth:725, innerHeight:544});
				});
				
				},
				
			updateBtn : function(){
				
				$("div.productitemcell input.cartInputText").each(function(){
				$(this).parent().append(" <a href='#' onclick='return false;'>update</a>");
				});
				
			},
			
			equalize : function(){
                                $('div.categories-a ul li').equalHeight();
                                $('div.products-a li').equalHeight();
                        },
			
			searchResultsFix : function(){
					if(window.location.href.indexOf("ProductSearch") != -1){
						/* $("td.productItem").each(function(){
							var html = $(this).html();
							$("table.productTable").hide();
							$("div.products-a ul").append(html);
						});*/
						
							// pagination
							if($(".productsearchNext").length === 1){
								var link = $(".productsearchNext").wrap("<span></span>").parent().html();
								var html = $("div.products-a").html();
								$("div.searchPager").each(function(){
										$(this).html(link);
										$(this).find("a.productsearchNext").text("Next Page");
								});
								//$("div.products-a").append(html);
							}
						
					}
				} // searchResultsFix
			, populateDealerList : function() {
				$('#dealer-container').load('/dealer-list.htm table', function(response, status, xhr) {		
					var cnt = 0;
					$('#dealer-container table tr').each(function(){
						var val = $(this).find('td:eq(1)').text();
						var display = $(this).find('td:eq(0)').text().trim();
						if (cnt == 0)
						{
							$('#CAT_Custom_166747').append('<option value="00002">--Select Dealer--</option>');
						}
						if (cnt > 0 && display != ''){					
							$('#CAT_Custom_166747').append('<option value="' + val + '">' + display + '</option>');
						}
						cnt++;
					});
					if ($.cookie('dealer_id') != null){
						$('#CAT_Custom_166747').val($.cookie('dealer_id'));	
					}
					
					// sort the list
					var $dd = $('#CAT_Custom_166747');
					if ($dd.length > 0) { // make sure we found the select we were looking for
					
						// save the selected value
						var selectedVal = $dd.val();
					
						// get the options and loop through them
						var $options = $('option', $dd);
						var arrVals = [];
						$options.each(function(){
							// push each option value and text into an array
							arrVals.push({
								val: $(this).val(),
								text: $(this).text()
							});
						});
					
						// sort the array by the value (change val to text to sort by text instead)
						arrVals.sort(function(a, b){
							if(a.text>b.text){
								return 1;
							}
							else if (a.text==b.text){
								return 0;
							}
							else {
								return -1;
							}
						});
					
						// loop through the sorted array and set the text/values to the options
						for (var i = 0, l = arrVals.length; i < l; i++) {
							$($options[i]).val(arrVals[i].val).text(arrVals[i].text);
						}
					
						// set the selected value back
						$dd.val(selectedVal);
					}
					
				});	
			}
			, affiliateCookie : function(name){

				name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
				var regexS = "[\\?&]"+name+"=([^&#]*)";
  				var regex = new RegExp( regexS );
				var results = regex.exec( window.location.href );
				if( results != null ){
				    $.cookie(name, decodeURIComponent(results[1].replace(/\+/g, " ")), { expires: 10, path: '/' });
					//alert($.cookie('dealer_id'));
					
				};
				
				//$('#cookieFrame').attr('src', 'https://ds4u.worldsecuresystems.com/cookie-setter?dealer_id=' + $.cookie('dealer_id') + '&secure_zone=' + $.cookie('secure_zone'));		
				var cookieFrameHTML= '<br /><iframe width="100%" height="300" id="cookieFrame" src="https://ds4u.worldsecuresystems.com/cookie-setter?dealer_id=' + $.cookie('dealer_id') + '&secure_zone=' + $.cookie('secure_zone') + '" style="display: none;"><p>Your browser does not support iframes.</p></iframe>'
				
				$("#cookieFrameHolder").html(cookieFrameHTML);

				//if($.cookie('dealer_id') != 'null' && $.cookie('dealer_id') != ''){ 
//					if ($('#CAT_Custom_166747').size() == 1) { 
//						$('#CAT_Custom_166747').val($.cookie('dealer_id'));  
//					}
//				}
				
				//$('#dealer-list').change(function(){
//					$('#CAT_Custom_166747').val($(this).val());  
//				});
			}
				
		} // tweaks
	};

	Engine.utils.links();
	Engine.utils.mails();
	
	Engine.fixes.productDetails();
	
	Engine.ui.testimonials();
	Engine.ui.slider();
	Engine.ui.featured( { speed: 10 });
	
	Engine.tweaks.cartBox();
	Engine.tweaks.ecomTweak();
	Engine.tweaks.affiliate();
	Engine.tweaks.loginPeepShow();
	Engine.tweaks.ccvBox();
	//Engine.tweaks.updateBtn();
	Engine.tweaks.equalize();
	Engine.tweaks.populateDealerList();
	//Engine.tweaks.affiliateCookie('dealer_id');
	//Engine.tweaks.affiliateCookie('secure_zone');
	
	Engine.tweaks.searchResultsFix();
	

});

function secure_zone_set(zone){
	var options = { path: '/', expires: 1000 };
	$.cookie('secure_zone', zone, options);
}

function secure_zone_redirect(){
	var zone = $.cookie('secure_zone');
	
	if (zone!=null){
		if (zone=='affiliate'){
			window.location="/affiliate-member-area";
		}
		if (zone=='shopper'){
			window.location="/my-account/my-account-home";
		}
	}
}

function secure_zone_clear(){
	var options = { path: '/', expires: 1000 };
	$.cookie('secure_zone', null, options);
}


(function(){ 
  var checkoutTracking = function(){
  if (typeof ValidateCart !== 'function'){ 
    return;
  }
 var _validateCart = ValidateCart;
 ValidateCart = function(){
  var link = document.getElementById('catshopbuy'),
  res = _validateCart.apply(this, arguments);
  if (res === true) {
  	var tempUrl = $("#catshopbuy").attr("href")+"&dealer_id="+$.cookie('dealer_id');
	$("#catshopbuy").attr("href",tempUrl)
	
  } 
  //return false;
  };
 };
  
  checkoutTracking(); 
  })();
