/*Here's where we use JQuery to call all the functions on their respective elements once the DOM has loaded*/
function InitializeAsh(){

 
//Timer function	
	var showTimes = false;
	var timeString = "1:";
	var timeDiff  =  {
    setStartTime:function (){
        d = new Date();
        time  = d.getTime();
    	},

    getDiff:function (i){
        d = new Date();
        return (d.getTime()-time);
    	}
	}	
/*add JS class to body to hide buttons (or other elements) with class of NonJS that won't be required once javascript alternatives are in place*/
$("body").addClass("JS");
// Start Timer
timeDiff.setStartTime();
	Shadowbox.init();
timeString = timeString + timeDiff.getDiff();
timeDiff.setStartTime();
	$('#switcher').switcher();
timeString = timeString + "ms - shadowbox\n2:" + timeDiff.getDiff() + "ms - switcher";
timeDiff.setStartTime();
	$("div.Tabber").semantictabs();
timeString = timeString + "\n3:" + timeDiff.getDiff() + "ms - tabber";
timeDiff.setStartTime();
	$("div.PersistantTabber").semantictabs({container:'PersistantTabber',persist:true});
timeString = timeString + "\n4:" + timeDiff.getDiff() + "ms - persistant tabber";
timeDiff.setStartTime();
	$('div.Promotions').cycle({
		timeout: 6000,
		speed:  1500,
		height: '180px',
		pause: true
		});
timeString = timeString + "\n5:" + timeDiff.getDiff() + "ms - promotions";
timeDiff.setStartTime();
	$().brandview();
timeString = timeString + "\n6:" + timeDiff.getDiff() + "ms - brandview";
timeDiff.setStartTime();
	$('ul.TwoColumns').columnize({columns:2, buildOnce:true});
timeString = timeString + "\n7:" + timeDiff.getDiff() + "ms - columnizer";
timeDiff.setStartTime();
	$('.ProductCard div.Prices table tr td.Quantity input').spin({max:999,min:1});
timeString = timeString + "\n8:" + timeDiff.getDiff() + "ms - pcard spinner";
timeDiff.setStartTime();
	$('div.InkFinder table tr td input').spin({max:999,min:0});
timeString = timeString + "\n9:" + timeDiff.getDiff() + "ms - inkfinder spinner";
timeDiff.setStartTime();
	$('div.InkFinder input.ResetAll').click(function(){
		$(this).parent().find('table tr td').removeClass('Selected');
	});
timeString = timeString + "\n10:" + timeDiff.getDiff() + "ms - inkfinder reset";
timeDiff.setStartTime();

//	$('div.PaymentChoice fieldset fieldset').hide();
	$("input[name='PaymentChoice']").click(function() {
		if ($("input[name='PaymentChoice']:checked").val() == 'CardPayment')
			{$(this).parent().nextAll('fieldset').slideDown()}
		else
			{$(this).parent().nextAll('fieldset').hide()};		
	});


    // hiding of the card types for cc payments...

    if(($("#CardType").val()!="MAESTRO")&&($("#CardType").val()!="SOLO")){
      $('#MaestroOnly').hide();
    }

	$("#CardType").change(function(){
    	$('#MaestroOnly') [(($(this).val() == 'MAESTRO')||($(this).val() == 'SOLO')) ? 'slideDown' : 'hide' ]()
	});

    $('#use_invoice_address').click(function(){
      address=$('#InvoiceAddress').html().split("\n");

      $("input[name='BillingAddress1']").val(address[0]);
      $("input[name='BillingAddress2']").val(address[1]);
      $("input[name='BillingCity']").val(address[3]);
      $("input[name='BillingPostCode']").val(address[4]);
      $("input[name='BillingPhone']").val($('#InvoiceTelephone').text());

    });

timeString = timeString + "\n11:" + timeDiff.getDiff() + "ms - card panel stuff";
timeDiff.setStartTime();
	$().accordioniser();
timeString = timeString + "\n12:" + timeDiff.getDiff() + "ms - accordioniser";
timeDiff.setStartTime();	
	$().filtericonswitcher();
timeString = timeString + "\n13:" + timeDiff.getDiff() + "ms - filtericonswitcher";

// End Timer
if(showTimes) {alert(timeString)};
}

/*Shadowbox form auto-focus*/
	function shadowboxFormFocus() {
		$("#shadowbox input:first").focus();
	};


/*Brand panel expander*/
(function($){
	 $.fn.brandview = function(){
		$("div.Brands").addClass("LimitHeight");    
		$("a.ShowBrands").click(function(event){
			event.preventDefault();
			$(this).closest("div.Brands").removeClass("LimitHeight").addClass("UnlimitHeight");
		});    
		$("a.HideBrands").click(function(event){
			event.preventDefault();
			$(this).closest("div.Brands").addClass("LimitHeight").removeClass("UnlimitHeight");
		});
	 };
})(jQuery);
	
/*Brand panel expander*/
(function($){
	 $.fn.brandview = function(){
		$("div.Brands").addClass("LimitHeight");    
		$("a.ShowBrands").click(function(event){
			event.preventDefault();
			$(this).closest("div.Brands").removeClass("LimitHeight").addClass("UnlimitHeight");
		});    
		$("a.HideBrands").click(function(event){
			event.preventDefault();
			$(this).closest("div.Brands").addClass("LimitHeight").removeClass("UnlimitHeight");
		});
	 };
})(jQuery);

/*Filter icon switcher*/
(function($){
	 $.fn.filtericonswitcher = function(){
		$("div.ProductFilters a.ClearFilters").hover(
				function () {$(this).next().find("li.FilterSelected a").addClass("FilterOff");},
				function () {$(this).next().find("li.FilterSelected a").removeClass("FilterOff");}
			);
		$("div.ProductFilters table ul li a").hover(
				function () {$(this).closest("ul").find("li.FilterSelected a").addClass("FilterOff");},
				function () {$(this).closest("ul").find("li.FilterSelected a").removeClass("FilterOff");}
			);
	 };
})(jQuery);

/*Product view switcher*/
(function($){
	$.fn.switcher = function(){
        var cookie = jQuery.cookie('jquery_ash_default_product_view');
        if (cookie == null) {
            chooser(this, 'Default');
        }
        else {
            chooser(this, cookie);
        }
        clicker(this);
    };    
    function clicker($obj){
        $('#' + $obj.attr('id') + ' a').click(function(){
			$(this).blur();
            var target = $(this).attr('rel');
            chooser($obj, target);
            return false;
        });
    };    
    function chooser($obj, $target){
		$obj.closest('.Products').removeClass('Default Mini Detailed Grid').addClass($target);
		$('#' + $obj.attr('id') + ' a[rel!=' + $target + ']').removeClass('on');
		$('#' + $obj.attr('id') + ' a[rel=' + $target + ']').addClass("on");
		$.cookie('jquery_ash_default_product_view', $target, {
			expires: 365,
			path: '/'
		});
    };
})(jQuery);

/*Accordioniser*/
(function($){
	$.fn.accordioniser = function(){		
		$(".Accordion").accordion({
			header: "h3",
			autoheight: false,
			alwaysOpen: false
			})
			.find("h3").hover(
				function () {$(this).addClass("hover");},
				function () {$(this).removeClass("hover");}
			);
		$("#CategoryAccordion")
			.accordion({
				active: ".SelectedCategory",
				header: "h3",
				autoheight: false,
				alwaysOpen: false
			})
		$("span.Expander .ExpandAll").css("display", "inline");
		$("span.Expander .ExpandAll").click(function () {		
			$(this).closest(":header").nextAll(".ui-accordion").accordion("destroy");
			$(this).css("display", "none");
			$(this).next(".Collapse").css("display", "inline");
			});
		$("span.Expander .Collapse").click(function () {		
			$(this).closest(":header").nextAll("div.CategoryAccordion").accordion({
					active: ".SelectedCategory",
					header: "h3",
					autoheight: false,
					alwaysOpen: false
				});		
			$(this).closest(":header").nextAll("div.Accordion").accordion({
					header: "h3",
					autoheight: false,
					alwaysOpen: false
				});
			$(this).css("display", "none");
			$(this).prev(".ExpandAll").css("display", "inline");
			});
	 	};
})(jQuery);

/*
 * jQuery UI Accordion 1.6
 * Copyright (c) 2007 Jörn Zaefferer
 * http://docs.jquery.com/UI/Accordion
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.accordion.js 4876 2008-03-08 11:49:04Z joern.zaefferer $
 *
 */;(function($){$.ui=$.ui||{};$.fn.extend({accordion:function(options,data){var args=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof options=="string"){var accordion=$.data(this,"ui-accordion");accordion[options].apply(accordion,args);}else if(!$(this).is(".ui-accordion"))$.data(this,"ui-accordion",new $.ui.accordion(this,options));});},activate:function(index){return this.accordion("activate",index);}});$.ui.accordion=function(container,options){this.options=options=$.extend({},$.ui.accordion.defaults,options);this.element=container;$(container).addClass("ui-accordion");if(options.navigation){var current=$(container).find("a").filter(options.navigationFilter);if(current.length){if(current.filter(options.header).length){options.active=current;}else{options.active=current.parent().parent().prev();current.addClass("current");}}}options.headers=$(container).find(options.header).hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");});;options.active=findActive(options.headers,options.active);if(options.fillSpace){var maxHeight=$(container).parent().height();options.headers.each(function(){maxHeight-=$(this).outerHeight();});var maxPadding=0;options.headers.next().each(function(){maxPadding=Math.max(maxPadding,$(this).innerHeight()-$(this).height());}).height(maxHeight-maxPadding);}else if(options.autoheight){var maxHeight=0;options.headers.next().each(function(){maxHeight=Math.max(maxHeight,$(this).outerHeight());}).height(maxHeight);}options.headers.not(options.active||"").next().hide();options.active.parent().andSelf().addClass(options.selectedClass);if(options.event)$(container).bind((options.event)+".ui-accordion",clickHandler);};$.ui.accordion.prototype={activate:function(index){clickHandler.call(this.element,{target:findActive(this.options.headers,index)[0]});},enable:function(){this.options.disabled=false;},disable:function(){this.options.disabled=true;},destroy:function(){this.options.headers.next().css("display","");if(this.options.fillSpace||this.options.autoheight){this.options.headers.next().css("height","");}$.removeData(this.element,"ui-accordion");$(this.element).removeClass("ui-accordion").unbind(".ui-accordion");}};																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																											function scopeCallback(callback,scope){return function(){return callback.apply(scope,arguments);};}function completed(cancel){if(!$.data(this,"ui-accordion"))return;var instance=$.data(this,"ui-accordion");var options=instance.options;options.running=cancel?0:--options.running;if(options.running)return;if(options.clearStyle){options.toShow.add(options.toHide).css({height:"",overflow:""});}$(this).triggerHandler("change.ui-accordion",[options.data],options.change);}function toggle(toShow,toHide,data,clickedActive,down){var options=$.data(this,"ui-accordion").options;options.toShow=toShow;options.toHide=toHide;options.data=data;var complete=scopeCallback(completed,this);options.running=toHide.size()==0?toShow.size():toHide.size();if(options.animated){if(!options.alwaysOpen&&clickedActive){$.ui.accordion.animations[options.animated]({toShow:jQuery([]),toHide:toHide,complete:complete,down:down,autoheight:options.autoheight});}else{$.ui.accordion.animations[options.animated]({toShow:toShow,toHide:toHide,complete:complete,down:down,autoheight:options.autoheight});}}else{if(!options.alwaysOpen&&clickedActive){toShow.toggle();}else{toHide.hide();toShow.show();}complete(true);}}function clickHandler(event){var options=$.data(this,"ui-accordion").options;if(options.disabled)return false;if(!event.target&&!options.alwaysOpen){options.active.parent().andSelf().toggleClass(options.selectedClass);var toHide=options.active.next(),data={instance:this,options:options,newHeader:jQuery([]),oldHeader:options.active,newContent:jQuery([]),oldContent:toHide},toShow=options.active=$([]);toggle.call(this,toShow,toHide,data);return false;}var clicked=$(event.target);if(clicked.parents(options.header).length)while(!clicked.is(options.header))clicked=clicked.parent();var clickedActive=clicked[0]==options.active[0];if(options.running||(options.alwaysOpen&&clickedActive))return false;if(!clicked.is(options.header))return;options.active.parent().andSelf().toggleClass(options.selectedClass);if(!clickedActive){clicked.parent().andSelf().addClass(options.selectedClass);}var toShow=clicked.next(),toHide=options.active.next(),data={instance:this,options:options,newHeader:clicked,oldHeader:options.active,newContent:toShow,oldContent:toHide},down=options.headers.index(options.active[0])>options.headers.index(clicked[0]);options.active=clickedActive?$([]):clicked;toggle.call(this,toShow,toHide,data,clickedActive,down);return false;};function findActive(headers,selector){return selector!=undefined?typeof selector=="number"?headers.filter(":eq("+selector+")"):headers.not(headers.not(selector)):selector===false?$([]):headers.filter(":eq(0)");}$.extend($.ui.accordion,{defaults:{selectedClass:"selected",alwaysOpen:true,animated:'slide',event:"click",header:"a",autoheight:true,running:0,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase();}},animations:{slide:function(options,additions){options=$.extend({easing:"swing",duration:300},options,additions);if(!options.toHide.size()){options.toShow.animate({height:"show"},options);return;}var hideHeight=options.toHide.height(),showHeight=options.toShow.height(),difference=showHeight/hideHeight;options.toShow.css({height:0,overflow:'hidden'}).show();options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{step:function(now){var current=(hideHeight-now)*difference;if($.browser.msie||$.browser.opera){current=Math.ceil(current);}options.toShow.height(current);},duration:options.duration,easing:options.easing,complete:function(){if(!options.autoheight){options.toShow.css("height","auto");}options.complete();}});},bounceslide:function(options){this.slide(options,{easing:options.down?"bounceout":"swing",duration:options.down?1000:200});},easeslide:function(options){this.slide(options,{easing:"easeinout",duration:700})}}});})(jQuery);

/*
jquery.semantictabs.js
Creates semantic tabs from nested divs
Chris Yates

Inspired by Niall Doherty's jQuery Coda-Slider v1.1 - http://www.ndoherty.com/coda-slider

Usage:
$("#mycontainer").semantictabs({
  container:'panelcontainer',   //-- Selector of element containing all panels
  panel:'mypanelclass',         //-- Selector of individual panel body
  head:'headelement',           //-- Selector of element containing panel header
  active:':first',              //-- Which panel to activate by default
  activate:':eq(2)'             //-- Argument used to activate panel programmatically
});

1 Nov 2007
*/

jQuery.fn.semantictabs = function(passedArgsObj) {
  /* defaults */
  args = { container:'Tabber', panel:'TabberTab', head:':header:first', active:':first', activate:false, persist:false};

 /* override the defaults if necessary */
  for (var argName in passedArgsObj) {
    args[argName] = passedArgsObj[argName];
  }
  
  // Cookie  
	var cookie = jQuery.cookie('jquery_ash_tab');
  
  // Allow activation of specific tab, by index 
	if (args.activate) {
	  return this.each(function(){
	    var container = jQuery(this);
			container.find("." + args.container + " ." + args.panel).hide();
			container.find("ul.tabs li").removeClass("active");
			container.find("div." + args.panel + ":eq(" + args.activate + ")").show();
			container.find("ul.tabs li:eq(" + args.activate + ")").addClass("active");      
	  });
	} else {
    return this.each(function(){
  		// Load behavior
  		var container = jQuery(this);
		container.addClass("TabberLive");
  		container.find("." + args.panel).hide();
		
		if (args.persist == true) {
			container.find("div." + args.panel).eq(cookie).show();
			} else {
			container.find("div." + args.panel + args.active).show();
		};
		
		
		var tablist = "<ul class=\"tabs semtabs clearfix\">";
  		container.parent().find("." + args.container + " ." + args.panel).each( function() {
  		  var title = $(this).find(args.head).text();
  		  tablist = tablist + "<li><a href=\"javascript:void(0);\">"+title+"</a></li>";
		  $(this).find(args.head).hide();
  		});
		tablist = tablist + "</ul>";
		container.prepend(tablist);
  		
		if (args.persist == true) {
			container.find("ul li").eq(cookie).addClass("active");
			} else {
			container.find("ul li" + args.active).addClass("active");
		};
		
		
  		// Tab click behavior
  		container.find("ul.tabs li").click(function(){
													
			var targettab = container.find("ul.tabs li").index(this);
													
  			container.find("." + args.panel).hide();
  			container.find("ul.tabs li").removeClass("active");
  			container.find("div." + args.panel).eq(targettab).show();
  			jQuery(this).addClass("active");
			
			$.cookie('jquery_ash_tab', targettab, {
				expires: 365,
				path: '/'
			});
			
  		});                                
  		container.find("#remtabs").click(function(){
  			container.find("ul.tabs").remove();
  			container.find("." + args.container + " ." + args.panel).show();
  			container.find("#remtabs").remove();
  		});
  	});
	}
		
};

/*
 * jQuery Cycle Lite Plugin
 * http://malsup.com/jquery/cycle/lite/
 * Copyright (c) 2008 M. Alsup
 * Version: 1.0 (06/08/2008)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.2.3 or later
 */
;(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute",top:0,left:0}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery);

/**
 * 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;
    }
};

/**
 *  jquery.spin-button
 *  (c) 2008 Semooh (http://semooh.jp/)
 *
 *  Dual licensed under the MIT (MIT-LICENSE.txt)
 *  and GPL (GPL-LICENSE.txt) licenses.
 *
 **/
(function($){
  $.fn.extend({
    spin: function(opt){
      return this.each(function(){
        opt = $.extend({
            imageBasePath: '/images/css/',
            spinBtnImage: 'spin-button.gif',
            spinUpImage: 'spin-up.gif',
            spinDownImage: 'spin-down.gif',
            interval: 1,
            max: null,
            min: null,
            timeInterval: 400,
            timeBlink: 200
          }, opt || {});
        
        var txt = $(this);
		var disabler = $(this).attr('disabled');
		
		$(this).change(function () {
			var val = txt.val();
				if(!isNaN(val)){
					val = parseFloat(val);
					if(val>0) $(txt).closest('td').addClass('Selected');
					if(val<1) $(txt).closest('td').removeClass('Selected');
				}
		});
        
        var spinBtnImage = opt.imageBasePath+opt.spinBtnImage;
        var btnSpin = new Image();
        btnSpin.src = spinBtnImage;
        var spinUpImage = opt.imageBasePath+opt.spinUpImage;
        var btnSpinUp = new Image();
        btnSpinUp.src = spinUpImage;
        var spinDownImage = opt.imageBasePath+opt.spinDownImage;
        var btnSpinDown = new Image();
        btnSpinDown.src = spinDownImage;
        
        var btn = $(document.createElement('img'));
        btn.attr('src', spinBtnImage);
        btn.css({verticalAlign: 'bottom', padding: 0, margin: 0});
        txt.after(btn);
        txt.css({marginRight:0, paddingRight:0});
        		
		  if(disabler!=true) {
			function spin(vector){
			  var val = txt.val();
				  if(!isNaN(val)){
					val = parseFloat(val) + (vector*opt.interval);
					$(txt).change();
					if(opt.min!=null && val<opt.min) val=opt.min;
					if(opt.min!=null && val>opt.max) val=opt.max;
					if(val != txt.val()){
					  txt.val(val);
					  txt.change();
					  src = (vector > 0 ? spinUpImage : spinDownImage);
					  btn.attr('src', src);
					  if(opt.timeBlink<opt.timeInterval)
						setTimeout(function(){btn.attr('src', spinBtnImage);}, opt.timeBlink);
					}
				  }
			}
			
				btn.mousedown(function(e){
					  var pos = e.pageY - btn.offset().top;
					  var vector = (btn.height()/2 > pos ? 1 : -1);
					  (function(){
						spin(vector);
						var tk = setTimeout(arguments.callee, opt.timeInterval);
						$(document).one('mouseup', function(){
						  clearTimeout(tk); btn.attr('src', spinBtnImage);
						});
					  })();
					  return false;
				});
			};
		  });
    }
  });
})(jQuery);

/*Columnizer - http://plugins.jquery.com/project/Columnizer */
(function($){$.fn.columnize=function(options){var defaults={width:400,columns:false,buildOnce:false,overflow:false};var options=$.extend(defaults,options);return this.each(function(){var $inBox=$(this);var maxHeight=$inBox.height();var $cache=$('<div></div>');var lastWidth=0;var columnizing=false;var kids=$inBox[0].childNodes;$inBox.append($(kids));$cache.append($inBox.children().clone());columnizeIt();if(!options.buildOnce){$(window).resize(function(){if(!options.buildOnce&&$.browser.msie){if($inBox.data("timeout")){clearTimeout($inBox.data("timeout"));}
$inBox.data("timeout",setTimeout(columnizeIt,200));}else if(!options.buildOnce){columnizeIt();}else{}});}
function columnize($putInHere,$pullOutHere,$parentColumn,height){while($parentColumn.height()<height&&$pullOutHere[0].childNodes.length){$putInHere.append($pullOutHere[0].childNodes[0]);}
if($putInHere[0].childNodes.length==0)return;var kids=$putInHere[0].childNodes;var lastKid=kids[kids.length-1];$putInHere[0].removeChild(lastKid);var $item=$(lastKid);if($item[0].nodeType==3){var oText=$item[0].nodeValue;var counter2=options.width/18;if(options.accuracy)
counter2=options.accuracy;var columnText;var latestTextNode=null;while($parentColumn.height()<height&&oText.length){if(oText.indexOf(' ',counter2)!='-1'){columnText=oText.substring(0,oText.indexOf(' ',counter2));}else{columnText=oText;}
latestTextNode=document.createTextNode(columnText);$putInHere.append(latestTextNode);if(oText.length>counter2){oText=oText.substring(oText.indexOf(' ',counter2));}else{oText="";}}
if($parentColumn.height()>=height&&latestTextNode!=null){$putInHere[0].removeChild(latestTextNode);oText=latestTextNode.nodeValue+oText;}
if(oText.length){$item[0].nodeValue=oText;}else{return false;}}
if($pullOutHere.children().length){$pullOutHere.prepend($item);}else{$pullOutHere.append($item);}
return $item[0].nodeType==3;}
function split($putInHere,$pullOutHere,$parentColumn,height){if($pullOutHere.children().length){$cloneMe=$pullOutHere.children(":first");$clone=$cloneMe.clone();if($clone.attr("nodeType")==1&&!$clone.hasClass("dontend")){$putInHere.append($clone);if($clone.is("img")&&$parentColumn.height()<height+20){$cloneMe.remove();}else if(!$cloneMe.hasClass("dontsplit")&&$parentColumn.height()<height+20){$cloneMe.remove();}else if($clone.is("img")||$cloneMe.hasClass("dontsplit")){$clone.remove();}else{$clone.empty();if(!columnize($clone,$cloneMe,$parentColumn,height)){if($cloneMe.children().length){split($clone,$cloneMe,$parentColumn,height);}}}}}}
function singleColumnizeIt(){if($inBox.data("columnized")&&$inBox.children().length==1){return;}
$inBox.data("columnized",true);$inBox.data("columnizing",true);$inBox.empty();$inBox.append($("<div class='first last column' style='width:98%; padding: 3px; float: left;'></div>"));$col=$inBox.children().eq($inBox.children().length-1);$destroyable=$cache.clone();if(options.overflow){targetHeight=options.overflow.height;columnize($col,$destroyable,$col,targetHeight);if(!$destroyable.children().find(":first-child").hasClass("dontend")){split($col,$destroyable,$col,targetHeight);}
while(checkDontEndColumn($col.children(":last").get(0))){var $lastKid=$col.children(":last");$lastKid.remove();$destroyable.prepend($lastKid);}
var html="";var div=document.createElement('DIV');while($destroyable[0].childNodes.length>0){var kid=$destroyable[0].childNodes[0];for(var i=0;i<kid.attributes.length;i++){if(kid.attributes[i].nodeName.indexOf("jQuery")==0){kid.removeAttribute(kid.attributes[i].nodeName);}}
div.innerHTML="";div.appendChild($destroyable[0].childNodes[0]);html+=div.innerHTML;}
var overflow=$(options.overflow.id)[0];overflow.innerHTML=html;}else{$col.append($destroyable);}
$inBox.data("columnizing",false);if(options.overflow){options.overflow.doneFunc();}}
function checkDontEndColumn(dom){if(dom.nodeType!=1)return false;if($(dom).hasClass("dontend"))return true;if(dom.childNodes.length==0)return false;return checkDontEndColumn(dom.childNodes[dom.childNodes.length-1]);}
function columnizeIt(){if(lastWidth==$inBox.width())return;lastWidth=$inBox.width();var numCols=Math.round($inBox.width()/options.width);if(options.columns)numCols=options.columns;if(numCols<=1){return singleColumnizeIt();}
if($inBox.data("columnizing"))return;$inBox.data("columnized",true);$inBox.data("columnizing",true);$inBox.empty();$inBox.append($("<div style='width:"+(Math.round(100/numCols)-2)+"%; float: left;'></div>"));$col=$inBox.children(":last");$col.append($cache.clone());maxHeight=$col.height();$inBox.empty();var targetHeight=maxHeight/numCols;var firstTime=true;var maxLoops=3;var scrollHorizontally=false;if(options.overflow){maxLoops=1;targetHeight=options.overflow.height;}else if(options.height&&options.width){maxLoops=1;targetHeight=options.height;scrollHorizontally=true;}
for(var loopCount=0;loopCount<maxLoops;loopCount++){$inBox.empty();var $destroyable=$cache.clone();$destroyable.css("visibility","hidden");for(var i=0;i<numCols;i++){var className=(i==0)?"first column":"column";var className=(i==numCols-1)?("last "+className):className;$inBox.append($("<div class='"+className+"' style='width:"+(Math.round(100/numCols)-2)+"%; float: left;'></div>"));}
var i=0;while(i<numCols-(options.overflow?0:1)||scrollHorizontally&&$destroyable.children().length){if($inBox.children().length<=i){$inBox.append($("<div class='"+className+"' style='width:"+(Math.round(100/numCols)-2)+"%; float: left;'></div>"));}
var $col=$inBox.children().eq(i);columnize($col,$destroyable,$col,targetHeight);if(!$destroyable.children().find(":first-child").hasClass("dontend")){split($col,$destroyable,$col,targetHeight);}else{}
while(checkDontEndColumn($col.children(":last").get(0))){var $lastKid=$col.children(":last");$lastKid.remove();$destroyable.prepend($lastKid);}
i++;}
if(options.overflow&&!scrollHorizontally){var html="";var div=document.createElement('DIV');while($destroyable[0].childNodes.length>0){var kid=$destroyable[0].childNodes[0];for(var i=0;i<kid.attributes.length;i++){if(kid.attributes[i].nodeName.indexOf("jQuery")==0){kid.removeAttribute(kid.attributes[i].nodeName);}}
div.innerHTML="";div.appendChild($destroyable[0].childNodes[0]);html+=div.innerHTML;}
var overflow=$(options.overflow.id)[0];overflow.innerHTML=html;}else if(!scrollHorizontally){$col=$inBox.children().eq($inBox.children().length-1);while($destroyable.children().length)$col.append($destroyable.children(":first"));var afterH=$col.height();var diff=afterH-targetHeight;var totalH=0;var min=10000000;var max=0;$inBox.children().each(function($inBox){return function($item){var h=$inBox.children().eq($item).height();totalH+=h;if(h>max)max=h;if(h<min)min=h;}}($inBox));var avgH=totalH/numCols;if(max-min>30){targetHeight=avgH+30;}else if(Math.abs(avgH-targetHeight)>20){targetHeight=avgH;}else{loopCount=maxLoops;}}else{$inBox.children().each(function(i){$col=$inBox.children().eq(i);$col.width(options.width+"px");if(i==0){$col.addClass("first");}else if(i==$inBox.children().length-1){$col.addClass("last");}else{$col.removeClass("first");$col.removeClass("last");}});$inBox.width($inBox.children().length*options.width+"px");}
$inBox.append($("<br style='clear:both;'>"));}
$inBox.find('.column').find(':first.removeiffirst').remove();$inBox.find('.column').find(':last.removeiflast').remove();$inBox.data("columnizing",false);if(options.overflow){options.overflow.doneFunc();}}});};})(jQuery);