
var FormValidator=Class.create({initialize:function(display_object,elements,prefix){this.prefix=prefix;if(!this.prefix){this.prefix='deal_';}
this.display_object=display_object;this.validations=new Hash;this.elements=$A();this.setUpValidationsFromElements(elements);},setUpValidationsFromElements:function(elements){$H(elements).each(function(validation){var element=$(validation[0])||$(this.prefix+validation[0]);if(element&&element.type!='hidden'&&element.tagName!='META'){this.addValidationsToElement(element,validation[1]);this.elements.push(element);}}.bind(this));},observeElement:function(element){if(!element.id.match(/_cost/)&&!element.id.match(/_savings/)){element.observe('blur',this.validate.bindAsEventListener(this));}},addValidationsToElement:function(element,validation_functions){this.validations.set(element.id,{'element':element,'functions':validation_functions});this.observeElement(element);},findValidationByElement:function(element){return match=this.validations.find(function(validation){return validation.value.element==element;});},elementIsVisible:function(element){if($(element).hasClassName('step')&&Element.visible(element))
return true;return Element.visible(element)&&this.elementIsVisible(element.parentNode);},validate:function(event){var element=Event.element(event);this.validateElement(element);},validateAllElements:function(){this.elements.each(function(element){this.validateElement(element);}.bind(this));},validateElement:function(element){var errors=[];if(this.elementIsVisible(element)){var validation=this.findValidationByElement(element);if(validation){$H(validation.value.functions).each(function(validation){var functioncall;var binding;if(this["validate_"+validation[0]]){var functioncall=this["validate_"+validation[0]];var binding=this;}else{var functioncall=this.display_object["validate_"+validation[0]];var binding=this.display_object;}
var ret=functioncall.bind(binding)({'string':$F(element),'extra':validation[1],'element':element});if(!ret['valid']){errors.push(ret['message']);}}.bind(this));}
if(errors.length>0){try{this.display_object.markFieldInvalid(element,errors);}catch(e){}}else{try{this.display_object.markFieldValid(element);}catch(e){}}}},validate_required:function(h){if(h['string']==null)h['string']='';return{'valid':h['string'].strip()!='','message':"Field cannot be left blank."};},validate_limit:function(h){if(h['string']==null)h['string']='';return{'valid':h['string'].length<h['extra'],'message':"The character limit is "+h['extra']+" and you have entered "+h['string'].length+" characters."};},validate_url:function(h){if(h['string']==''){return{'valid':true,'message':''}}
if(h['string'].match(/^www/i)){h['string']='http://'+h['string'];$(h['element']).setValue(h['string']);}
var regexp=/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;return{'valid':regexp.test(h['string']),'message':"Doesn't look like a valid URL to me! It should start with 'http://'"};},validate_date:function(h){var regexp=/^(\d{2}\/\d{2}\/\d{4}|)$/;return{'valid':regexp.test(h['string']),'message':"Should be in the format MM/DD/YYYY."};},validate_checkbox:function(h){return{'valid':true,'message':''};},validate_email:function(h){var regexp;if(h['string']==''){regexp=/.*/;}else{regexp=/(.+)@(.+)\.(.{2,})/;}
return{'valid':regexp.test(h['string']),'message':"Doesn't look like a valid email to me!"};},validate_greater_than_zero:function(h){return{'valid':Number(h['string'])>0,'message':"Must be greater than zero."};}});


var Calendar=Class.create();Calendar.VERSION='1.2';Calendar.DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');Calendar.SHORT_DAY_NAMES=new Array('S','M','T','W','T','F','S','S');Calendar.MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December');Calendar.SHORT_MONTH_NAMES=new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');Calendar.NAV_PREVIOUS_YEAR=-2;Calendar.NAV_PREVIOUS_MONTH=-1;Calendar.NAV_TODAY=0;Calendar.NAV_NEXT_MONTH=1;Calendar.NAV_NEXT_YEAR=2;Calendar._checkCalendar=function(event){if(!window._popupCalendar)
return false;if(Element.descendantOf(Event.element(event),window._popupCalendar.container))
return;window._popupCalendar.callCloseHandler();return Event.stop(event);};Calendar.handleMouseDownEvent=function(event){Event.observe(document,'mouseup',Calendar.handleMouseUpEvent);Event.stop(event);};Calendar.handleMouseUpEvent=function(event)
{var el=Event.element(event);var calendar=el.calendar;var isNewDate=false;if(!calendar)return false;if(typeof el.navAction=='undefined')
{if(calendar.currentDateElement){Element.removeClassName(calendar.currentDateElement,'selected');Element.addClassName(el,'selected');calendar.shouldClose=(calendar.currentDateElement==el);if(!calendar.shouldClose)calendar.currentDateElement=el;}
var now=new Date();now=new Date(now.getFullYear(),now.getMonth(),now.getDate(),0,0,0);if(!calendar.canSelectPast&&el.date<now){alert("Your selected date cannot be in the past.");}else{calendar.date.setDateOnly(el.date);isNewDate=true;calendar.shouldClose=!el.hasClassName('otherDay');var isOtherMonth=!calendar.shouldClose;if(isOtherMonth)calendar.update(calendar.date);}}
else
{var date=new Date(calendar.date);if(el.navAction==Calendar.NAV_TODAY)
date.setDateOnly(new Date());var year=date.getFullYear();var mon=date.getMonth();function setMonth(m){var day=date.getDate();var max=date.getMonthDays(m);if(day>max)date.setDate(max);date.setMonth(m);}
switch(el.navAction){case Calendar.NAV_PREVIOUS_YEAR:if(year>calendar.minYear)
date.setFullYear(year-1);break;case Calendar.NAV_PREVIOUS_MONTH:if(mon>0){setMonth(mon-1);}
else if(year-->calendar.minYear){date.setFullYear(year);setMonth(11);}
break;case Calendar.NAV_TODAY:break;case Calendar.NAV_NEXT_MONTH:if(mon<11){setMonth(mon+1);}
else if(year<calendar.maxYear){date.setFullYear(year+1);setMonth(0);}
break;case Calendar.NAV_NEXT_YEAR:if(year<calendar.maxYear)
date.setFullYear(year+1);break;}
if(!date.equalsTo(calendar.date)){calendar.setDate(date);isNewDate=true;}else if(el.navAction==0){isNewDate=(calendar.shouldClose=true);}}
if(isNewDate)event&&calendar.callSelectHandler();if(calendar.shouldClose)event&&calendar.callCloseHandler();Event.stopObserving(document,'mouseup',Calendar.handleMouseUpEvent);return Event.stop(event);};Calendar.defaultSelectHandler=function(calendar)
{if(!calendar.dateField)return false;if(calendar.dateField.tagName=='DIV')
Element.update(calendar.dateField,calendar.date.print(calendar.dateFormat));else if(calendar.dateField.tagName=='INPUT'){calendar.dateField.value=calendar.date.print(calendar.dateFormat);}
if(typeof calendar.dateField.onchange=='function')
calendar.dateField.onchange();if(calendar.shouldClose)calendar.callCloseHandler();};Calendar.defaultCloseHandler=function(calendar)
{calendar.hide();};Calendar.setup=function(params)
{function param_default(name,def){if(typeof(params[name])=='undefined')params[name]=def;}
param_default('canSelectPast',true);param_default('dateField',null);param_default('triggerElement',null);param_default('parentElement',null);param_default('selectHandler',null);param_default('closeHandler',null);if(params.parentElement)
{var calendar=new Calendar(params.parentElement);calendar.setSelectHandler(params.selectHandler||Calendar.defaultSelectHandler);if(params.dateFormat)
calendar.setDateFormat(params.dateFormat);if(params.dateField){calendar.setDateField(params.dateField);calendar.parseDate(calendar.dateField.innerHTML||calendar.dateField.value);}
calendar.show();return calendar;}
else
{var triggerElement=$(params.triggerElement||params.dateField);triggerElement.onclick=function(){var calendar=new Calendar();calendar.setSelectHandler(params.selectHandler||Calendar.defaultSelectHandler);calendar.setCloseHandler(params.closeHandler||Calendar.defaultCloseHandler);if(params.dateFormat)
calendar.setDateFormat(params.dateFormat);calendar.setCanSelectPast(params.canSelectPast);if(params.dateField){calendar.setDateField(params.dateField);calendar.parseDate(calendar.dateField.innerHTML||calendar.dateField.value);}
if(params.dateField)
Date.parseDate(calendar.dateField.value||calendar.dateField.innerHTML,calendar.dateFormat);calendar.showAtElement(triggerElement);return calendar;}}};Calendar.prototype={container:null,selectHandler:null,closeHandler:null,minYear:1900,maxYear:2100,dateFormat:'%Y-%m-%d',date:new Date(),currentDateElement:null,shouldClose:false,isPopup:true,dateField:null,canSelectPast:true,initialize:function(parent)
{if(parent)
this.create($(parent));else
this.create();},update:function(date)
{var calendar=this;var today=new Date();var thisYear=today.getFullYear();var thisMonth=today.getMonth();var thisDay=today.getDate();var month=date.getMonth();var dayOfMonth=date.getDate();if(date.getFullYear()<this.minYear)
date.setFullYear(this.minYear);else if(date.getFullYear()>this.maxYear)
date.setFullYear(this.maxYear);this.date=new Date(date);date.setDate(1);date.setDate(-(date.getDay())+1);Element.getElementsBySelector(this.container,'tbody tr').each(function(row,i){var rowHasDays=false;row.immediateDescendants().each(function(cell,j){var day=date.getDate();var dayOfWeek=date.getDay();var isCurrentMonth=(date.getMonth()==month);cell.className='';cell.date=new Date(date);cell.update(day);if(!isCurrentMonth)
cell.addClassName('otherDay');else
rowHasDays=true;if(isCurrentMonth&&day==dayOfMonth){cell.addClassName('selected');calendar.currentDateElement=cell;}
if(date.getFullYear()==thisYear&&date.getMonth()==thisMonth&&day==thisDay)
cell.addClassName('today');if([0,6].indexOf(dayOfWeek)!=-1)
cell.addClassName('weekend');date.setDate(day+1);});!rowHasDays?row.hide():row.show();});this.container.getElementsBySelector('td.title')[0].update(Calendar.MONTH_NAMES[month]+' '+this.date.getFullYear());},create:function(parent)
{if(!parent){parent=document.getElementsByTagName('body')[0];this.isPopup=true;}else{this.isPopup=false;}
var table=new Element('table');var thead=new Element('thead');table.appendChild(thead);var row=new Element('tr');var cell=new Element('td',{colSpan:7});cell.addClassName('title');row.appendChild(cell);thead.appendChild(row);row=new Element('tr');this._drawButtonCell(row,'&#x00ab;',1,Calendar.NAV_PREVIOUS_YEAR);this._drawButtonCell(row,'&#x2039;',1,Calendar.NAV_PREVIOUS_MONTH);this._drawButtonCell(row,'Today',3,Calendar.NAV_TODAY);this._drawButtonCell(row,'&#x203a;',1,Calendar.NAV_NEXT_MONTH);this._drawButtonCell(row,'&#x00bb;',1,Calendar.NAV_NEXT_YEAR);thead.appendChild(row);row=new Element('tr');for(var i=0;i<7;++i){cell=new Element('th').update(Calendar.SHORT_DAY_NAMES[i]);if(i==0||i==6)
cell.addClassName('weekend');row.appendChild(cell);}
thead.appendChild(row);var tbody=table.appendChild(new Element('tbody'));for(i=6;i>0;--i){row=tbody.appendChild(new Element('tr'));row.addClassName('days');for(var j=7;j>0;--j){cell=row.appendChild(new Element('td'));cell.calendar=this;}}
this.container=new Element('div');this.container.addClassName('calendar');if(this.isPopup){this.container.setStyle({position:'absolute',display:'none'});this.container.addClassName('popup');}
this.container.appendChild(table);this.update(this.date);Event.observe(this.container,'mousedown',Calendar.handleMouseDownEvent);parent.appendChild(this.container);},_drawButtonCell:function(parent,text,colSpan,navAction)
{var cell=new Element('td');if(colSpan>1)cell.colSpan=colSpan;cell.className='button';cell.calendar=this;cell.navAction=navAction;cell.innerHTML=text;cell.unselectable='on';parent.appendChild(cell);return cell;},callSelectHandler:function()
{if(this.selectHandler)
this.selectHandler(this,this.date.print(this.dateFormat));},callCloseHandler:function()
{if(this.closeHandler)
this.closeHandler(this);},show:function()
{this.container.show();if(this.isPopup){window._popupCalendar=this;Event.observe(document,'mousedown',Calendar._checkCalendar);}},showAt:function(x,y)
{this.container.setStyle({left:x+'px',top:y+'px'});this.show();},showAtElement:function(element)
{var eleWidth=Element.getWidth(element);var containerWidth=Element.getWidth(this.container);Element.clonePosition(this.container,element,{setWidth:false,setHeight:false,offsetLeft:(eleWidth/2)-(containerWidth/2),offsetTop:-10});this.show();},hide:function()
{if(this.isPopup)
Event.stopObserving(document,'mousedown',Calendar._checkCalendar);this.container.hide();},parseDate:function(str,format)
{if(!format)
format=this.dateFormat;this.setDate(Date.parseDate(str,format));},setSelectHandler:function(selectHandler)
{this.selectHandler=selectHandler;},setCloseHandler:function(closeHandler)
{this.closeHandler=closeHandler;},setDate:function(date)
{if(!date.equalsTo(this.date))
this.update(date);},setDateFormat:function(format)
{this.dateFormat=format;},setCanSelectPast:function(bool){this.canSelectPast=bool;},setDateField:function(field)
{this.dateField=$(field);},setRange:function(minYear,maxYear)
{this.minYear=minYear;this.maxYear=maxYear;}};window._popupCalendar=null;Date.DAYS_IN_MONTH=new Array(31,28,31,30,31,30,31,31,30,31,30,31);Date.SECOND=1000;Date.MINUTE=60*Date.SECOND;Date.HOUR=60*Date.MINUTE;Date.DAY=24*Date.HOUR;Date.WEEK=7*Date.DAY;Date.parseDate=function(str,fmt){var today=new Date();var y=0;var m=-1;var d=0;var a=str.split(/\W+/);var b=fmt.match(/%./g);var i=0,j=0;var hr=0;var min=0;for(i=0;i<a.length;++i){if(!a[i])continue;switch(b[i]){case"%d":case"%e":d=parseInt(a[i],10);break;case"%m":m=parseInt(a[i],10)-1;break;case"%Y":case"%y":y=parseInt(a[i],10);(y<100)&&(y+=(y>29)?1900:2000);break;case"%b":case"%B":for(j=0;j<12;++j){if(Calendar.MONTH_NAMES[j].substr(0,a[i].length).toLowerCase()==a[i].toLowerCase()){m=j;break;}}
break;case"%H":case"%I":case"%k":case"%l":hr=parseInt(a[i],10);break;case"%P":case"%p":if(/pm/i.test(a[i])&&hr<12)
hr+=12;else if(/am/i.test(a[i])&&hr>=12)
hr-=12;break;case"%M":min=parseInt(a[i],10);break;}}
if(isNaN(y))y=today.getFullYear();if(isNaN(m))m=today.getMonth();if(isNaN(d))d=today.getDate();if(isNaN(hr))hr=today.getHours();if(isNaN(min))min=today.getMinutes();if(y!=0&&m!=-1&&d!=0)
return new Date(y,m,d,hr,min,0);y=0;m=-1;d=0;for(i=0;i<a.length;++i){if(a[i].search(/[a-zA-Z]+/)!=-1){var t=-1;for(j=0;j<12;++j){if(Calendar.MONTH_NAMES[j].substr(0,a[i].length).toLowerCase()==a[i].toLowerCase()){t=j;break;}}
if(t!=-1){if(m!=-1){d=m+1;}
m=t;}}else if(parseInt(a[i],10)<=12&&m==-1){m=a[i]-1;}else if(parseInt(a[i],10)>31&&y==0){y=parseInt(a[i],10);(y<100)&&(y+=(y>29)?1900:2000);}else if(d==0){d=a[i];}}
if(y==0)
y=today.getFullYear();if(m!=-1&&d!=0)
return new Date(y,m,d,hr,min,0);return today;};Date.prototype.getMonthDays=function(month){var year=this.getFullYear();if(typeof month=="undefined")
month=this.getMonth();if(((0==(year%4))&&((0!=(year%100))||(0==(year%400))))&&month==1)
return 29;else
return Date.DAYS_IN_MONTH[month];};Date.prototype.getDayOfYear=function(){var now=new Date(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0);var then=new Date(this.getFullYear(),0,0,0,0,0);var time=now-then;return Math.floor(time/Date.DAY);};Date.prototype.getWeekNumber=function(){var d=new Date(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0);var DoW=d.getDay();d.setDate(d.getDate()-(DoW+6)%7+3);var ms=d.valueOf();d.setMonth(0);d.setDate(4);return Math.round((ms-d.valueOf())/(7*864e5))+1;};Date.prototype.equalsTo=function(date){return((this.getFullYear()==date.getFullYear())&&(this.getMonth()==date.getMonth())&&(this.getDate()==date.getDate())&&(this.getHours()==date.getHours())&&(this.getMinutes()==date.getMinutes()));};Date.prototype.setDateOnly=function(date){var tmp=new Date(date);this.setDate(1);this.setFullYear(tmp.getFullYear());this.setMonth(tmp.getMonth());this.setDate(tmp.getDate());};Date.prototype.print=function(str){var m=this.getMonth();var d=this.getDate();var y=this.getFullYear();var wn=this.getWeekNumber();var w=this.getDay();var s={};var hr=this.getHours();var pm=(hr>=12);var ir=(pm)?(hr-12):hr;var dy=this.getDayOfYear();if(ir==0)
ir=12;var min=this.getMinutes();var sec=this.getSeconds();s["%a"]=Calendar.SHORT_DAY_NAMES[w];s["%A"]=Calendar.DAY_NAMES[w];s["%b"]=Calendar.SHORT_MONTH_NAMES[m];s["%B"]=Calendar.MONTH_NAMES[m];s["%C"]=1+Math.floor(y/100);s["%d"]=(d<10)?("0"+d):d;s["%e"]=d;s["%H"]=(hr<10)?("0"+hr):hr;s["%I"]=(ir<10)?("0"+ir):ir;s["%j"]=(dy<100)?((dy<10)?("00"+dy):("0"+dy)):dy;s["%k"]=hr;s["%l"]=ir;s["%m"]=(m<9)?("0"+(1+m)):(1+m);s["%M"]=(min<10)?("0"+min):min;s["%n"]="\n";s["%p"]=pm?"PM":"AM";s["%P"]=pm?"pm":"am";s["%s"]=Math.floor(this.getTime()/1000);s["%S"]=(sec<10)?("0"+sec):sec;s["%t"]="\t";s["%U"]=s["%W"]=s["%V"]=(wn<10)?("0"+wn):wn;s["%u"]=w+1;s["%w"]=w;s["%y"]=(''+y).substr(2,2);s["%Y"]=y;s["%%"]="%";return str.gsub(/%./,function(match){return s[match]||match;});};Date.prototype.__msh_oldSetFullYear=Date.prototype.setFullYear;Date.prototype.setFullYear=function(y){var d=new Date(this);d.__msh_oldSetFullYear(y);if(d.getMonth()!=this.getMonth())
this.setDate(28);this.__msh_oldSetFullYear(y);};


DailyDeals=Class.create({initialize:function(is_admin){this.list_items=$('primary').select('.deals_block li');this.list_items.each(function(item){this.setUpListeners(item);}.bind(this));if($('winner_popup')){this.winnerTemplate=new Template($('winner_popup').innerHTML);this.winnerTimer=null;$('winner_popup').setOpacity(0.9).observe('mouseover',this.winnerKeepPopupOpen.bindAsEventListener(this)).observe('mouseout',this.winnerMouseOut.bindAsEventListener(this));$('primary').select('.winner').each(function(item){item.observe('mouseover',this.winnerMouseOver.bindAsEventListener(this));}.bind(this));}
this.isAdmin=!!is_admin;},setUpListeners:function(item){item.observe('mouseover',this.mouseOverDeal.bindAsEventListener(this));item.observe('mouseout',this.mouseOutDeal.bindAsEventListener(this));item.observe('click',this.toggleDealExpansionEvent.bindAsEventListener(this));var ln=item.down('span.ln');if(ln){ln.observe('click',this.goToDeal.bindAsEventListener(this));}
var ln2=item.down('span.ln2');if(ln2){ln2.observe('click',this.showDeal.bindAsEventListener(this));}},showDeal:function(evt){var ele=evt.element();window.open('/daily_deals/show/'+ele.id.replace(/^dd_link2_/,''));},goToDeal:function(evt){var ele=evt.element();window.open('/daily_deals/out/'+ele.id.replace(/^dd_link_/,''));},winnerMouseOver:function(evt){var icon=evt.findElement('.staff-validated-icon');var li=evt.findElement('li');$('winner_popup').update(this.winnerTemplate.evaluate({username:li.down('.user_name').innerHTML,amount:li.down('.amount').innerHTML,first_bt_string:li.down('.unique_to_us')?" because their deal was First at BeatThat!":", but could have won $125 if their deal was First at BeatThat!"}));var mouse_y=evt.pointerY()-20;var mouse_x=evt.pointerX()-135;$('winner_popup').setStyle({top:mouse_y+'px',left:mouse_x+'px'}).show();},winnerMouseOut:function(evt){this.winnerTimer=setTimeout("$('winner_popup').style.display='none';",500);},winnerKeepPopupOpen:function(evt){if(this.winnerTimer!=null)clearTimeout(this.winnerTimer);},toggleAllDeals:function(link){Element.extend(link);this.list_items.each(function(li){this.toggleDealExpansion(li);}.bind(this));if(this.list_items.first().hasClassName('expanded')){link.update('Collapse All Deals');}else{link.update('Expand All Deals');}},mouseOverDeal:function(evt){evt.findElement('li').addClassName('hover');},mouseOutDeal:function(evt){evt.findElement('li').removeClassName('hover');},toggleDealExpansionEvent:function(evt){var li=evt.findElement('li');if(li.hasClassName('unexpandable')&&!evt.findElement('.info')&&!evt.findElement('.title_textbox')){if(li.hasClassName('no_new_window')){window.location.href=li.down('a').href;}else{window.open(li.down('a').href);}
evt.stop();}else{var clicked_link=evt.findElement('.title');if(clicked_link){evt.stop();this.toggleDealExpansion(li);}}},resizeDeal:function(li,expanding,new_height,on_complete){var li_height=li.getHeight();if(expanding){li.addClassName('expanded');}else{li.removeClassName('expanded');}
if(!new_height)new_height=li.down('.holder').getHeight();if(!on_complete)on_complete=Prototype.emptyFunction;var effect=new Fx.Style(li,'height',{duration:250,onComplete:on_complete});effect.set(li_height);effect.custom(li_height,new_height);},toggleDealExpansion:function(li){var new_height,on_complete=null;var expanding=false;var info_box=li.down('.info');if(li.hasClassName('expanded')){new_height=41;on_complete=function(){info_box.style.display='none';}.bind(this);}else{expanding=true;info_box.style.display='block';if(this.isAdmin&&!li.down('.admin')){on_complete=function(){new Ajax.Request('/daily_deals/edit/'+li.id.replace('dd_',''),{onComplete:function(req){var text=req.responseText;text.evalScripts();li.down('.info').insert({bottom:text.stripScripts()});li.setStyle({height:'auto'});li.scrollTo();}.bind(this)});};}}
if(this.isAdmin){this.list_items.each(function(new_li){if(new_li.down('.admin')){new_li.down('.admin').remove();new_li.down('.editor').remove();new_li.down('.editor_toolbar').remove();new_li.down('.title_textbox').remove();new_li.down('.title').show();new_li.down('.description').show();new_li.down('.collapse_link').remove();if(new_li!=li)this.resizeDeal(new_li,false,41);}}.bind(this));}
this.resizeDeal(li,expanding,new_height,on_complete);},submitDealAdmin:function(dd_id){if($F('daily_deal_awesomeness_'+dd_id).blank()){alert("You must select an awesomeness rating.");return false;}
$('dd_'+dd_id+'_edit_title').setValue($F('dd_'+dd_id+'_title_textbox').strip());$('dd_'+dd_id+'_edit_description').setValue($('editor_'+dd_id).innerHTML.strip().replace(/<br>$/,''));var form=$('dd_'+dd_id+'_edit_form');var this_row=$('dd_'+dd_id);form.select('.image_input').each(function(item){if(item.value=='Enter new URL here...'){item.setValue('');}}.bind(this));new Ajax.Request(form.action,{parameters:form.serialize()+'&alt='+this_row.hasClassName('alt'),onFailure:function(req){alert("ERROR! ERROR! YOU MADE ME CRY :( -- check your image urls and shopping/amazon IDs. if you didn't mess those up, talk to chris.");},onSuccess:function(req){this_row.replace(req.responseText);this.setUpListeners($('dd_'+dd_id));$('dd_'+dd_id).scrollTo();}.bind(this)});return true;},winnerChosen:function(dd_id,evt){var ele=evt.element();var container=$('winner_reason_'+dd_id);if(ele.checked){container.show();container.down('textarea').focus();}else{container.hide();}
this.resizeDeal(container.up('li'),true);},validateCommentForm:function(f){var errors=$A();if($F('vote_user_name').blank()){errors.push("You must fill in your name");}
if($F('vote_up')==null&&$F('vote_down')==null){errors.push("You gotta tell me if whether this deal sucks or rocks.");}
if($F('email_signup')&&$F('vote_user_email').blank()){errors.push("If you want our daily deal email, you gotta enter your email address. Otherwise, uncheck that box.");}
if(errors.length>0){$('comment_form_errors').show().update(errors.join('<br/>'));return false;}else{$('comment_form_errors').hide();return true;}}});DailyDealsEditor=Class.create({initialize:function(id){this.dd_id=id;if($("editor_"+id)){this.editor=$("editor_"+id);}else{this.editor=new Element('div',{className:'editor',id:"editor_"+id,contentEditable:'true'});$('dd_'+id+'_description').insert({before:this.editor});$('dd_'+id+'_description').hide();this.editor.style.backgroundColor='white';this.editor.style.fontFamily='"Trebuchet MS",Arial,Helvetica,sans-serif';this.editor.style.fontSize='1em';this.editor.innerHTML=$('dd_'+id+'_description').innerHTML.strip();this.editor.focus();}
var tb=this.generateToolbar();this.editor.insert({before:tb});},generateToolbar:function(){var buttons=$A([{label:"Bold",execCommand:'bold'},{label:"Underline",execCommand:'underline'},{label:"Link",handler:this.promptLinkSelection},{label:'Google',handler:function(evt){evt.stop();this.popUpUrlWithSelection('http://www.google.com/search?q=');}},{label:'G-Products',handler:function(evt){evt.stop();this.popUpUrlWithSelection('http://www.google.com/products?q=');}},{label:'G-Images',handler:function(evt){evt.stop();this.popUpUrlWithSelection('http://images.google.com/images?q=');}},{label:'Search Deals Sites',handler:function(evt){evt.stop();this.popUpUrlWithSelection('http://www.google.com/cse?cx=001558510172660599089%3Alvqvuyb-v2i&ie=UTF-8&sa=Search&as_qdr=w&q=');}},{label:'&cent;',handler:function(evt){evt.stop();this.addSymbol('&cent;');}}]);var toolbar=new Element('div',{className:'editor_toolbar'});buttons.each(function(hash){var button=new Element('a',{href:'#',className:'button'}).update(hash['label']);if(hash['handler']){button.observe('click',hash['handler'].bindAsEventListener(this));}else{button.observe('click',function(evt){evt.stop();this.execEditorCommand(hash['execCommand']);}.bindAsEventListener(this));}
toolbar.appendChild(button);}.bind(this));return toolbar;},execEditorCommand:function(command,arg){document.execCommand(command,false,arg);},addSymbol:function(symbol){document.execCommand("inserthtml",false,symbol);},promptLinkSelection:function(evt){evt.stop();if(this.getSelectionRange().collapsed){alert("Select some text to link, then click me again!");}else{if(this.linkSelected()){if(confirm('Unlink?'))this.editor.execCommand("unlink",false,null);}else{var url=prompt("Enter a URL, default will take the user to the deal","/daily_deals/out/"+this.dd_id);if(url){document.execCommand("createLink",false,url);}}}},linkSelected:function(){try{var first_non_text_node=$A(dde.getSelectionContent().childNodes).reject(function(node){return node.nodeName=='#text';}).first();return first_non_text_node&&first_non_text_node.nodeName=='A';}catch(e){return false;}},getSelection:function(){return window.getSelection();},getSelectionRange:function(){return window.getSelection().getRangeAt(0);},getSelectionContent:function(){return this.getSelectionRange().cloneContents();},getSelectionTextContent:function(){var textbox_obj=$('dd_'+this.dd_id+'_title_textbox');var text=null;if(document.getSelection()!=''){text=document.getSelection();}else if(textbox_obj.selectionEnd-textbox_obj.selectionStart!=0){text=textbox_obj.value.slice(textbox_obj.selectionStart,textbox_obj.selectionEnd);}
return text;},popUpUrlWithSelection:function(url){var text=this.getSelectionTextContent();if(text){window.open(url+escape(text));}else{alert("Select some text and then click me!");}}});Position.GetWindowSize=function(w){var width,height;w=w?w:window;this.width=w.innerWidth||(w.document.documentElement.clientWidth||w.document.body.clientWidth);this.height=w.innerHeight||(w.document.documentElement.clientHeight||w.document.body.clientHeight);return this;};


AmazonSearcher=Class.create({initialize:function(input,lookup_url,display_list,hidden_field){this.input=$(input);if(display_list)this.display_list=$(display_list);if(hidden_field)this.hidden_field=$(hidden_field);this.lookup_url=lookup_url;this.delay=1000;this.timer=null;this.input.observe('keydown',this.delayedLookup.bindAsEventListener(this));this.input.observe('focus',this.selectInput.bindAsEventListener(this));if(this.hiden_field)this.hidden_field.setValue('');this.input.setValue('');try{this.input.focus();}catch(e){}},delayedLookup:function(event){this.input.removeClassName('selected');if(this.timer!=null)clearTimeout(this.timer);this.timer=setTimeout(function(){this.lookup();this.timer=null;}.bind(this),this.delay);},selectInput:function(event){this.input.select();},lookup:function(){var value=$F(this.input);if(!value.blank()){$('amazon_loading').show();new Ajax.Request(this.lookup_url,{method:'get',parameters:{searchTerms:value},onSuccess:this.updateResultsFromJSON.bind(this)});}},updateResultsFromJSON:function(transport){var products=transport.responseJSON;$('amazon_loading').hide();this.display_list.innerHTML='';var ul=new Element('ul');if(products.length==0){var li=new Element('li',{style:'cursor: default'}).update('No results found! Please refine your search terms. Generic terms like "Apple" should work, as well as more specific terms like "Canon Powershot A560".');ul.appendChild(li);}else{products.each(function(product){var li=new Element('li',{id:product.asin});var p=new Element('p');if(product.small_image_url.blank()){product.small_image_url='/images/no-product-image.gif';}
var imgHolder=new Element('div',{className:'image_holder'});var img=new Image();img.src=product.small_image_url;imgHolder.appendChild(img);li.appendChild(imgHolder);p.appendChild(document.createTextNode(product.name.replace('&amp;','&').truncate(80)));li.appendChild(p);li.observe('click',this.itemClicked.bindAsEventListener(this));li.observe('mouseover',this.itemHover.bindAsEventListener(this));li.observe('mouseout',this.itemUnhover.bindAsEventListener(this));ul.appendChild(li);}.bind(this));}
this.display_list.appendChild(ul);this.display_list.show();},getItemFromEvent:function(event){var item=Event.element(event);if(item.tagName!='LI')item=item.up('li');return item;},itemHover:function(event){var item=this.getItemFromEvent(event);item.addClassName('hover');},itemUnhover:function(event){var item=this.getItemFromEvent(event);item.removeClassName('hover');},itemClicked:function(event){var item=this.getItemFromEvent(event);this.display_list.select('li').invoke('removeClassName','selected');item.addClassName('selected');this.input.setValue(item.down('p').innerHTML);this.input.addClassName('selected');this.hidden_field.setValue(item.id);},submit:function(form){if(this.input.hasClassName('selected')){return true;}else{alert('Select a product from the list that appears when you search for a product name, then hit Continue');return false;}}});


var DailyDealsWizard=Class.create({initialize:function(validations,search_lookup_url){$('as').setValue('all-set');$('daily_deal_kind').setValue('');$('daily_deal_amazon_asin').setValue('');$('daily_deal_shopping_id').setValue('');this.expires_at_default='Show Calendar';$('daily_deal_expires_at').setValue(this.expires_at_default);$('primary').select('.next').each(function(item){var next_funct=item.className.replace('next','').strip();var next_function=null;if(next_funct==''){next_function=this.showNextStep.bindAsEventListener(this);}else if(this[next_funct]){next_function=this[next_funct].bindAsEventListener(this);}else{next_function=function(evt){this.showNextStep(evt,$(next_funct));}.bindAsEventListener(this);}
item.observe('click',next_function);}.bind(this));this.fv=new FormValidator(this,validations,'daily_deal_');this.combo_searcher=new ComboSearcher($('product_name'),search_lookup_url);if($('submit_button'))$('submit_button').observe('click',this.submitForm.bindAsEventListener(this));},submitForm:function(evt){if(!this.verifyForm(evt.findElement('.step'))){return;}
$('daily_deal_form').submit();},resetField:function(field){return field.removeClassName('invalid').removeClassName('valid');},markFieldValid:function(unsafe_field){var field=this.resetField($(unsafe_field));field.addClassName('valid');this.fixedExample(field,'valid').update('Looks good to me.');},markFieldInvalid:function(unsafe_field,messages){var field=this.resetField($(unsafe_field));field.addClassName('invalid');this.fixedExample(field,'invalid').update(messages.join('<br/>'));},fixedExample:function(field,class_name){return this.resetField(field.next('h4')).removeClassName('example').addClassName(class_name);},verifyForm:function(step){this.fv.validateAllElements();if(step.down('.invalid')){$('form_error').show();return false;}else{$('form_error').hide();return true;}},showNextStep:function(evt,next_step_override){var this_step=evt.findElement('.step');if(!this.verifyForm(this_step)){return;}
var next_step=next_step_override?next_step_override:this_step.next('.step');var this_kind=$F('daily_deal_kind');if(this_kind){var opposite_kind=this_kind=='product_specific'?'site_wide':'product_specific';next_step.select('.'+opposite_kind).invoke('hide');next_step.select('.'+this_kind).invoke('show');}
this_step.hide();next_step.show();try{var focus_this=next_step.down('input');if(focus_this&&!focus_this.hasClassName('next')){focus_this.activate();}}catch(e){}},goBack:function(evt,step_to_show){var this_step=evt.findElement('.step');var next_step=$(step_to_show);this_step.hide();next_step.show();},setKind:function(evt){var item=evt.findElement('input');$('daily_deal_kind').setValue(item.name);this.showNextStep(evt);},setImageStep:function(evt){var ele=evt.element();var next_step;if(ele==$('yes_on_amazon')){next_step=$('product_searcher');}else{$('daily_deal_amazon_asin').setValue('');$('daily_deal_shopping_id').setValue('');next_step=$('product_image_step');new Ajax.Request('/daily_deals/get_images_from_url',{parameters:{url:$F('daily_deal_url')},onComplete:this.processImages.bind(this)});}
var this_step=evt.findElement('.step');if(this.verifyForm(this_step)){this.showNextStep(evt,next_step);}},processImages:function(req){var obj=req.responseJSON;if(obj==null||obj.length==0){$('image_results_loading').update('No images found on the URL you submitted. Try entering an image URL directly into the box below.');return;}
var num=obj.length;if(num<13)$('image_results').setStyle({height:(100*Math.ceil(num/6))+'px'});$A(obj).each(function(img_src){var img=new Image();img.src=img_src;Event.observe(img,'load',function(evt){if(img.width&&img.height){var skip=img.width*img.height<2500;var scale,w,h=null;var aspect=img.width/img.height;if(aspect>1){scale=75/img.width;}else{scale=75/img.height;}
if(scale<1){w=parseInt(img.width*scale,10);h=parseInt(img.height*scale,10);}else{w=img.width;h=img.height;}
Element.setStyle(img,{width:w+'px',height:h+'px'});Element.observe(img,'click',this.choseImage.bindAsEventListener(this));}
if(!skip)$('image_results').appendChild(img);}.bindAsEventListener(this));}.bind(this));$('image_results_loading').replace('<h4 style="font-size: 1.2em; font-weight: bold">Click on an appropriate image, if you see one.</h4>');},choseImage:function(evt){var img=evt.element();$('image_url').setValue(img.src);this.unSelectAllImages();img.addClassName('chosen');$('image_next_button').show();$('no_good_image').checked=false;$('image_url_error').hide();},unSelectAllImages:function(){$('image_results').select('img').invoke('removeClassName','chosen');},noGoodImage:function(){$('image_url_error').hide();if($('no_good_image').checked){$('image_url').setValue('');this.unSelectAllImages();if(!$('no_good_image_holder').down('span.thats_ok'))$('no_good_image_holder').insert({bottom:"<span class=\"thats_ok\"><br/>That's OK, we'll find one for you!</span>"});$('image_next_button').show();}else{if($F('image_url').blank()){$('image_next_button').hide();}
$('no_good_image_holder').down('span.thats_ok').remove();}},manualImageInput:function(){this.unSelectAllImages();if($F('image_url').blank()&&!$('no_good_image').checked){$('image_next_button').hide();$('image_url_error').hide();}else{var res=this.fv.validate_url({'string':$F('image_url'),'element':$('image_url')});if(res.valid){$('image_next_button').show();$('image_url_error').hide();}else{$('image_url_error').show();if(!$('no_good_image').checked)$('image_next_button').hide();}}},closedCalendar:function(calendar){if($F('daily_deal_expires_at')==this.expires_at_default||$F('daily_deal_expires_at').blank()){$('daily_deal_expires_at').setValue(this.expires_at_default);}else{$('daily_deal_expires_at').type='text';$('daily_deal_expires_at_reset').show();}
calendar.hide();},resetCalendar:function(){$('daily_deal_expires_at').type='button';$('daily_deal_expires_at').setValue(this.expires_at_default);$('daily_deal_expires_at_reset').hide();}});var ComboSearcher=Class.create(AmazonSearcher,{updateResultsFromJSON:function(transport){var resp=transport.responseJSON;this.processResults(resp.amazon,$('amazon_results'));this.processResults(resp.shopping,$('shopping_results'));$('amazon_loading').hide();},processResults:function(results,container){container.select('li.result').invoke('remove');results.each(function(item){var name=item.name;var image,image_class;try{if(item.small_image_url){image=item.small_image_url;image_class='amazon';}else{image=item.images.small_image.url;image_class='shopping';}}catch(e){image='/images/no-product-image.gif';image_class='no_image';}
var id=item.asin||item.reported_product_id;var li=new Element('li',{className:'result','id':id}).update('<div class="image_holder"><img class="'+image_class+'" src="'+image+'" /></div><h4>'+name+'</h4><div class="clear"></div>');li.observe('mouseover',function(evt){li.addClassName('hover');});li.observe('mouseout',function(evt){li.removeClassName('hover');});li.observe('click',this.selectedResult.bindAsEventListener(this));container.insert({bottom:li});}.bind(this));container.show();},selectedResult:function(evt){var li=evt.findElement('li');var container=li.parentNode;container.select('li.result[id!='+li.id+']').invoke('removeClassName','selected');var obj_to_update=container.id=='amazon_results'?$('daily_deal_amazon_asin'):$('daily_deal_shopping_id');var new_value;if(li.hasClassName('selected')){li.removeClassName('selected').removeClassName('hover');new_value='';}else{li.addClassName('selected');new_value=li.id;}
obj_to_update.setValue(new_value);return true;}});