/* Copyright 2010 Crushpad */var CP={};Object.extend(CP,{init:function(){},debugCheck:function(){return(CP.Constants.Force.Debug||document.body.className.match(/(^|\s)debug($|\s)/)?true:false);},log:function(){var args=CP.toArray(arguments);if(CP.debugCheck()){if(!CP.Constants.Force.GhettoConsole&&typeof console!='undefined'&&typeof console.log=='function'){console.log.apply(console,args);}else{if(!CP.Globals.console){CP.Globals.console=$(document.createElement('textarea'));CP.Globals.console.writeAttribute('readonly','readonly');CP.Globals.console.writeAttribute('id','console-interface');$(document.body).appendChild(CP.Globals.console);}
CP.Globals.console.setValue(CP.Globals.console.getValue()+args.join('\n')+'\n');}}},toArray:function(iterable){var arrayed=[];for(var i=0;i<iterable.length;i++){arrayed.push(iterable[i]);};return arrayed;},timeAgo:function(s_ago){var rounded=s_ago;var human_ago='';if(rounded<=1)
{human_ago='1 sec ago';return human_ago;}
if(rounded<60)
{human_ago=rounded+' sec ago';return human_ago;}
var m_ago=s_ago/60;rounded=Math.round(m_ago);if(rounded<=1)
{human_ago='1 min ago';return human_ago;}
if(rounded<60)
{human_ago=rounded+' min ago';return human_ago;}
var h_ago=m_ago/60;rounded=Math.round(h_ago);if(rounded<=1)
{human_ago='1 hour ago';return human_ago;}
if(rounded<24)
{human_ago=rounded+' hours ago';return human_ago;}
var d_ago=h_ago/24;rounded=Math.round(d_ago);if(rounded<=1)
{human_ago='1 day ago';return human_ago;}
if(rounded<365)
{human_ago=rounded+' days ago';return human_ago;}
var y_ago=d_ago/365;rounded=Math.round(y_ago);if(rounded<=1)
{human_ago='1 year ago';return human_ago;}
human_ago=rounded+' years ago';return human_ago;},timeToGo:function(delta){var obj={"day":0,"hour":0,"minute":0,"second":0}
if(delta<=0){return obj;}
var days;var hrs;var rem;var mins;days=Math.abs(delta/86400);rem=Math.abs(delta%86400);if(days<1){days=0;};hrs=Math.abs(rem/3600);rem=Math.abs(rem%3600);if(hrs<1){hrs=0;}
mins=rem/60;if(mins<1){mins=0;}
secs=rem%60;obj.day=Math.floor(days);obj.hour=Math.floor(hrs);obj.minute=Math.floor(mins);obj.second=Math.floor(secs);return obj;},openPopup:function(url,height,width){newwindow=window.open(url,'name','height = '+height+',width = '+width);if(window.focus){newwindow.focus()}
return false;},Constants:{Force:{Debug:'0'=='1',GhettoConsole:false},URL:{MagentoBase:'http://store.brixr.com'}},Globals:{console:false}});Event.observe(document,'dom:loaded',CP.init);var CP;if(typeof CP.UI=='undefined'){CP.UI={};}
if(typeof CP.UI.HoverPalette=='undefined'){CP.UI.HoverPalette=Class.create({initialize:function(args){var that=this;var target=$(args.target);var content=args.content;var classes=args.classes;var display=false;var closing=false;var palette;var tip;var timer_id;var options={hook:{target:'topRight',tip:'topRight'},offset:{x:0,y:0},delay:{start:0,end:0},start_effect:function(ele){var fx=new Fx.Style(ele,'opacity',{duration:100});fx.custom(0,1);},end_effect:function(ele){var fx=new Fx.Style(ele,'opacity',{duration:100,onComplete:clearPalette});fx.custom(1,0);}};var palette_template=new Template("<div class=\"#{baseClass} #{cssClasses}\" style=\"display: none;\"><table id=\"#{id}\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"#{baseClass}-sb-table\"><tr class=\"#{baseClass}-toprow\"><td class=\"#{baseClass}-sb-ul\">&nbsp;</td><td class=\"#{baseClass}-sb-um\">&nbsp;</td><td class=\"#{baseClass}-sb-ur\">&nbsp;</td></tr><tr class=\"middle\"><td class=\"#{baseClass}-sb-left\">&nbsp;<div class=\"#{baseClass}-tip-left\">&nbsp;</div></td><td class=\"#{baseClass}-sb-content\">#{content}</td><td class=\"#{baseClass}-sb-right\">&nbsp;</td></tr><tr class=\"#{baseClass}-bottomrow\"><td class=\"#{baseClass}-sb-ll\">&nbsp;</td><td class=\"#{baseClass}-sb-lm\">&nbsp;</td><td class=\"#{baseClass}-sb-lr\">&nbsp;</td></tr></table></div>");function turnOn(event){event.stop();if(display){return;}
if(options.delay.start&&options.delay.start>0){timer_id=setTimeout(function(){timer_id=false;showPalette(event);},options.delay.start*1000);return;}
showPalette(event);};this.turnOn=turnOn;function turnOff(event){if(timer_id){clearTimeout(timer_id);timer_id=false;return;}
if(!display){return;}
if(closing){return;}
closing=true;if(options.end_effect&&!CP.Utility.needsIECSS()){options.end_effect(palette);}else{if(options.delay.end&&options.delay.end>0){setTimeout(function(){clearPalette();},options.delay.end*1000);return;}
clearPalette();}};this.turnOff=turnOff;function showPalette(event){display=true;generatePalette();offsets=position(event);parentId=target.parentNode;successorId=target;palette.remove();parentId.insertBefore(palette,successorId);palette.setStyle({position:'absolute',top:offsets.top+"px",left:offsets.left+"px",display:'block',overflow:'visible','zIndex':'100'});tip.setStyle({'zIndex':'101'});palette.show();if(options.start_effect&&!CP.Utility.needsIECSS()){options.start_effect(palette);}};this.showPalette=showPalette;function position(event){palette_position=target.cumulativeOffset();target_dimensions=target.getDimensions();palette.show();tip_dimensions=tip.getDimensions();tip_offset=tip.positionedOffset();palette.hide();calculateOffsets(palette_position,target_dimensions,options.hook.target,1);palette_position.left+=tip_dimensions.width/2;palette_position.top-=tip_dimensions.height/2;palette_position.top-=tip_offset.top/2;palette_position.top+=options.offset.y;palette_position.left+=options.offset.x;return palette_position;};function calculateOffsets(position,box,corner,neg){switch(corner){case'topRight':position.left+=box.width*neg;break;case'topLeft':break;case'bottomLeft':position.top+=box.height*neg;break;case'bottomRight':position.top+=box.height*neg;position.left+=box.width*neg;break;case'top':position.left+=(box.width/2)*neg;break;case'left':position.top+=(box.height/2)*neg;break;case'bottom':position.top+=box.height*neg;position.left+=(box.width/2)*neg;break;case'rightMid':position.top+=(box.height/2)*neg;position.left+=box.width*neg;break;case'auto':break;}};function clearPalette(){palette.remove();display=false;closing=false;};function destroy(){target.stopObserving("mouseover",mouse_over);target.stopObserving("mouseout",mouse_out);clearPalette();};this.destroy=destroy;function generatePalette(){if(Object.isElement(palette)){$(document.body).appendChild(palette);return;};palette=$(palette_template.evaluate({cssClasses:classes,baseClass:'hoverpalette',content:content}).toDOM());$(document.body).appendChild(palette);tip=palette.down('.hoverpalette-tip-left');};if(Object.isElement(content)){content=content.cloneNode(true);var div=$(document.createElement('div'));div.appendChild(content);content=div.innerHTML;};var mouse_over=turnOn.bindAsEventListener(this);var mouse_out=turnOff.bindAsEventListener(this);target.observe("mouseover",mouse_over);target.observe("mouseout",mouse_out);}});}
var CP;if(typeof CP.TastingRoom=='undefined'){CP.TastingRoom={};}
Object.extend(CP.TastingRoom,{tastingId:null,addToCartUrl:null,scriptsToClean:null,scriptCounter:0,reloadPageTimer:null,startTime:null,endTime:null,clockTimer:null,player:null,tastingState:null,loginLink:null,destination:null,timeLineEvents:null,aVideoIsPlaying:0,jump_to:null,currentState:null,currentJumpAnchor:null,time_seconds:null,viddler:null,viddlerTimer:null,tastedProducts:{},init:function(){var tid=$('tasting_id');if(tid){CP.TastingRoom.tastingId=tid.value;}
var sd=$('store_domain');if(sd){CP.TastingRoom.addToCartUrl=sd.value;}
CP.TastingRoom.scriptsToClean=new Hash();$$('.taste-this').each(function(item){new CP.TastingRoom.TasteThis(item);});var t=$('reloadAt');if(t){var date=new Date();var now=Math.round(date.getTime()/1000+date.getTimezoneOffset()*60);CP.TastingRoom.startTime=now+parseInt(t.value);CP.TastingRoom.reloadPageAt(t.value);CP.TastingRoom.clockTimer=setInterval(CP.TastingRoom.clockTick,1000);}
var st=$('tasting-start');if(st){CP.TastingRoom.startTime=st.value;CP.TastingRoom.tastingClock(st.value);}
var et=$('tasting-end');if(et){CP.TastingRoom.endTime=et.value;}
$$('form.add-to-cart').each(function(form){function submitHandler(event){CP.TastingRoom.addProductToCart(form.id);event.stop();};Event.observe(form,'submit',submitHandler);});$$('.wine-list form').each(function(form){if($$('.ondemand')){var product_id=$F(form.down('input[name=product]'));CP.TastingRoom.tastedProducts[product_id]={tasting:$('tasting-lower-container').down('input[value='+product_id+']').up('table')};}});window.setTimeout(function(){if(typeof viddlerGetMovie=='function'){CP.TastingRoom.viddler=viddlerGetMovie();}},1);var player_overlay_inner=$('tasting-video-overlay-inner');var player_overlay=$('tasting-video-overlay');if(player_overlay){Event.observe(player_overlay,'click',function(event){if(event.findElement()==this&&typeof CP.TastingRoom.viddler!='undefined'){CP.TastingRoom.viddler.viddlerSeek(0);}});};CP.TastingRoom.loginLink=$('comment-login');if(CP.TastingRoom.loginLink){CP.TastingRoom.loginLink.observe('click',function(event){CP.TastingRoom.loginSignup('signup');event.stop();});}
var dest=$('destination');if(dest){CP.TastingRoom.destination=dest.value;};var jump_to=$$('.jumpto');if(jump_to){CP.TastingRoom.jump_to=jump_to;CP.TastingRoom.jump_to.each(function(link){Event.observe(link,'click',CP.TastingRoom.flashJumpToSeconds,link.href);});};$$('#winelist-container .wine-name').each(function(ele){new CP.UI.HoverPalette({'target':ele,'content':ele.adjacent('.wine-hover').first().remove().show()});});setTimeout(function(){CP.Utility.EventRegistry.addEvent(CP.Utility.ModalOverlay,'close',CP.TastingRoom.modalOverlayEvent.bind(CP.TastingRoom.modalOverlayEvent,'close'),false);},1);if(CP.TastingRoom.tastingState=='live'){CP.TastingRoom.currentlytastingloop();}
var start_tweeting=$('tweet-signup-link');if(start_tweeting){Event.observe(start_tweeting,'click',function(event){CP.TastingRoom.tweetModalPopup();event.stop();});}
var redirect_tweeting=$('tweet-modal-agreed');if(redirect_tweeting){Event.observe(redirect_tweeting,'click',function(event){window.location='/account';event.stop();});}},currentlytastingloop:function(){if(typeof CP.TastingRoom.currentlytastingloop.running=='undefined'){CP.TastingRoom.currentlytastingloop.running=false;}
if(CP.TastingRoom.currentlytastingloop.running){return;}
CP.TastingRoom.currentlytastingloop.running=true;new Ajax.Request('/tastings/gettimelineevent',{method:'get',parameters:{'tasting':CP.TastingRoom.tastingId},onSuccess:function(data){CP.TastingRoom.currentlytastingloop.running=false;var thatResponse=data.responseText.evalJSON();if(thatResponse.pid=='nothing'){$$('.now-product-container').invoke('hide');}else{var t=$('tasting-lower-container').down('input[value='+thatResponse.pid+']').up('table');if(t){$$('.now-product-container').invoke('hide');t.show();}}
setTimeout('CP.TastingRoom.currentlytastingloop()',(parseInt('20')<=0?3000:parseInt('20')*1000));},onFailure:function(data){CP.TastingRoom.currentlytastingloop.running=false;CP.log('Failed to make current tasting AJAJ request.');setTimeout('CP.TastingRoom.currentlytastingloop()',(parseInt('40')<=0?20000:parseInt('40')*1000));}});},flashJumpToSeconds:function(e){if(arguments.length!=0){CP.TastingRoom.currentJumpAnchor=Event.element(e);}
href=CP.TastingRoom.currentJumpAnchor.href.split('#');time_code=href[1].replace('s','');time_minutes=time_code.split('m');time_seconds=parseInt(time_minutes[0]*60)+parseInt(time_minutes[1]);if(typeof CP.TastingRoom.viddler!='undefined'){CP.TastingRoom.viddler.viddlerSeek(time_seconds);}},loginSignup:function(formName){var frame=$(document.createElement('iframe'));frame.setAttribute('frameBorder',0);frame.setAttribute('border',0);frame.setAttribute('scrolling','NO');frame.id='lb-login-signup';frame.src='/'+formName+'?chrome=false&destination='+CP.TastingRoom.destination;frame.width=300;frame.height=335;frame.title='Sign Up / Log In';if(CP.TastingRoom.tastingState=='live'&&(CP.Utility.needsIE6CSS()||CP.Utility.needsIE7CSS())&&Object.isElement($('mediaspace'))){$('mediaspace').setStyle({visibility:'hidden'});}
CP.Utility.ModalOverlay.open(frame);},resizeIframe:function(frameId){var frame=$(frameId);var lightbox=$('modal-overlay-contents');if(frame){var hw=CP.Utility.getViewportDims();var vph=hw[0];var vpw=hw[1];var h;var w;var isSignup=frame.contentWindow.document.getElementById('agree-privacy-tos');if(frame.contentWindow.document.getElementById('flashes-error')!=null){h=(isSignup)?440:255;w=540;}else{h=(isSignup)?360:190;w=(isSignup)?305:275;}
lightbox.setStyle({left:(vpw/2-w/2)+'px'});frame.height=h;frame.width=w;}},addProductToCart:function(id){var product_id=$(id).select('input[name=product]')[0].value;var group_product_id=$(id).select('input[name=group_id]')[0].value;product_selector=$(id).select('input[name=qty]');if(product_selector[0]!=null){var qty=product_selector[0].value;}else{var qty=1;}
var token=id+CP.TastingRoom.scriptCounter;if(group_product_id=='simple'){var url=CP.TastingRoom.addToCartUrl+'?product='+product_id+'&qty='+qty+'&token='+token;}else{var url=CP.TastingRoom.addToCartUrl+'?product='+group_product_id+'&super_group['+product_id+']='+qty+'&token='+token;}
var call=$(document.createElement('script'));call.src=url;call.charset='utf-8';call.type='text/javascript';$(document.body).appendChild(call);CP.TastingRoom.scriptsToClean.set(token,call);CP.TastingRoom.scriptCounter++;cart=$$('.cart-ico');cart[0].addClassName('cart-ico-loading');var lb=$(document.createElement('div'));lb.id='lb-add-to-cart';var loading=$(document.createElement('div'));loading.id='cart-loading';loading.setStyle({display:'none'});lb.appendChild(loading);if(CP.TastingRoom.tastingState=='live'&&CP.Utility.needsIE6CSS()&&Object.isElement($('mediaspace'))){$('mediaspace').setStyle({visibility:'hidden'});}
CP.Utility.ModalOverlay.open(lb);$('cart-loading').show();},reloadPageAt:function(time){var ms=time*1000;CP.log("TastingRoom.reloadPageAt: Setting reload in "+ms+" seconds.");if(ms<86400000){CP.TastingRoom.reloadPageTimer=setTimeout("window.location.href = window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search;",time*1000);}
CP.log(CP.timeToGo(time));},tastingClock:function(startTime){var date=new Date();var now=Math.round(date.getTime()/1000+date.getTimezoneOffset()*60);var delta=CP.TastingRoom.startTime-now;var hrs;var rem;var mins;hrs=Math.abs(delta/3600);rem=Math.abs(delta%3600);if(hrs<1)hrs=0;mins=rem/60;if(mins<1)mins=0;secs=rem%60;var h=Math.floor(hrs);var m=Math.floor(mins);var s=secs;h=(h<10)?'0'+h.toString():h.toString();m=(m<10)?'0'+m.toString():m.toString();s=(s<10)?'0'+s.toString():s.toString();$('hours').innerHTML=h;$('minutes').innerHTML=m;$('seconds').innerHTML=s;if(delta<=0){$('host-timer').removeClassName('tasting-future').addClassName('tasting-live');}
if(now==CP.TastingRoom.endTime){$('host-timer').removeClassName('tasting-live').addClassName('tasting-past');}
setTimeout('CP.TastingRoom.tastingClock(CP.TastingRoom.startTime)',1000);},clockTick:function(){var date=new Date();var now=Math.round(date.getTime()/1000+date.getTimezoneOffset()*60);var delta=CP.TastingRoom.startTime-now;var remaining=CP.timeToGo(delta);$('seconds').update(remaining.second);$('minutes').update(remaining.minute);$('hours').update(remaining.hour);$('days').update(remaining.day);if(remaining.day==0&&remaining.hour==0&&remaining.minute<2){}},flashPlayCallback:function(obj){if(CP.TastingRoom.viddlerTimer!=null){window.clearInterval(CP.TastingRoom.viddlerTimer);CP.TastingRoom.viddlerTimer=null;};CP.TastingRoom.viddlerTimer=window.setInterval(CP.TastingRoom.flashTimeCallback,700);var player_overlay=$('tasting-video-overlay');CP.TastingRoom.aVideoIsPlaying=1;if(player_overlay){player_overlay.hide();};},flashPausedCallback:function(){window.clearInterval(CP.TastingRoom.viddlerTimer);CP.TastingRoom.viddlerTimer=null;},flashEndedCallback:function(){window.clearInterval(CP.TastingRoom.viddlerTimer);CP.TastingRoom.viddlerTimer=null;var player_overlay=$('tasting-video-overlay');CP.TastingRoom.aVideoIsPlaying=1;if(player_overlay){player_overlay.show();};},modalOverlayEvent:function(event){if(event=='close'&&CP.Utility.needsIE6CSS()&&CP.TastingRoom.tastingState=='live'&&$('tasting-video')){$('tasting-video').setStyle({visibility:''});}
if(event=='close'&&CP.TastingRoom.tastingState=='live'&&(CP.Utility.needsIE6CSS()||CP.Utility.needsIE7CSS())&&$('mediaspace')){$('mediaspace').setStyle({visibility:''});}},flashTimeCallback:function(){var position=CP.TastingRoom.viddler.getCurrentTime();if(CP.TastingRoom.time_line_events!=null){CP.TastingRoom.time_line_events.each(function(event_item){var tasting=CP.TastingRoom.tastedProducts[event_item.event_data].tasting;if(tasting){if(event_item.tasted_on<position&&event_item.tasted_off>position){$$('.now-product-container').invoke('hide');tasting.show();}
if(event_item.tasted_off<position){tasting.hide();}};});}},TastingStatus:function(state){new Ajax.Request('/tastings/logtimelineevent',{method:'post',parameters:{'product':null,'tasting':CP.TastingRoom.tastingId,'state':state},onSuccess:function(data){var goodStuff=data.responseText.evalJSON();if(state=='event_start'){$$('#host-wines .taste-this-control').invoke('show');}else if(state=='event_end'){$$('#host-wines .taste-this-control').invoke('hide');}
CP.log(goodStuff);},onFailure:function(data){CP.log('Failed to make AJAJ request.');alert('Sorry, unable to save your tasting time. Please try again.');e.preventDefault();e.stopPropagation();}});},TasteThis:Class.create({initialize:function(element){var that=this;var myProductId=element.id.substring(11);element.href='#';function clickTasteCallback(e){CP.log('regarding product: '+myProductId+' in room : '+CP.TastingRoom.tastingId);CP.log(this.checked);var tasteOnOrOff='tasted_off';if(this.checked){tasteOnOrOff='tasted_on';}
new Ajax.Request('/tastings/logtimelineevent',{method:'post',parameters:{'product':myProductId,'tasting':CP.TastingRoom.tastingId,'state':tasteOnOrOff},onSuccess:function(data){var goodStuff=data.responseText.evalJSON();CP.log(goodStuff);if(tasteOnOrOff=='on'){$$('li.product-entity').each(function(item){item.removeClassName('taste-active');})
element.up('li.product-entity').addClassName('taste-active');}else{element.up('li.product-entity').removeClassName('taste-active');}},onFailure:function(data){CP.log('Failed to make AJAJ request.');alert('Sorry, unable to save your tasting time. Please try again.');e.preventDefault();e.stopPropagation();}});}
element=$(element);Event.observe(element,'click',clickTasteCallback);}}),tweetModalPopup:function(){CP.Utility.ModalOverlay.open($('tweet-setup-lightbox').show());}});Event.observe(document,'dom:loaded',CP.TastingRoom.init);var CP;if(typeof CP.Cart=='undefined'){CP.Cart={};}
Object.extend(CP.Cart,{init:function(){var cartContainer=$('header-cart-container');var cartCount=$('cart-count');var hasProductBeenPulled=0;if(!cartContainer||!cartCount){return;}
CP.Cart.cartCount=cartCount;CP.Cart.cartContainer=cartContainer.down();CP.Cart.hasProductBeenPulled=hasProductBeenPulled;CP.Cart.productListDomain=CP.Constants.URL.MagentoBase;cartContainer.observe('click',CP.Cart.navigateToCart);$('check-out-btn').down().observe('click',CP.Cart.navigateToCart);},navigateToCart:function(e){try{var cartAnchor=Event.findElement(e,'a');if((CP.TastingRoom.tastingState=='live'||CP.TastingRoom.tastingState=='ondemand')&&(CP.TastingRoom.aVideoIsPlaying==1)){Event.stop(e);window.open(cartAnchor.href,'brixrCartWin');}}catch(e){return true;}},updateCart:function(cartData){if(cartData){CP.log(cartData);CP.Cart.cartCount.update(cartData['total_items']);var subtotal=$('cart-subtotal');if(subtotal){subtotal.update(cartData['subtotal']);}
if(CP.TastingRoom.scriptsToClean.get(cartData['token'])){CP.TastingRoom.scriptsToClean.get(cartData['token']).remove();CP.TastingRoom.scriptsToClean.unset(cartData['token']);if(CP.TastingRoom.scriptsToClean.keys().length==0){CP.Utility.ModalOverlay.changeContents(cartData['output'],[{selector:'#checkout',event:'click',callback:CP.Utility.ModalOverlay.close.bind(CP.Utility.ModalOverlay)}]);};};}},getCartProducts:function(){var body=$(document.body);var cartProducts=$('detailed-cart-products');if(cartProducts==null&&CP.Cart.hasProductBeenPulled==0){var call=$(document.createElement('script'));call.src=CP.Cart.productListDomain;call.charset='utf-8';call.type='text/javascript';call.id='get-product-list';body.appendChild(call);body.removeChild($('get-product-list'));CP.Cart.hasProductBeenPulled=1;}else{if(cartProducts!=null){CP.Cart.hasProductBeenPulled=0;CP.Cart.cartContainer.removeChild($('detailed-cart-products'));}}},showCartProducts:function(cartdata){var total=0;var outter_div=$(document.createElement('div'));outter_div.id='detailed-cart-products';var clr_div=$(document.createElement('div'));clr_div.className='clr';if(cartdata['products'].length!=0){$H(cartdata['products']).each(function(product){var product_item=$(document.createElement('div'));product_item.addClassName('pdetails');var img_div=$(document.createElement('div'));img_div.className='float-left';var product_img=$(document.createElement('img'));product_img.className='pdetails-img';product_img.src=product[1].img;var details_div=$(document.createElement('div'));details_div.className="float-left details-text"
var name_div=$(document.createElement('div'));name_div.className='pdetails-name';var formated_name='';if(product[1].name.length>30){formated_name=product[1].name.truncate(30,'...');}else{formated_name=product[1].name;}
var name_text=$(document.createTextNode(formated_name));var qty_div=$(document.createElement('div'));qty_div.className='pdetails-qty float-left';var qty_text=$(document.createTextNode('Qty: '+product[1].qty));var price_div=$(document.createElement('div'));price_div.className='pdetails-price float-right';var price_text=$(document.createTextNode('Price $'+product[1].price.truncate(5,'')));total+=(product[1].qty*product[1].price);img_div.appendChild(product_img);product_item.appendChild(img_div);name_div.appendChild(name_text);details_div.appendChild(name_div);qty_div.appendChild(qty_text);details_div.appendChild(qty_div);price_div.appendChild(price_text);details_div.appendChild(price_div);details_div.appendChild(clr_div);product_item.appendChild(details_div);outter_div.appendChild(product_item);outter_div.appendChild(clr_div);});}else{var empty_cart=$(document.createElement('div'));empty_cart.id='pdetails-empty';var empty_text=$(document.createTextNode('You have No Products in your cart'));empty_cart.appendChild(empty_text);outter_div.appendChild(empty_cart);}
var total_div=$(document.createElement('div'));total_div.className='float-left';var total_text=$(document.createTextNode('Total: $'+total));total_div.appendChild(total_text);var check_div=$(document.createElement('div'));check_div.className='float-right';var check_out=$(document.createElement('a'));check_out.id='pdetails-checkout';check_out.href=CP.Constants.URL.MagentoBase+'/checkout/cart/';var check_text=$(document.createTextNode('Check Out'));outter_div.appendChild(total_div);check_out.appendChild(check_text);check_div.appendChild(check_out);outter_div.appendChild(check_div);outter_div.appendChild(clr_div);CP.Cart.cartContainer.appendChild(outter_div);}});Event.observe(document,'dom:loaded',CP.Cart.init);var CP;if(Object.isUndefined(CP.Utility)){CP.Utility={postToWindow:function(url,target,data){var form=$(document.createElement('form'));form.target=target;form.action=url;form.method='post';form.acceptCharset='UTF-8';form.enctype='multipart/form-data';form.hide();$H(data).each(function(pair){var field=document.createElement('input');field.type='hidden';field.name=pair.key;field.value=pair.value;form.appendChild(field);});document.body.appendChild(form);form.submit();FB.yield(form.remove.bind(form));},getViewportDims:function(){var viewportwidth;var viewportheight;if(typeof window.innerWidth!='undefined'){viewportwidth=window.innerWidth,viewportheight=window.innerHeight}else{viewportwidth=document.documentElement.clientWidth,viewportheight=document.documentElement.clientHeight}
return[viewportheight,viewportwidth];},changeDocumentStyles:function(styleobj){var body=$$('body').first();if(!body){return false;}
var html=$$('html').first();if(!html){return false;}
$H(styleobj).each(function(pair){body.style[pair.key]=pair.value;html.style[pair.key]=pair.value;})
return true;},needsIECSS:function(){/*@cc_on
     return true;
   @*/return false;},needsIE6CSS:function(){/*@cc_on
    /*@if ( @_jscript_version <= 5.6 || @_jscript_version == 5.7 )
     return true && !window.XMLHttpRequest;
    @else @*/return false;/*@end
   @*/},needsIE7CSS:function(){/*@cc_on
    /*@if ( @_jscript_version > 5.6 && @_jscript_version < 5.8)
     return true && window.XMLHttpRequest;
    @else @*/return false;/*@end
   @*/},needsIEPNGFilter:function(){/*@cc_on
    /*@if ((@_jscript_version >= 5.5 && @_jscript_version <= 5.6) || @_jscript_version == 5.7)
     return true && !window.XMLHttpRequest;
    @else @*/return false;/*@end
   @*/},version:function(){return'1.0';},currentQueryString:function(){var qs=window.location.search.substr(1);var params={};qs.split('&').each(function(param){var split_params=param.split('=');params[split_params[0]]=split_params[1];});return params;},currentFragment:function(){var hash;if(typeof window.location.hash!='undefined'){hash=window.location.hash;}else{hash=window.location.href;}
var frag_pos=hash.indexOf('#');if(frag_pos==-1){return hash;}
return hash.substr(frag_pos+1);},loadScript:function(url,callback,sentinel){var load_check,script=$(document.createElement('script'));script.charset='utf-8';script.type='text/javascript';script.src=url;document.body.appendChild(script);if(typeof callback=='function'&&typeof sentinel!='undefined'){load_check=setInterval(function(){try{if(typeof window[sentinel]!='undefined'){clearInterval(load_check);callback.defer(script);}}catch(e){CP.log(e);}},50);};},LinkedList:function(){var that=this;var head=null;var num_objects=0;function push(){for(var i=arguments.length-1;i>=0;i--){if(typeof arguments[i]=='undefined'){throw"Pushing undefined value"}
head={o:arguments[i],n:head};num_objects++;};return that;};this.push=push;function pop(){if(!head){throw"Poping empty list";}
var obj=head.o;head=head.n;num_objects--;return obj;};this.pop=pop;function remove(obj){var walk=head;var last=null;while(walk){if(walk.o===obj){if(last===null){head=walk.n;}else{last.n=walk.n;}
delete walk;num_objects--;break;}else{last=walk;walk=walk.n;}}
return that;};this.remove=remove;function reverse(){var tail=null,next,walk=head;while(walk){tail=walk;walk=walk.n;}
walk=head;while(walk&&walk!=tail){next=tail.n;tail.n=walk;walk=walk.n;tail.n.n=next;}
head=tail;return that;};this.reverse=reverse;function empty(){var walk=head,last;while(walk){last=walk;walk=walk.n;last.n=null;delete last;num_objects--;}
head=null;return that;};this.empty=empty;function filter(callback){var walk=head;var last=null;while(walk){if(callback(walk.o)){if(last===null){head=walk.n;delete walk;walk=head;}else{last.n=walk.n;delete walk;walk=last.n;}
num_objects--;}else{last=walk;walk=walk.n;}}
return that;};this.filter=filter;function length(){return num_objects;};this.length=length;function string(){var walk=head;var str='<@LinkedList: ';while(walk){str+=walk.o.toString();walk=walk.n;if(walk){str+=', ';}}
return str+'>';};this.string=string;this.toString=string;function contains(obj){var walk=head;while(walk){if(walk.o===obj){return true;}
walk=walk.n;}
return false;};this.contains=contains;for(var i=arguments.length-1;i>=0;i--){push(arguments[i]);};},EventRegistry:function(){var event_queue_next_id=0;var queues={};function objToId(obj){try{if(typeof obj[CP.Utility.Constants.EventRegistryMagicKey]!='undefined'){return obj[CP.Utility.Constants.EventRegistryMagicKey];}
return false;}catch(e){return false;}};function initQueue(obj){var id=objToId(obj);if(id===false){id=obj[CP.Utility.Constants.EventRegistryMagicKey]=event_queue_next_id++;}
if(!queues[id]){queues[id]={};}
return true;};this.initQueue=initQueue;function addEvent(obj,event,callback,single_shot){var id=objToId(obj);if(id===false||!queues[id]||typeof callback!='function'){return false;}
if(!queues[id][event]){queues[id][event]=new CP.Utility.LinkedList();}
queues[id][event].push({'callback':callback,'single_shot':single_shot==true});return true;};this.addEvent=addEvent;function removeEvent(obj,event,callback){var id=objToId(obj);if(id===false||!queues[id]||typeof callback!='function'){return false;}
if(queues[id][event]){queues[id][event].filter(function(o){return o.callback===callback;});}
return true;};this.removeEvent=removeEvent;function fireEvent(obj,event,synchronous){var id=objToId(obj);if(id===false||!queues[id]){return false;}
if(queues[id][event]){var args=$A(arguments).slice(3);queues[id][event].filter(function(o){if(synchronous){o.callback.apply(o,args);}else{Function.defer.apply(o.callback,args);}
return o.single_shot;});}
return true;};this.fireEvent=fireEvent;function removeEvents(obj,event){var id=objToId(obj);if(id===false||!queues[id]){return false;}
if(queues[id][event]){queues[id][event].empty();}
return true;};this.removeEvents=removeEvents;},EventHandler:function(element,event,callback,one_shot){function callCallback(e){callback(e);if(one_shot){clear();}};function register(){Event.observe(element,event,callCallback);};this.register=register;function clear(){Event.stopObserving(element,event,callCallback);};this.clear=clear;function fire(){callCallback();};this.fire=fire;},Constants:{Debug:true,DebugParam:'__debug',EventRegistryMagicKey:'__EventRegistryId'}};CP.Utility.EventRegistry=new CP.Utility.EventRegistry();(function(){var params=CP.Utility.currentQueryString();if(params[CP.Utility.Constants.DebugParam]=='false'){CP.Utility.Constants.Debug=false;}else if(params[CP.Utility.Constants.DebugParam]=='true'){CP.Utility.Constants.Debug=true;}})();Element.addMethods({removeChildren:function(element){element=$(element);for(var i=element.childNodes.length-1;i>=0;i--){element.removeChild(element.childNodes[i]);};return element;}});Object.extend(String.prototype,{toDOM:function(){var div=$(document.createElement('div'));div.update(this);return div.down();}});};var CP;if(Object.isUndefined(CP.Utility.ModalOverlay)){CP.Utility.ModalOverlay={init:function(){if(Object.isElement(this.overlay)){return;};CP.Utility.EventRegistry.initQueue(this);this.overlay=$(document.createElement('div'));this.overlay.id='modal-overlay';this.overlay_contents=$(document.createElement('div'));this.overlay_contents.id='modal-overlay-contents';this.overlay.hide();this.overlay_contents.hide();this.event_handlers=[];var body=$$('body').first();body.appendChild(this.overlay);body.appendChild(this.overlay_contents);Event.observe(this.overlay,'click',this.closeEvent.bindAsEventListener(this));}.bind(CP.Utility.ModalOverlay),open:function(contents,actions){if(this.isOpen()){this.changeContents(contents,actions);return;}
if(self.pageYOffset){this.yPos=self.pageYOffset;}else if(document.documentElement&&document.documentElement.scrollTop){this.yPos=document.documentElement.scrollTop;}else if(document.body){this.yPos=document.body.scrollTop;}
if(CP.Utility.needsIE6CSS()||CP.Utility.needsIE7CSS()){CP.Utility.changeDocumentStyles({height:'100%'});$$('select').each(function(element){element.style.visibility='hidden';});this.overlay.style.height=document.body.clientHeight/13+'em';}
window.scrollTo(0,0);this.overlay.show();this.changeContents(contents,actions);CP.Utility.EventRegistry.fireEvent(this,'open',false);this.overlay_contents.show();}.bind(CP.Utility.ModalOverlay),close:function(){if(!this.isOpen()){return;}
window.scrollTo(0,this.yPos);if(CP.Utility.needsIE6CSS()||CP.Utility.needsIE7CSS()){CP.Utility.changeDocumentStyles({height:'auto'});$$('select').each(function(element){element.style.visibility='visible';});this.overlay.style.height='auto';}
this.overlay.hide();this.overlay_contents.hide();while(this.event_handlers.length>0){var eh=this.event_handlers.pop();eh.clear();delete eh;}
CP.Utility.EventRegistry.fireEvent(this,'close',false);}.bind(CP.Utility.ModalOverlay),closeEvent:function(event){event.stop();this.close();}.bind(CP.Utility.ModalOverlay),changeContents:function(contents,actions){if(Object.isElement(contents)){this.changeContents([contents],actions);}else{CP.Utility.EventRegistry.fireEvent(this,'before-change-contents',true);while(this.event_handlers.length>0){var eh=this.event_handlers.pop();eh.clear();delete eh;}
if(Object.isArray(contents)){this.overlay_contents.removeChildren();contents.each(function(ele){this.overlay_contents.appendChild(ele);}.bind(this));}else{this.overlay_contents.removeChildren();this.overlay_contents.update(contents);}
if(!Object.isArray(actions)){actions=[];}
actions.push({selector:'a[rel=close]',event:'click',callback:this.closeEvent.bind(this)});actions.each(function(action){if(typeof action.event_handler!='undefined'){this.event_handlers.push(action.event_handler);}else{this.overlay_contents.select(action.selector).each(function(ele){var eh=new CP.Utility.EventHandler(ele,action.event,action.callback);eh.register();this.event_handlers.push(eh);}.bind(this));}}.bind(this));if(CP.Utility.needsIE6CSS()||CP.Utility.needsIE7CSS()){$(this.overlay_contents).select('select').each(function(element){element.style.visibility='visible';});}
CP.Utility.EventRegistry.fireEvent(this,'after-change-contents',false);}}.bind(CP.Utility.ModalOverlay),isOpen:function(){return this.overlay.visible();}.bind(CP.Utility.ModalOverlay),dispatcher:function(){var fragment=CP.Utility.currentFragment();if(this.fragment!=fragment){this.fragment=fragment;CP.Utility.EventRegistry.fireEvent(this,'change-location',false,fragment);}}.bind(CP.Utility.ModalOverlay),addEventHandlers:function(ehs){ehs.each(function(eh){this.event_handlers.push(eh);}.bind(this));}.bind(CP.Utility.ModalOverlay)};document.observe('dom:loaded',function(){CP.Utility.ModalOverlay.init();setInterval(CP.Utility.ModalOverlay.dispatcher.bind(CP.Utility.ModalOverlay),50);});}
function viddlerGetMovie(movieName){if(movieName){if(navigator.appName.indexOf("Microsoft")!=-1){return window[movieName];}else{return document[movieName];}}else{var temp=viddlerGetMovie('viddler');var temp2=viddlerGetMovie('viddler1');if(temp){return temp}else if(temp2){return temp2;}
return alert('Movie not found');}}
function pointInMovie(offset){viddlerSeek(offset);}
function viddlerSeek(arg1,arg2){if(arguments.length>1){var mv=viddlerGetMovie(arg1);mv.viddlerSeek(arg2);}else{var mv=viddlerGetMovie();mv.viddlerSeek(arg1);}}
function viddlerPause(){var mv=viddlerGetMovie();mv.viddlerPause();}
function viddlerOpen(arg1,arg2,arg3){if(arguments.length>2){var mv=viddlerGetMovie(arg1);mv.viddlerOpen(arg2,arg3);}else{var mv=viddlerGetMovie();mv.viddlerOpen(arg1,arg2);}}
function viddlerOpenSecret(playerid,key,offset,secretCode){var mv=viddlerGetMovie(playerid);mv.viddlerOpen(key,offset,secretCode);}
function viddlerSwitch(arg1,arg2,arg3,arg4){if(arguments.length>3){var mv=viddlerGetMovie(arg1);mv.viddlerSwitch(arg2,arg3,arg4);}else{var mv=viddlerGetMovie();mv.viddlerSwitch(arg1,arg2,arg3);}}
function viddlerSwitchSecret(playerid,username,videoNr,offset,secretCode){var mv=viddlerGetMovie(playerid);mv.viddlerSwitch(username,videoNr,offset,secretCode);}
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return"";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;var CP;if(typeof CP.Comments=='undefined'){CP.Comments={};}
Object.extend(CP.Comments,{tastingRoomId:null,latestCommentId:null,pollingTime:(parseInt('10')<=0?5000:parseInt('10')*1000),commentTimer:null,requestInProgress:null,broadcastMode:false,hasTwitter:false,init:function(){if(!Object.isElement($('tasting'))||!Object.isElement($('latest_comment'))){CP.log("comments.js: init of function bypassing...");return;}
CP.Comments.tastingRoomId=$('tasting').value;CP.Comments.latestCommentId=$('latest_comment').value;CP.Comments.hasTwitter=$('tweet-comment');CP.Comments.commentTimer=setTimeout('CP.Comments.getLatestComments()',CP.Comments.pollingTime);if(Object.isElement($('host-comments'))){CP.Comments.broadcastMode=true;}
if(Object.isElement($('fetch-older-comments'))){CP.Comments.youngestId=$('youngest-comment-id').value;CP.Comments.youngerCommentsLink=$('fetch-older-comments');CP.Comments.youngerCommentsLink.observe('click',CP.Comments.getOlderComments);}
var postarea=$('add-comment-container');if(Object.isElement(postarea)){var postform=postarea.down('form');if(!Object.isElement(postform)){return;}
Event.observe(postform,'submit',function(event){CP.Comments.postComment();event.stop();});Event.observe(postform,'keydown',function(event){if(event.keyCode==Event.KEY_RETURN){CP.Comments.postComment();event.stop();}});}},postComment:function(){clearTimeout(CP.Comments.commentTimer);CP.Comments.requestInProgress=null;var comment=$('comment').value;if(comment.strip().length==0){return;}
$('post-comment-button').addClassName('disabled').down('input').disabled='disabled';var tweet='false';if(CP.Comments.hasTwitter&&CP.Comments.hasTwitter.checked){tweet='true';}
new Ajax.Request('/comments/post/',{method:'post',parameters:{'comment':comment,'tasting':CP.Comments.tastingRoomId,'tweet':tweet},onSuccess:function(data){CP.Comments.getLatestComments();$('comment').value='';$('post-comment-button').removeClassName('disabled').down('input').disabled='';if(CP.Comments.hasTwitter){CP.Comments.hasTwitter.checked=false;}},onFailure:function(data){alert('Sorry, unable to post your comment. Please try again.');$('post-comment-button').removeClassName('disabled').down('input').disabled='';}});},getLatestComments:function(){var force=false;if(arguments.length>0){force=arguments[0];}
if(CP.Comments.requestInProgress!=null){CP.Comments.commentTimer=setTimeout('CP.Comments.getLatestComments()',CP.Comments.pollingTime);return;}
CP.Comments.requestInProgress=true;var url='/comments/latest/tasting/'+CP.Comments.tastingRoomId+'/since/'+CP.Comments.latestCommentId;new Ajax.Request(url,{method:'get',onSuccess:function(data){data=data.responseText.evalJSON();CP.Comments.renderNewComments(data);},onFailure:function(data){CP.log('Error, unable to pull down new comments.');},onComplete:function(){CP.Comments.requestInProgress=null;}});CP.Comments.commentTimer=setTimeout('CP.Comments.getLatestComments()',CP.Comments.pollingTime);},getOlderComments:function(event){var url='/comments/oldest/tasting/'+CP.Comments.tastingRoomId+'/before/'+CP.Comments.youngestId;new Ajax.Request(url,{method:'get',onSuccess:function(data){var response=data.responseText.evalJSON();for(var i=0;i<response.comments.length;i++){var comment=response.comments[i];$('comments-container').innerHTML+=comment.text;$('tasting-comments-old').hide();};CP.Comments.updateCommentTimestamps(response.server_time);},onFailure:function(data){CP.log('Error, unable to pull down older comments.');}});event.stop();},renderNewComments:function(data){if(data==null){CP.log("renderNewComments: No data to load.");return;}
if(data.latest_id==null||data.latest_id==''){return}
CP.Comments.latestCommentId=data.latest_id;data.comments.each(function(comment){var html=comment.text;var comments=$$('.comment-box');if(!comments||comments.length==0){$('comments-container').insert(html);return;}else{if(comments.first().hasClassName('zebra')){comments.first().insert({'before':html});return;}
comments.first().insert({'before':html});$$('.comment-box').first().addClassName('zebra');}});CP.Comments.updateCommentTimestamps(data.server_time);},updateCommentTimestamps:function(now){$$('#comments-container .comment-box').each(function(comment){var id=comment.id.replace('comment_','');var delta=now-comment.select('input').first().value;comment.select('.timestamp').first().update(CP.timeAgo(delta));});}});Event.observe(document,'dom:loaded',CP.Comments.init);