(function(a){a("html").addClass("stylish-select");Array.prototype.indexOf=function(c,d){for(var b=(d||0);b<this.length;b++){if(this[b]==c){return b}}};a.fn.extend({getSetSSValue:function(b){if(b){a(this).val(b).change();return this}else{return a(this).find(":selected").val()}},resetSS:function(){var b=a(this).data("ssOpts");$this=a(this);$this.next().remove();$this.unbind().sSelect(b)}});a.fn.sSelect=function(b){return this.each(function(){var i={defaultText:"Please select",animationSpeed:0,ddMaxHeight:""};var l=a.extend(i,b),e=a(this),j=a('<div class="selectedTxt"></div>'),r=a('<div class="newListSelected" tabindex="0"></div>'),z=a('<ul class="newList"></ul>'),t=-1,d=-1,m=[],w=false,v=false,x;a(this).data("ssOpts",b);r.insertAfter(e);j.prependTo(r);z.appendTo(r);e.hide();if(e.children("optgroup").length==0){e.children().each(function(B){var C=a(this).text();var A=a(this).val();m.push(C.charAt(0).toLowerCase());if(a(this).attr("selected")==true){l.defaultText=C;d=B}z.append(a('<li><a href="JavaScript:void(0);">'+C+"</a></li>").data("key",A))});x=z.children().children()}else{e.children("optgroup").each(function(){var A=a(this).attr("label"),C=a('<li class="newListOptionTitle">'+A+"</li>");C.appendTo(z);var B=a("<ul></ul>");B.appendTo(C);a(this).children().each(function(){++t;var E=a(this).text();var D=a(this).val();m.push(E.charAt(0).toLowerCase());if(a(this).attr("selected")==true){l.defaultText=E;d=t}B.append(a('<li><a href="JavaScript:void(0);">'+E+"</a></li>").data("key",D))})});x=z.find("ul li a")}var o=z.height(),n=r.height(),y=x.length;if(d!=-1){h(d,true)}else{j.text(l.defaultText)}function p(){var B=r.offset().top,A=jQuery(window).height(),C=jQuery(window).scrollTop();if(o>parseInt(l.ddMaxHeight)){o=parseInt(l.ddMaxHeight)}B=B-C;if(B+o>=A){z.css({top:"-"+o+"px",height:o});e.onTop=true}else{z.css({top:n+"px",height:o});e.onTop=false}}p();a(window).resize(function(){p()});a(window).scroll(function(){p()});function s(){r.css("position","relative")}function c(){r.css("position","static")}j.click(function(A){A.stopPropagation();a(".newList").not(a(this).next()).hide().parent().removeClass("newListSelFocus");z.toggle();s();x.eq(d).focus()});x.click(function(B){var A=a(B.target);d=x.index(A);v=true;h(d);z.hide();r.css("position","static")});x.hover(function(B){var A=a(B.target);A.addClass("newListHover")},function(B){var A=a(B.target);A.removeClass("newListHover")});function h(A,D){x.removeClass("hiLite").eq(A).addClass("hiLite");if(z.is(":visible")){x.eq(A).focus()}var C=x.eq(A).text();var B=x.eq(A).parent().data("key");if(D==true){e.val(B);j.text(C);return false}e.val(B);e.change();j.text(C)}e.change(function(A){$targetInput=a(A.target);if(v==true){v=false;return false}$currentOpt=$targetInput.find(":selected");d=$targetInput.find("option").index($currentOpt);h(d,true)});function q(A){A.onkeydown=function(D){var C;if(D==null){C=event.keyCode}else{C=D.which}v=true;switch(C){case 40:case 39:u();return false;break;case 38:case 37:k();return false;break;case 33:case 36:g();return false;break;case 34:case 35:f();return false;break;case 13:case 27:z.hide();c();return false;break}keyPressed=String.fromCharCode(C).toLowerCase();var B=m.indexOf(keyPressed);if(typeof B!="undefined"){++d;d=m.indexOf(keyPressed,d);if(d==-1||d==null||w!=keyPressed){d=m.indexOf(keyPressed)}h(d);w=keyPressed;return false}}}function u(){if(d<(y-1)){++d;h(d)}}function k(){if(d>0){--d;h(d)}}function g(){d=0;h(d)}function f(){d=y-1;h(d)}r.click(function(){q(this)});r.focus(function(){a(this).addClass("newListSelFocus");q(this)});r.blur(function(){a(this).removeClass("newListSelFocus")});a("body").click(function(){r.removeClass("newListSelFocus");z.hide();c()});j.hover(function(B){var A=a(B.target);A.parent().addClass("newListSelHover")},function(B){var A=a(B.target);A.parent().removeClass("newListSelHover")});z.css("left","0").hide()})}})(jQuery);;(function($){var reEscape=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\"].join("|\\")+")","g");function fnFormatResult(value,data,currentValue){var pattern="("+currentValue.replace(reEscape,"\\$1")+")";return value.replace(new RegExp(pattern,"gi"),"<strong>$1</strong>")}function Autocomplete(el,options){this.el=$(el);this.el.attr("autocomplete","off");this.suggestions=[];this.data=[];this.badQueries=[];this.selectedIndex=-1;this.currentValue=this.el.val();this.intervalId=0;this.cachedResponse=[];this.onChangeInterval=null;this.ignoreValueChange=false;this.serviceUrl=options.serviceUrl;this.isLocal=false;this.options={autoSubmit:false,minChars:1,maxHeight:300,deferRequestBy:0,width:0,highlight:true,params:{},fnFormatResult:fnFormatResult,delimiter:null,zIndex:9999};this.initialize();this.setOptions(options)}$.fn.autocomplete=function(options){return new Autocomplete(this.get(0)||$("<input />"),options)};Autocomplete.prototype={killerFn:null,initialize:function(){var me,uid,autocompleteElId;me=this;uid=Math.floor(Math.random()*1048576).toString(16);autocompleteElId="Autocomplete_"+uid;this.killerFn=function(e){if($(e.target).parents(".autocomplete").size()===0){me.killSuggestions();me.disableKillerFn()}};if(!this.options.width){this.options.width=this.el.width()}this.mainContainerId="AutocompleteContainter_"+uid;$('<div id="'+this.mainContainerId+'" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="'+autocompleteElId+'" style="display:none; width:300px;"></div></div></div>').appendTo("body");this.container=$("#"+autocompleteElId);this.fixPosition();if(window.opera){this.el.keypress(function(e){me.onKeyPress(e)})}else{this.el.keydown(function(e){me.onKeyPress(e)})}this.el.keyup(function(e){me.onKeyUp(e)});this.el.blur(function(){me.enableKillerFn()});this.el.focus(function(){me.fixPosition()})},setOptions:function(options){var o=this.options;$.extend(o,options);if(o.lookup){this.isLocal=true;if($.isArray(o.lookup)){o.lookup={suggestions:o.lookup,data:[]}}}$("#"+this.mainContainerId).css({zIndex:o.zIndex});this.container.css({maxHeight:o.maxHeight+"px",width:o.width})},clearCache:function(){this.cachedResponse=[];this.badQueries=[]},disable:function(){this.disabled=true},enable:function(){this.disabled=false},fixPosition:function(){var offset=this.el.offset();$("#"+this.mainContainerId).css({top:(offset.top+this.el.innerHeight())+"px",left:offset.left+"px"})},enableKillerFn:function(){var me=this;$(document).bind("click",me.killerFn)},disableKillerFn:function(){var me=this;$(document).unbind("click",me.killerFn)},killSuggestions:function(){var me=this;this.stopKillSuggestions();this.intervalId=window.setInterval(function(){me.hide();me.stopKillSuggestions()},300)},stopKillSuggestions:function(){window.clearInterval(this.intervalId)},onKeyPress:function(e){if(this.disabled||!this.enabled){return}switch(e.keyCode){case 27:this.el.val(this.currentValue);this.hide();break;case 9:case 13:if(this.selectedIndex===-1){this.hide();return}this.select(this.selectedIndex);if(e.keyCode===9){return}break;case 38:this.moveUp();break;case 40:this.moveDown();break;default:return}e.stopImmediatePropagation();e.preventDefault()},onKeyUp:function(e){if(this.disabled){return}switch(e.keyCode){case 38:case 40:return}clearInterval(this.onChangeInterval);if(this.currentValue!==this.el.val()){if(this.options.deferRequestBy>0){var me=this;this.onChangeInterval=setInterval(function(){me.onValueChange()},this.options.deferRequestBy)}else{this.onValueChange()}}},onValueChange:function(){clearInterval(this.onChangeInterval);this.currentValue=this.el.val();var q=this.getQuery(this.currentValue);this.selectedIndex=-1;if(this.ignoreValueChange){this.ignoreValueChange=false;return}if(q===""||q.length<this.options.minChars){this.hide()}else{this.getSuggestions(q)}},getQuery:function(val){var d,arr;d=this.options.delimiter;if(!d){return $.trim(val)}arr=val.split(d);return $.trim(arr[arr.length-1])},getSuggestionsLocal:function(q){var ret,arr,len,val,i;arr=this.options.lookup;len=arr.suggestions.length;ret={suggestions:[],data:[]};q=q.toLowerCase();for(i=0;i<len;i++){val=arr.suggestions[i];if(val.toLowerCase().indexOf(q)===0){ret.suggestions.push(val);ret.data.push(arr.data[i])}}return ret},getSuggestions:function(q){var cr,me,fn;cr=this.isLocal?this.getSuggestionsLocal(q):this.cachedResponse[q];if(cr&&$.isArray(cr.suggestions)){this.suggestions=cr.suggestions;this.data=cr.data;this.suggest()}else{if(!this.isBadQuery(q)){me=this;me.options.params.query=q;if(typeof this.xhr!=='undefined'){this.xhr.abort();};this.xhr=$.get(this.serviceUrl,me.options.params,function(txt){me.processResponse(txt)},"text")}}},isBadQuery:function(q){var i=this.badQueries.length;while(i--){if(q.indexOf(this.badQueries[i])===0){return true}}return false},hide:function(){this.enabled=false;this.selectedIndex=-1;this.container.hide()},suggest:function(){var me=this,len,div,f,v,i,s,mOver,mClick,fn;fn=me.options.onResponse;if($.isFunction(fn)){fn()}if(this.suggestions.length===0){this.hide();return}len=this.suggestions.length;f=this.options.fnFormatResult;v=this.getQuery(this.currentValue);mOver=function(xi){return function(){me.activate(xi)}};mClick=function(xi){return function(){me.select(xi)}};this.container.hide().empty();for(i=0;i<len;i++){s=this.suggestions[i];div=$((me.selectedIndex===i?'<div class="selected"':"<div")+' title="'+s+'">'+f(s,this.data[i],v)+"</div>");div.mouseover(mOver(i));div.click(mClick(i));this.container.append(div)}this.enabled=true;this.container.show()},processResponse:function(text){var response;try{response=eval("("+text+")")}catch(err){return}if(!$.isArray(response.data)){response.data=[]}if(!this.options.noCache){this.cachedResponse[response.query]=response;if(response.suggestions.length===0){this.badQueries.push(response.query)}}if(response.query===this.getQuery(this.currentValue)){this.suggestions=response.suggestions;this.data=response.data;this.suggest()}},activate:function(index){var divs,activeItem;divs=this.container.children();if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){$(divs.get(this.selectedIndex)).removeClass()}this.selectedIndex=index;if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){activeItem=divs.get(this.selectedIndex);$(activeItem).addClass("selected")}return activeItem},deactivate:function(div,index){div.className="";if(this.selectedIndex===index){this.selectedIndex=-1}},select:function(i){var selectedValue,f;selectedValue=this.suggestions[i];if(selectedValue){this.el.val(selectedValue);if(this.options.autoSubmit){f=this.el.parents("form");if(f.length>0){f.get(0).submit()}}this.ignoreValueChange=true;this.hide();this.onSelect(i)}},moveUp:function(){if(this.selectedIndex===-1){return}if(this.selectedIndex===0){this.container.children().get(0).className="";this.selectedIndex=-1;this.el.val(this.currentValue);return}this.adjustScroll(this.selectedIndex-1)},moveDown:function(){if(this.selectedIndex===(this.suggestions.length-1)){return}this.adjustScroll(this.selectedIndex+1)},adjustScroll:function(i){var activeItem,offsetTop,upperBound,lowerBound;activeItem=this.activate(i);offsetTop=activeItem.offsetTop;upperBound=this.container.scrollTop();lowerBound=upperBound+this.options.maxHeight-25;if(offsetTop<upperBound){this.container.scrollTop(offsetTop)}else{if(offsetTop>lowerBound){this.container.scrollTop(offsetTop-this.options.maxHeight+25)}}this.el.val(this.getValue(this.suggestions[i]))},onSelect:function(i){var me,fn,s,d;me=this;fn=me.options.onSelect;s=me.suggestions[i];d=me.data[i];me.el.val(me.getValue(s));if($.isFunction(fn)){fn(s,d,me.el)}},getValue:function(value){var del,currVal,arr,me;me=this;del=me.options.delimiter;if(!del){return value}currVal=me.currentValue;arr=currVal.split(del);if(arr.length===1){return value}return currVal.substr(0,currVal.length-arr[arr.length-1].length)+value}}}(jQuery));;var overlay=false,container=false,content=false,close=false,source,defaults={showClose:true,inline:false,css:{width:250,height:100},autoResize:false},popup_close=function(e){content.html('');container.fadeOut(150,function(){container.css({backgroundPosition:'center'});overlay.fadeOut(50);});if(e)
{e.preventDefault();}
$(document).unbind('keydown');},show_content=function(autoResize,css,wWidth,wHeight,sTop){if(autoResize)
{var cWidth=css.width||content.width();var cHeight=css.height||content.height();container.animate({width:cWidth,height:cHeight,left:wWidth/2-cWidth/2,top:Math.max(sTop,wHeight/2-cHeight/2+sTop)},350,function(){content.fadeIn(350);});}
else
{content.fadeIn(350);}};function popup(source,options,event)
{var settings=$.extend(true,{},defaults,options);var b=$('body');var w=$(window);var wWidth=w.width();var wHeight=w.height();var sTop=w.scrollTop();if(!source)
{source=settings.html;settings.inline=true;}
else
if(typeof source=='object')
{source=source.attr('href');}
else
{source=$(source).html();settings.inline=true;}
if(!container)
{b.append('<div class="popup-container"></div>');container=$('div.popup-container');}
if(!content)
{container.append('<div class="popup-content"></div>');content=$('div.popup-content');}
if(!overlay)
{b.append('<div class="popup-overlay"></div>');overlay=$('div.popup-overlay');overlay.click(function(){popup_close(null)});}
if(!close&&settings.showClose)
{container.prepend('<a class="popup-close"><span>Close</span></a>');close=$('a.popup-close');close.click(function(){popup_close(null)});}
$(document).keydown(function(e){if(e.which==27)
{popup_close(e);}});content.text('').hide();if(settings.inline)
{container.css({backgroundPosition:-100});content.html(source);}
else
{content.load(source,function(xhr,content){container.css({backgroundPosition:-100});show_content(settings.autoResize,options.css||{},wWidth,wHeight,sTop);});}
overlay.fadeTo(150,0.3,function(){settings.css.left=wWidth/2-settings.css.width/2;settings.css.top=Math.max(sTop,wHeight/2-settings.css.height/2+sTop);container.css(settings.css).fadeIn(150,function(){if(settings.inline)
{show_content(settings.autoResize,options.css||{},wWidth,wHeight,sTop);}});});if(event)
{event.preventDefault();}};function logout()
{window.location='/auth/logout';}
$(document).ready(function(){$('input').first().focus();$("a[href*='http://']:not([href*='"+location.hostname+"'])").click(function(){this.target="_blank";});$('a.print').live('click',function(){window.open(this.href,'print','width=700,height=700,location=0,menubar=0,'+'status=0,toolbar=0,modal=1,allwaysRaised=1');return false;});$('input#dontshow').live('change',function(){var message=$(this).attr('class');$.get('/account/showmessage/key/'+message+'/value/no',function(){$('div.help_message').fadeOut(500);});});$('#check_all').click(function(){$('#filters input').attr('checked',true);});$('#uncheck_all').click(function(){$('#filters input').attr('checked',false);});$("#filters ul").hide();$('#searchform legend').show();$("#filters legend").click(function(){$("#filters ul").slideToggle();});$('#filters ul li.buttons a.hide').show().click(function(){$("#filters ul").slideUp();});$.address.init(function(){$('#searchform, ul#results-tabs li a:not(.manage), #search-results tr th a, form#sort_options,'+'#search-results .product-name a, #search-results #pagination li a, #add-pantry-to-cart').address(function(){if(this.tagName=='A')
{return $(this).attr('href').replace(/http:\/\/.+?\//,'');}
else if(this.tagName=='FORM')
{return $(this).attr('action')+'?'+$(this).serialize();}});}).change(function(e){var page=$.address.pathNames()[1];if(!isNaN(page)||page=='page'){page='search';}
if(page=='addpantrytocart'){page='cart';}
var query=$.address.queryString();var scrollTop=$(window).scrollTop();var scrollTo=$("#content").offset().top;if(ajax_address(page,query))
{$('#results-tabs li.selected').removeClass('selected');$('#results-tabs li#'+page+'_tab').addClass('selected');show_loading();if(scrollTop>scrollTo)
{$('html, body').animate({scrollTop:scrollTo},1000);}
var xhr=ajax_page(page);}});function ajax_page(page,query_string){var path=$.address.path();if(path==''){path='/catalog/'+page;}
if(typeof query_string=='undefined'){query_string='';}
return $.get(path+query_string,$.address.queryString(),function(data,status){if(data.match(/^(<!DOCTYPE|expired|.*SoapFault)/)){window.location='/auth/expired';return;}
if(data!=''||!data.match(/^<!DOCTYPE/)){$('#search-results').html(data);}
if(page=='cart'){deliver_datepicker();}
if(page=='pantry'){table_reorder();}
if(page=='favourites'){table_reorder();}});}
function show_loading(){$('#search-results').append('<div id="search_load">Loading</div>');$('#search-results #search_load').show();$('#search-results #text, #search-results :not(#search_load)').css({opacity:0.5});}
$('#search-results th a').live('click',function(){$('#results-tabs li.selected a').attr('href',$(this).attr('href'));});function ajax_address(page,query)
{if($.inArray(page,['search','pantry','favourites','history','cart'])>=0)
{return true;}
if(query!=='')
{return true;}}
$('ul#quick-tabs li:last').css('margin','0');$('#quick-tabs li:not(#cart-quickview) div').hide();$('#quick-tabs li h2').click(function(){$(this).next("div").slideToggle();});$('ul#faqs div').hide();$('ul#faqs h2').click(function(){$(this).next("div").slideToggle();});$('#select-add input:radio:checked').parent().addClass("selected");$('#select-add input:radio').click(function(){$('#select-add input:radio').parent().removeClass("selected");$(this).parent().addClass('selected');});$('.in-favourites a').live('click',function(){var type,trigger=$(this);if(trigger.hasClass('pantry')){type='pantry';}
else if(trigger.hasClass('favourites')){type='favourites';}
trigger.toggleClass('loading');$.get($(this).attr('href'),function(id){$('table.'+type+' tr#pid_'+id).fadeOut(200);trigger.toggleClass('loading').toggleClass('not');});return false;});var getOrder=function(){$('table.custom_sort tbody').children('tr:not(.nodrag)').each(function(i,e){var id=e.id.replace(/pid_/,'');var position=parseInt(i,10)+1;productList[id].position=position;});};var updatePantryOrder=function(){var products=[],pantry=$('#current_pantry').val();$('table.pantry tr:not(.nodrag)').each(function(){var id=this.id.replace(/pid_/,'');products.push({"ProductID":id,"unit":productList[id].pantries[pantry].unit,"carton":productList[id].pantries[pantry].carton});});$.post('/catalog/updatepantries',{"type":'Reposition',"name":pantry,"products":products},function(){});},updateFavouritesOrder=function(from,to){$.get('/product/setposition?type=favourites&current='+from+'&new='+to,function(r){if(r==0){getOrder();}});},table_reorder=function(){$('table.custom_sort').tableDnD({onDrop:function(table,row){var type=$(row).parents('table').attr('class').split(' ')[0];if(type=='pantry'){updatePantryOrder();}else{updateFavouritesOrder(productList[row.id.replace(/pid_/,'')].position,$('table.custom_sort tbody').children().index($(row)));}},onDragClass:'dragging'});};table_reorder();$('#pantry_tab.selected').live('mouseenter',function(){$('#pantry-list').show();}).live('mouseleave',function(){$('#pantry-list').hide();});$('#pantry-list a.pantry').live('click',function(){$('#pantry_tab .pantry-name').text($(this).text());$('#pantry_tab > a:first').attr('href',this.href);});$('#pantry-list .manage').live('click',function(e){popup($(this),{css:{width:310}},e);});$('#new-pantry').live('click',function(){var context=$(this).parent();var rows=$('table tr.pantry:not(.new)',context);if(rows.length>9){alert('Maximum pantries reached');return false;}
rows.last().after($('tr.new',context).clone());$('tr:last',context).attr('class','pantry p'+(rows.length+1));$('tr:last input[name=id]',context).val(rows.length+1);$('tr:last input[name=name]',context).focus();return false;});$('.manage-pantries input[name=name]').live('focus',function(){$(this).select().prev().removeClass('hidden');});$('.manage-pantries input[name=name]').live('blur',function(){$(this).prev().addClass('hidden');});$('.manage-pantries form').live('submit',function(){if(this.name.value==''){alert('Please enter a name');return false;}
var type=this.type.value,old_name=this.old_name.value,name=this.name.value;$.post(this.action,$(this).serialize(),function(){if(type=='Rename'){$('#pantry-list a[href$='+old_name+']').text(name).attr('href','/catalog/pantry/show/'+encodeURI(name));}else{var rows=$('#pantry-list li.pantry-entry');rows.last().after(rows.last().clone());$('.pantry-entry:last a').attr('class','pantry p'+(rows.length+1)).text(name).attr('href','/catalog/pantry/show/'+encodeURI(name));}});$('.manage-pantries input').blur();return false;});$('.manage-pantries a.delete').live('click',function(){if($('.popup-content .manage-pantries tr').length<3){alert('You can\'t delete all your pantries!');return false;}
$.get(this.href);$(this).parents('tr').fadeOut(function(){$(this).remove();});return false;});$('.pantry-select input.type + label').live('click',function(){var type=($(this).prev().val()=='unit')?'carton':'unit';$(this).removeClass('carton unit').addClass(type).text(type).prev().val(type);});var before_pantries={};$('.in-pantry').live('mouseenter',function(){before_pantries[$('input[name=productid]',this).val()]=$('form',this).serialize();$('.pantry-select',this).show();}).live('mouseleave',function(){$('.pantry-select',this).hide();$('.pantry-select li.current').removeClass('current');$('form',this).submit();});$('.pantry-select li a.pantry.not').live('click',function(e){$('.pantry-select li.current').removeClass('current');$(this).removeClass('not').parent().addClass('current');pantry_quantity($('input.quantity',$(this).next()),1);return false;});$('.pantry-select li.current a.pantry:not(.not)').live('click',function(e){$(this).addClass('not').parent().removeClass('current');pantry_quantity($('input.quantity',$(this).next()),0);return false;});$('.pantry-select li:not(.current) a.pantry:not(.not)').live('click',function(e){$('.pantry-select li.current').removeClass('current');$(this).removeClass('not').parent().addClass('current');});$('.in-pantry form').live('submit',function(){var data=$(this).serialize();var current_pantry=$('#current_pantry').val();if($('#current_pantry').length>0){$('.current_quantity',$(this).next()).text($('li[title='+current_pantry+'] input.quantity',this).val()+$('li[title='+current_pantry+'] input.type',this).val()[0]);}
if($('input.quantity:not([value=]):not([value=0])',this).length<1){$(this).next().addClass('not');}else{$(this).next().removeClass('not');}
if(data==before_pantries[$('input[name=productid]',this).val()]){return false;}
$.post(this.action,data,function(r){for(product in r){$('#pid_'+r[product].ProductID).find('li[title='+r[product].PantryName+'] input.position').val(r[product].PositionNum);};},'json');return false;});function pantry_quantity(input,quantity){input.val(quantity).change();}
$('.pantry-select ol').live('mousewheel',function(e,d){d=(d>0)?1:-1;var input=$('.current input.quantity',this);var quantity=Math.max(0,Math.min(9999,parseInt(input.val(),10)+parseInt(d,10)));pantry_quantity(input,quantity);return false;});$('.pantry-select ol input').live('change',function(){if(this.value==0){$(this).parent().prev().addClass('not');}else{$(this).parent().prev().removeClass('not');}});$('.pantry-select ol input').focus(function(){$(this).select();});$('#save-to-pantry').live('submit',function(){console.log(pantries.length);if($('input[name=pantry_name]',this).val()==''){alert('Please enter a pantry name');$(this.pantry_name).focus();return false;}
if($.inArray(this.pantry_name.value,pantries)>=0){if(!confirm('This will replace pantry '+this.pantry_name.value+'. Are you sure?')){return false;}}else{if(pantries.length>=10){alert('Maximum pantries reached');return false;}}});$('#bykeyword').keypress(function(e){var val=$(this).val();var k=parseInt(e.which,10);if(!val.match(/^\d+/)&&(val.length)>1&&(k==32||(k>47&&k<58)||(k>64&&k<91)||(k>96&&k<123))){setTimeout(check_request,100);$(this).addClass('searching');}else{$(this).removeClass('searching');}});window.check_request=function(){if(suggesting.xhr&&suggesting.xhr.readyState===4){$('#bykeyword').removeClass('searching');}else{setTimeout(check_request,100);}};var suggesting;$('#bykeyword').each(function(){suggesting=$(this).autocomplete({serviceUrl:'/catalog/suggest/',minChars:3,width:218,zIndex:9999,onResponse:function(){$('#bykeyword').removeClass('searching');}});});$('#searchform').submit(function(){if(typeof suggesting.xhr!=='undefined'){suggesting.xhr.abort();}
$('#bykeyword').removeClass('searching');});function tooltip(trigger,target){trigger.css('cursor','help');trigger.find('a').css('cursor','help');var position=trigger.position();var top=position.top-(target.height()+25);var left=position.left-213;target.css({top:top,left:left}).show();}
$('th.in-favourites').live('mouseover mouseout',function(event){if(event.type=='mouseover'){tooltip($(this),$('#favTooltip'));}
else{$('#favTooltip').hide();}});$('th.in-pantry').live('mouseover mouseout',function(event){if(event.type=='mouseover'){tooltip($(this),$('#pantryTooltip'));}
else{$('#pantryTooltip').hide();}});$('img.recommended').live('mouseover mouseout',function(event){if(event.type=='mouseover'){tooltip($(this),$('#recommendedTooltip'));}
else{$('#recommendedTooltip').hide();}});$('img.new').live('mouseover mouseout',function(event){if(event.type=='mouseover'){tooltip($(this),$('#newTooltip'));}
else{$('#newTooltip').hide();}});$('th.ptsth').live('mouseover mouseout',function(event){if(event.type=='mouseover'){tooltip($(this),$('#pointsTooltip'));}
else{$('#pointsTooltip').hide();}});$('th.delete').live('mouseover mouseout',function(event){if(event.type=='mouseover'){tooltip($(this),$('#deleteTooltip'));}
else{$('#deleteTooltip').hide();}});function formtooltip(prodID,left,top,price,points,type,random){$('.formTooltip input.productid').val(prodID);$('.formTooltip input.quantity').val(1);$('.formTooltip input.quantitytype').val(type);$('.formTooltip p.total-price .dd').text('$'+price);$('.formTooltip p.total-points .dd').text(points);$('.formTooltip li.random').hide();if(random){$('.formTooltip li.random').show();}
var bgimg=(type=='unit')?'red-bg':'blue-bg';$('.formTooltip').toggle().css({'left':left,'top':top}).removeClass('red-bg').removeClass('blue-bg').addClass(bgimg);}
var currentProdID,currentColumn,values;$('td .amount a').live('click',function(e){currentProdID=$(this).attr('rel');currentColumn=($(this).hasClass('unit'))?'unit':'carton';values=(currentColumn=='unit')?productList[currentProdID].unit:productList[currentProdID].carton;var left=$(this).position().left-141;var top=$(this).position().top+15;var type=($(this).hasClass('unit'))?'unit':'carton';var random=productList[currentProdID].randomWeight;formtooltip(currentProdID,left,top,values.price.toFixed(2),values.points,type,random);e.preventDefault();});$('.formTooltip input#cancel').live('click',function(){$('.formTooltip').hide();});function setQuantity(current,inc){var amount=parseInt(current,10)+inc;if(amount<1||amount>9999){return current;}
var values=(currentColumn=='unit')?productList[currentProdID].unit:productList[currentProdID].carton;var price=amount*values.price;$('form.item-amount .total-price .dd').text('$'+price.toFixed(2));$('form.item-amount .total-points .dd').text(amount*values.points);return amount;}
$('form.item-amount input.add').live('click',function(){$('form.item-amount input.quantity').val(function(i,v){return setQuantity(v,1);});});$('form.item-amount input.remove').live('click',function(){$('form.item-amount input.quantity').val(function(i,v){return setQuantity(v,-1);});});$('form.item-amount input.quantity').live('mousewheel',function(e,d){d=(d>0)?1:-1;$(this).val(function(i,v){return setQuantity(v,d);});return false;});$('form.item-amount input.quantity').change(function(){setQuantity($(this).val(),0);});$('.item-quantity .add').live('click',function(){$('p.need-update').css({background:'#DDDDFF'});$('p.need-update span').text('Please update your cart to save your changes.');var current_input=$(this).siblings("input");var current_value=parseInt(current_input.val(),10);if(current_value<9999){current_input.val(current_value+1);}});$('.item-quantity .remove').live('click',function(){$('p.need-update').css({background:'#DDDDFF'});$('p.need-update span').text('Please update your cart to save your changes.');var current_input=$(this).siblings("input");var current_value=parseInt(current_input.val(),10);if(current_value>0){current_input.val(current_value-1);}});$('input.quantity').change(function(){$('p.need-update').css({background:'#DDDDFF'});$('p.need-update span').text('Please update your cart to save your changes.');});function parseForm(form)
{var data={};$.map(form.serializeArray(),function(o,i){data[o['name']]=o['value'];});return data;}
function addToCart(form,caller){var form_data=parseForm(form);if(!form_data.productid){alert('Please choose a product');return 1;}
if(!form_data.quantity_type){alert('Please choose unit or carton');return 1;}
$.post('/product/addtocart',form.serialize(),function(r){try{r=$.parseJSON(r);}catch(err){}
if(typeof r=='string'){offerAlternatives(r);}
if(caller instanceof jQuery){caller.text('$'+values.price.toFixed(2)).removeClass('adding').next().show();}
if(caller=='product_page'){window.history.back();}
$('.formTooltip #submit').removeClass('disabled').attr('disabled',false);updateCart();});return false;}
$('#search-results .available').live('click',function(){var pid=$(this).parents('tr').attr('id').replace(/\D/g,'');var type=$(this).attr('class').match('unit')?'unit':'carton';$.post('/product/addtocart',{productid:pid,quantity:1,quantity_type:type,event:'alternate'},function(r){offerAlternatives(r);});});function updateCart(){$.get('/catalog/cartquickview',function(cart){if(cart=='expired')
{window.location='/auth/expired';return;}
if(cart!=''){$('li#cart-quickview').replaceWith(cart);$('#cart-quickview #cart-summary').scrollTop($('#quick-cart').height());}});}
function offerAlternatives(alternatives){popup(null,{html:alternatives,css:{width:710,height:500}},null);}
$('form.choose_alternative').live('submit',function(e){if(!addToCart($(this),null)){popup_close(e);if($('#cart-details').length>0){show_loading();ajax_page('cart','?supress_warning=true');}}else{return false;}});$('#alternatives tr input:radio').live('click',function(e){$('#alternatives tr').removeClass('highlight');$('tr.'+$(this).attr('class').replace('alternative ','')).addClass('highlight');});$('form.item-amount').live('submit',function(){$('.formTooltip').hide();var caller=$('#pid_'+currentProdID+' .'+currentColumn+' .price');caller.text('Adding').addClass('adding').next().hide();$('.formTooltip #submit').addClass('disabled').attr('disabled',true);return addToCart($(this),caller);});$('form#addtocart').live('submit',function(){return addToCart($(this),'product_page');});var pending=false;$('#quick_add h2').click(function(){$('#quick_productid').focus();});$('#quick_submit').click(function(){if(pending){return false;}
$('#quick_productid, #quick_quantity').removeClass('quick-error');if(!$('#quick_productid').val().match(/^\d{6}$/)){$('#quick_productid').addClass('quick-error').focus().select();return false;}
if(!$('#quick_quantity').val().match(/^[1-9][0-9]{0,3}$/)){$('#quick_quantity').addClass('quick-error').focus().select();return false;}
pending=true;$('#quick_add #mask').fadeTo('fast',0.8);$.post('/product/addtocart',$(this).parent().serialize()+'&quantity_type=unit',function(r){try{r=$.parseJSON(r);}catch(err){}
pending=false;$('#quick_add #mask').fadeOut();if(r&&r.ResponseID=='0'){'ok';}else if(typeof r=='string'){offerAlternatives(r);quick_add_status('Out of Stock!','success',false);}else{quick_add_status('Invalid product code','error','#quick_productid');}
updateCart();});return false;});function quick_add_status(message,cssClass,input){$('#quick_add #status').stop().show().css({opacity:1}).removeClass('success error').addClass(cssClass).text(message).fadeOut(3000);if(input){$(input).focus().select();}
else{$('#quick_quantity').val('');$('#quick_productid').val('').focus();}
return false;}
$('#addtocart select#quantity_type').live('change',function(){var price=($(this).val()=='unit')?product.unitprice:product.cartonprice;var points=($(this).val()=='unit')?product.unitpoints:product.cartonpoints;var quantity=parseInt($('form#addtocart :text').val(),10);$('#addtocart ul li#total-points span.totalprice').text('$'+(quantity*price).toFixed(2));$('#addtocart ul li#total-points span.totalpoints').text((quantity*points));});$('#addtocart ul li#quantity .add').live('click',function(){var new_value=parseInt($('form#addtocart :text').val(),10)+1;if(new_value>9999){return;}
$('form#addtocart :text').val(new_value);var price=($('#addtocart select#quantity_type').val()=='unit')?product.unitprice:product.cartonprice;var points=($('#addtocart select#quantity_type').val()=='unit')?product.unitpoints:product.cartonpoints;$('#addtocart ul li#total-points span.totalprice').text('$'+(new_value*price).toFixed(2));$('#addtocart ul li#total-points span.totalpoints').text((new_value*points));});$('#addtocart ul li#quantity .remove').live('click',function(){var new_value=parseInt($('form#addtocart :text').val(),10)-1;if(new_value<0){return;}
$('form#addtocart :text').val(new_value);var price=($('#addtocart select#quantity_type').val()=='unit')?product.unitprice:product.cartonprice;var points=($('#addtocart select#quantity_type').val()=='unit')?product.unitpoints:product.cartonpoints;$('#addtocart ul li#total-points span.totalprice').text('$'+(new_value*price).toFixed(2));$('#addtocart ul li#total-points span.totalpoints').text((new_value*points));});$('a.removeproduct').live('click',function(){$(this).addClass('loading');$.get(this,function(r){$('tr#p'+r.productid).fadeOut(200).remove();$('span.num_items').text(r.num_items);$('span.total').text(r.total);$('span.points').text(r.points);$('span.rounding').text(r.rounding);$('span.fuel').text(r.fuel);$('span.inc_gst').text(r.gst);updateCart();},'json');return false;});$('input.confirm-payment-details').click(function(){var number=$('#CC_number1').val();number+='-'+$('#CC_number2').val();number+='-'+$('#CC_number3').val();number+='-'+$('#CC_number4').val();var month=$('#expiry_date_month').val();var year=$('#expiry_date_year').val();$('li.type .dd').text($('#credit_card_type').val());$('li.name .dd').text($('#card_name').val());$('li.number .dd').text(number);$('li.ccv .dd').text($('#CCV').val());$('li.date .dd').text(month+'/'+year);});$('#final-confirm').live('click',function(){$('#creditcard').submit();});$('a.close-popup').live('click',function(e){popup_close(e);});$('a.forgot').click(function(e){popup($(this),{css:{width:500,height:264}},e);});$('p.new-sign-up a').click(function(e){popup($(this),{css:{width:500,height:699}},e);});$('p.existing-sign-up a').click(function(e){popup($(this),{css:{width:500,height:458}},e);});$('a.requestchanges').click(function(e){popup($(this),{css:{width:500,height:399}},e);});$('input.confirm-payment-details').click(function(e){popup('#confirm-order-popup',{css:{width:500,height:351}},e);});$('a.quick-tour').click(function(e){popup($(this),{css:{width:655,height:470}},e);});if($('div.loginerror').length){$('div.loginerror').hide();popup('div.loginerror',{inline:true,autoResize:true},null);}
$('a.logout').click(function(e){e.preventDefault();$.get('/catalog/numcartitems',function(text){if(text!==''){popup(null,{css:{width:354,height:148},html:text},null);}
else{window.location='/auth/logout';}});});$('.checkout.confirm').live('click',function(e){$('#purchase_order_number-hidden').val($('#purchase_order_number').val());$('#remark-hidden').val($('#remark').val());$('#delivery_date-hidden').val($('#delivery_date').val());var order_number=$('#purchase_order_number').val();if(order_number!==''){$('#details-confirm .number .dd').text($('#purchase_order_number').val());$('li.number').show();}
else{$('li.number').hide();}
$('#details-confirm .address .dd').text($('select#shipping_add option:selected').text());popup('#details-confirm',{autoResize:true,css:{width:500}},e);e.preventDefault();});$('.closePopup').live('click',function(e){popup_close(e);});$('.return-to-search').click(function(){window.history.back();});$('.carton-pts, .unit-pts').each(function(){if(parseInt($(this).text(),10)===0){$(this).remove();}});$('.popup-container input.checkout').live('click',function(){$('#checkout').submit();});$('#masquerading-form select').change(function(){$('#loading').fadeIn();$('#masquerading-form').submit();});$('div#desc-nutrition p').hide();$('div#desc-dietary p').hide();$('a.desc-nutrition').click(function(e){$('div#desc-nutrition p').toggle();e.preventDefault();});$('a.desc-dietary').click(function(e){$('div#desc-dietary p').toggle();e.preventDefault();});$('.results-perpage select').live('change',function(){$(this).parents('.results-perpage').submit();});$('#checkout-cart').click(function(){$('#shipping-add').submit();return false;});deliver_datepicker();$('input.CC_number').keyup(function(){if($(this).val().length==4){$(this).next().focus();}});$('div#hamper_invoices').css('overflow','hidden');$('div#hamper_invoices ul#pagination').show();$.address.init(function(){$('#hamper_invoices #pagination').address();}).change(function(e){var page=e.path.replace(/[^0-9]*/,'')||1;if(page==''){page=1;}
$('#pagination li').removeClass('selected');$('#pagination li#page-'+page).addClass('selected');page-=1;$('#slider').animate({marginLeft:'-'+page*500+'px'});});$('#creditcard input[name^=invoice][type=checkbox]').change(function(){$('input#amount').attr('disabled',$(':checked',$(this).parents('tbody')).length);}).change();$('#apply_surcharge').change(function(){$('#surcharge_percent').attr('disabled',!this.checked);}).change();});function deliver_datepicker()
{$('input#delivery_date').datepicker({dateFormat:'yy-mm-dd',showAnim:'slideDown',constrainInput:true,beforeShowDay:function(date){var date_str=$.datepicker.formatDate('yy-mm-dd',date);if(available_dates[date_str]){return[true,''];}else{return[false,'unavailable','Not available for delivery'];}}});}
