$(document).ajaxSend(function(e,xhr,options){var token=$("meta[name='csrf-token']").attr("content");xhr.setRequestHeader("X-CSRF-Token",token)});var GLUI={Pages:{},Dialogs:{},Models:{},Util:{},Widgets:{},TICKET_ID_PADDING:5,ORDER_ID_PADDING:5,DEFAULT_BT_PARAMS:{fill:'#fff7df',strokeStyle:'#ffe69a',padding:'10px',width:200,cornerRadius:5,strokeWidth:1,spikeGirth:15,spikeLength:9,overflow:'auto',shadow:true,shadowOffsetX:2,shadowOffsetY:2,shadowBlur:5,shadowColor:'rgba(0,0,0,.15)',shadowOverlap:false,noShadowOpts:{strokeStyle:'#ffe69a',strokeWidth:1},positions:['top']},flash:function(hash){$.cookie('flash',JSON.stringify(hash),{path:'/'})}};(function($){$.fn.highlight=function(){$(this).css('background-color','#ffa').animate({backgroundColor:"#fff"},1500)};$.preloadImages=function(images){var urls=[];if(arguments.length==1&&typeof(images)=='object'){urls=$.merge(urls,images)}else{urls=$.merge(urls,arguments)}$.each(urls,function(i,url){$("<img>").attr("src",url)})}})(jQuery);GLUI.Util={randomString:function(length){var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";var result='';for(var i=0;i<length;i++){var rnum=Math.floor(Math.random()*chars.length);result+=chars.substring(rnum,rnum+1)}return result},genericDateFromTzDate:function(dateString){return new Date(dateString.replace(/ [-+][0-9]+$/,''))},isoDateString:function(d){if(!d){return''}function pad(n){return n<10?'0'+n:n}return d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate())+' '+pad(d.getHours())+':'+pad(d.getMinutes())+':'+pad(d.getSeconds())},reloadWithoutHash:function(){window.location=location.href.replace(/#.*$/,'')},loadTemplate:function(id,args){var tpl=$.support.scriptEval()?$(id).text():$(id).html();try{return jsontemplate.Template(tpl,{undefined_str:''}).expand(args)}catch(exception){alert('Error loading template: '+exception.message);return null}},escapeTags:function(text){return!text?'':text.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,'&quot;')},getHashString:function(url){return url.replace(/^.*#/,'')},formatLocation:function(location){if(!location){return''}var h=GLUI.Util.escapeTags;lines=[];if(location.name){lines.push(h(location.name))}if(location.address_1){lines.push(h(location.address_1))}if(location.address_2){lines.push(h(location.address_2))}cityAndState=[];if(location.city){cityAndState.push(h(location.city))}if(location.state){cityAndState.push(h(location.state))}cityAndStateString=cityAndState.join(', ');if(location.postal){cityAndStateString+='&nbsp;&nbsp;'+h(location.postal)}if(cityAndStateString){lines.push(h(cityAndStateString))}if(location.country){lines.push(h(location.country))}return lines.join('<br/>')},formatMoney:function(amount){if(typeof(amount)==='undefined'||amount===null){return'n/a'}return parseFloat(amount).toFixed(2)},googleMapsUrl:function(location){return'http://maps.google.com/maps?f=q&h1=en&saddr='+escape(GLUI.Util.locationAsString(location))},locationAsString:function(loc){if(!loc){return''}var pieces=[];if(loc.address_1){pieces.push(loc.address_1)}if(loc.address_2){pieces.push(loc.address_2)}if(loc.city){pieces.push(loc.city)}if(loc.state){pieces.push(loc.state)}if(loc.country){pieces.push(loc.country)}if(loc.postal){pieces.push(loc.postal)}return pieces.join(' ')},zeroPadInteger:function(num,count){var numZeropad=num+'';while(numZeropad.length<count){numZeropad="0"+numZeropad}return numZeropad},roundDateToNearest30Mins:function(date){var hours=date.getHours();var mins=date.getMinutes();if(mins<15){date.setMinutes(0)}else if(mins>44){date.setHours(hours+1);date.setMinutes(0)}else{date.setMinutes(30)}return date},abbrev:function(str,max){if(str.length<=max){return str}return str.substr(0,max+1)+'&hellip'},verboseDate:function(date){var year=date.getYear()==(new Date()).getYear()?'':', '+date.getFullYear();return date.strftime('%A, %B ')+date.getDate()+year},verboseTime:function(date){return date.strftime('%I:%M').replace(/^0/,'')+' '+((date.getHours()>11)?'pm':'am')},verboseDateTime:function(date){return GLUI.Util.verboseDate(date)+' at '+GLUI.Util.verboseTime(date)},verboseDateRange:function(start,stop){if(stop&&stop.getDay()!=start.getDay()){return GLUI.Util.verboseDate(start)+' to '+GLUI.Util.verboseDate(stop)}else{return GLUI.Util.verboseDate(start)}}};GLUI.Widgets.Base=Base.extend({constructor:function(){}});GLUI.Widgets.DateSection=GLUI.Widgets.Base.extend({constructor:function(){var self=this;var addToCalendarLinks=$("#add-to-calendar-links");var dropDownLink=addToCalendarLinks.closest('div.dropdown-link');var pixelOffset=4;if($.browser.mozilla){pixelOffset+=1}addToCalendarLinks.width(dropDownLink.width()-pixelOffset);var _hideMenu=function(){addToCalendarLinks.hide();dropDownLink.removeClass('active');$(document).unbind('click',_onDocumentClick)};var _onDocumentClick=function(e){if($(e.target).closest('div.dropdown-link').length){return true}_hideMenu();return false};$('#add-to-calendar-launcher').click(function(){if(addToCalendarLinks.is(':visible')){_hideMenu()}else{addToCalendarLinks.show();dropDownLink.addClass('active');$(document).click(_onDocumentClick)}return false})}});GLUI.Widgets.Location=GLUI.Widgets.Base.extend({constructor:function(){var self=this;if(typeof(google)!=='undefined'){self.gmapUI=new GLUI.Widgets.GoogleMap()}},load:function(location,showMap){var self=this;if(!location){return}var location_data=GLUI.Util.locationAsString(location);var map_url=GLUI.Util.googleMapsUrl(location);var maps_link=(location_data!=='')?'<span class="map-add"><a href="'+map_url+'">Go to Google Maps</a></span>':'';var formatted_location=GLUI.Util.formatLocation(location);$('#evt-location').empty().append('<p>'+formatted_location+'  <br/></p>');if(typeof(self.gmapUI)!=='undefined'&&showMap){$('#evt-location p').append(maps_link);$('#evt-location').append('<div id="google-map" style="height:238px;width:240px;display:none"></div>');self.gmapUI.load($('#google-map'),location)}}});GLUI.Widgets.GoogleMap=GLUI.Widgets.Base.extend({constructor:function(){var self=this;self.geocoder=null;if(google&&google.maps.Geocoder){self.geocoder=new google.maps.Geocoder()}},load:function($container,location){var self=this;self.$container=$container;if(!self.geocoder){return}self.geocoder.geocode({address:GLUI.Util.locationAsString(location)},function(results,status){if(status==google.maps.GeocoderStatus.OK&&results.length){self.$container.show();self.map=new google.maps.Map($container.get(0),{zoom:14,mapTypeId:google.maps.MapTypeId.ROADMAP});self.map.setCenter(results[0].geometry.location);var marker=new google.maps.Marker({position:results[0].geometry.location,map:self.map})}})}});GLUI.Widgets.EventDate=GLUI.Widgets.Base.extend({constructor:function(parentObj){var self=this;self.parentObj=parentObj},onLoad:function(){var self=this;var $container=self.parentObj.$container;var $startDate=$container.find('input[name="event[start]"]').date_input();var $stopDate=$container.find('input[name="event[stop]"]').date_input();$startDate.change(function(){var startDate=self.getDateObjFromInput('start');var stopDate=self.getDateObjFromInput('stop');if(startDate>stopDate){stopDate=startDate;stopDate.setHours(startDate.getHours()+3);self.loadInputFromDateObj('stop',stopDate)}});$container.find('input.multi-date').change(function(){if($(this).is(':checked')){$container.find('div.stop-date').show()}else{$container.find('div.stop-date').hide()}})},onOpen:function(event){var self=this;if(typeof event==='undefined'){event=self.parentObj.page.event}var $container=self.parentObj.$container;var startDate=GLUI.Util.genericDateFromTzDate(event.attrs.start);self.loadInputFromDateObj('start',startDate);var stopDate;if(event.attrs.stop){stopDate=GLUI.Util.genericDateFromTzDate(event.attrs.stop);self.loadInputFromDateObj('stop',stopDate);$container.find('input.multi-date').attr('checked',true).change()}else{$container.find('input.multi-date').removeAttr('checked').change();stopDate=GLUI.Util.genericDateFromTzDate(event.attrs.start);stopDate.setHours(stopDate.getHours()+3);self.loadInputFromDateObj('stop',stopDate)}$container.find('select[name="event[timezone]"]').val(event.attrs.timezone).change()},loadInputFromDateObj:function(inputName,date){var self=this;var $container=self.parentObj.$container;var roundedDate=GLUI.Util.roundDateToNearest30Mins(date);var hour=parseInt(roundedDate.strftime('%I'),10);var mins=roundedDate.strftime('%M');var time=hour+':'+mins;$container.find('select[name="event['+inputName+'][time]"]').val(time).change();$container.find('select[name="event['+inputName+'][am_pm]"]').val(roundedDate.strftime('%p')).change();$container.find('input[name="event['+inputName+']"]').val(roundedDate.strftime('%m/%d/%Y'))},getDateObjFromInput:function(inputName){var self=this;var $container=self.parentObj.$container;var date=new Date($container.find('input[name="event['+inputName+']"]').val());var inputTime=$container.find('select[name="event['+inputName+'][time]"]').val();var inputAmPm=$container.find('select[name="event['+inputName+'][am_pm]"]').val();var t=inputTime.split(':');var hour=parseInt(t[0],10);var amPmOffset=(inputAmPm=='AM'?0:12);if(hour==12){amPmOffset=amPmOffset-12}var mins=t[1];date.setHours(hour+amPmOffset);date.setMinutes(mins);return date},isMultiDate:function(){return this.parentObj.$container.find('.multi-date').is(':checked')},getAttrs:function(){var self=this;var $container=self.parentObj.$container;var startDate=self.getDateObjFromInput('start');var stopDate=self.isMultiDate()?self.getDateObjFromInput('stop'):'';return{start:GLUI.Util.isoDateString(startDate),stop:GLUI.Util.isoDateString(stopDate),timezone:$container.find('select[name="event[timezone]"]').val()}}});GLUI.Widgets.Chart=GLUI.Widgets.Base.extend({constructor:function(selector,series){var self=this;var graph=$(selector);graph.removeClass('loading');$.plot(graph,series,{xaxis:{mode:"time",minTickSize:[1,'day']},yaxis:{min:0,tickDecimals:0},grid:{borderColor:null,borderWidth:null,hoverable:true,clickable:true,color:'#bebebe',labelMargin:20},series:{lines:{show:true},points:{show:true,fill:true}},shadowSize:1,colors:['#7fc62b','#2b83c6','#782bc6','#0ccad1','#edbe00','#c30202','#ed8000','#d618dd']});var previousPoint=null;$(selector).bind("plothover",function(event,pos,item){if(item){if(previousPoint!=item.datapoint){previousPoint=item.datapoint;$('#graph-tooltip').btOff().remove();var x=item.datapoint[0].toFixed(2),y=item.datapoint[1].toFixed(2);self.showTooltip(item.pageX,item.pageY,Math.floor(y)+" sales")}}else{$('#graph-tooltip').btOff().remove();previousPoint=null}})},showTooltip:function(x,y,contents){var tt=$('<div id="graph-tooltip" title="'+contents+'"></div>').css({position:'absolute',display:'block',top:y,left:x,visibility:'hidden'}).appendTo("body");$(tt).bt($.extend({},GLUI.DEFAULT_BT_PARAMS,{shrinkToFit:true}));$(tt).btOn()}});GLUI.Dialogs.Base=Base.extend({dialogOptions:function(){return{}},constructor:function(page,reveal,params){var self=this;self.waiting=false;self.components={};self.loadTemplate(params);self.page=page;self._attachToContent(self.$container);if(typeof(reveal)!='undefined'&&reveal){$(reveal).click(function(e){self.open(e);return false})}self.onLoad()},loadTemplate:function(params){var self=this;if(self.template){var tpl=GLUI.Util.loadTemplate(self.template,params);self.$container=$(tpl)}},_attachToContent:function(){var self=this;self.$container.dialog($.extend({autoOpen:false,modal:true,draggable:false,resizable:false,buttons:{'Save':function(){return self.save()},'Cancel':function(){return self.cancel()}},beforeclose:function(){return self.onClose()},width:'auto'},self.dialogOptions()))},_clearErrors:function(){$('div.error',this.$container).remove()},delayRender:function(){this.waiting=true},continueRender:function(){var self=this;self.waiting=false;self.$container.dialog('open');self.afterOpen()},save:function(){var self=this;self.disableButtons();self.onSave()},open:function(e){var self=this;self.enableButtons();self.onOpen(e);if(!self.waiting){self.$container.dialog('open');self.afterOpen(e)}return false},cancel:function(){var self=this;self.onCancel();self.close();return false},close:function(){var self=this;self.$container.dialog('close')},onSave:function(){},onLoad:function(){},onOpen:function(){},onCancel:function(){},afterOpen:function(){var self=this;self.$container.find(':text:first').focus()},onClose:function(){var self=this;self._clearErrors()},hasError:function(){return this.$container.find('div.error').length>0},onError:function(errors){var self=this;self._clearErrors();self.enableButtons();self.$container.find('div.error').remove();var out='<div class="message error popup"><b></b>';out+=errors.join(', ');out+='</div>';self.$container.find('form').before(out);return false},disableButtons:function(){var self=this;self.$container.parent().find('button').attr('disabled',true).addClass('disabled')},enableButtons:function(){var self=this;self.$container.parent().find('button').removeAttr('disabled').removeClass('disabled')}});GLUI.Dialogs.ShowOrder=GLUI.Dialogs.Base.extend({template:'#order-dialog-tpl',constructor:function(page,reveal,order){var self=this;self.order=order;self.order.attrs.admin_order_number=GLUI.Util.zeroPadInteger(order.attrs.id,GLUI.ORDER_ID_PADDING);var templateVars=$.merge(order.attrs,{});templateVars.purchase_date=new Date(templateVars.purchase_date).strftime('%B %d, %Y');templateVars.coupon_info='';if(order.attrs.coupon_code_id){var coupon_code=$.grep(page.event.attrs.coupon_codes,function(cc){return cc.id===order.attrs.coupon_code_id})[0];if(coupon_code){templateVars.coupon_info=templateVars.coupon_info+'<tr>  <td>Coupon Code</td>  <td class="ta_right">'+coupon_code.code+' ('+coupon_code.verbose_description+')</td></tr>'}}$.each(templateVars.tickets,function(i,ticket){templateVars.tickets[i].url=page.eventUrl+'/tickets#'+ticket.id;templateVars.tickets[i].paid=ticket.paid.toFixed(2)+'';templateVars.tickets[i].ticket_type_name=ticket.ticket_type.name});self.base(page,reveal,templateVars)},dialogOptions:function(){var self=this;return{buttons:{'Save':function(){return self.onSave()},'Cancel':function(){$(this).dialog('close')},'Delete':function(){self.deleteOrder()}}}},deleteOrder:function(){var self=this;if(confirm("Are you sure you want to delete this order?\n\nIf you want to refund it instead you will have to\nrefund the corresponding transaction in your PayPal\naccount. Guestlist will automatically update to reflect\nthe refund.")){self.order.destroy({success:function(){self.close();GLUI.flash({notice:'Order deleted.'});GLUI.Util.reloadWithoutHash()}})}},onSave:function(){var self=this;self.order.save({first_name:self.$container.find('input[name="order[first_name]"]').val(),last_name:self.$container.find('input[name="order[last_name]"]').val(),email:self.$container.find('input[name="order[email]"]').val()},{success:function(){self.close();GLUI.flash({notice:'Order updated.'});GLUI.Util.reloadWithoutHash()},error:function(json){self.onError(json)}})},onClose:function(){var self=this;self.$container.dialog('destroy');self.$container.remove();return false}});GLUI.Dialogs.AttendeeBase=GLUI.Dialogs.Base.extend({populatePrice:function(typeId){var self=this;$.each(self.page.event.attrs.ticket_types,function(i,tt){if(tt.id==typeId){self.$container.find('input[name="ticket[price_paid]"]').val(tt.price.toFixed(2))}})},getCustomFieldPostParams:function(){var self=this;var custom_fields=[];self.$container.find('div.attendee-custom-field').each(function(){var $field=$(this);var klass=$(this).find('input[name="ticket[custom_field][klass]"]').val();var field={id:$field.find('input[name="ticket[custom_field][id]"]').val(),custom_field_type_id:$field.find('input[name="ticket[custom_field][custom_field_type_id]"]').val()};switch(klass){case"text":case"textarea":field.text=$field.find(':input[name="ticket[custom_field][text]"]').val();break;case"checkbox":field.value=$field.find('input[name="ticket[custom_field][value]"]').is(':checked');break;case"address":$.extend(field,{street_1:$field.find('input[name="ticket[custom_field][street_1]"]').val(),street_2:$field.find('input[name="ticket[custom_field][street_2]"]').val(),city:$field.find('input[name="ticket[custom_field][city]"]').val(),state:$field.find('input[name="ticket[custom_field][state]"]').val(),country:$field.find('input[name="ticket[custom_field][country]"]').val(),postal_code:$field.find('input[name="ticket[custom_field][postal_code]"]').val()});break;case"select_one":field.value=$field.find('select[name="ticket[custom_field][value]"]').val();break}custom_fields.push(field)});return custom_fields}});GLUI.Dialogs.ShowAttendee=GLUI.Dialogs.AttendeeBase.extend({template:'#attendee-dialog-tpl',constructor:function(page,reveal,ticket){var self=this;self.ticket=ticket;var templateArgs=$.extend(ticket.attrs,{title:'Attendee #'+GLUI.Util.zeroPadInteger(ticket.attrs.id,GLUI.TICKET_ID_PADDING),id_prefix:'show_',price_paid:ticket.attrs.paid.toFixed(2)+'',order_url:page.eventUrl+'/orders#'+ticket.attrs.order_id,ticket_id:ticket.attrs.id});self.base(page,reveal,templateArgs);$(".resend-ticket").click(function(){var ticket_id=$(this).attr('data-ticket-id');var link=$(this);$.ajax({url:window.location.pathname+'/'+ticket_id+'/resend_email',type:'POST',dataType:'json',success:function(){link.replaceWith("ticket resent")}})});if(ticket.attrs.custom_fields){$.each(ticket.attrs.custom_fields,function(i,field){var $typeid=self.$container.find('input[name="ticket[custom_field][custom_field_type_id]"][value='+field.custom_field_type_id+']');var $div=$typeid.parent();var $id=$typeid.next();$id.val(field.id);if(field.type=='TextCustomField'){$div.find('[name="ticket[custom_field][text]"]').val(field.text)}else if(field.type=='BooleanCustomField'){var $checkbox=$div.find('[name="ticket[custom_field][value]"]');if(field.value){$checkbox.attr('checked','checked')}else{$checkbox.removeAttr('checked')}}else if(field.type=='SelectOneCustomField'){var $select=$div.find('[name="ticket[custom_field][value]"]');if(field.value){$select.val(field.value)}}else if(field.type=='AddressCustomField'){$div.find('input[name="ticket[custom_field][street_1]"]').val(field.street_1);$div.find('input[name="ticket[custom_field][street_2]"]').val(field.street_2);$div.find('input[name="ticket[custom_field][city]"]').val(field.city);$div.find('input[name="ticket[custom_field][state]"]').val(field.state);$div.find('input[name="ticket[custom_field][country]"]').val(field.country);$div.find('input[name="ticket[custom_field][postal_code]"]').val(field.postal_code)}})}self.$container.find('select[name="ticket[ticket_type_id]"]').val(ticket.attrs.ticket_type_id)},dialogOptions:function(){var self=this;return{buttons:{'Save':function(){return self.onSave()},'Cancel':function(){$(this).dialog('close')},'Delete':function(){return self.deleteAttendee()}}}},deleteAttendee:function(){var self=this;if(confirm("Are you sure you want to delete this attendee?\n\nIf you want to refund the ticket you have to refund\nthe corresponding transaction in your PayPal account.\nGuestlist will automatically update to reflect the\nrefund.")){self.ticket.destroy({success:function(){self.close();GLUI.flash({notice:'Attendee deleted.'});GLUI.Util.reloadWithoutHash()}})}},onSave:function(){var self=this;self.ticket.save({first_name:self.$container.find('input[name="ticket[first_name]"]').val(),last_name:self.$container.find('input[name="ticket[last_name]"]').val(),email:self.$container.find('input[name="ticket[email]"]').val(),website:self.$container.find('input[name="ticket[website]"]').val(),ticket_type_id:self.$container.find('select[name="ticket[ticket_type_id]"]').val(),price_paid:self.$container.find('input[name="ticket[price_paid]"]').val(),custom_fields:self.getCustomFieldPostParams()},{success:function(){self.close();GLUI.flash({notice:'Attendee updated.'});GLUI.Util.reloadWithoutHash()},error:function(json){self.onError(json)}})},onClose:function(){var self=this;self.$container.dialog('destroy');self.$container.remove()}});GLUI.Dialogs.NewAttendee=GLUI.Dialogs.AttendeeBase.extend({template:'#attendee-dialog-tpl',constructor:function(page,reveal,params){this.base(page,reveal,{title:'Add Attendee',id_prefix:'new_'})},dialogOptions:function(){var self=this;return{buttons:{'Create':function(){return self.onSave()},'Cancel':function(){$(this).dialog('close')}}}},onLoad:function(){this.base();var self=this;self.$container.find('form').submit(function(){self.save();return false});self.$container.find('select[name="ticket[ticket_type_id]"]').change(function(){var typeId=$(this).val();self.populatePrice(typeId)});$('#new_send-confirmation-block').show()},onOpen:function(){var self=this;var typeId=self.$container.find('select[name="ticket[ticket_type_id]"]').val();self.populatePrice(typeId)},onSave:function(){var self=this;var attendeeParams={first_name:self.$container.find('input[name="ticket[first_name]"]').val(),last_name:self.$container.find('input[name="ticket[last_name]"]').val(),email:self.$container.find('input[name="ticket[email]"]').val(),tickets:{0:{first_name:self.$container.find('input[name="ticket[first_name]"]').val(),last_name:self.$container.find('input[name="ticket[last_name]"]').val(),email:self.$container.find('input[name="ticket[email]"]').val(),website:self.$container.find('input[name="ticket[website]"]').val(),ticket_type_id:self.$container.find('select[name="ticket[ticket_type_id]"]').val(),price_paid:self.$container.find('input[name="ticket[price_paid]"]').val(),custom_fields:self.getCustomFieldPostParams()}}};if(self.$container.find('input[name="send_confirmation"]').is(':checked')){attendeeParams.send_confirmation=true}self.page.createAttendee(attendeeParams,self)},onClose:function(){$.historyLoad('')}});GLUI.Dialogs.Event=GLUI.Dialogs.Base.extend({template:'#evt-create-dialog-tpl',dialogOptions:function(){var self=this;return{buttons:{'Create':function(){return self.onSave()},'Cancel':function(){$(this).dialog('close')}}}},onLoad:function(){var self=this;self.$container.find('form').submit(function(){self.save();return false});self.components.date=new GLUI.Widgets.EventDate(self);self.components.date.onLoad()},onClose:function(){$('div.datepicker').hide()}});GLUI.Dialogs.CreateEvent=GLUI.Dialogs.Event.extend({template:'#evt-create-dialog-tpl',constructor:function(page,reveal,params){this.base(page,reveal,$.extend({title:'New Event',id_prefix:'new_'},params))},onOpen:function(){var self=this;var event=self.page.event;self.delayRender();event.load('new',{success:function(){self.$container.find('input[name="event[name]"]').val(event.attrs.name?event.attrs.name:'');self.$container.find('select[name="event[timezone]"]').val('Eastern Time (US & Canada)').change();self.components.date.onOpen(event);self.continueRender()}});return false},onSave:function(){var self=this;var eventAttrs=$.extend(self.components.date.getAttrs(),{name:self.$container.find('input[name="event[name]"]').val()});self.page.saveEvent(eventAttrs,self)}});GLUI.Dialogs.CopyEvent=GLUI.Dialogs.Event.extend({constructor:function(page,reveal,params){this.base(page,reveal,$.extend(params,{title:'Copy Event'}))},onOpen:function(e){var self=this;var event=self.event=new GLUI.Models.Event({},'/manage/events/'+$(e.target).attr('data-id'));event.load('',{success:function(){self.$container.find('input[name="event[name]"]').val(event.attrs.name);self.$container.find('select[name="event[timezone]"]').val(event.attrs.timezone).change();self.components.date.onOpen(event)}})},onSave:function(){var self=this;var src=self.event;var target=new GLUI.Models.Event({},'/manage/events/'+src.attrs.id+'/copy');target.attrs=$.extend(self.components.date.getAttrs(),{name:self.$container.find('input[name="event[name]"]').val()});target.save(target.attrs,{success:function(response){var newEvent=new GLUI.Models.Event(response,'/manage/events');GLUI.flash({notice:"Event copied! Click the \"Edit Event\" tab to continue customizing your event, or consult the checklist below."});window.location=newEvent.url()},error:function(json){self.onError(json)}})}});GLUI.Dialogs.EditEventName=GLUI.Dialogs.Base.extend({template:'#evt-name-dialog-tpl',onLoad:function(){var self=this;self.$container.find('form').submit(function(){self.save();return false})},onOpen:function(){var self=this;self.$container.find(':input:first').val(self.page.event.attrs.name);return false},onSave:function(){var self=this;self.page.saveEvent({name:self.$container.find('input[name="event[name]"]').val()},self)}});GLUI.Dialogs.EditEventDescription=GLUI.Dialogs.Base.extend({template:'#evt-description-dialog-tpl',onLoad:function(){var self=this;self.$container.find('form').submit(function(){self.save();return false})},onOpen:function(){var self=this;if(self.page.event.attrs.description){self.$container.find('textarea').val(self.page.event.attrs.description)}},afterOpen:function(){tinyMCE.execCommand('mceAddControl',false,'event_description')},onClose:function(){tinyMCE.execCommand('mceRemoveControl',false,'event_description')},onSave:function(){var self=this;var content=tinyMCE.activeEditor.getContent({format:'raw'});content=content.replace(/(<p><br><\/p>|<P>&nbsp;<\/P>(\r\n)?)+$/i,'');content=content.replace(/^(<p><br><\/p>|<P>&nbsp;<\/P>(\r\n)?)+/i,'');self.page.saveEvent({description:content},self);return false}});GLUI.Widgets.MailingListIntegration=GLUI.Widgets.Base.extend({constructor:function(parent,$container){var self=this;self.parent=parent;self.$container=$container;self.lastResponseCache={}},integrationParamName:null,elementIds:{enableDisable:null,accountKey:null,changeKey:null,fieldsContainer:null,showAccountKey:null,editAccountKey:null,listContainer:null,fetchLists:null,showList:null,editList:null,listSelector:null,loadingAnimation:null},get:function(key){return this.$container.find(this.elementIds[key])},populateListSelect:function(){},fetchLists:function(){},onLoad:function(){var self=this;var get=function(id){return self.get(id)};get('enableDisable').click(function(){if($(this).is(':checked')){get('showAccountKey').hide();get('editAccountKey').show();get('listSection').hide();get('fieldsContainer').show().find('input:visible:first').focus()}else{get('fieldsContainer').hide()}});get('changeKey').click(function(){get('listSection').hide();get('showAccountKey').hide();get('editAccountKey').show();return false});get('fetchLists').click(function(){var token=self.get('accountKey').val();get('editAccountKey').hide();get('showAccountKey').find('span').html(token).end().show();get('editList').hide();get('showList').hide();get('loadingAnimation').show();get('listSection').show();self.fetchLists(token,function(json){get('loadingAnimation').hide();get('editList').show();self.lastResponseCache=json;self.populateListSelect(json)},function(xmlHttpRequest){get('loadingAnimation').hide();get('listSection').hide();get('showAccountKey').hide();get('editAccountKey').show();self.parent.onError(JSON.parse(xmlHttpRequest.responseText))});self.parent._clearErrors();return false})},extractAttrs:function(params){var self=this;var list={};if(!self.get('enableDisable').is(':checked')){params[self.integrationParamName]='';return false}else if(self.get('showList')[0].style.display!='none'){return false}return true},isEnabled:function(){return this.get('enableDisable').is(':checked')}});GLUI.Widgets.CampaignMonitorIntegration=GLUI.Widgets.MailingListIntegration.extend({integrationParamName:'campaign_monitor',elementIds:{enableDisable:'#cm-enabled',accountKey:'input[name="event[campaign_monitor_account_key]"]',changeKey:'#cm-change-key',fieldsContainer:'#cm-fields',showAccountKey:'#cm-show-account-key',editAccountKey:'#cm-edit-account-key',listSection:'#cm-list-section',fetchLists:'a.cm-refresh',showList:'#cm-show-list',editList:'#cm-edit-list',listSelect:'#campaign-monitor-lists',loadingAnimation:'#cm-loading'},populateListSelect:function(clients){var self=this;var listSelect=self.get('listSelect');html='';$.each(clients,function(_,client){html+='<optgroup label="'+client.name+'">';$.each(client.lists,function(id,name){html+='<option value="'+id+'">'+name+'</option>'});html+='</optgroup>'});listSelect.html(html);listSelect.find('option:first').attr('selected','selected');listSelect.change()},fetchLists:function(token,onSuccess,onError){var self=this;$.ajax({url:'/proxies/campaign_monitor/lists',data:{api_key:token,timestamp:(new Date()).getMilliseconds()},dataType:'json',success:onSuccess,error:onError})},onOpen:function(){var self=this;var parent=self.parent;var event=parent.page.event;if(event.attrs.campaign_monitor){$('#cm-enabled').attr('checked','checked').redraw();self.$container.find('input[name="event[campaign_monitor_account_key]"]').val(event.attrs.campaign_monitor.account_key)}else{$('#cm-fields').hide()}},extractAttrs:function(params){var self=this;if(!self.base(params)){return false}var client={},list={};list={id:self.get('listSelect').val(),name:self.get('listSelect').find('option:selected').html()};$.each(self.lastResponseCache,function(clientid,data){if(data.lists[list.id]){client.id=clientid;client.name=data.name}});params.campaign_monitor={account_key:self.$container.find('input[name="event[campaign_monitor_account_key]"]').val(),list_id:list.id,list_name:list.name,client_id:client.id,client_name:client.name};return true}});GLUI.Widgets.MailChimpIntegration=GLUI.Widgets.MailingListIntegration.extend({integrationParamName:'mailchimp',elementIds:{enableDisable:'#chimp-enabled',accountKey:'input[name="event[mailchimp_account_key]"]',changeKey:'#chimp-change-key',fieldsContainer:'#chimp-fields',showAccountKey:'#chimp-show-account-key',editAccountKey:'#chimp-edit-account-key',listSection:'#chimp-list-section',fetchLists:'a.chimp-refresh',showList:'#chimp-show-list',editList:'#chimp-edit-list',listSelect:'#chimp-lists',loadingAnimation:'#chimp-loading'},populateListSelect:function(lists){var self=this;var listSelect=self.get('listSelect');html='';$.each(lists,function(id,list){html+='<option value="'+list.id+'">'+list.name+'</option>'});listSelect.html(html);listSelect.find('option:first').attr('selected','selected');listSelect.change()},onOpen:function(){var self=this;var parent=self.parent;var event=parent.page.event;if(event.attrs.mailchimp){$('#chimp-enabled').attr('checked','checked').redraw();self.$container.find('input[name="event[mailchimp_account_key]"]').val(event.attrs.mailchimp.account_key)}else{$('#chimp-fields').hide()}},fetchLists:function(token,onSuccess,onError){var self=this;$.ajax({url:'/proxies/mailchimp/lists',data:{api_key:token,timestamp:(new Date()).getMilliseconds()},dataType:'json',success:onSuccess,error:onError});return false},extractAttrs:function(params){var self=this;if(!self.base(params)){return false}params.mailchimp={api_key:self.$container.find('input[name="event[mailchimp_account_key]"]').val(),list_id:self.get('listSelect').val(),list_name:self.get('listSelect').find('option:selected').html()};return true}});GLUI.Dialogs.NewField=GLUI.Dialogs.Base.extend({template:'#evt-new-field-dialog-tpl',constructor:function(parent,reveal,params,$row){var self=this;self.base(parent,reveal,params);self.parent=parent;self.$row=$row;if(params.klass){self.$container.find('select[name="field[klass]"]').val(params.klass);if(params.klass=='select_one'){$.each(params.options,function(i,opt){self.addSelectOption(opt)});$('#custom-field-options ul').after('<a href="#" class="new-custom-field-options-line"><span><b class="new"></b>New</span></a>');$('#custom-field-options').show()}}$("#custom-field-options").sortable({handle:"span.handle",items:'li',placeholder:"ui-sortable-placeholder",start:function(event,ui){ui.item.addClass('ondrag');$('body').addClass('cursor-move')},stop:function(event,ui){ui.item.removeClass('ondrag');$('body').removeClass('cursor-move')}});$('a.new-custom-field-options-line').live('click',function(){self.addSelectOption();self.$container.find('#custom-field-options li:last input:visible:first').focus();return false});self.$container.find('select[name="field[klass]"]').change(function(){if($(this).val()=='select_one'){if($('#custom-field-options').find('li').length==0){self.addSelectOption();$('#custom-field-options ul').after('<a href="#" class="new-custom-field-options-line"><span><b class="new"></b>New</span></a>')}$('#custom-field-options').show()}else{$('#custom-field-options').hide()}})},onClose:function(){var self=this;self.$container.dialog('destroy');self.$container.remove();return false},addSelectOption:function(opt){var self=this;var value=opt?opt:'';var $dest=$('#custom-field-options ul');var $li=$('<li>      <span class="handle">&nbsp;</span>      <div class="value"><input type="text" style="width: 200px" value="'+value+'"/></div>      <div class="remove"><a href="#" class="custom-field-remove-button"/></div>      </li>');$li.appendTo($dest);$li.find('a.custom-field-remove-button').click(function(){if(self.$container.find('li input').length==1){return false}var $li=$(this).closest('li');$li.fadeOut(function(){$li.remove()});return false})},onSave:function(){var self=this;var name=self.$container.find('input[name="field[name]"]').val();var description=self.$container.find('input[name="field[description]"]').val();var klass=self.$container.find('select[name="field[klass]"]').val();if(klass=="select_one"){var options=$.map(self.$container.find('li input'),function(el){return $(el).val()})}else{var options=null}if($.trim(name)==''){self.onError(["Name can't be blank"]);return}if(klass=="select_one"&&$.trim(options.join(''))==''){self.onError(["Must provide at least one option"]);return}if(self.$row!==undefined){self.parent.updateCustomField(self.$row,{name:name,options:options,description:description})}else{self.parent.addCustomField({name:name,options:options,required:false,id:'',description:description},klass)}self.close()}});GLUI.Dialogs.EditEventSettings=GLUI.Dialogs.Base.extend({template:'#evt-settings-tpl',constructor:function(page,reveal,params){var self=this;self.base(page,reveal,params)},onOpen:function(tab){var self=this;self.reveal(tab);if(self.page.event.attrs.show_attendee_list){self.$container.find('input[name="event[show_attendee_list]"]').attr('checked','checked').redraw()}$('li.attendeefields-list-item-useradded').remove();var customFieldTypes=$.makeArray(self.page.event.attrs.custom_field_types);var couponCodes=$.makeArray(self.page.event.attrs.coupon_codes);customFieldTypes.sort(function(a,b){return a.sequence-b.sequence});$.each(customFieldTypes,function(i,cft){self.addCustomField(cft,cft.klass)});self.$container.find('li.coupons-row').remove();$.each(couponCodes,function(i,cc){self.addCouponCode(cc)});self.mailChimpSection.onOpen();self.campaignMonitorSection.onOpen();$('#settings-advanced select[name="event[order_ticket_limit]"]').val(self.page.event.attrs.order_ticket_limit).redraw()},restoreCustomField:function(field){var $opts=$('option','#attendeefields-add').filter(function(){return $(this).val()==field.name});$opts.removeAttr('disabled')},updateCustomField:function($row,field){var self=this;$row.find('input[name="event[custom_field_types][name]"]').val(field.name);$row.find('input[name="event[custom_field_types][description]"]').val(field.description);$row.find('div.attendeefields-column-label span').html(field.name);if(field.options){$row.find('input[name="event[custom_field_types][options][]"]').remove();$.each(field.options,function(idx,val){$row.append('<input type="hidden" name="event[custom_field_types][options][]" value="'+val+'"/>')})}},addCustomField:function(field,klass){var self=this;if(typeof klass==='undefined'){if(field.name=='Address'){field.klass='address'}else{field.klass='text'}}else{field.klass=klass}var $dest=$('#attendeefields-list-required');var $opts=$('option','#attendeefields-add').filter(function(){return $(this).val()==field.name});$opts.attr('disabled','disabled');var li_text='<li class="attendeefields-list-item-useradded">';if(field.options){$.each(field.options,function(idx,val){li_text=li_text+'<input type="hidden" name="event[custom_field_types][options][]" value="'+val+'"/>'})}var $li=$(li_text+'<input type="hidden" name="event[custom_field_types][id]" value="'+field.id+'"/>        <input type="hidden" name="event[custom_field_types][name]" value="'+GLUI.Util.escapeTags(field.name)+'"/>        <input type="hidden" name="event[custom_field_types][required]" value="'+field.required+'"/>        <input type="hidden" name="event[custom_field_types][klass]" value="'+field.klass+'"/>        <input type="hidden" name="event[custom_field_types][description]" value="'+GLUI.Util.escapeTags(field.description)+'"/>        <div class="attendeefields-column-handle"></div>        <div class="attendeefields-column-label"><span>'+GLUI.Util.escapeTags(field.name)+'</span><b></b></div>        <div class="attendeefields-column-status">          <div class="dropdown-text">            <span class="launcher" style="width: 56px">'+(field.required?'Required':'Optional')+'</span>            <div style="overflow: hidden; clear: both; height: 1px; margin-bottom: -1px;"></div>            <div class="dropdown" style="width: 76px;">              <a href="#" class="attendeefields-make-required">Required</a>              <a href="#" class="attendeefields-make-optional">Optional</a>            </div>          </div>        </div>        <div class="attendeefields-column-delete"><span class="action"></span></div>      </li>    ');$li.appendTo($dest);var $required=$li.find('input[name="event[custom_field_types][required]"]');var $label=$li.find('span.launcher');if($.inArray(field.name,self.defaultCustomFields)===-1){var $a=$li.find('div.attendeefields-column-label span').wrap('<a href="#"></a>').click(function(){var newFieldDialog=new GLUI.Dialogs.NewField(self,null,{title:"Edit Custom Field",name:$li.find('input[name="event[custom_field_types][name]"]').val(),description:$li.find('input[name="event[custom_field_types][description]"]').val(),options:$.map($li.find('input[name="event[custom_field_types][options][]"]'),function(el){return $(el).val()}),klass:$li.find('input[name="event[custom_field_types][klass]"]').val()},$li);newFieldDialog.open()})}$li.find('a.attendeefields-make-optional').click(function(){$label.html('Optional');$required.val(false);$(this).closest('.dropdown-text').removeClass('active');return false});$li.find('a.attendeefields-make-required').click(function(){$label.html('Required');$required.val(true);$(this).closest('.dropdown-text').removeClass('active');return false});$li.find('div.attendeefields-column-delete').click(function(){var $li=$(this).closest('li');if(!field.id){$li.fadeOut(function(){$li.remove();self.restoreCustomField(field)});return false}else if(confirm("Are you sure you want to delete this field? Any data you've collected for this field will be deleted.")){$.ajax({data:{_method:'delete'},url:'/manage/events/'+self.page.event.attrs.id+'/custom_field_types/'+field.id,type:'POST',dataType:'json',success:function(response){$li.fadeOut(function(){$li.remove();self.restoreCustomField(field)})}})}return false})},updateCouponCode:function($row,coupon_code){var self=this;$row.find('input[name="event[coupon_codes][code]"]').val(coupon_code.code);$row.find('input[name="event[coupon_codes][discount]"]').val(coupon_code.discount);$row.find('input[name="event[coupon_codes][uses]"]').val(coupon_code.uses);$row.find('input[name="event[coupon_codes][used]"]').val(coupon_code.times_used)},addCouponCode:function(coupon_code){var self=this;var $dest=$('ul.coupons-table');var $li=$('<li class="coupons-row">      <input type="hidden" name="event[coupon_codes][id]" value="'+coupon_code.id+'"/>      <div class="coupons-row-code">        <input type="text" name="event[coupon_codes][code]" class="table-input-clean" style="width: 140px" value="'+GLUI.Util.escapeTags(coupon_code.code)+'">      </div>      <div class="coupons-row-discount">        <input name="event[coupon_codes][discount]" value="'+GLUI.Util.escapeTags(coupon_code.discount)+'" type="text" class="table-input-clean" style="width: 60px">      </div>      <input type="hidden" name="event[coupon_codes][discount_type]" value="'+coupon_code.discount_type+'"/>      <div class="coupons-row-type">        <div class="dropdown-text" style="margin-top: 5px">          <span class="launcher" style="width: 33px">'+(coupon_code.discount_type==='percent'?'% off':'$ off')+'</span>          <div style="overflow: hidden; clear: both; height: 1px; margin-bottom: -1px;"></div>          <div class="dropdown" style="width: 53px;">            <a href="#" class="coupons-set-percent">% off</a>            <a href="#" class="coupons-set-fixed">$ off</a>          </div>        </div>      </div>      <div class="coupons-row-uses">        <input type="text" name="event[coupon_codes][uses]" class="table-input-clean ta_right" style="width: 55px" value="'+coupon_code.uses+'">      </div>      <div class="coupons-row-used ta_right">'+coupon_code.times_used+'</div>      <div class="coupons-row-remove">      </div>    </li>');$li.appendTo($dest);var $discount_type=$li.find('input[name="event[coupon_codes][discount_type]"]');var $label=$li.find('span.launcher');$li.find('a.coupons-set-percent').click(function(){$label.html('% off');$discount_type.val('percent');$(this).closest('.dropdown-text').removeClass('active');return false});$li.find('a.coupons-set-fixed').click(function(){$label.html('$ off');$discount_type.val('dollars');$(this).closest('.dropdown-text').removeClass('active');return false});$li.find('div.coupons-row-remove').append(coupon_code.times_used>0?'<span class="ticket-types-row-lock-button"/>':'<a href="#" class="coupons-row-remove-button"/>');$li.find('a.coupons-row-remove-button').click(function(){var $li=$(this).closest('li');if(!coupon_code.id){$li.fadeOut(function(){$li.remove()});return false}else if(confirm("Are you sure you want to delete this coupon code?")){$.ajax({data:{_method:'delete'},url:'/manage/events/'+self.page.event.attrs.id+'/coupon_codes/'+coupon_code.id,type:'POST',dataType:'json',success:function(response){$li.fadeOut(function(){$li.remove()})}})}return false})},addBlankCouponCode:function(){var self=this;var defaults={id:'',code:'',discount:'',discount_type:'percent',uses:10,times_used:0};var li=$('ul.coupons-table li:last');if(li.hasClass('coupons-row')){var last_coupon_code=self.extractCouponCodeData(li);defaults=$.extend(defaults,{discount:last_coupon_code.discount,discount_type:last_coupon_code.discount_type,uses:last_coupon_code.uses})}self.addCouponCode(defaults)},defaultCustomFields:["Company Name","Title","Phone Number","Website","Address","Twitter ID"],reveal:function(tab_id){var self=this;self.$container.find('#glui-menu').find('a[href="'+tab_id+'"]').click()},onLoad:function(){var self=this;self.$container.find('#glui-menu').find('a').click(function(){$('#glui-menu').find('a.active').removeClass('active');var id=$(this).addClass('active').attr('href');id=id.replace(/^.*#/,'#');self.$container.find('div.glui-tab').hide();self.$container.find('div.error').remove();$(id).show();return false});var $standardFields=$('#attendeefields-add');$.each(self.defaultCustomFields,function(i,name){$standardFields.append('          <option value="'+name+'">'+name+'</option>        ')});$standardFields.change(function(){var $select=$(this);if($select.val()===''){return}else{self.addCustomField({id:'',name:$select.val(),required:false})}$select.val('')});$('#attendeefields-add-custom').click(function(){var newFieldDialog=new GLUI.Dialogs.NewField(self,null,{title:"New Custom Field"});newFieldDialog.open()});$("#attendeefields-list-required").sortable({handle:"div.attendeefields-column-handle",items:'li:not(.attendeefields-list-item-permanent)',placeholder:"ui-sortable-placeholder",start:function(event,ui){ui.item.addClass('ondrag');$('body').addClass('cursor-move')},stop:function(event,ui){ui.item.removeClass('ondrag');$('body').removeClass('cursor-move')}});self.mailChimpSection=new GLUI.Widgets.MailChimpIntegration(self,self.$container);self.mailChimpSection.onLoad();self.campaignMonitorSection=new GLUI.Widgets.CampaignMonitorIntegration(self,self.$container);self.campaignMonitorSection.onLoad();self.changeBackground=new GLUI.Widgets.ChangeBackground(self,self.$container);self.changeBackground.onLoad();self.$container.find('a.new-coupon-line .blank').click(function(){self.addBlankCouponCode();self.$container.find('li.coupons-row:last input:visible:first').focus();return false});self.$container.find('a.new-coupon-line .random').click(function(){var defaults={id:'',code:GLUI.Util.randomString(15),discount:'',discount_type:'percent',uses:10,times_used:0};var li=$('ul.coupons-table li:last');if(li.hasClass('coupons-row')){var last_coupon_code=self.extractCouponCodeData(li);defaults=$.extend(defaults,{discount:last_coupon_code.discount,discount_type:last_coupon_code.discount_type,uses:last_coupon_code.uses})}self.addCouponCode(defaults);self.$container.find('li.coupons-row:last input:visible:first').focus();return false})},extractCouponCodeData:function($li){return{id:$li.find('input[name="event[coupon_codes][id]"]').val(),code:$.trim($li.find('input[name="event[coupon_codes][code]"]').val()),discount_type:$li.find('input[name="event[coupon_codes][discount_type]"]').val(),discount:$.trim($li.find('input[name="event[coupon_codes][discount]"]').val()),uses:$.trim($li.find('input[name="event[coupon_codes][uses]"]').val())}},onSave:function(){var self=this;self._clearErrors();var params={};params.show_attendee_list=!!self.$container.find('input[name="event[show_attendee_list]"]:checked').val();params.redirect_url=self.$container.find('input[name="event[redirect_url]"]').val();params.order_ticket_limit=self.$container.find('#settings-advanced select[name="event[order_ticket_limit]"]').val();params.custom_field_types=[];var i=0;self.$container.find('li.attendeefields-list-item-useradded').each(function(){var $li=$(this);params.custom_field_types.push({id:$li.find('input[name="event[custom_field_types][id]"]').val(),name:$li.find('input[name="event[custom_field_types][name]"]').val(),klass:$li.find('input[name="event[custom_field_types][klass]"]').val(),required:$li.find('input[name="event[custom_field_types][required]"]').val()=='true'?1:0,description:$li.find('input[name="event[custom_field_types][description]"]').val(),options:$.map($li.find('input[name="event[custom_field_types][options][]"]'),function(el){return $(el).val()}),sequence:i++})});self.mailChimpSection.extractAttrs(params);self.campaignMonitorSection.extractAttrs(params);self.changeBackground.extractAttrs(params);var used_codes={};var coupon_validation_errors=[];params.coupon_codes=[];self.$container.find('li.coupons-row').each(function(){var $li=$(this);var coupon_code=self.extractCouponCodeData($li);if(coupon_code.code){self.validateCouponCode(coupon_code,used_codes,coupon_validation_errors);used_codes[coupon_code.code]=true;params.coupon_codes.push(coupon_code)}});if(coupon_validation_errors.length>0){self.onError(coupon_validation_errors)}params.web_property_id=self.$container.find('input[name="event[web_property_id]"]').val();if(!self.hasError()){self.page.saveEvent(params,self)}return false},validateCouponCode:function(coupon_code,used_codes,errors){self=this;if(used_codes[coupon_code.code]){errors.push("Code has already been used for this event")}if(coupon_code.code.length<4){errors.push("Code is too short (minimum is 4 characters)")}if(coupon_code.code.length>30){errors.push("Code is too long (maximum is 30 characters)")}if(!coupon_code.discount){errors.push("Discount can't be blank")}else{coupon_code.discount=parseFloat(coupon_code.discount);if(isNaN(coupon_code.discount)){errors.push("Discount is not a number")}else if(coupon_code<=0){errors.push("Discount must be greater than 0")}else{if(coupon_code.discount_type==="dollars"&&coupon_code.discount>99999999.99){errors.push("Discount must be less than or equal to 99999999.99")}else if(coupon_code.discount_type==="percent"&&coupon_code.discount>100){errors.push("Discount must be less than or equal to 100")}}}if(!coupon_code.uses){errors.push("Uses can't be blank")}else{coupon_code.uses=parseFloat(coupon_code.uses);if(isNaN(coupon_code.uses)){errors.push("Uses is not a number")}else if(coupon_code.uses<=0){errors.push("Uses must be greater than 0")}else if(coupon_code.uses>1000000){errors.push("Uses must be less than or equal to 1000000")}}}});GLUI.Dialogs.EditEventDate=GLUI.Dialogs.Base.extend({template:'#evt-date-dialog-tpl',afterOpen:function(){},onLoad:function(){var self=this;self.$container.find('form').submit(function(){self.save();return false});self.components.date=new GLUI.Widgets.EventDate(self);self.components.date.onLoad()},onOpen:function(){var self=this;var event=self.page.event;self.components.date.onOpen()},onSave:function(){var self=this;self.page.saveEvent(self.components.date.getAttrs(),self);return false},onClose:function(){$('div.datepicker').hide()}});GLUI.Dialogs.EditEventLocation=GLUI.Dialogs.Base.extend({template:'#evt-location-dialog-tpl',onLoad:function(){var self=this;self.$container.find('form').submit(function(){self.save();return false})},onOpen:function(){var self=this;var location=self.page.event.attrs.location;if(!location){location={}}self.$container.find('input[name="event[location][name]"]').val(location.name);self.$container.find('input[name="event[location][address_1]"]').val(location.address_1);self.$container.find('input[name="event[location][address_2]"]').val(location.address_2);self.$container.find('input[name="event[location][city]"]').val(location.city);self.$container.find('input[name="event[location][state]"]').val(location.state);self.$container.find('input[name="event[location][postal]"]').val(location.postal);self.$container.find('input[name="event[location][country]"]').val(location.country);if(self.page.event.attrs.show_map){self.$container.find('input[name="event[show_map]"]').attr('checked','checked').redraw()}else{self.$container.find('input[name="event[show_map]"]').removeAttr('checked').redraw()}return false},onSave:function(){var self=this;self.page.saveEvent({show_map:self.$container.find('input[name="event[show_map]"]').is(':checked'),location:{name:self.$container.find('input[name="event[location][name]"]').val(),address_1:self.$container.find('input[name="event[location][address_1]"]').val(),address_2:self.$container.find('input[name="event[location][address_2]"]').val(),city:self.$container.find('input[name="event[location][city]"]').val(),state:self.$container.find('input[name="event[location][state]"]').val(),postal:self.$container.find('input[name="event[location][postal]"]').val(),country:self.$container.find('input[name="event[location][country]"]').val()}},self);return false}});GLUI.Dialogs.EditEventTicketType=GLUI.Dialogs.Base.extend({template:"#evt-ticket-type-dialog-tpl",addBlankTicketType:function(){var self=this;self.addTicketType({id:'',name:'',description:'',status:'selling',price:'',tickets_sold:'',quantity:''})},_calculateTicketFee:function(event,amount){if(amount==0.0||!event.attrs.charge_fees){return null}else{var max_fee=event.attrs.currency_code=='JPY'?1000:10.00;return Math.min(amount*0.02,max_fee)}},addTicketType:function(ticketType){var self=this;var event=self.page.event;var status_label_lookup={"selling":"Selling","sold_out":"Sold Out","hidden":"Hidden"};var $table=self.$container.find('ul.ticket-types-table');var formattedPrice='';if(ticketType.price!==''){formattedPrice=GLUI.Util.formatMoney(ticketType.base_price)}$row=$('      <li class="ticket-types-row">        <input type="hidden" name="event[ticket_types][id]" value="'+ticketType.id+'"/>        <span class="ticket-types-row-handle">&nbsp;</span>        <div class="ticket-types-row-name"><input name="event[ticket_types][name]" type="text" class="table-input-clean" style="width: 155px" value="'+GLUI.Util.escapeTags(ticketType.name)+'"/></div>        <div class="ticket-types-row-description"><input name="event[ticket_types][description]" value="'+GLUI.Util.escapeTags(ticketType.description)+'"type="text" class="table-input-clean" style="width: 215px" /></div>        <div class="ticket-types-row-price"><input name="event[ticket_types][base_price]" type="text" class="table-input-clean ta_right" style="width: 60px" value="'+formattedPrice+'"/></div>        <div class="ticket-types-row-quantity"><input name="event[ticket_types][quantity]" type="text" class="table-input-clean ta_right" style="width: 60px" value="'+ticketType.quantity+'"/></div>        <div class="ticket-types-row-sold ta_right">'+ticketType.tickets_sold+'</div>        <input type="hidden" name="event[ticket_types][status]" value="'+ticketType.status+'"/>        <div class="ticket-types-row-status">          <div class="dropdown-text" style="margin-top: 5px">            <span class="launcher" style="width: 47px">'+status_label_lookup[ticketType.status]+'</span>            <div style="overflow: hidden; clear: both; height: 1px; margin-bottom: -1px;"></div>            <div class="dropdown" style="width: 67px;">              <a href="#" class="ticket-types-set-selling">Selling</a>              <a href="#" class="ticket-types-set-sold_out">Sold Out</a>              <a href="#" class="ticket-types-set-hidden">Hidden</a>            </div>          </div>        </div>        <div class="ticket-types-row-remove"><!-- things go here --></div>      </li>    ');$table.append($row);var $status=$row.find('input[name="event[ticket_types][status]"]');var $label=$row.find('span.launcher');$row.find('a.ticket-types-set-selling').click(function(){$label.html('Selling');$status.val('selling');$(this).closest('.dropdown-text').removeClass('active');return false});$row.find('a.ticket-types-set-sold_out').click(function(){$label.html('Sold Out');$status.val('sold_out');$(this).closest('.dropdown-text').removeClass('active');return false});$row.find('a.ticket-types-set-hidden').click(function(){$label.html('Hidden');$status.val('hidden');$(this).closest('.dropdown-text').removeClass('active');return false});$row.find('div.ticket-types-row-remove').append(ticketType.tickets_sold>0?'<span class="ticket-types-row-lock-button"/>':'<a href="#" class="ticket-types-row-remove-button"/>');$row.find('input[type=text]').focus(function(){$(this).closest('div').addClass('ticket-types-cell-focus')}).blur(function(){$(this).closest('div').removeClass('ticket-types-cell-focus')});$row.find('a.ticket-types-row-remove-button').click(function(){var $row=$(this).closest('li');if(!ticketType.id){$row.slideUp('fast',function(){$row.remove()})}else{$.ajax({data:{_method:'delete'},url:'/manage/events/'+self.page.event.attrs.id+'/ticket_types/'+ticketType.id,type:'POST',dataType:'json',success:function(response){$row.slideUp('fast',function(){$row.remove();var rowCount=$table.find('li.ticket-types-row').length;if(rowCount==0){window.location.reload()}})}})}return false})},onLoad:function(){var self=this;self.$container.find("ul.ticket-types-table").sortable({placeholder:"ui-sortable-placeholder",handle:"span.ticket-types-row-handle",items:'li:not(.ticket-types-header)',start:function(event,ui){ui.item.addClass('ondrag');$('body').addClass('cursor-move')},stop:function(event,ui){ui.item.removeClass('ondrag');$('body').removeClass('cursor-move')}});self.$container.find('a.new-ticket-line').click(function(){self.addBlankTicketType();self.$container.find('li.ticket-types-row:last input:visible:first').focus();return false});self.$container.find('form').submit(function(){self.save();return false})},onOpen:function(){var self=this;var $container=self.$container;var event=self.page.event;$container.find('select[name="event[currency_code]"]').val(event.attrs.currency_code).redraw();$container.find('select[name="event[include_fee]"]').val(event.attrs.include_fee?1:0).redraw();var ticketTypes=event.attrs.ticket_types;$container.find('li.ticket-types-row').remove();ticketTypes.sort(function(a,b){return a.sequence-b.sequence});var mt;if(mt=event.attrs.max_tickets){$('#event_max_tickets').val(mt)}var total_tickets=0;$.each(ticketTypes,function(index,ticketType){total_tickets+=ticketType.quantity;self.addTicketType(ticketType)});$('#event_max_tickets').attr('placeholder',total_tickets);var blankTicketTypesToAdd=Math.max(3-ticketTypes.length,1);while(blankTicketTypesToAdd--){self.addBlankTicketType()}if(self.page.event.attrs.gateways[0]){$container.find('input[name="event[gateway][account_name]"]').val(event.attrs.gateways[0].account_name)}},onSave:function(){var self=this;var $container=self.$container;var ticketTypes=[];var i=0;$container.find('li.ticket-types-row').each(function(){var $row=$(this);var tt={id:$row.find('input[name="event[ticket_types][id]"]').val(),name:$row.find('input[name="event[ticket_types][name]"]').val(),description:$row.find('input[name="event[ticket_types][description]"]').val(),status:$row.find('input[name="event[ticket_types][status]"]').val(),base_price:$row.find('input[name="event[ticket_types][base_price]"]').val(),quantity:$row.find('input[name="event[ticket_types][quantity]"]').val(),sequence:i++};if(tt.name||tt.base_price||tt.quantity||tt.id){ticketTypes.push(tt)}});self.page.saveEvent({ticket_types:ticketTypes,max_tickets:$('#event_max_tickets').val(),currency_code:$container.find('select[name="event[currency_code]"]').val(),include_fee:$container.find('select[name="event[include_fee]"]').val(),gateway:{account_name:$container.find('input[name="event[gateway][account_name]"]').val()}},self)}});GLUI.Widgets.ChangeBackground=GLUI.Widgets.Base.extend({template:'#evt-background-dialog-tpl',constructor:function(parent,$container){this.parent=parent;this.$container=$container},setBackground:function(bg){$('body').removeAttr('style');$('body').attr('style',bg)},onLoad:function(){var self=this;self.imagesPreloaded=false;$('div.background-container div.block').livequery('click',function(){var $this=$(this);self.setBackground($this.attr('rel'));$this.find('input[type=radio]').attr('checked',true);$('div.background-container div.block').removeClass('selected').find('div.cancel').show();$this.addClass('selected').find('div.cancel').hide();if($this.hasClass('built-in')){$('#tilebackground').parent().parent().hide()}else{var bg_repeat=$this.find('input[name="background_repeat"]');$('#tilebackground').attr('checked',(bg_repeat.val()=='repeat')).redraw();$('#tilebackground').parent().parent().show()}var bgId=parseInt($this.find('input[name="event[background_id]"]').val());if(self.parent.page.event.attrs.background_id==bgId)return;self.parent.page.event.attrs.background_id=bgId;$.ajax({url:'/manage/events/'+self.parent.page.event.attrs.id,data:{'_method':'put','event':{'background_id':bgId,'timezone':self.parent.page.event.attrs.timezone}},type:'POST',dataType:'json',error:function(xmlHttpRequest){},success:function(response){}})});$('div.background-container div.cancel').livequery('click',function(event){var $this=$(this);var bgId=$this.parent().find('input[name="event[background_id]"]').val();if(bgId){$.ajax({url:'/manage/backgrounds/'+parseInt(bgId),data:{_method:'DELETE'},type:'POST',dataType:'json',error:function(xmlHttpRequest){},success:function(response){}})}var block_div=$('#bg-'+bgId);if(block_div.length){block_div.fadeOut(250,function(){$(this).remove()});event.preventDefault()}event.stopPropagation()});$('#tilebackground').click(function(){var params={};self.extractAttrs(params);var bgId=params.background_id;var bg_repeat=$(this).parent().find('input[name="background_repeat"]');if($(this).attr('checked')){bg_repeat.val('repeat')}else{bg_repeat.val('no-repeat')}$.ajax({url:'/manage/backgrounds/'+bgId,data:{_method:'PUT','repeat':$(this).attr('checked')?'repeat':'no-repeat'},type:'POST',dataType:'json',error:function(xmlHttpRequest){},success:function(response){self.setBackground(response.style)}})});var bgId=self.parent.page.event.attrs['background_id'];$('#bg-'+bgId).click()},onOpen:function(){var self=this;if(!self.imagesPreloaded){var bgUrls=self.$container.find('div.background-container div').map(function(i,elem){return $(elem).attr('rel')});$.preloadImages(bgUrls);self.imagesPreloaded=true}},extractAttrs:function(params){var self=this;params.background_id=self.$container.find('input[name="event[background_id]"]:checked').val()}});GLUI.Dialogs.EditEventLogo=GLUI.Dialogs.Base.extend({template:'#evt-logo-dialog-tpl',onOpen:function(){},onSave:function(){var self=this;self.$container.find('form').submit()}});GLUI.Pages.Orders=Base.extend({constructor:function(event,eventUrl){var self=this;self.event=event;self.eventUrl=eventUrl},init:function(){var self=this;var hashOnChange=function(hash){if(hash!==''){self.showOrder(hash)}};$.historyInit(hashOnChange);$("a.view-order").click(function(){var hash=GLUI.Util.getHashString(this.href);$.historyLoad(hash);return false});$.getJSON(self.eventUrl+'/orders/report',function(json){if(json.length>0){var firstDate=new Date(json[0].date);firstDate.setDate(firstDate.getDate()-1);var tickets=[[firstDate.getTime(),0]];$.each(json,function(i,row){tickets.push([(new Date(row.date)).getTime(),row.total_tickets])})}else{tickets=[(new Date()).getTime(),0]}var series=[{data:tickets}];new GLUI.Widgets.Chart('div.graph',series)})},showOrder:function(id){var self=this;self.order=new GLUI.Models.Order({},self.eventUrl+'/orders');self.order.load(id,{success:function(){var showOrderDialog=new GLUI.Dialogs.ShowOrder(self,null,self.order);showOrderDialog.open()}});return false}});GLUI.Pages.Attendees=Base.extend({constructor:function(event,eventUrl){var self=this;self.eventUrl=eventUrl;self.event=event},init:function(){var self=this;self.newAttendeeDialog=new GLUI.Dialogs.NewAttendee(self,'#new-attendee:not(.disabled)');var hashOnChange=function(hash){switch(hash){case'':break;case'add':self.newAttendeeDialog.open();break;default:self.showTicket(hash)}return false};$.historyInit(hashOnChange);$("a.view-ticket").click(function(){var hash=GLUI.Util.getHashString(this.href);$.historyLoad(hash);return false})},showTicket:function(id){var self=this;self.ticket=new GLUI.Models.Ticket({},self.eventUrl+'/tickets/');self.ticket.load(id,{success:function(){var showAttendeeDialog=new GLUI.Dialogs.ShowAttendee(self,null,self.ticket);showAttendeeDialog.open()}});return false},createAttendee:function(newAttrs,dialog){var self=this;var order=new GLUI.Models.Order({},self.eventUrl+'/orders/');order.save(newAttrs,{success:function(resp){dialog.close();var ticketNumber=resp.tickets[0].number_for_admin;var notice='Attendee #'+ticketNumber+' added.';if(typeof newAttrs.send_confirmation!=='undefined'){notice+=' Email confirmation sent.'}GLUI.flash({'notice':notice});window.location.reload(true)},error:function(json){dialog.onError(json)}})}});GLUI.Pages.EventDashboard=Base.extend({init:function(){var self=this;self.copyEventDialog=new GLUI.Dialogs.CopyEvent(self,'span.copyevent')}});GLUI.Pages.CreateEvent=Base.extend({init:function(){var self=this;self.event=new GLUI.Models.Event({},'/manage/events/');self.createEventDialog=new GLUI.Dialogs.CreateEvent(self,'a.newevent')},saveEvent:function(newAttrs,dialog){var self=this;self.event.save(newAttrs,{success:function(response){var newEvent=new GLUI.Models.Event(response,'/manage/events');GLUI.flash({notice:"Event created! Click the \"Edit Event\" tab to continue customizing your event, or consult the checklist below."});window.location=newEvent.url()},error:function(json){dialog.onError(json)}})}});GLUI.Pages.PublicEvent=Base.extend({constructor:function(location,show_map){this.location=location;this.show_map=show_map},_revealAvatars:function(){var position=$(window).height()+$(document).scrollTop();var $portraits=$('img.no-avatar:visible');for(var i=0;i<$portraits.length;i++){var $img=$($portraits[i]);var offset=$img.offset();if(position>(offset.top-200)){$img.removeClass('no-avatar');$img.attr('src',$img.attr('data-src'))}else{break}}},init:function(){var self=this;self.locationUI=new GLUI.Widgets.Location();self.locationUI.load(self.location,self.show_map);$(window).scroll(self._revealAvatars);$('.show-more-attendees').live('click',function(){var url=$(this).data('next-page');$(this).closest('h5').remove();$.get(url,function(data){var new_attendees=$(data).find('.attendee');var more=$(data).find('h5');$("#public-attendee-list").append(new_attendees);if(more){$('#public-attendee-list').after(more)}});return false});self.dateSection=new GLUI.Widgets.DateSection();self._revealAvatars()}});GLUI.Pages.EditEvent=Base.extend({constructor:function(eventModel){this.event=eventModel},init:function(){var self=this;self.editNameDialog=new GLUI.Dialogs.EditEventName(self,'#evt-name-reveal');self.editDescriptionDialog=new GLUI.Dialogs.EditEventDescription(self,'#evt-description-reveal');self.editDateDialog=new GLUI.Dialogs.EditEventDate(self,'#evt-date-reveal');self.editLocationDialog=new GLUI.Dialogs.EditEventLocation(self,'#evt-location-reveal');self.editTicketTypeDialog=new GLUI.Dialogs.EditEventTicketType(self,'#evt-ticket-type-reveal');self.editLogoDialog=new GLUI.Dialogs.EditEventLogo(self,'#evt-logo-reveal');self.editSettingsDialog=new GLUI.Dialogs.EditEventSettings(self,'#evt-settings-reveal',self.event.attrs);var anchor=document.location.hash;switch(anchor){case'#name':self.editNameDialog.open();break;case'#description':self.editDescriptionDialog.open();break;case'#date':self.editDateDialog.open();break;case'#location':self.editLocationDialog.open();break;case'#tickets':self.editTicketTypeDialog.open();break;case'#logo':self.editLogoDialog.open();break;case'#settings':self.editSettingsDialog.open();break;case'#settings-background':self.editSettingsDialog.open('#settings-background');break;case'#settings-attendees':self.editSettingsDialog.open('#settings-attendees');break;case'#settings-fields':self.editSettingsDialog.open('#settings-fields');break;case'#settings-embed':self.editSettingsDialog.open('#settings-embed');break;case'#settings-campaign-monitor':self.editSettingsDialog.open('#settings-campaign-monitor');break}self.locationUI=new GLUI.Widgets.Location(typeof(google)!=='undefined');self.locationUI.load(self.event.attrs.location,self.event.attrs.show_map);self.dateSection=new GLUI.Widgets.DateSection()},saveEvent:function(newAttrs,dialog){var self=this;self.event.save(newAttrs,{success:function(){self.refresh();dialog.close()},error:function(json){dialog.onError(json)}})},refresh:function(){var self=this;var event=self.event;$('h1:first').text(event.attrs.name);$('#active-event-tab a').html(GLUI.Util.abbrev(GLUI.Util.escapeTags(event.attrs.name),20));var subtitle=GLUI.Util.verboseDateRange(event.startDate(),event.stopDate());if(event.attrs.location){subtitle+=' at '+event.attrs.location.name}$('h6:first').text(subtitle);if(event.attrs.description){$('#event-description').html(event.attrs.description)}if(event.attrs.stop){$('#event-date').hide();$('#event-date-range').show()}else{$('#event-date-range').hide();$('#event-date').show()}$('#event-start, #event-date').text(GLUI.Util.verboseDateTime(event.startDate()));$('#event-stop').text(GLUI.Util.verboseDateTime(event.stopDate()));$('#event-tz').text(event.attrs.formatted_timezone);$('#ticket-type-tbl tbody').empty();var ticketTypes=event.attrs.ticket_types;ticketTypes=ticketTypes.sort(function(a,b){return a.sequence-b.sequence});$(ticketTypes).each(function(index,ticketType){var price;if(ticketType.price){price=event.attrs.currency_symbol+ticketType.price.toFixed(2)}else{price='Free'}$('#ticket-type-tbl tbody').append('<tr>  <td class="type"><strong>'+GLUI.Util.escapeTags(ticketType.name)+'</strong><p>'+GLUI.Util.escapeTags(ticketType.description)+'</p></td>  <td class="price">'+price+'</td>  <td class="quantity"><div class="select-wrapper disabled"><span>0</span></div></td></tr>')});if(typeof(self.event.attrs.location)!='undefined'){self.locationUI.load(self.event.attrs.location,self.event.attrs.show_map)}if(event.attrs['publishable?']){$('a.publish').removeClass('disabled').find('div.help-bubble').remove()}else{}}});GLUI.Models.Base=Base.extend({keyifyErrors:function(attrs,baseName){var self=this;if(typeof(baseName)=='undefined'){baseName=self.modelName}var keyedErrors={};$.each(attrs,function(k,v){if(k=='errors'){$.each(v,function(index,errArray){keyedErrors[baseName+'['+errArray[0]+']']=errArray[1]})}else if(typeof(v)=='object'){$.each(v,function(index,child){$.extend(keyedErrors,self.keyifyErrors(child,baseName+'['+k+']['+index+']'))})}});return keyedErrors},constructor:function(attrs,baseUrl){var self=this;if(typeof(baseUrl)!='undefined'){self.baseUrl=baseUrl}if(attrs===undefined){this.attrs={}}else{this.attrs=attrs}},id:function(){return this.attrs.id},_buildPostHash:function(paramName,data){var self=this;var dataOut={};$.each(data,function(k,v){if(!v&&typeof(v)=='object'){return}var fullKey=paramName+'['+k+']';if(typeof(v)==='object'){$.extend(dataOut,self._buildPostHash(fullKey,v))}else{dataOut[fullKey]=v}});return dataOut},save:function(newAttrs,callbacks){var self=this;if(typeof(newAttrs)=='undefined'){newAttrs={}}if(typeof(callbacks)=='undefined'){callbacks={success:function(){},error:function(){}}}var dataOut=$.extend({_method:self.id()?'PUT':'POST'},self._buildPostHash(self.modelName,newAttrs));$.ajax({url:self.url(),data:dataOut,type:'POST',dataType:'json',error:function(xmlHttpRequest){response=JSON.parse(xmlHttpRequest.responseText);callbacks.error(response.errors)},success:function(response){self.attrs=response;callbacks.success(response)}})},load:function(id,callbacks){var self=this;$.ajax({url:self.url()+'/'+id,type:'GET',dataType:'json',timeout:1000,error:callbacks.error,success:function(response){$.extend(self.attrs,response);callbacks.success(response)}})},destroy:function(callbacks){var self=this;$.ajax({data:{_method:'delete'},url:self.url(),type:'POST',dataType:'json',error:callbacks.error,success:function(response){$.extend(self.attrs,response);callbacks.success(response)}})},url:function(action){var urlParts=[this.baseUrl.replace(/\/$/,'')];if(this.id()){urlParts.push(this.id())}if(typeof(action)!='undefined'){urlParts.push(action)}return urlParts.join('/')}});GLUI.Models.Event=GLUI.Models.Base.extend({constructor:function(params,baseUrl){var self=this;self.modelName='event';self.base(params,baseUrl)},addressString:function(){var self=this;if(!self.attrs.location){return''}var loc=self.attrs.location;pieces=[];if(loc.address_1){pieces.push(loc.address_1)}if(loc.address_2){pieces.push(loc.address_2)}if(loc.city){pieces.push(loc.city)}if(loc.state){pieces.push(loc.state)}if(loc.country){pieces.push(loc.country)}if(loc.postal){pieces.push(loc.postal)}return pieces.join(' ')},startDate:function(){var self=this;return GLUI.Util.genericDateFromTzDate(self.attrs.start)},stopDate:function(){var self=this;if(self.attrs.stop){return GLUI.Util.genericDateFromTzDate(self.attrs.stop)}else{return self.startDate()}}});GLUI.Models.Order=GLUI.Models.Base.extend({constructor:function(params,baseUrl){var self=this;self.modelName='order';self.base(params,baseUrl)}});GLUI.Models.Ticket=GLUI.Models.Base.extend({constructor:function(params,baseUrl){var self=this;self.modelName='ticket';self.base(params,baseUrl)}});GLUI.Helpers={submitLinkAsForm:function(elem,method){var csrf_token=$('meta[name=csrf-token]').attr('content');var csrf_param=$('meta[name=csrf-param]').attr('content');var f=$('<form style="display:none" action="'+$(elem).attr('href')+'" method="post"></form>');var metadata_input='<input class="hidden" type="hidden" value="'+method+'" name="_method"/>';if(csrf_param!==undefined&&csrf_token!==undefined){metadata_input+='<input name="'+csrf_param+'" value="'+csrf_token+'" type="hidden" />'}f.hide().append(metadata_input).appendTo(elem);$(elem).attr('href','#');return f.submit()},disableForm:function(obj){obj.hide().find('input').attr('disabled',true)},enableForm:function(obj){obj.show().find('input').attr('disabled',false)[0].focus();return false}};GLUI.init=function(){(function(){var _hideLauncherMenu=function(){$('div.dropdown-text:not(.ignore-me)').removeClass('active');$(document).unbind('click',_launcherOnDocClick)};var _launcherOnDocClick=function(e){if($(e.target).closest('div.dropdown-text').length){return true}_hideLauncherMenu();return false};$('span.launcher').live('click',function(){var $parent=$(this).parent();$parent.addClass('ignore-me');_hideLauncherMenu();$parent.removeClass('ignore-me');if(!$parent.hasClass('active')){$parent.addClass('active');$(document).click(_launcherOnDocClick)}else{$parent.removeClass('active')}})})();$('a.submit-post').click(function(){if($(this).is(':not(.disabled)')){GLUI.Helpers.submitLinkAsForm(this,'post')}return false});$('span.deleteevent').click(function(){if(confirm("Are you sure? This can't be undone.")){GLUI.Helpers.submitLinkAsForm($(this).parent(),'delete')}return false});$('input[name="_method"][value="delete"]').parents('form').submit(function(){return confirm("Are you sure? This can't be undone.")});GLUI.Helpers.disableForm($('.default_disabled'));$('a.enabler').click(function(){$(this).hide();GLUI.Helpers.enableForm($('~ .default_disabled',this))});$('a.print-me').click(function(){window.print()});$('a.icon-search').click(function(){if($('div.search-bar').is(':hidden')){$('div.search-bar').slideDown(function(){$('div.search-bar :input:visible:first').focus()})}else{$('div.search-bar').slideUp()}return false});$('div.search-bar a.close').click(function(){$(this).closest('div.search-bar').slideUp();return false});$('input.readonly-disabled').livequery('focus',function(){$(this).blur()});$('input[name="event[ticket_types][quantity]"]').live('change',function(){var total_tickets=0;$('input[name="event[ticket_types][quantity]"]').each(function(){var quantity=Number($(this).val());if(!isNaN(quantity)){total_tickets+=quantity}});$('#event_max_tickets').attr('placeholder',total_tickets)});$(":input.focus:first").focus();$('button.disabled').closest('form').submit(function(){return false});$('.tooltip-hover-top').livequery(function(){$(this).bt($.extend({},GLUI.DEFAULT_BT_PARAMS,{showTip:function(box){$(box).show()},hideTip:function(box,callback){$(box).animate({marginTop:"-10px",opacity:0},250,callback)}}))});$('.tooltip-hover-bottom').livequery(function(){$(this).bt($.extend({},GLUI.DEFAULT_BT_PARAMS,{showTip:function(box){$(box).show()},hideTip:function(box,callback){$(box).animate({marginTop:"10px",opacity:0},250,callback)},width:115,positions:['bottom']}))});$('.tooltip-click').livequery(function(){$(this).bt($.extend({},GLUI.DEFAULT_BT_PARAMS,{showTip:function(box){$(box).show()},hideTip:function(box,callback){$(box).animate({marginTop:"-10px",opacity:0},250,callback)},width:200,trigger:'click'}))});$.extend(DateInput.DEFAULT_OPTS,{start_of_week:0,stringToDate:function(string){var matches;if(matches=string.match(/^(\d{2,2})\/(\d{2,2})\/(\d{4,4})$/)){return new Date(matches[3],matches[1]-1,matches[2])}else{return null}},dateToString:function(date){var month=(date.getMonth()+1).toString();var dom=date.getDate().toString();if(month.length==1)month="0"+month;if(dom.length==1)dom="0"+dom;return month+"/"+dom+"/"+date.getFullYear()}})};$(function(){GLUI.init()});(function($){$.fn.redraw=function(){var $this=$(this);if($this.length==0)return;if($this[0].tagName.match(/select/i)){$this.prev().text($('option:selected',this).text())}else{if($this.is(":checked")){$this.parent().removeClass("checkbox-mousedown");$this.parent().addClass("checkbox-checked")}else{$this.parent().removeClass("checkbox-mousedown");$this.parent().removeClass("checkbox-checked")}}};$("div.select-wrapper select, div.checkbox-wrapper input").livequery($.fn.redraw).livequery('change',$.fn.redraw)})(jQuery);
